You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cloudflare-pages-action/index.js

22198 lines
1.1 MiB
JavaScript

3 years ago
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3 years ago
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
3 years ago
// node_modules/@actions/core/lib/utils.js
var require_utils = __commonJS({
"node_modules/@actions/core/lib/utils.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toCommandProperties = exports.toCommandValue = void 0;
function toCommandValue(input) {
if (input === null || input === void 0) {
return "";
} else if (typeof input === "string" || input instanceof String) {
return input;
}
return JSON.stringify(input);
}
exports.toCommandValue = toCommandValue;
function toCommandProperties(annotationProperties) {
if (!Object.keys(annotationProperties).length) {
return {};
}
return {
title: annotationProperties.title,
file: annotationProperties.file,
line: annotationProperties.startLine,
endLine: annotationProperties.endLine,
col: annotationProperties.startColumn,
endColumn: annotationProperties.endColumn
};
}
exports.toCommandProperties = toCommandProperties;
}
});
// node_modules/@actions/core/lib/command.js
var require_command = __commonJS({
"node_modules/@actions/core/lib/command.js"(exports) {
"use strict";
var __createBinding = exports && exports.__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 __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports && exports.__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))
__createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.issue = exports.issueCommand = void 0;
var os = __importStar(require("os"));
var utils_1 = require_utils();
function issueCommand(command, properties, message) {
const cmd = new Command3(command, properties, message);
process.stdout.write(cmd.toString() + os.EOL);
}
exports.issueCommand = issueCommand;
function issue(name, message = "") {
issueCommand(name, {}, message);
}
exports.issue = issue;
var CMD_STRING = "::";
var Command3 = class {
constructor(command, properties, message) {
if (!command) {
command = "missing.command";
}
this.command = command;
this.properties = properties;
this.message = message;
}
toString() {
let cmdStr = CMD_STRING + this.command;
if (this.properties && Object.keys(this.properties).length > 0) {
cmdStr += " ";
let first = true;
for (const key in this.properties) {
if (this.properties.hasOwnProperty(key)) {
const val = this.properties[key];
if (val) {
if (first) {
first = false;
} else {
cmdStr += ",";
}
cmdStr += `${key}=${escapeProperty(val)}`;
}
}
}
}
cmdStr += `${CMD_STRING}${escapeData(this.message)}`;
return cmdStr;
}
};
function escapeData(s) {
return utils_1.toCommandValue(s).replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
}
function escapeProperty(s) {
return utils_1.toCommandValue(s).replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A").replace(/:/g, "%3A").replace(/,/g, "%2C");
}
}
});
// node_modules/uuid/dist/rng.js
var require_rng = __commonJS({
"node_modules/uuid/dist/rng.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = rng;
var _crypto = _interopRequireDefault(require("crypto"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var rnds8Pool = new Uint8Array(256);
var poolPtr = rnds8Pool.length;
function rng() {
if (poolPtr > rnds8Pool.length - 16) {
_crypto.default.randomFillSync(rnds8Pool);
poolPtr = 0;
}
return rnds8Pool.slice(poolPtr, poolPtr += 16);
}
}
});
// node_modules/uuid/dist/regex.js
var require_regex = __commonJS({
"node_modules/uuid/dist/regex.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
exports.default = _default;
}
});
// node_modules/uuid/dist/validate.js
var require_validate = __commonJS({
"node_modules/uuid/dist/validate.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _regex = _interopRequireDefault(require_regex());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function validate(uuid) {
return typeof uuid === "string" && _regex.default.test(uuid);
}
var _default = validate;
exports.default = _default;
}
});
// node_modules/uuid/dist/stringify.js
var require_stringify = __commonJS({
"node_modules/uuid/dist/stringify.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _validate = _interopRequireDefault(require_validate());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 256).toString(16).substr(1));
}
function stringify(arr, offset = 0) {
const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
if (!(0, _validate.default)(uuid)) {
throw TypeError("Stringified UUID is invalid");
}
return uuid;
}
var _default = stringify;
exports.default = _default;
}
});
// node_modules/uuid/dist/v1.js
var require_v1 = __commonJS({
"node_modules/uuid/dist/v1.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _rng = _interopRequireDefault(require_rng());
var _stringify = _interopRequireDefault(require_stringify());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var _nodeId;
var _clockseq;
var _lastMSecs = 0;
var _lastNSecs = 0;
function v1(options, buf, offset) {
let i = buf && offset || 0;
const b = buf || new Array(16);
options = options || {};
let node = options.node || _nodeId;
let clockseq = options.clockseq !== void 0 ? options.clockseq : _clockseq;
if (node == null || clockseq == null) {
const seedBytes = options.random || (options.rng || _rng.default)();
if (node == null) {
node = _nodeId = [seedBytes[0] | 1, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
}
if (clockseq == null) {
clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383;
}
}
let msecs = options.msecs !== void 0 ? options.msecs : Date.now();
let nsecs = options.nsecs !== void 0 ? options.nsecs : _lastNSecs + 1;
const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4;
if (dt < 0 && options.clockseq === void 0) {
clockseq = clockseq + 1 & 16383;
}
if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === void 0) {
nsecs = 0;
}
if (nsecs >= 1e4) {
throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
}
_lastMSecs = msecs;
_lastNSecs = nsecs;
_clockseq = clockseq;
msecs += 122192928e5;
const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296;
b[i++] = tl >>> 24 & 255;
b[i++] = tl >>> 16 & 255;
b[i++] = tl >>> 8 & 255;
b[i++] = tl & 255;
const tmh = msecs / 4294967296 * 1e4 & 268435455;
b[i++] = tmh >>> 8 & 255;
b[i++] = tmh & 255;
b[i++] = tmh >>> 24 & 15 | 16;
b[i++] = tmh >>> 16 & 255;
b[i++] = clockseq >>> 8 | 128;
b[i++] = clockseq & 255;
for (let n = 0; n < 6; ++n) {
b[i + n] = node[n];
}
return buf || (0, _stringify.default)(b);
}
var _default = v1;
exports.default = _default;
}
});
// node_modules/uuid/dist/parse.js
var require_parse = __commonJS({
"node_modules/uuid/dist/parse.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _validate = _interopRequireDefault(require_validate());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function parse2(uuid) {
if (!(0, _validate.default)(uuid)) {
throw TypeError("Invalid UUID");
}
let v;
const arr = new Uint8Array(16);
arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
arr[1] = v >>> 16 & 255;
arr[2] = v >>> 8 & 255;
arr[3] = v & 255;
arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
arr[5] = v & 255;
arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
arr[7] = v & 255;
arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
arr[9] = v & 255;
arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255;
arr[11] = v / 4294967296 & 255;
arr[12] = v >>> 24 & 255;
arr[13] = v >>> 16 & 255;
arr[14] = v >>> 8 & 255;
arr[15] = v & 255;
return arr;
}
var _default = parse2;
exports.default = _default;
}
});
// node_modules/uuid/dist/v35.js
var require_v35 = __commonJS({
"node_modules/uuid/dist/v35.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
exports.URL = exports.DNS = void 0;
var _stringify = _interopRequireDefault(require_stringify());
var _parse = _interopRequireDefault(require_parse());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function stringToBytes(str) {
str = unescape(encodeURIComponent(str));
const bytes = [];
for (let i = 0; i < str.length; ++i) {
bytes.push(str.charCodeAt(i));
}
return bytes;
}
var DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
exports.DNS = DNS;
var URL2 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
exports.URL = URL2;
function _default(name, version, hashfunc) {
function generateUUID(value, namespace, buf, offset) {
if (typeof value === "string") {
value = stringToBytes(value);
}
if (typeof namespace === "string") {
namespace = (0, _parse.default)(namespace);
}
if (namespace.length !== 16) {
throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");
}
let bytes = new Uint8Array(16 + value.length);
bytes.set(namespace);
bytes.set(value, namespace.length);
bytes = hashfunc(bytes);
bytes[6] = bytes[6] & 15 | version;
bytes[8] = bytes[8] & 63 | 128;
if (buf) {
offset = offset || 0;
for (let i = 0; i < 16; ++i) {
buf[offset + i] = bytes[i];
}
return buf;
}
return (0, _stringify.default)(bytes);
}
try {
generateUUID.name = name;
} catch (err) {
}
generateUUID.DNS = DNS;
generateUUID.URL = URL2;
return generateUUID;
}
}
});
// node_modules/uuid/dist/md5.js
var require_md5 = __commonJS({
"node_modules/uuid/dist/md5.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _crypto = _interopRequireDefault(require("crypto"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function md5(bytes) {
if (Array.isArray(bytes)) {
bytes = Buffer.from(bytes);
} else if (typeof bytes === "string") {
bytes = Buffer.from(bytes, "utf8");
}
return _crypto.default.createHash("md5").update(bytes).digest();
}
var _default = md5;
exports.default = _default;
}
});
// node_modules/uuid/dist/v3.js
var require_v3 = __commonJS({
"node_modules/uuid/dist/v3.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _v = _interopRequireDefault(require_v35());
var _md = _interopRequireDefault(require_md5());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var v3 = (0, _v.default)("v3", 48, _md.default);
var _default = v3;
exports.default = _default;
}
});
// node_modules/uuid/dist/v4.js
var require_v4 = __commonJS({
"node_modules/uuid/dist/v4.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _rng = _interopRequireDefault(require_rng());
var _stringify = _interopRequireDefault(require_stringify());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function v4(options, buf, offset) {
options = options || {};
const rnds = options.random || (options.rng || _rng.default)();
rnds[6] = rnds[6] & 15 | 64;
rnds[8] = rnds[8] & 63 | 128;
if (buf) {
offset = offset || 0;
for (let i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return (0, _stringify.default)(rnds);
}
var _default = v4;
exports.default = _default;
}
});
// node_modules/uuid/dist/sha1.js
var require_sha1 = __commonJS({
"node_modules/uuid/dist/sha1.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _crypto = _interopRequireDefault(require("crypto"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function sha1(bytes) {
if (Array.isArray(bytes)) {
bytes = Buffer.from(bytes);
} else if (typeof bytes === "string") {
bytes = Buffer.from(bytes, "utf8");
}
return _crypto.default.createHash("sha1").update(bytes).digest();
}
var _default = sha1;
exports.default = _default;
}
});
// node_modules/uuid/dist/v5.js
var require_v5 = __commonJS({
"node_modules/uuid/dist/v5.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _v = _interopRequireDefault(require_v35());
var _sha = _interopRequireDefault(require_sha1());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var v5 = (0, _v.default)("v5", 80, _sha.default);
var _default = v5;
exports.default = _default;
}
});
// node_modules/uuid/dist/nil.js
var require_nil = __commonJS({
"node_modules/uuid/dist/nil.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _default = "00000000-0000-0000-0000-000000000000";
exports.default = _default;
}
});
// node_modules/uuid/dist/version.js
var require_version = __commonJS({
"node_modules/uuid/dist/version.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _validate = _interopRequireDefault(require_validate());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function version(uuid) {
if (!(0, _validate.default)(uuid)) {
throw TypeError("Invalid UUID");
}
return parseInt(uuid.substr(14, 1), 16);
}
var _default = version;
exports.default = _default;
}
});
// node_modules/uuid/dist/index.js
var require_dist = __commonJS({
"node_modules/uuid/dist/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "v1", {
enumerable: true,
get: function() {
return _v.default;
}
});
Object.defineProperty(exports, "v3", {
enumerable: true,
get: function() {
return _v2.default;
}
});
Object.defineProperty(exports, "v4", {
enumerable: true,
get: function() {
return _v3.default;
}
});
Object.defineProperty(exports, "v5", {
enumerable: true,
get: function() {
return _v4.default;
}
});
Object.defineProperty(exports, "NIL", {
enumerable: true,
get: function() {
return _nil.default;
}
});
Object.defineProperty(exports, "version", {
enumerable: true,
get: function() {
return _version.default;
}
});
Object.defineProperty(exports, "validate", {
enumerable: true,
get: function() {
return _validate.default;
}
});
Object.defineProperty(exports, "stringify", {
enumerable: true,
get: function() {
return _stringify.default;
}
});
Object.defineProperty(exports, "parse", {
enumerable: true,
get: function() {
return _parse.default;
}
});
var _v = _interopRequireDefault(require_v1());
var _v2 = _interopRequireDefault(require_v3());
var _v3 = _interopRequireDefault(require_v4());
var _v4 = _interopRequireDefault(require_v5());
var _nil = _interopRequireDefault(require_nil());
var _version = _interopRequireDefault(require_version());
var _validate = _interopRequireDefault(require_validate());
var _stringify = _interopRequireDefault(require_stringify());
var _parse = _interopRequireDefault(require_parse());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
}
});
3 years ago
// node_modules/@actions/core/lib/file-command.js
var require_file_command = __commonJS({
"node_modules/@actions/core/lib/file-command.js"(exports) {
"use strict";
var __createBinding = exports && exports.__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 __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports && exports.__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))
__createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareKeyValueMessage = exports.issueFileCommand = void 0;
3 years ago
var fs = __importStar(require("fs"));
var os = __importStar(require("os"));
var uuid_1 = require_dist();
3 years ago
var utils_1 = require_utils();
function issueFileCommand(command, message) {
3 years ago
const filePath = process.env[`GITHUB_${command}`];
if (!filePath) {
throw new Error(`Unable to find environment variable for file command ${command}`);
}
if (!fs.existsSync(filePath)) {
throw new Error(`Missing file at path: ${filePath}`);
}
fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, {
encoding: "utf8"
});
}
exports.issueFileCommand = issueFileCommand;
function prepareKeyValueMessage(key, value) {
const delimiter = `ghadelimiter_${uuid_1.v4()}`;
const convertedValue = utils_1.toCommandValue(value);
if (key.includes(delimiter)) {
throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`);
}
if (convertedValue.includes(delimiter)) {
throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`);
}
return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`;
}
exports.prepareKeyValueMessage = prepareKeyValueMessage;
3 years ago
}
});
// node_modules/@actions/http-client/lib/proxy.js
3 years ago
var require_proxy = __commonJS({
"node_modules/@actions/http-client/lib/proxy.js"(exports) {
3 years ago
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkBypass = exports.getProxyUrl = void 0;
3 years ago
function getProxyUrl(reqUrl) {
const usingSsl = reqUrl.protocol === "https:";
3 years ago
if (checkBypass(reqUrl)) {
return void 0;
3 years ago
}
const proxyVar = (() => {
if (usingSsl) {
return process.env["https_proxy"] || process.env["HTTPS_PROXY"];
} else {
return process.env["http_proxy"] || process.env["HTTP_PROXY"];
}
})();
3 years ago
if (proxyVar) {
return new URL(proxyVar);
} else {
return void 0;
3 years ago
}
}
exports.getProxyUrl = getProxyUrl;
function checkBypass(reqUrl) {
if (!reqUrl.hostname) {
return false;
}
const noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || "";
3 years ago
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()];
3 years ago
if (typeof reqPort === "number") {
upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
}
for (const upperNoProxyItem of noProxy.split(",").map((x) => x.trim().toUpperCase()).filter((x) => x)) {
3 years ago
if (upperReqHosts.some((x) => x === upperNoProxyItem)) {
return true;
}
}
return false;
}
exports.checkBypass = checkBypass;
}
});
// node_modules/tunnel/lib/tunnel.js
var require_tunnel = __commonJS({
"node_modules/tunnel/lib/tunnel.js"(exports) {
"use strict";
var net = require("net");
var tls = require("tls");
var http = require("http");
var https = require("https");
var events = require("events");
var assert = require("assert");
var util = require("util");
exports.httpOverHttp = httpOverHttp;
exports.httpsOverHttp = httpsOverHttp;
exports.httpOverHttps = httpOverHttps;
exports.httpsOverHttps = httpsOverHttps;
function httpOverHttp(options) {
var agent = new TunnelingAgent(options);
agent.request = http.request;
return agent;
}
function httpsOverHttp(options) {
var agent = new TunnelingAgent(options);
agent.request = http.request;
agent.createSocket = createSecureSocket;
agent.defaultPort = 443;
return agent;
}
function httpOverHttps(options) {
var agent = new TunnelingAgent(options);
agent.request = https.request;
return agent;
}
function httpsOverHttps(options) {
var agent = new TunnelingAgent(options);
agent.request = https.request;
agent.createSocket = createSecureSocket;
agent.defaultPort = 443;
return agent;
}
function TunnelingAgent(options) {
var self = this;
self.options = options || {};
self.proxyOptions = self.options.proxy || {};
self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;
self.requests = [];
self.sockets = [];
self.on("free", function onFree(socket, host, port, localAddress) {
var options2 = toOptions(host, port, localAddress);
for (var i = 0, len = self.requests.length; i < len; ++i) {
var pending = self.requests[i];
if (pending.host === options2.host && pending.port === options2.port) {
self.requests.splice(i, 1);
pending.request.onSocket(socket);
return;
}
}
socket.destroy();
self.removeSocket(socket);
});
}
util.inherits(TunnelingAgent, events.EventEmitter);
TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {
var self = this;
var options = mergeOptions({ request: req }, self.options, toOptions(host, port, localAddress));
if (self.sockets.length >= this.maxSockets) {
self.requests.push(options);
return;
}
self.createSocket(options, function(socket) {
socket.on("free", onFree);
socket.on("close", onCloseOrRemove);
socket.on("agentRemove", onCloseOrRemove);
req.onSocket(socket);
function onFree() {
self.emit("free", socket, options);
}
function onCloseOrRemove(err) {
self.removeSocket(socket);
socket.removeListener("free", onFree);
socket.removeListener("close", onCloseOrRemove);
socket.removeListener("agentRemove", onCloseOrRemove);
}
});
};
TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
var self = this;
var placeholder = {};
self.sockets.push(placeholder);
var connectOptions = mergeOptions({}, self.proxyOptions, {
method: "CONNECT",
path: options.host + ":" + options.port,
agent: false,
headers: {
host: options.host + ":" + options.port
}
});
if (options.localAddress) {
connectOptions.localAddress = options.localAddress;
}
if (connectOptions.proxyAuth) {
connectOptions.headers = connectOptions.headers || {};
connectOptions.headers["Proxy-Authorization"] = "Basic " + new Buffer(connectOptions.proxyAuth).toString("base64");
}
debug("making CONNECT request");
var connectReq = self.request(connectOptions);
connectReq.useChunkedEncodingByDefault = false;
connectReq.once("response", onResponse);
connectReq.once("upgrade", onUpgrade);
connectReq.once("connect", onConnect);
connectReq.once("error", onError);
connectReq.end();
function onResponse(res) {
res.upgrade = true;
}
function onUpgrade(res, socket, head) {
process.nextTick(function() {
onConnect(res, socket, head);
});
}
function onConnect(res, socket, head) {
connectReq.removeAllListeners();
socket.removeAllListeners();
if (res.statusCode !== 200) {
debug(
"tunneling socket could not be established, statusCode=%d",
res.statusCode
);
3 years ago
socket.destroy();
var error = new Error("tunneling socket could not be established, statusCode=" + res.statusCode);
error.code = "ECONNRESET";
options.request.emit("error", error);
self.removeSocket(placeholder);
return;
}
if (head.length > 0) {
debug("got illegal response body from proxy");
socket.destroy();
var error = new Error("got illegal response body from proxy");
error.code = "ECONNRESET";
options.request.emit("error", error);
self.removeSocket(placeholder);
return;
}
debug("tunneling connection has established");
self.sockets[self.sockets.indexOf(placeholder)] = socket;
return cb(socket);
}
function onError(cause) {
connectReq.removeAllListeners();
debug(
"tunneling socket could not be established, cause=%s\n",
cause.message,
cause.stack
);
3 years ago
var error = new Error("tunneling socket could not be established, cause=" + cause.message);
error.code = "ECONNRESET";
options.request.emit("error", error);
self.removeSocket(placeholder);
}
};
TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
var pos = this.sockets.indexOf(socket);
if (pos === -1) {
return;
}
this.sockets.splice(pos, 1);
var pending = this.requests.shift();
if (pending) {
this.createSocket(pending, function(socket2) {
pending.request.onSocket(socket2);
});
}
};
function createSecureSocket(options, cb) {
var self = this;
TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
var hostHeader = options.request.getHeader("host");
var tlsOptions = mergeOptions({}, self.options, {
socket,
servername: hostHeader ? hostHeader.replace(/:.*$/, "") : options.host
});
var secureSocket = tls.connect(0, tlsOptions);
self.sockets[self.sockets.indexOf(socket)] = secureSocket;
cb(secureSocket);
});
}
function toOptions(host, port, localAddress) {
if (typeof host === "string") {
return {
host,
port,
localAddress
};
}
return host;
}
function mergeOptions(target) {
for (var i = 1, len = arguments.length; i < len; ++i) {
var overrides = arguments[i];
if (typeof overrides === "object") {
var keys = Object.keys(overrides);
for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
var k = keys[j];
if (overrides[k] !== void 0) {
target[k] = overrides[k];
}
}
}
}
return target;
}
var debug;
if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
debug = function() {
var args = Array.prototype.slice.call(arguments);
if (typeof args[0] === "string") {
args[0] = "TUNNEL: " + args[0];
} else {
args.unshift("TUNNEL:");
}
console.error.apply(console, args);
};
} else {
debug = function() {
};
}
exports.debug = debug;
}
});
// node_modules/tunnel/index.js
var require_tunnel2 = __commonJS({
"node_modules/tunnel/index.js"(exports, module2) {
module2.exports = require_tunnel();
}
});
// node_modules/@actions/http-client/lib/index.js
var require_lib = __commonJS({
"node_modules/@actions/http-client/lib/index.js"(exports) {
3 years ago
"use strict";
var __createBinding = exports && exports.__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 __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports && exports.__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))
__createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function(resolve, 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 ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
3 years ago
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0;
var http = __importStar(require("http"));
var https = __importStar(require("https"));
var pm = __importStar(require_proxy());
var tunnel = __importStar(require_tunnel2());
3 years ago
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 = exports.HttpCodes || (exports.HttpCodes = {}));
var Headers;
(function(Headers2) {
Headers2["Accept"] = "accept";
Headers2["ContentType"] = "content-type";
})(Headers = exports.Headers || (exports.Headers = {}));
var MediaTypes;
(function(MediaTypes2) {
MediaTypes2["ApplicationJson"] = "application/json";
})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {}));
function getProxyUrl(serverUrl) {
const proxyUrl = pm.getProxyUrl(new URL(serverUrl));
3 years ago
return proxyUrl ? proxyUrl.href : "";
}
exports.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 extends Error {
constructor(message, statusCode) {
super(message);
this.name = "HttpClientError";
this.statusCode = statusCode;
Object.setPrototypeOf(this, HttpClientError.prototype);
}
};
exports.HttpClientError = HttpClientError;
var HttpClientResponse = class {
constructor(message) {
this.message = message;
}
readBody() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve) => __awaiter(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", () => {
resolve(output.toString());
});
}));
3 years ago
});
}
};
exports.HttpClientResponse = HttpClientResponse;
function isHttps(requestUrl) {
const parsedUrl = new URL(requestUrl);
3 years ago
return parsedUrl.protocol === "https:";
}
exports.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;
}
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 __awaiter(this, void 0, void 0, function* () {
return this.request("OPTIONS", requestUrl, null, additionalHeaders || {});
});
3 years ago
}
get(requestUrl, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
return this.request("GET", requestUrl, null, additionalHeaders || {});
});
3 years ago
}
del(requestUrl, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
return this.request("DELETE", requestUrl, null, additionalHeaders || {});
});
3 years ago
}
post(requestUrl, data, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
return this.request("POST", requestUrl, data, additionalHeaders || {});
});
3 years ago
}
patch(requestUrl, data, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
return this.request("PATCH", requestUrl, data, additionalHeaders || {});
});
3 years ago
}
put(requestUrl, data, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
return this.request("PUT", requestUrl, data, additionalHeaders || {});
});
3 years ago
}
head(requestUrl, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
return this.request("HEAD", requestUrl, null, additionalHeaders || {});
});
3 years ago
}
sendStream(verb, requestUrl, stream, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
return this.request(verb, requestUrl, stream, additionalHeaders);
});
}
getJson(requestUrl, additionalHeaders = {}) {
return __awaiter(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 __awaiter(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 __awaiter(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 __awaiter(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);
});
}
request(verb, requestUrl, data, headers) {
return __awaiter(this, void 0, void 0, function* () {
if (this._disposed) {
throw new Error("Client has already been disposed.");
}
const parsedUrl = new URL(requestUrl);
let info = 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(info, 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, info, 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) {
3 years ago
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];
}
}
}
info = this._prepareRequest(verb, parsedRedirectUrl, headers);
response = yield this.requestRaw(info, data);
redirectsRemaining--;
3 years ago
}
if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) {
3 years ago
return response;
}
numTries += 1;
if (numTries < maxTries) {
yield response.readBody();
yield this._performExponentialBackoff(numTries);
3 years ago
}
} while (numTries < maxTries);
return response;
});
3 years ago
}
dispose() {
if (this._agent) {
this._agent.destroy();
}
this._disposed = true;
}
requestRaw(info, data) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
function callbackForResult(err, res) {
if (err) {
reject(err);
} else if (!res) {
reject(new Error("Unknown error"));
} else {
resolve(res);
}
3 years ago
}
this.requestRawWithCallback(info, data, callbackForResult);
});
3 years ago
});
}
requestRawWithCallback(info, data, onResult) {
if (typeof data === "string") {
if (!info.options.headers) {
info.options.headers = {};
}
3 years ago
info.options.headers["Content-Length"] = Buffer.byteLength(data, "utf8");
}
let callbackCalled = false;
function handleResult(err, res) {
3 years ago
if (!callbackCalled) {
callbackCalled = true;
onResult(err, res);
}
}
const req = info.httpModule.request(info.options, (msg) => {
const res = new HttpClientResponse(msg);
handleResult(void 0, res);
3 years ago
});
let socket;
3 years ago
req.on("socket", (sock) => {
socket = sock;
});
req.setTimeout(this._socketTimeout || 3 * 6e4, () => {
if (socket) {
socket.end();
}
handleResult(new Error(`Request timeout: ${info.options.path}`));
3 years ago
});
req.on("error", function(err) {
handleResult(err);
3 years ago
});
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();
}
}
getAgent(serverUrl) {
const parsedUrl = new URL(serverUrl);
3 years ago
return this._getAgent(parsedUrl);
}
_prepareRequest(method, requestUrl, headers) {
const info = {};
info.parsedUrl = requestUrl;
const usingSsl = info.parsedUrl.protocol === "https:";
info.httpModule = usingSsl ? https : http;
const defaultPort = usingSsl ? 443 : 80;
info.options = {};
info.options.host = info.parsedUrl.hostname;
info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort;
info.options.path = (info.parsedUrl.pathname || "") + (info.parsedUrl.search || "");
info.options.method = method;
info.options.headers = this._mergeHeaders(headers);
if (this.userAgent != null) {
info.options.headers["user-agent"] = this.userAgent;
}
info.options.agent = this._getAgent(info.parsedUrl);
if (this.handlers) {
for (const handler of this.handlers) {
3 years ago
handler.prepareRequest(info.options);
}
3 years ago
}
return info;
}
_mergeHeaders(headers) {
if (this.requestOptions && this.requestOptions.headers) {
return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));
3 years ago
}
return lowercaseKeys(headers || {});
}
_getExistingOrDefaultHeader(additionalHeaders, header, _default) {
let clientHeader;
if (this.requestOptions && this.requestOptions.headers) {
clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
}
return additionalHeaders[header] || clientHeader || _default;
}
_getAgent(parsedUrl) {
let agent;
const proxyUrl = pm.getProxyUrl(parsedUrl);
const useProxy = proxyUrl && proxyUrl.hostname;
3 years ago
if (this._keepAlive && useProxy) {
agent = this._proxyAgent;
}
if (this._keepAlive && !useProxy) {
agent = this._agent;
}
if (agent) {
3 years ago
return agent;
}
const usingSsl = parsedUrl.protocol === "https:";
let maxSockets = 100;
if (this.requestOptions) {
3 years ago
maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
}
if (proxyUrl && proxyUrl.hostname) {
3 years ago
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 })
3 years ago
};
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 (this._keepAlive && !agent) {
const options = { keepAlive: this._keepAlive, maxSockets };
agent = usingSsl ? new https.Agent(options) : new http.Agent(options);
this._agent = agent;
}
if (!agent) {
agent = usingSsl ? https.globalAgent : http.globalAgent;
}
if (usingSsl && this._ignoreSslError) {
agent.options = Object.assign(agent.options || {}, {
rejectUnauthorized: false
});
}
return agent;
}
_performExponentialBackoff(retryNumber) {
return __awaiter(this, void 0, void 0, function* () {
retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
return new Promise((resolve) => setTimeout(() => resolve(), ms));
});
3 years ago
}
_processResponse(res, options) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
const statusCode = res.message.statusCode || 0;
const response = {
statusCode,
result: null,
headers: {}
};
if (statusCode === HttpCodes.NotFound) {
resolve(response);
}
function dateTimeDeserializer(key, value) {
if (typeof value === "string") {
const a = new Date(value);
if (!isNaN(a.valueOf())) {
return a;
}
3 years ago
}
return value;
3 years ago
}
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);
3 years ago
} else {
resolve(response);
3 years ago
}
}));
3 years ago
});
}
};
exports.HttpClient = HttpClient;
var lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {});
3 years ago
}
});
// node_modules/@actions/http-client/lib/auth.js
3 years ago
var require_auth = __commonJS({
"node_modules/@actions/http-client/lib/auth.js"(exports) {
3 years ago
"use strict";
var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function(resolve, 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 ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
3 years ago
Object.defineProperty(exports, "__esModule", { value: true });
exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0;
3 years ago
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")}`;
3 years ago
}
canHandleAuthentication() {
3 years ago
return false;
}
handleAuthentication() {
return __awaiter(this, void 0, void 0, function* () {
throw new Error("not implemented");
});
3 years ago
}
};
exports.BasicCredentialHandler = BasicCredentialHandler;
var BearerCredentialHandler = class {
constructor(token) {
this.token = token;
}
prepareRequest(options) {
if (!options.headers) {
throw Error("The request has no headers");
}
options.headers["Authorization"] = `Bearer ${this.token}`;
3 years ago
}
canHandleAuthentication() {
3 years ago
return false;
}
handleAuthentication() {
return __awaiter(this, void 0, void 0, function* () {
throw new Error("not implemented");
});
3 years ago
}
};
exports.BearerCredentialHandler = BearerCredentialHandler;
var PersonalAccessTokenCredentialHandler = class {
constructor(token) {
this.token = token;
}
prepareRequest(options) {
if (!options.headers) {
throw Error("The request has no headers");
}
options.headers["Authorization"] = `Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`;
3 years ago
}
canHandleAuthentication() {
3 years ago
return false;
}
handleAuthentication() {
return __awaiter(this, void 0, void 0, function* () {
throw new Error("not implemented");
});
3 years ago
}
};
exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;
}
});
// node_modules/@actions/core/lib/oidc-utils.js
var require_oidc_utils = __commonJS({
"node_modules/@actions/core/lib/oidc-utils.js"(exports) {
"use strict";
var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function(resolve, 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 ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OidcClient = void 0;
var http_client_1 = require_lib();
3 years ago
var auth_1 = require_auth();
var core_1 = require_core();
var OidcClient = class {
static createHttpClient(allowRetry = true, maxRetry = 10) {
const requestOptions = {
allowRetries: allowRetry,
maxRetries: maxRetry
};
return new http_client_1.HttpClient("actions/oidc-client", [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions);
}
static getRequestToken() {
const token = process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"];
if (!token) {
throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable");
}
return token;
}
static getIDTokenUrl() {
const runtimeUrl = process.env["ACTIONS_ID_TOKEN_REQUEST_URL"];
if (!runtimeUrl) {
throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable");
}
return runtimeUrl;
}
static getCall(id_token_url) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const httpclient = OidcClient.createHttpClient();
const res = yield httpclient.getJson(id_token_url).catch((error) => {
throw new Error(`Failed to get ID Token.
Error Code : ${error.statusCode}
Error Message: ${error.result.message}`);
});
const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value;
if (!id_token) {
throw new Error("Response json body do not have ID Token field");
}
return id_token;
});
}
static getIDToken(audience) {
return __awaiter(this, void 0, void 0, function* () {
try {
let id_token_url = OidcClient.getIDTokenUrl();
if (audience) {
const encodedAudience = encodeURIComponent(audience);
id_token_url = `${id_token_url}&audience=${encodedAudience}`;
}
core_1.debug(`ID token url is ${id_token_url}`);
const id_token = yield OidcClient.getCall(id_token_url);
core_1.setSecret(id_token);
return id_token;
} catch (error) {
throw new Error(`Error message: ${error.message}`);
}
});
}
};
exports.OidcClient = OidcClient;
}
});
// node_modules/@actions/core/lib/summary.js
var require_summary = __commonJS({
"node_modules/@actions/core/lib/summary.js"(exports) {
"use strict";
var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function(resolve, 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 ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0;
var os_1 = require("os");
var fs_1 = require("fs");
var { access, appendFile, writeFile } = fs_1.promises;
exports.SUMMARY_ENV_VAR = "GITHUB_STEP_SUMMARY";
exports.SUMMARY_DOCS_URL = "https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary";
var Summary = class {
constructor() {
this._buffer = "";
}
filePath() {
return __awaiter(this, void 0, void 0, function* () {
if (this._filePath) {
return this._filePath;
}
const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR];
if (!pathFromEnv) {
throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`);
}
try {
yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK);
} catch (_a) {
throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`);
}
this._filePath = pathFromEnv;
return this._filePath;
});
}
wrap(tag2, content, attrs = {}) {
const htmlAttrs = Object.entries(attrs).map(([key, value]) => ` ${key}="${value}"`).join("");
if (!content) {
return `<${tag2}${htmlAttrs}>`;
}
return `<${tag2}${htmlAttrs}>${content}</${tag2}>`;
}
write(options) {
return __awaiter(this, void 0, void 0, function* () {
const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite);
const filePath = yield this.filePath();
const writeFunc = overwrite ? writeFile : appendFile;
yield writeFunc(filePath, this._buffer, { encoding: "utf8" });
return this.emptyBuffer();
});
}
clear() {
return __awaiter(this, void 0, void 0, function* () {
return this.emptyBuffer().write({ overwrite: true });
});
}
stringify() {
return this._buffer;
}
isEmptyBuffer() {
return this._buffer.length === 0;
}
emptyBuffer() {
this._buffer = "";
return this;
}
addRaw(text, addEOL = false) {
this._buffer += text;
return addEOL ? this.addEOL() : this;
}
addEOL() {
return this.addRaw(os_1.EOL);
}
addCodeBlock(code, lang) {
const attrs = Object.assign({}, lang && { lang });
const element = this.wrap("pre", this.wrap("code", code), attrs);
return this.addRaw(element).addEOL();
}
addList(items, ordered = false) {
const tag2 = ordered ? "ol" : "ul";
const listItems = items.map((item) => this.wrap("li", item)).join("");
const element = this.wrap(tag2, listItems);
return this.addRaw(element).addEOL();
}
addTable(rows) {
const tableBody = rows.map((row) => {
const cells = row.map((cell) => {
if (typeof cell === "string") {
return this.wrap("td", cell);
}
const { header, data, colspan, rowspan } = cell;
const tag2 = header ? "th" : "td";
const attrs = Object.assign(Object.assign({}, colspan && { colspan }), rowspan && { rowspan });
return this.wrap(tag2, data, attrs);
}).join("");
return this.wrap("tr", cells);
}).join("");
const element = this.wrap("table", tableBody);
return this.addRaw(element).addEOL();
}
addDetails(label, content) {
const element = this.wrap("details", this.wrap("summary", label) + content);
return this.addRaw(element).addEOL();
}
addImage(src, alt, options) {
const { width, height } = options || {};
const attrs = Object.assign(Object.assign({}, width && { width }), height && { height });
const element = this.wrap("img", null, Object.assign({ src, alt }, attrs));
return this.addRaw(element).addEOL();
}
addHeading(text, level) {
const tag2 = `h${level}`;
const allowedTag = ["h1", "h2", "h3", "h4", "h5", "h6"].includes(tag2) ? tag2 : "h1";
const element = this.wrap(allowedTag, text);
return this.addRaw(element).addEOL();
}
addSeparator() {
const element = this.wrap("hr", null);
return this.addRaw(element).addEOL();
}
addBreak() {
const element = this.wrap("br", null);
return this.addRaw(element).addEOL();
}
addQuote(text, cite) {
const attrs = Object.assign({}, cite && { cite });
const element = this.wrap("blockquote", text, attrs);
return this.addRaw(element).addEOL();
}
addLink(text, href) {
const element = this.wrap("a", text, { href });
return this.addRaw(element).addEOL();
}
};
var _summary = new Summary();
exports.markdownSummary = _summary;
exports.summary = _summary;
}
});
// node_modules/@actions/core/lib/path-utils.js
var require_path_utils = __commonJS({
"node_modules/@actions/core/lib/path-utils.js"(exports) {
"use strict";
var __createBinding = exports && exports.__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 __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports && exports.__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))
__createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0;
var path3 = __importStar(require("path"));
function toPosixPath(pth) {
return pth.replace(/[\\]/g, "/");
}
exports.toPosixPath = toPosixPath;
function toWin32Path(pth) {
return pth.replace(/[/]/g, "\\");
}
exports.toWin32Path = toWin32Path;
function toPlatformPath(pth) {
return pth.replace(/[/\\]/g, path3.sep);
}
exports.toPlatformPath = toPlatformPath;
}
});
3 years ago
// node_modules/@actions/core/lib/core.js
var require_core = __commonJS({
"node_modules/@actions/core/lib/core.js"(exports) {
"use strict";
var __createBinding = exports && exports.__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 __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports && exports.__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))
__createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function(resolve, 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 ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;
var command_1 = require_command();
var file_command_1 = require_file_command();
var utils_1 = require_utils();
var os = __importStar(require("os"));
var path3 = __importStar(require("path"));
3 years ago
var oidc_utils_1 = require_oidc_utils();
var ExitCode;
(function(ExitCode2) {
ExitCode2[ExitCode2["Success"] = 0] = "Success";
ExitCode2[ExitCode2["Failure"] = 1] = "Failure";
})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));
function exportVariable(name, val) {
const convertedVal = utils_1.toCommandValue(val);
process.env[name] = convertedVal;
const filePath = process.env["GITHUB_ENV"] || "";
if (filePath) {
return file_command_1.issueFileCommand("ENV", file_command_1.prepareKeyValueMessage(name, val));
3 years ago
}
command_1.issueCommand("set-env", { name }, convertedVal);
3 years ago
}
exports.exportVariable = exportVariable;
function setSecret(secret) {
command_1.issueCommand("add-mask", {}, secret);
}
exports.setSecret = setSecret;
function addPath(inputPath) {
const filePath = process.env["GITHUB_PATH"] || "";
if (filePath) {
file_command_1.issueFileCommand("PATH", inputPath);
3 years ago
} else {
command_1.issueCommand("add-path", {}, inputPath);
}
process.env["PATH"] = `${inputPath}${path3.delimiter}${process.env["PATH"]}`;
3 years ago
}
exports.addPath = addPath;
function getInput2(name, options) {
const val = process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] || "";
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
if (options && options.trimWhitespace === false) {
return val;
}
return val.trim();
}
exports.getInput = getInput2;
function getMultilineInput(name, options) {
const inputs = getInput2(name, options).split("\n").filter((x) => x !== "");
if (options && options.trimWhitespace === false) {
return inputs;
}
return inputs.map((input) => input.trim());
3 years ago
}
exports.getMultilineInput = getMultilineInput;
function getBooleanInput(name, options) {
const trueValue = ["true", "True", "TRUE"];
const falseValue = ["false", "False", "FALSE"];
const val = getInput2(name, options);
if (trueValue.includes(val))
return true;
if (falseValue.includes(val))
return false;
throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}
Support boolean input list: \`true | True | TRUE | false | False | FALSE\``);
}
exports.getBooleanInput = getBooleanInput;
function setOutput2(name, value) {
const filePath = process.env["GITHUB_OUTPUT"] || "";
if (filePath) {
return file_command_1.issueFileCommand("OUTPUT", file_command_1.prepareKeyValueMessage(name, value));
}
3 years ago
process.stdout.write(os.EOL);
command_1.issueCommand("set-output", { name }, utils_1.toCommandValue(value));
3 years ago
}
exports.setOutput = setOutput2;
function setCommandEcho(enabled) {
command_1.issue("echo", enabled ? "on" : "off");
}
exports.setCommandEcho = setCommandEcho;
function setFailed2(message) {
process.exitCode = ExitCode.Failure;
error(message);
}
exports.setFailed = setFailed2;
function isDebug() {
return process.env["RUNNER_DEBUG"] === "1";
}
exports.isDebug = isDebug;
function debug(message) {
command_1.issueCommand("debug", {}, message);
}
exports.debug = debug;
function error(message, properties = {}) {
command_1.issueCommand("error", utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
}
exports.error = error;
function warning(message, properties = {}) {
command_1.issueCommand("warning", utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
}
exports.warning = warning;
function notice(message, properties = {}) {
command_1.issueCommand("notice", utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
}
exports.notice = notice;
function info(message) {
process.stdout.write(message + os.EOL);
}
exports.info = info;
function startGroup(name) {
command_1.issue("group", name);
}
exports.startGroup = startGroup;
function endGroup() {
command_1.issue("endgroup");
}
exports.endGroup = endGroup;
function group(name, fn) {
return __awaiter(this, void 0, void 0, function* () {
startGroup(name);
let result;
try {
result = yield fn();
} finally {
endGroup();
}
return result;
});
}
exports.group = group;
function saveState(name, value) {
const filePath = process.env["GITHUB_STATE"] || "";
if (filePath) {
return file_command_1.issueFileCommand("STATE", file_command_1.prepareKeyValueMessage(name, value));
}
command_1.issueCommand("save-state", { name }, utils_1.toCommandValue(value));
3 years ago
}
exports.saveState = saveState;
function getState(name) {
return process.env[`STATE_${name}`] || "";
}
exports.getState = getState;
function getIDToken(aud) {
return __awaiter(this, void 0, void 0, function* () {
return yield oidc_utils_1.OidcClient.getIDToken(aud);
});
}
exports.getIDToken = getIDToken;
var summary_1 = require_summary();
Object.defineProperty(exports, "summary", { enumerable: true, get: function() {
return summary_1.summary;
} });
var summary_2 = require_summary();
Object.defineProperty(exports, "markdownSummary", { enumerable: true, get: function() {
return summary_2.markdownSummary;
} });
var path_utils_1 = require_path_utils();
Object.defineProperty(exports, "toPosixPath", { enumerable: true, get: function() {
return path_utils_1.toPosixPath;
} });
Object.defineProperty(exports, "toWin32Path", { enumerable: true, get: function() {
return path_utils_1.toWin32Path;
} });
Object.defineProperty(exports, "toPlatformPath", { enumerable: true, get: function() {
return path_utils_1.toPlatformPath;
} });
3 years ago
}
});
// node_modules/@actions/github/lib/context.js
var require_context = __commonJS({
"node_modules/@actions/github/lib/context.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Context = void 0;
var fs_1 = require("fs");
var os_1 = require("os");
var Context = class {
constructor() {
var _a, _b, _c;
this.payload = {};
if (process.env.GITHUB_EVENT_PATH) {
if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) {
this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: "utf8" }));
} else {
const path3 = process.env.GITHUB_EVENT_PATH;
process.stdout.write(`GITHUB_EVENT_PATH ${path3} does not exist${os_1.EOL}`);
3 years ago
}
}
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.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 };
}
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'");
}
};
exports.Context = Context;
}
});
// node_modules/@actions/github/lib/internal/utils.js
var require_utils2 = __commonJS({
"node_modules/@actions/github/lib/internal/utils.js"(exports) {
"use strict";
var __createBinding = exports && exports.__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 __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports && exports.__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))
__createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0;
var httpClient = __importStar(require_lib());
3 years ago
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}`;
}
exports.getAuthString = getAuthString;
function getProxyAgent(destinationUrl) {
const hc = new httpClient.HttpClient();
return hc.getAgent(destinationUrl);
}
exports.getProxyAgent = getProxyAgent;
function getApiBaseUrl() {
return process.env["GITHUB_API_URL"] || "https://api.github.com";
}
exports.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"(exports) {
"use strict";
Object.defineProperty(exports, "__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 "<environment undetectable>";
}
exports.getUserAgent = getUserAgent;
}
});
// node_modules/before-after-hook/lib/register.js
var require_register = __commonJS({
"node_modules/before-after-hook/lib/register.js"(exports, 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"(exports, 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(error) {
return orig(error, 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"(exports, 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"(exports, 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]
);
3 years ago
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'
);
3 years ago
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/is-plain-object/dist/is-plain-object.js
var require_is_plain_object = __commonJS({
"node_modules/is-plain-object/dist/is-plain-object.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function isObject(o) {
return Object.prototype.toString.call(o) === "[object Object]";
}
function isPlainObject(o) {
var ctor, prot;
if (isObject(o) === false)
return false;
ctor = o.constructor;
if (ctor === void 0)
return true;
prot = ctor.prototype;
if (isObject(prot) === false)
return false;
if (prot.hasOwnProperty("isPrototypeOf") === false) {
return false;
}
return true;
}
exports.isPlainObject = isPlainObject;
}
});
// node_modules/@octokit/endpoint/dist-node/index.js
var require_dist_node2 = __commonJS({
"node_modules/@octokit/endpoint/dist-node/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var isPlainObject = require_is_plain_object();
var universalUserAgent = require_dist_node();
function lowercaseKeys(object) {
if (!object) {
return {};
}
return Object.keys(object).reduce((newObj, key) => {
newObj[key.toLowerCase()] = object[key];
return newObj;
}, {});
}
function mergeDeep(defaults, options) {
const result = Object.assign({}, defaults);
Object.keys(options).forEach((key) => {
if (isPlainObject.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 merge(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 (defaults && defaults.mediaType.previews.length) {
mergedOptions.mediaType.previews = defaults.mediaType.previews.filter((preview) => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews);
}
mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map((preview) => preview.replace(/-preview/, ""));
return mergedOptions;
}
function addQueryParameters(url, parameters) {
const separator = /\?/.test(url) ? "&" : "?";
const names = Object.keys(parameters);
if (names.length === 0) {
return url;
}
return url + separator + names.map((name) => {
if (name === "q") {
return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
}
return `${name}=${encodeURIComponent(parameters[name])}`;
}).join("&");
}
var urlVariableRegex = /\{[^}]+\}/g;
function removeNonChars(variableName) {
return variableName.replace(/^\W+|\W+$/g, "").split(/,/);
}
function extractUrlVariableNames(url) {
const matches = url.match(urlVariableRegex);
if (!matches) {
return [];
}
return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
}
function omit(object, keysToOmit) {
return Object.keys(object).filter((option) => !keysToOmit.includes(option)).reduce((obj, key) => {
obj[key] = object[key];
return obj;
}, {});
}
function encodeReserved(str) {
return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {
if (!/%[0-9A-Fa-f]/.test(part)) {
part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
}
return part;
}).join("");
}
function encodeUnreserved(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return "%" + c.charCodeAt(0).toString(16).toUpperCase();
});
}
function encodeValue(operator, value, key) {
value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
if (key) {
return encodeUnreserved(key) + "=" + value;
} else {
return value;
}
}
function isDefined(value) {
return value !== void 0 && value !== null;
}
function isKeyOperator(operator) {
return operator === ";" || operator === "&" || operator === "?";
}
function getValues(context2, operator, key, modifier) {
var value = context2[key], result = [];
if (isDefined(value) && value !== "") {
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
value = value.toString();
if (modifier && modifier !== "*") {
value = value.substring(0, parseInt(modifier, 10));
}
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
} else {
if (modifier === "*") {
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function(value2) {
result.push(encodeValue(operator, value2, isKeyOperator(operator) ? key : ""));
});
} else {
Object.keys(value).forEach(function(k) {
if (isDefined(value[k])) {
result.push(encodeValue(operator, value[k], k));
}
});
}
} else {
const tmp = [];
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function(value2) {
tmp.push(encodeValue(operator, value2));
});
} else {
Object.keys(value).forEach(function(k) {
if (isDefined(value[k])) {
tmp.push(encodeUnreserved(k));
tmp.push(encodeValue(operator, value[k].toString()));
}
});
}
if (isKeyOperator(operator)) {
result.push(encodeUnreserved(key) + "=" + tmp.join(","));
} else if (tmp.length !== 0) {
result.push(tmp.join(","));
}
}
}
} else {
if (operator === ";") {
if (isDefined(value)) {
result.push(encodeUnreserved(key));
}
} else if (value === "" && (operator === "&" || operator === "?")) {
result.push(encodeUnreserved(key) + "=");
} else if (value === "") {
result.push("");
}
}
return result;
}
function parseUrl(template) {
return {
expand: expand.bind(null, template)
};
}
function expand(template, context2) {
var operators = ["+", "#", ".", "/", ";", "?", "&"];
return 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);
}
});
}
function parse2(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((preview) => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(",");
}
if (options.mediaType.previews.length) {
const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || [];
headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => {
const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
return `application/vnd.github.${preview}-preview${format}`;
}).join(",");
}
}
if (["GET", "HEAD"].includes(method)) {
url = addQueryParameters(url, remainingParameters);
} else {
if ("data" in remainingParameters) {
body = remainingParameters.data;
} else {
if (Object.keys(remainingParameters).length) {
body = remainingParameters;
} else {
headers["content-length"] = 0;
}
}
}
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 parse2(merge(defaults, route, options));
}
function withDefaults(oldDefaults, newDefaults) {
const DEFAULTS2 = merge(oldDefaults, newDefaults);
const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2);
return Object.assign(endpoint2, {
DEFAULTS: DEFAULTS2,
defaults: withDefaults.bind(null, DEFAULTS2),
merge: merge.bind(null, DEFAULTS2),
parse: parse2
});
}
var VERSION = "6.0.12";
var userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`;
var DEFAULTS = {
method: "GET",
baseUrl: "https://api.github.com",
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": userAgent
},
mediaType: {
format: "",
previews: []
}
};
var endpoint = withDefaults(null, DEFAULTS);
exports.endpoint = endpoint;
}
});
// node_modules/webidl-conversions/lib/index.js
var require_lib2 = __commonJS({
3 years ago
"node_modules/webidl-conversions/lib/index.js"(exports, module2) {
"use strict";
var conversions = {};
module2.exports = conversions;
function sign(x) {
return x < 0 ? -1 : 1;
}
function evenRound(x) {
if (x % 1 === 0.5 && (x & 1) === 0) {
return Math.floor(x);
} else {
return Math.round(x);
}
}
function createNumberConversion(bitLength, typeOpts) {
if (!typeOpts.unsigned) {
--bitLength;
}
const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength);
const upperBound = Math.pow(2, bitLength) - 1;
const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength);
const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1);
return function(V, opts) {
if (!opts)
opts = {};
let x = +V;
if (opts.enforceRange) {
if (!Number.isFinite(x)) {
throw new TypeError("Argument is not a finite number");
}
x = sign(x) * Math.floor(Math.abs(x));
if (x < lowerBound || x > upperBound) {
throw new TypeError("Argument is not in byte range");
}
return x;
}
if (!isNaN(x) && opts.clamp) {
x = evenRound(x);
if (x < lowerBound)
x = lowerBound;
if (x > upperBound)
x = upperBound;
return x;
}
if (!Number.isFinite(x) || x === 0) {
return 0;
}
x = sign(x) * Math.floor(Math.abs(x));
x = x % moduloVal;
if (!typeOpts.unsigned && x >= moduloBound) {
return x - moduloVal;
} else if (typeOpts.unsigned) {
if (x < 0) {
x += moduloVal;
} else if (x === -0) {
return 0;
}
}
return x;
};
}
conversions["void"] = function() {
return void 0;
};
conversions["boolean"] = function(val) {
return !!val;
};
conversions["byte"] = createNumberConversion(8, { unsigned: false });
conversions["octet"] = createNumberConversion(8, { unsigned: true });
conversions["short"] = createNumberConversion(16, { unsigned: false });
conversions["unsigned short"] = createNumberConversion(16, { unsigned: true });
conversions["long"] = createNumberConversion(32, { unsigned: false });
conversions["unsigned long"] = createNumberConversion(32, { unsigned: true });
conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 });
conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 });
conversions["double"] = function(V) {
const x = +V;
if (!Number.isFinite(x)) {
throw new TypeError("Argument is not a finite floating-point value");
}
return x;
};
conversions["unrestricted double"] = function(V) {
const x = +V;
if (isNaN(x)) {
throw new TypeError("Argument is NaN");
}
return x;
};
conversions["float"] = conversions["double"];
conversions["unrestricted float"] = conversions["unrestricted double"];
conversions["DOMString"] = function(V, opts) {
if (!opts)
opts = {};
if (opts.treatNullAsEmptyString && V === null) {
return "";
}
return String(V);
};
conversions["ByteString"] = function(V, opts) {
const x = String(V);
let c = void 0;
for (let i = 0; (c = x.codePointAt(i)) !== void 0; ++i) {
if (c > 255) {
throw new TypeError("Argument is not a valid bytestring");
}
}
return x;
};
conversions["USVString"] = function(V) {
const S = String(V);
const n = S.length;
const U = [];
for (let i = 0; i < n; ++i) {
const c = S.charCodeAt(i);
if (c < 55296 || c > 57343) {
U.push(String.fromCodePoint(c));
} else if (56320 <= c && c <= 57343) {
U.push(String.fromCodePoint(65533));
} else {
if (i === n - 1) {
U.push(String.fromCodePoint(65533));
} else {
const d = S.charCodeAt(i + 1);
if (56320 <= d && d <= 57343) {
const a = c & 1023;
const b = d & 1023;
U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b));
++i;
} else {
U.push(String.fromCodePoint(65533));
}
}
}
}
return U.join("");
};
conversions["Date"] = function(V, opts) {
if (!(V instanceof Date)) {
throw new TypeError("Argument is not a Date object");
}
if (isNaN(V)) {
return void 0;
}
return V;
};
conversions["RegExp"] = function(V, opts) {
if (!(V instanceof RegExp)) {
V = new RegExp(V);
}
return V;
};
}
});
// node_modules/whatwg-url/lib/utils.js
var require_utils3 = __commonJS({
"node_modules/whatwg-url/lib/utils.js"(exports, module2) {
"use strict";
module2.exports.mixin = function mixin(target, source) {
const keys = Object.getOwnPropertyNames(source);
for (let i = 0; i < keys.length; ++i) {
Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i]));
}
};
module2.exports.wrapperSymbol = Symbol("wrapper");
module2.exports.implSymbol = Symbol("impl");
module2.exports.wrapperForImpl = function(impl) {
return impl[module2.exports.wrapperSymbol];
};
module2.exports.implForWrapper = function(wrapper) {
return wrapper[module2.exports.implSymbol];
};
}
});
// node_modules/tr46/lib/mappingTable.json
var require_mappingTable = __commonJS({
"node_modules/tr46/lib/mappingTable.json"(exports, module2) {
module2.exports = [[[0, 44], "disallowed_STD3_valid"], [[45, 46], "valid"], [[47, 47], "disallowed_STD3_valid"], [[48, 57], "valid"], [[58, 64], "disallowed_STD3_valid"], [[65, 65], "mapped", [97]], [[66, 66], "mapped", [98]], [[67, 67], "mapped", [99]], [[68, 68], "mapped", [100]], [[69, 69], "mapped", [101]], [[70, 70], "mapped", [102]], [[71, 71], "mapped", [103]], [[72, 72], "mapped", [104]], [[73, 73], "mapped", [105]], [[74, 74], "mapped", [106]], [[75, 75], "mapped", [107]], [[76, 76], "mapped", [108]], [[77, 77], "mapped", [109]], [[78, 78], "mapped", [110]], [[79, 79], "mapped", [111]], [[80, 80], "mapped", [112]], [[81, 81], "mapped", [113]], [[82, 82], "mapped", [114]], [[83, 83], "mapped", [115]], [[84, 84], "mapped", [116]], [[85, 85], "mapped", [117]], [[86, 86], "mapped", [118]], [[87, 87], "mapped", [119]], [[88, 88], "mapped", [120]], [[89, 89], "mapped", [121]], [[90, 90], "mapped", [122]], [[91, 96], "disallowed_STD3_valid"], [[97, 122], "valid"], [[123, 127], "disallowed_STD3_valid"], [[128, 159], "disallowed"], [[160, 160], "disallowed_STD3_mapped", [32]], [[161, 167], "valid", [], "NV8"], [[168, 168], "disallowed_STD3_mapped", [32, 776]], [[169, 169], "valid", [], "NV8"], [[170, 170], "mapped", [97]], [[171, 172], "valid", [], "NV8"], [[173, 173], "ignored"], [[174, 174], "valid", [], "NV8"], [[175, 175], "disallowed_STD3_mapped", [32, 772]], [[176, 177], "valid", [], "NV8"], [[178, 178], "mapped", [50]], [[179, 179], "mapped", [51]], [[180, 180], "disallowed_STD3_mapped", [32, 769]], [[181, 181], "mapped", [956]], [[182, 182], "valid", [], "NV8"], [[183, 183], "valid"], [[184, 184], "disallowed_STD3_mapped", [32, 807]], [[185, 185], "mapped", [49]], [[186, 186], "mapped", [111]], [[187, 187], "valid", [], "NV8"], [[188, 188], "mapped", [49, 8260, 52]], [[189, 189], "mapped", [49, 8260, 50]], [[190, 190], "mapped", [51, 8260, 52]], [[191, 191], "valid", [], "NV8"], [[192, 192], "mapped", [224]], [[193, 193], "mapped", [225]], [[194, 194], "mapped", [226]], [[195, 195], "mapped", [227]], [[196, 196], "mapped", [228]], [[197, 197], "mapped", [229]], [[198, 198], "mapped", [230]], [[199, 199], "mapped", [231]], [[200, 200], "mapped", [232]], [[201, 201], "mapped", [233]], [[202, 202], "mapped", [234]], [[203, 203], "mapped", [235]], [[204, 204], "mapped", [236]], [[205, 205], "mapped", [237]], [[206, 206], "mapped", [238]], [[207, 207], "mapped", [239]], [[208, 208], "mapped", [240]], [[209, 209], "mapped", [241]], [[210, 210], "mapped", [242]], [[211, 211], "mapped", [243]], [[212, 212], "mapped", [244]], [[213, 213], "mapped", [245]], [[214, 214], "mapped", [246]], [[215, 215], "valid", [], "NV8"], [[216, 216], "mapped", [248]], [[217, 217], "mapped", [249]], [[218, 218], "mapped", [250]], [[219, 219], "mapped", [251]], [[220, 220], "mapped", [252]], [[221, 221], "mapped", [253]], [[222, 222], "mapped", [254]], [[223, 223], "deviation", [115, 115]], [[224, 246], "valid"], [[247, 247], "valid", [], "NV8"], [[248, 255], "valid"], [[256, 256], "mapped", [257]], [[257, 257], "valid"], [[258, 258], "mapped", [259]], [[259, 259], "valid"], [[260, 260], "mapped", [261]], [[261, 261], "valid"], [[262, 262], "mapped", [263]], [[263, 263], "valid"], [[264, 264], "mapped", [265]], [[265, 265], "valid"], [[266, 266], "mapped", [267]], [[267, 267], "valid"], [[268, 268], "mapped", [269]], [[269, 269], "valid"], [[270, 270], "mapped", [271]], [[271, 271], "valid"], [[272, 272], "mapped", [273]], [[273, 273], "valid"], [[274, 274], "mapped", [275]], [[275, 275], "valid"], [[276, 276], "mapped", [277]], [[277, 277], "valid"], [[278, 278], "mapped", [279]], [[279, 279], "valid"], [[280, 280], "mapped", [281]], [[281, 281], "valid"], [[282, 282], "mapped", [283]], [[283, 283], "valid"], [[284, 284], "mapped", [285]], [[285, 285], "valid"], [[286, 286], "mapped", [287]], [[287, 287], "valid"], [[288, 288], "mapped", [289]], [[289, 289], "valid"], [[290, 290], "mapped", [291]], [[291, 291], "valid"], [[292, 292], "mapped", [293]], [[293, 293], "valid"], [[294, 294], "mapped", [295]], [[295, 295], "valid"], [[296, 2
}
});
// node_modules/tr46/index.js
var require_tr46 = __commonJS({
"node_modules/tr46/index.js"(exports, module2) {
"use strict";
var punycode = require("punycode");
var mappingTable = require_mappingTable();
var PROCESSING_OPTIONS = {
TRANSITIONAL: 0,
NONTRANSITIONAL: 1
};
function normalize(str) {
return str.split("\0").map(function(s) {
return s.normalize("NFC");
}).join("\0");
}
function findStatus(val) {
var start = 0;
var end = mappingTable.length - 1;
while (start <= end) {
var mid = Math.floor((start + end) / 2);
var target = mappingTable[mid];
if (target[0][0] <= val && target[0][1] >= val) {
return target;
} else if (target[0][0] > val) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return null;
}
var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
function countSymbols(string) {
return string.replace(regexAstralSymbols, "_").length;
}
function mapChars(domain_name, useSTD3, processing_option) {
var hasError = false;
var processed = "";
var len = countSymbols(domain_name);
for (var i = 0; i < len; ++i) {
var codePoint = domain_name.codePointAt(i);
var status = findStatus(codePoint);
switch (status[1]) {
case "disallowed":
hasError = true;
processed += String.fromCodePoint(codePoint);
break;
case "ignored":
break;
case "mapped":
processed += String.fromCodePoint.apply(String, status[2]);
break;
case "deviation":
if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) {
processed += String.fromCodePoint.apply(String, status[2]);
} else {
processed += String.fromCodePoint(codePoint);
}
break;
case "valid":
processed += String.fromCodePoint(codePoint);
break;
case "disallowed_STD3_mapped":
if (useSTD3) {
hasError = true;
processed += String.fromCodePoint(codePoint);
} else {
processed += String.fromCodePoint.apply(String, status[2]);
}
break;
case "disallowed_STD3_valid":
if (useSTD3) {
hasError = true;
}
processed += String.fromCodePoint(codePoint);
break;
}
}
return {
string: processed,
error: hasError
};
}
var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/;
function validateLabel(label, processing_option) {
if (label.substr(0, 4) === "xn--") {
label = punycode.toUnicode(label);
processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL;
}
var error = false;
if (normalize(label) !== label || label[3] === "-" && label[4] === "-" || label[0] === "-" || label[label.length - 1] === "-" || label.indexOf(".") !== -1 || label.search(combiningMarksRegex) === 0) {
error = true;
}
var len = countSymbols(label);
for (var i = 0; i < len; ++i) {
var status = findStatus(label.codePointAt(i));
if (processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid" || processing === PROCESSING_OPTIONS.NONTRANSITIONAL && status[1] !== "valid" && status[1] !== "deviation") {
error = true;
break;
}
}
return {
label,
error
};
}
function processing(domain_name, useSTD3, processing_option) {
var result = mapChars(domain_name, useSTD3, processing_option);
result.string = normalize(result.string);
var labels = result.string.split(".");
for (var i = 0; i < labels.length; ++i) {
try {
var validation = validateLabel(labels[i]);
labels[i] = validation.label;
result.error = result.error || validation.error;
} catch (e) {
result.error = true;
}
}
return {
string: labels.join("."),
error: result.error
};
}
module2.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) {
var result = processing(domain_name, useSTD3, processing_option);
var labels = result.string.split(".");
labels = labels.map(function(l) {
try {
return punycode.toASCII(l);
} catch (e) {
result.error = true;
return l;
}
});
if (verifyDnsLength) {
var total = labels.slice(0, labels.length - 1).join(".").length;
if (total.length > 253 || total.length === 0) {
result.error = true;
}
for (var i = 0; i < labels.length; ++i) {
if (labels.length > 63 || labels.length === 0) {
result.error = true;
break;
}
}
}
if (result.error)
return null;
return labels.join(".");
};
module2.exports.toUnicode = function(domain_name, useSTD3) {
var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL);
return {
domain: result.string,
error: result.error
};
};
module2.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS;
}
});
// node_modules/whatwg-url/lib/url-state-machine.js
var require_url_state_machine = __commonJS({
"node_modules/whatwg-url/lib/url-state-machine.js"(exports, module2) {
"use strict";
var punycode = require("punycode");
var tr46 = require_tr46();
var specialSchemes = {
ftp: 21,
file: null,
gopher: 70,
http: 80,
https: 443,
ws: 80,
wss: 443
};
var failure = Symbol("failure");
function countSymbols(str) {
return punycode.ucs2.decode(str).length;
}
function at(input, idx) {
const c = input[idx];
return isNaN(c) ? void 0 : String.fromCodePoint(c);
}
function isASCIIDigit(c) {
return c >= 48 && c <= 57;
}
function isASCIIAlpha(c) {
return c >= 65 && c <= 90 || c >= 97 && c <= 122;
}
function isASCIIAlphanumeric(c) {
return isASCIIAlpha(c) || isASCIIDigit(c);
}
function isASCIIHex(c) {
return isASCIIDigit(c) || c >= 65 && c <= 70 || c >= 97 && c <= 102;
}
function isSingleDot(buffer) {
return buffer === "." || buffer.toLowerCase() === "%2e";
}
function isDoubleDot(buffer) {
buffer = buffer.toLowerCase();
return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e";
}
function isWindowsDriveLetterCodePoints(cp1, cp2) {
return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124);
}
function isWindowsDriveLetterString(string) {
return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|");
}
function isNormalizedWindowsDriveLetterString(string) {
return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":";
}
function containsForbiddenHostCodePoint(string) {
return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1;
}
function containsForbiddenHostCodePointExcludingPercent(string) {
return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1;
}
function isSpecialScheme(scheme) {
return specialSchemes[scheme] !== void 0;
}
function isSpecial(url) {
return isSpecialScheme(url.scheme);
}
function defaultPort(scheme) {
return specialSchemes[scheme];
}
function percentEncode(c) {
let hex = c.toString(16).toUpperCase();
if (hex.length === 1) {
hex = "0" + hex;
}
return "%" + hex;
}
function utf8PercentEncode(c) {
const buf = new Buffer(c);
let str = "";
for (let i = 0; i < buf.length; ++i) {
str += percentEncode(buf[i]);
}
return str;
}
function utf8PercentDecode(str) {
const input = new Buffer(str);
const output = [];
for (let i = 0; i < input.length; ++i) {
if (input[i] !== 37) {
output.push(input[i]);
} else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) {
output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16));
i += 2;
} else {
output.push(input[i]);
}
}
return new Buffer(output).toString();
}
function isC0ControlPercentEncode(c) {
return c <= 31 || c > 126;
}
var extraPathPercentEncodeSet = /* @__PURE__ */ new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]);
function isPathPercentEncode(c) {
return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c);
}
var extraUserinfoPercentEncodeSet = /* @__PURE__ */ new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]);
function isUserinfoPercentEncode(c) {
return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c);
}
function percentEncodeChar(c, encodeSetPredicate) {
const cStr = String.fromCodePoint(c);
if (encodeSetPredicate(c)) {
return utf8PercentEncode(cStr);
}
return cStr;
}
function parseIPv4Number(input) {
let R = 10;
if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") {
input = input.substring(2);
R = 16;
} else if (input.length >= 2 && input.charAt(0) === "0") {
input = input.substring(1);
R = 8;
}
if (input === "") {
return 0;
}
const regex = R === 10 ? /[^0-9]/ : R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/;
if (regex.test(input)) {
return failure;
}
return parseInt(input, R);
}
function parseIPv4(input) {
const parts = input.split(".");
if (parts[parts.length - 1] === "") {
if (parts.length > 1) {
parts.pop();
}
}
if (parts.length > 4) {
return input;
}
const numbers = [];
for (const part of parts) {
if (part === "") {
return input;
}
const n = parseIPv4Number(part);
if (n === failure) {
return input;
}
numbers.push(n);
}
for (let i = 0; i < numbers.length - 1; ++i) {
if (numbers[i] > 255) {
return failure;
}
}
if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) {
return failure;
}
let ipv4 = numbers.pop();
let counter = 0;
for (const n of numbers) {
ipv4 += n * Math.pow(256, 3 - counter);
++counter;
}
return ipv4;
}
function serializeIPv4(address) {
let output = "";
let n = address;
for (let i = 1; i <= 4; ++i) {
output = String(n % 256) + output;
if (i !== 4) {
output = "." + output;
}
n = Math.floor(n / 256);
}
return output;
}
function parseIPv6(input) {
const address = [0, 0, 0, 0, 0, 0, 0, 0];
let pieceIndex = 0;
let compress = null;
let pointer = 0;
input = punycode.ucs2.decode(input);
if (input[pointer] === 58) {
if (input[pointer + 1] !== 58) {
return failure;
}
pointer += 2;
++pieceIndex;
compress = pieceIndex;
}
while (pointer < input.length) {
if (pieceIndex === 8) {
return failure;
}
if (input[pointer] === 58) {
if (compress !== null) {
return failure;
}
++pointer;
++pieceIndex;
compress = pieceIndex;
continue;
}
let value = 0;
let length = 0;
while (length < 4 && isASCIIHex(input[pointer])) {
value = value * 16 + parseInt(at(input, pointer), 16);
++pointer;
++length;
}
if (input[pointer] === 46) {
if (length === 0) {
return failure;
}
pointer -= length;
if (pieceIndex > 6) {
return failure;
}
let numbersSeen = 0;
while (input[pointer] !== void 0) {
let ipv4Piece = null;
if (numbersSeen > 0) {
if (input[pointer] === 46 && numbersSeen < 4) {
++pointer;
} else {
return failure;
}
}
if (!isASCIIDigit(input[pointer])) {
return failure;
}
while (isASCIIDigit(input[pointer])) {
const number = parseInt(at(input, pointer));
if (ipv4Piece === null) {
ipv4Piece = number;
} else if (ipv4Piece === 0) {
return failure;
} else {
ipv4Piece = ipv4Piece * 10 + number;
}
if (ipv4Piece > 255) {
return failure;
}
++pointer;
}
address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece;
++numbersSeen;
if (numbersSeen === 2 || numbersSeen === 4) {
++pieceIndex;
}
}
if (numbersSeen !== 4) {
return failure;
}
break;
} else if (input[pointer] === 58) {
++pointer;
if (input[pointer] === void 0) {
return failure;
}
} else if (input[pointer] !== void 0) {
return failure;
}
address[pieceIndex] = value;
++pieceIndex;
}
if (compress !== null) {
let swaps = pieceIndex - compress;
pieceIndex = 7;
while (pieceIndex !== 0 && swaps > 0) {
const temp = address[compress + swaps - 1];
address[compress + swaps - 1] = address[pieceIndex];
address[pieceIndex] = temp;
--pieceIndex;
--swaps;
}
} else if (compress === null && pieceIndex !== 8) {
return failure;
}
return address;
}
function serializeIPv6(address) {
let output = "";
const seqResult = findLongestZeroSequence(address);
const compress = seqResult.idx;
let ignore0 = false;
for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) {
if (ignore0 && address[pieceIndex] === 0) {
continue;
} else if (ignore0) {
ignore0 = false;
}
if (compress === pieceIndex) {
const separator = pieceIndex === 0 ? "::" : ":";
output += separator;
ignore0 = true;
continue;
}
output += address[pieceIndex].toString(16);
if (pieceIndex !== 7) {
output += ":";
}
}
return output;
}
function parseHost(input, isSpecialArg) {
if (input[0] === "[") {
if (input[input.length - 1] !== "]") {
return failure;
}
return parseIPv6(input.substring(1, input.length - 1));
}
if (!isSpecialArg) {
return parseOpaqueHost(input);
}
const domain = utf8PercentDecode(input);
const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false);
if (asciiDomain === null) {
return failure;
}
if (containsForbiddenHostCodePoint(asciiDomain)) {
return failure;
}
const ipv4Host = parseIPv4(asciiDomain);
if (typeof ipv4Host === "number" || ipv4Host === failure) {
return ipv4Host;
}
return asciiDomain;
}
function parseOpaqueHost(input) {
if (containsForbiddenHostCodePointExcludingPercent(input)) {
return failure;
}
let output = "";
const decoded = punycode.ucs2.decode(input);
for (let i = 0; i < decoded.length; ++i) {
output += percentEncodeChar(decoded[i], isC0ControlPercentEncode);
}
return output;
}
function findLongestZeroSequence(arr) {
let maxIdx = null;
let maxLen = 1;
let currStart = null;
let currLen = 0;
for (let i = 0; i < arr.length; ++i) {
if (arr[i] !== 0) {
if (currLen > maxLen) {
maxIdx = currStart;
maxLen = currLen;
}
currStart = null;
currLen = 0;
} else {
if (currStart === null) {
currStart = i;
}
++currLen;
}
}
if (currLen > maxLen) {
maxIdx = currStart;
maxLen = currLen;
}
return {
idx: maxIdx,
len: maxLen
};
}
function serializeHost(host) {
if (typeof host === "number") {
return serializeIPv4(host);
}
if (host instanceof Array) {
return "[" + serializeIPv6(host) + "]";
}
return host;
}
function trimControlChars(url) {
return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, "");
}
function trimTabAndNewline(url) {
return url.replace(/\u0009|\u000A|\u000D/g, "");
}
function shortenPath(url) {
const path3 = url.path;
if (path3.length === 0) {
3 years ago
return;
}
if (url.scheme === "file" && path3.length === 1 && isNormalizedWindowsDriveLetter(path3[0])) {
3 years ago
return;
}
path3.pop();
3 years ago
}
function includesCredentials(url) {
return url.username !== "" || url.password !== "";
}
function cannotHaveAUsernamePasswordPort(url) {
return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file";
}
function isNormalizedWindowsDriveLetter(string) {
return /^[A-Za-z]:$/.test(string);
}
function URLStateMachine(input, base, encodingOverride, url, stateOverride) {
this.pointer = 0;
this.input = input;
this.base = base || null;
this.encodingOverride = encodingOverride || "utf-8";
this.stateOverride = stateOverride;
this.url = url;
this.failure = false;
this.parseError = false;
if (!this.url) {
this.url = {
scheme: "",
username: "",
password: "",
host: null,
port: null,
path: [],
query: null,
fragment: null,
cannotBeABaseURL: false
};
const res2 = trimControlChars(this.input);
if (res2 !== this.input) {
this.parseError = true;
}
this.input = res2;
}
const res = trimTabAndNewline(this.input);
if (res !== this.input) {
this.parseError = true;
}
this.input = res;
this.state = stateOverride || "scheme start";
this.buffer = "";
this.atFlag = false;
this.arrFlag = false;
this.passwordTokenSeenFlag = false;
this.input = punycode.ucs2.decode(this.input);
for (; this.pointer <= this.input.length; ++this.pointer) {
const c = this.input[this.pointer];
const cStr = isNaN(c) ? void 0 : String.fromCodePoint(c);
const ret = this["parse " + this.state](c, cStr);
if (!ret) {
break;
} else if (ret === failure) {
this.failure = true;
break;
}
}
}
URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) {
if (isASCIIAlpha(c)) {
this.buffer += cStr.toLowerCase();
this.state = "scheme";
} else if (!this.stateOverride) {
this.state = "no scheme";
--this.pointer;
} else {
this.parseError = true;
return failure;
}
return true;
};
URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) {
if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) {
this.buffer += cStr.toLowerCase();
} else if (c === 58) {
if (this.stateOverride) {
if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) {
return false;
}
if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) {
return false;
}
if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") {
return false;
}
if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) {
return false;
}
}
this.url.scheme = this.buffer;
this.buffer = "";
if (this.stateOverride) {
return false;
}
if (this.url.scheme === "file") {
if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) {
this.parseError = true;
}
this.state = "file";
} else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) {
this.state = "special relative or authority";
} else if (isSpecial(this.url)) {
this.state = "special authority slashes";
} else if (this.input[this.pointer + 1] === 47) {
this.state = "path or authority";
++this.pointer;
} else {
this.url.cannotBeABaseURL = true;
this.url.path.push("");
this.state = "cannot-be-a-base-URL path";
}
} else if (!this.stateOverride) {
this.buffer = "";
this.state = "no scheme";
this.pointer = -1;
} else {
this.parseError = true;
return failure;
}
return true;
};
URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) {
if (this.base === null || this.base.cannotBeABaseURL && c !== 35) {
return failure;
} else if (this.base.cannotBeABaseURL && c === 35) {
this.url.scheme = this.base.scheme;
this.url.path = this.base.path.slice();
this.url.query = this.base.query;
this.url.fragment = "";
this.url.cannotBeABaseURL = true;
this.state = "fragment";
} else if (this.base.scheme === "file") {
this.state = "file";
--this.pointer;
} else {
this.state = "relative";
--this.pointer;
}
return true;
};
URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) {
if (c === 47 && this.input[this.pointer + 1] === 47) {
this.state = "special authority ignore slashes";
++this.pointer;
} else {
this.parseError = true;
this.state = "relative";
--this.pointer;
}
return true;
};
URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) {
if (c === 47) {
this.state = "authority";
} else {
this.state = "path";
--this.pointer;
}
return true;
};
URLStateMachine.prototype["parse relative"] = function parseRelative(c) {
this.url.scheme = this.base.scheme;
if (isNaN(c)) {
this.url.username = this.base.username;
this.url.password = this.base.password;
this.url.host = this.base.host;
this.url.port = this.base.port;
this.url.path = this.base.path.slice();
this.url.query = this.base.query;
} else if (c === 47) {
this.state = "relative slash";
} else if (c === 63) {
this.url.username = this.base.username;
this.url.password = this.base.password;
this.url.host = this.base.host;
this.url.port = this.base.port;
this.url.path = this.base.path.slice();
this.url.query = "";
this.state = "query";
} else if (c === 35) {
this.url.username = this.base.username;
this.url.password = this.base.password;
this.url.host = this.base.host;
this.url.port = this.base.port;
this.url.path = this.base.path.slice();
this.url.query = this.base.query;
this.url.fragment = "";
this.state = "fragment";
} else if (isSpecial(this.url) && c === 92) {
this.parseError = true;
this.state = "relative slash";
} else {
this.url.username = this.base.username;
this.url.password = this.base.password;
this.url.host = this.base.host;
this.url.port = this.base.port;
this.url.path = this.base.path.slice(0, this.base.path.length - 1);
this.state = "path";
--this.pointer;
}
return true;
};
URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) {
if (isSpecial(this.url) && (c === 47 || c === 92)) {
if (c === 92) {
this.parseError = true;
}
this.state = "special authority ignore slashes";
} else if (c === 47) {
this.state = "authority";
} else {
this.url.username = this.base.username;
this.url.password = this.base.password;
this.url.host = this.base.host;
this.url.port = this.base.port;
this.state = "path";
--this.pointer;
}
return true;
};
URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) {
if (c === 47 && this.input[this.pointer + 1] === 47) {
this.state = "special authority ignore slashes";
++this.pointer;
} else {
this.parseError = true;
this.state = "special authority ignore slashes";
--this.pointer;
}
return true;
};
URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) {
if (c !== 47 && c !== 92) {
this.state = "authority";
--this.pointer;
} else {
this.parseError = true;
}
return true;
};
URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) {
if (c === 64) {
this.parseError = true;
if (this.atFlag) {
this.buffer = "%40" + this.buffer;
}
this.atFlag = true;
const len = countSymbols(this.buffer);
for (let pointer = 0; pointer < len; ++pointer) {
const codePoint = this.buffer.codePointAt(pointer);
if (codePoint === 58 && !this.passwordTokenSeenFlag) {
this.passwordTokenSeenFlag = true;
continue;
}
const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode);
if (this.passwordTokenSeenFlag) {
this.url.password += encodedCodePoints;
} else {
this.url.username += encodedCodePoints;
}
}
this.buffer = "";
} else if (isNaN(c) || c === 47 || c === 63 || c === 35 || isSpecial(this.url) && c === 92) {
if (this.atFlag && this.buffer === "") {
this.parseError = true;
return failure;
}
this.pointer -= countSymbols(this.buffer) + 1;
this.buffer = "";
this.state = "host";
} else {
this.buffer += cStr;
}
return true;
};
URLStateMachine.prototype["parse hostname"] = URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) {
if (this.stateOverride && this.url.scheme === "file") {
--this.pointer;
this.state = "file host";
} else if (c === 58 && !this.arrFlag) {
if (this.buffer === "") {
this.parseError = true;
return failure;
}
const host = parseHost(this.buffer, isSpecial(this.url));
if (host === failure) {
return failure;
}
this.url.host = host;
this.buffer = "";
this.state = "port";
if (this.stateOverride === "hostname") {
return false;
}
} else if (isNaN(c) || c === 47 || c === 63 || c === 35 || isSpecial(this.url) && c === 92) {
--this.pointer;
if (isSpecial(this.url) && this.buffer === "") {
this.parseError = true;
return failure;
} else if (this.stateOverride && this.buffer === "" && (includesCredentials(this.url) || this.url.port !== null)) {
this.parseError = true;
return false;
}
const host = parseHost(this.buffer, isSpecial(this.url));
if (host === failure) {
return failure;
}
this.url.host = host;
this.buffer = "";
this.state = "path start";
if (this.stateOverride) {
return false;
}
} else {
if (c === 91) {
this.arrFlag = true;
} else if (c === 93) {
this.arrFlag = false;
}
this.buffer += cStr;
}
return true;
};
URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) {
if (isASCIIDigit(c)) {
this.buffer += cStr;
} else if (isNaN(c) || c === 47 || c === 63 || c === 35 || isSpecial(this.url) && c === 92 || this.stateOverride) {
if (this.buffer !== "") {
const port = parseInt(this.buffer);
if (port > Math.pow(2, 16) - 1) {
this.parseError = true;
return failure;
}
this.url.port = port === defaultPort(this.url.scheme) ? null : port;
this.buffer = "";
}
if (this.stateOverride) {
return false;
}
this.state = "path start";
--this.pointer;
} else {
this.parseError = true;
return failure;
}
return true;
};
var fileOtherwiseCodePoints = /* @__PURE__ */ new Set([47, 92, 63, 35]);
URLStateMachine.prototype["parse file"] = function parseFile(c) {
this.url.scheme = "file";
if (c === 47 || c === 92) {
if (c === 92) {
this.parseError = true;
}
this.state = "file slash";
} else if (this.base !== null && this.base.scheme === "file") {
if (isNaN(c)) {
this.url.host = this.base.host;
this.url.path = this.base.path.slice();
this.url.query = this.base.query;
} else if (c === 63) {
this.url.host = this.base.host;
this.url.path = this.base.path.slice();
this.url.query = "";
this.state = "query";
} else if (c === 35) {
this.url.host = this.base.host;
this.url.path = this.base.path.slice();
this.url.query = this.base.query;
this.url.fragment = "";
this.state = "fragment";
} else {
if (this.input.length - this.pointer - 1 === 0 || !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || this.input.length - this.pointer - 1 >= 2 && !fileOtherwiseCodePoints.has(this.input[this.pointer + 2])) {
this.url.host = this.base.host;
this.url.path = this.base.path.slice();
shortenPath(this.url);
} else {
this.parseError = true;
}
this.state = "path";
--this.pointer;
}
} else {
this.state = "path";
--this.pointer;
}
return true;
};
URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) {
if (c === 47 || c === 92) {
if (c === 92) {
this.parseError = true;
}
this.state = "file host";
} else {
if (this.base !== null && this.base.scheme === "file") {
if (isNormalizedWindowsDriveLetterString(this.base.path[0])) {
this.url.path.push(this.base.path[0]);
} else {
this.url.host = this.base.host;
}
}
this.state = "path";
--this.pointer;
}
return true;
};
URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) {
if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) {
--this.pointer;
if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) {
this.parseError = true;
this.state = "path";
} else if (this.buffer === "") {
this.url.host = "";
if (this.stateOverride) {
return false;
}
this.state = "path start";
} else {
let host = parseHost(this.buffer, isSpecial(this.url));
if (host === failure) {
return failure;
}
if (host === "localhost") {
host = "";
}
this.url.host = host;
if (this.stateOverride) {
return false;
}
this.buffer = "";
this.state = "path start";
}
} else {
this.buffer += cStr;
}
return true;
};
URLStateMachine.prototype["parse path start"] = function parsePathStart(c) {
if (isSpecial(this.url)) {
if (c === 92) {
this.parseError = true;
}
this.state = "path";
if (c !== 47 && c !== 92) {
--this.pointer;
}
} else if (!this.stateOverride && c === 63) {
this.url.query = "";
this.state = "query";
} else if (!this.stateOverride && c === 35) {
this.url.fragment = "";
this.state = "fragment";
} else if (c !== void 0) {
this.state = "path";
if (c !== 47) {
--this.pointer;
}
}
return true;
};
URLStateMachine.prototype["parse path"] = function parsePath(c) {
if (isNaN(c) || c === 47 || isSpecial(this.url) && c === 92 || !this.stateOverride && (c === 63 || c === 35)) {
if (isSpecial(this.url) && c === 92) {
this.parseError = true;
}
if (isDoubleDot(this.buffer)) {
shortenPath(this.url);
if (c !== 47 && !(isSpecial(this.url) && c === 92)) {
this.url.path.push("");
}
} else if (isSingleDot(this.buffer) && c !== 47 && !(isSpecial(this.url) && c === 92)) {
this.url.path.push("");
} else if (!isSingleDot(this.buffer)) {
if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) {
if (this.url.host !== "" && this.url.host !== null) {
this.parseError = true;
this.url.host = "";
}
this.buffer = this.buffer[0] + ":";
}
this.url.path.push(this.buffer);
}
this.buffer = "";
if (this.url.scheme === "file" && (c === void 0 || c === 63 || c === 35)) {
while (this.url.path.length > 1 && this.url.path[0] === "") {
this.parseError = true;
this.url.path.shift();
}
}
if (c === 63) {
this.url.query = "";
this.state = "query";
}
if (c === 35) {
this.url.fragment = "";
this.state = "fragment";
}
} else {
if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
this.parseError = true;
}
this.buffer += percentEncodeChar(c, isPathPercentEncode);
}
return true;
};
URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) {
if (c === 63) {
this.url.query = "";
this.state = "query";
} else if (c === 35) {
this.url.fragment = "";
this.state = "fragment";
} else {
if (!isNaN(c) && c !== 37) {
this.parseError = true;
}
if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
this.parseError = true;
}
if (!isNaN(c)) {
this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode);
}
}
return true;
};
URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) {
if (isNaN(c) || !this.stateOverride && c === 35) {
if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") {
this.encodingOverride = "utf-8";
}
const buffer = new Buffer(this.buffer);
for (let i = 0; i < buffer.length; ++i) {
if (buffer[i] < 33 || buffer[i] > 126 || buffer[i] === 34 || buffer[i] === 35 || buffer[i] === 60 || buffer[i] === 62) {
this.url.query += percentEncode(buffer[i]);
} else {
this.url.query += String.fromCodePoint(buffer[i]);
}
}
this.buffer = "";
if (c === 35) {
this.url.fragment = "";
this.state = "fragment";
}
} else {
if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
this.parseError = true;
}
this.buffer += cStr;
}
return true;
};
URLStateMachine.prototype["parse fragment"] = function parseFragment(c) {
if (isNaN(c)) {
} else if (c === 0) {
this.parseError = true;
} else {
if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) {
this.parseError = true;
}
this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode);
}
return true;
};
function serializeURL(url, excludeFragment) {
let output = url.scheme + ":";
if (url.host !== null) {
output += "//";
if (url.username !== "" || url.password !== "") {
output += url.username;
if (url.password !== "") {
output += ":" + url.password;
}
output += "@";
}
output += serializeHost(url.host);
if (url.port !== null) {
output += ":" + url.port;
}
} else if (url.host === null && url.scheme === "file") {
output += "//";
}
if (url.cannotBeABaseURL) {
output += url.path[0];
} else {
for (const string of url.path) {
output += "/" + string;
}
}
if (url.query !== null) {
output += "?" + url.query;
}
if (!excludeFragment && url.fragment !== null) {
output += "#" + url.fragment;
}
return output;
}
function serializeOrigin(tuple) {
let result = tuple.scheme + "://";
result += serializeHost(tuple.host);
if (tuple.port !== null) {
result += ":" + tuple.port;
}
return result;
}
module2.exports.serializeURL = serializeURL;
module2.exports.serializeURLOrigin = function(url) {
switch (url.scheme) {
case "blob":
try {
return module2.exports.serializeURLOrigin(module2.exports.parseURL(url.path[0]));
} catch (e) {
return "null";
}
case "ftp":
case "gopher":
case "http":
case "https":
case "ws":
case "wss":
return serializeOrigin({
scheme: url.scheme,
host: url.host,
port: url.port
});
case "file":
return "file://";
default:
return "null";
}
};
module2.exports.basicURLParse = function(input, options) {
if (options === void 0) {
options = {};
}
const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride);
if (usm.failure) {
return "failure";
}
return usm.url;
};
module2.exports.setTheUsername = function(url, username) {
url.username = "";
const decoded = punycode.ucs2.decode(username);
for (let i = 0; i < decoded.length; ++i) {
url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode);
}
};
module2.exports.setThePassword = function(url, password) {
url.password = "";
const decoded = punycode.ucs2.decode(password);
for (let i = 0; i < decoded.length; ++i) {
url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode);
}
};
module2.exports.serializeHost = serializeHost;
module2.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort;
module2.exports.serializeInteger = function(integer) {
return String(integer);
};
module2.exports.parseURL = function(input, options) {
if (options === void 0) {
options = {};
}
return module2.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride });
};
}
});
// node_modules/whatwg-url/lib/URL-impl.js
var require_URL_impl = __commonJS({
"node_modules/whatwg-url/lib/URL-impl.js"(exports) {
"use strict";
var usm = require_url_state_machine();
exports.implementation = class URLImpl {
constructor(constructorArgs) {
const url = constructorArgs[0];
const base = constructorArgs[1];
let parsedBase = null;
if (base !== void 0) {
parsedBase = usm.basicURLParse(base);
if (parsedBase === "failure") {
throw new TypeError("Invalid base URL");
}
}
const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase });
if (parsedURL === "failure") {
throw new TypeError("Invalid URL");
}
this._url = parsedURL;
}
get href() {
return usm.serializeURL(this._url);
}
set href(v) {
const parsedURL = usm.basicURLParse(v);
if (parsedURL === "failure") {
throw new TypeError("Invalid URL");
}
this._url = parsedURL;
}
get origin() {
return usm.serializeURLOrigin(this._url);
}
get protocol() {
return this._url.scheme + ":";
}
set protocol(v) {
usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" });
}
get username() {
return this._url.username;
}
set username(v) {
if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
return;
}
usm.setTheUsername(this._url, v);
}
get password() {
return this._url.password;
}
set password(v) {
if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
return;
}
usm.setThePassword(this._url, v);
}
get host() {
const url = this._url;
if (url.host === null) {
return "";
}
if (url.port === null) {
return usm.serializeHost(url.host);
}
return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port);
}
set host(v) {
if (this._url.cannotBeABaseURL) {
return;
}
usm.basicURLParse(v, { url: this._url, stateOverride: "host" });
}
get hostname() {
if (this._url.host === null) {
return "";
}
return usm.serializeHost(this._url.host);
}
set hostname(v) {
if (this._url.cannotBeABaseURL) {
return;
}
usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" });
}
get port() {
if (this._url.port === null) {
return "";
}
return usm.serializeInteger(this._url.port);
}
set port(v) {
if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
return;
}
if (v === "") {
this._url.port = null;
} else {
usm.basicURLParse(v, { url: this._url, stateOverride: "port" });
}
}
get pathname() {
if (this._url.cannotBeABaseURL) {
return this._url.path[0];
}
if (this._url.path.length === 0) {
return "";
}
return "/" + this._url.path.join("/");
}
set pathname(v) {
if (this._url.cannotBeABaseURL) {
return;
}
this._url.path = [];
usm.basicURLParse(v, { url: this._url, stateOverride: "path start" });
}
get search() {
if (this._url.query === null || this._url.query === "") {
return "";
}
return "?" + this._url.query;
}
set search(v) {
const url = this._url;
if (v === "") {
url.query = null;
return;
}
const input = v[0] === "?" ? v.substring(1) : v;
url.query = "";
usm.basicURLParse(input, { url, stateOverride: "query" });
}
get hash() {
if (this._url.fragment === null || this._url.fragment === "") {
return "";
}
return "#" + this._url.fragment;
}
set hash(v) {
if (v === "") {
this._url.fragment = null;
return;
}
const input = v[0] === "#" ? v.substring(1) : v;
this._url.fragment = "";
usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" });
}
toJSON() {
return this.href;
}
};
}
});
// node_modules/whatwg-url/lib/URL.js
var require_URL = __commonJS({
"node_modules/whatwg-url/lib/URL.js"(exports, module2) {
"use strict";
var conversions = require_lib2();
3 years ago
var utils = require_utils3();
var Impl = require_URL_impl();
var impl = utils.implSymbol;
function URL2(url) {
if (!this || this[impl] || !(this instanceof URL2)) {
throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function.");
}
if (arguments.length < 1) {
throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present.");
}
const args = [];
for (let i = 0; i < arguments.length && i < 2; ++i) {
args[i] = arguments[i];
}
args[0] = conversions["USVString"](args[0]);
if (args[1] !== void 0) {
args[1] = conversions["USVString"](args[1]);
}
module2.exports.setup(this, args);
}
URL2.prototype.toJSON = function toJSON() {
if (!this || !module2.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
const args = [];
for (let i = 0; i < arguments.length && i < 0; ++i) {
args[i] = arguments[i];
}
return this[impl].toJSON.apply(this[impl], args);
};
Object.defineProperty(URL2.prototype, "href", {
get() {
return this[impl].href;
},
set(V) {
V = conversions["USVString"](V);
this[impl].href = V;
},
enumerable: true,
configurable: true
});
URL2.prototype.toString = function() {
if (!this || !module2.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this.href;
};
Object.defineProperty(URL2.prototype, "origin", {
get() {
return this[impl].origin;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL2.prototype, "protocol", {
get() {
return this[impl].protocol;
},
set(V) {
V = conversions["USVString"](V);
this[impl].protocol = V;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL2.prototype, "username", {
get() {
return this[impl].username;
},
set(V) {
V = conversions["USVString"](V);
this[impl].username = V;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL2.prototype, "password", {
get() {
return this[impl].password;
},
set(V) {
V = conversions["USVString"](V);
this[impl].password = V;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL2.prototype, "host", {
get() {
return this[impl].host;
},
set(V) {
V = conversions["USVString"](V);
this[impl].host = V;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL2.prototype, "hostname", {
get() {
return this[impl].hostname;
},
set(V) {
V = conversions["USVString"](V);
this[impl].hostname = V;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL2.prototype, "port", {
get() {
return this[impl].port;
},
set(V) {
V = conversions["USVString"](V);
this[impl].port = V;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL2.prototype, "pathname", {
get() {
return this[impl].pathname;
},
set(V) {
V = conversions["USVString"](V);
this[impl].pathname = V;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL2.prototype, "search", {
get() {
return this[impl].search;
},
set(V) {
V = conversions["USVString"](V);
this[impl].search = V;
},
enumerable: true,
configurable: true
});
Object.defineProperty(URL2.prototype, "hash", {
get() {
return this[impl].hash;
},
set(V) {
V = conversions["USVString"](V);
this[impl].hash = V;
},
enumerable: true,
configurable: true
});
module2.exports = {
is(obj) {
return !!obj && obj[impl] instanceof Impl.implementation;
},
create(constructorArgs, privateData) {
let obj = Object.create(URL2.prototype);
this.setup(obj, constructorArgs, privateData);
return obj;
},
setup(obj, constructorArgs, privateData) {
if (!privateData)
privateData = {};
privateData.wrapper = obj;
obj[impl] = new Impl.implementation(constructorArgs, privateData);
obj[impl][utils.wrapperSymbol] = obj;
},
interface: URL2,
expose: {
Window: { URL: URL2 },
Worker: { URL: URL2 }
}
};
}
});
// node_modules/whatwg-url/lib/public-api.js
var require_public_api = __commonJS({
"node_modules/whatwg-url/lib/public-api.js"(exports) {
"use strict";
exports.URL = require_URL().interface;
exports.serializeURL = require_url_state_machine().serializeURL;
exports.serializeURLOrigin = require_url_state_machine().serializeURLOrigin;
exports.basicURLParse = require_url_state_machine().basicURLParse;
exports.setTheUsername = require_url_state_machine().setTheUsername;
exports.setThePassword = require_url_state_machine().setThePassword;
exports.serializeHost = require_url_state_machine().serializeHost;
exports.serializeInteger = require_url_state_machine().serializeInteger;
exports.parseURL = require_url_state_machine().parseURL;
}
});
// node_modules/node-fetch/lib/index.js
var require_lib3 = __commonJS({
3 years ago
"node_modules/node-fetch/lib/index.js"(exports, module2) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function _interopDefault(ex) {
return ex && typeof ex === "object" && "default" in ex ? ex["default"] : ex;
}
var Stream = _interopDefault(require("stream"));
var http = _interopDefault(require("http"));
var Url = _interopDefault(require("url"));
var whatwgUrl = _interopDefault(require_public_api());
var https = _interopDefault(require("https"));
var zlib = _interopDefault(require("zlib"));
var Readable = Stream.Readable;
var BUFFER = Symbol("buffer");
var TYPE = Symbol("type");
var Blob = class {
constructor() {
this[TYPE] = "";
const blobParts = arguments[0];
const options = arguments[1];
const buffers = [];
let size = 0;
if (blobParts) {
const a = blobParts;
const length = Number(a.length);
for (let i = 0; i < length; i++) {
const element = a[i];
let buffer;
if (element instanceof Buffer) {
buffer = element;
} else if (ArrayBuffer.isView(element)) {
buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
} else if (element instanceof ArrayBuffer) {
buffer = Buffer.from(element);
} else if (element instanceof Blob) {
buffer = element[BUFFER];
} else {
buffer = Buffer.from(typeof element === "string" ? element : String(element));
}
size += buffer.length;
buffers.push(buffer);
}
}
this[BUFFER] = Buffer.concat(buffers);
let type = options && options.type !== void 0 && String(options.type).toLowerCase();
if (type && !/[^\u0020-\u007E]/.test(type)) {
this[TYPE] = type;
}
}
get size() {
return this[BUFFER].length;
}
get type() {
return this[TYPE];
}
text() {
return Promise.resolve(this[BUFFER].toString());
}
arrayBuffer() {
const buf = this[BUFFER];
const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
return Promise.resolve(ab);
}
stream() {
const readable = new Readable();
readable._read = function() {
};
readable.push(this[BUFFER]);
readable.push(null);
return readable;
}
toString() {
return "[object Blob]";
}
slice() {
const size = this.size;
const start = arguments[0];
const end = arguments[1];
let relativeStart, relativeEnd;
if (start === void 0) {
relativeStart = 0;
} else if (start < 0) {
relativeStart = Math.max(size + start, 0);
} else {
relativeStart = Math.min(start, size);
}
if (end === void 0) {
relativeEnd = size;
} else if (end < 0) {
relativeEnd = Math.max(size + end, 0);
} else {
relativeEnd = Math.min(end, size);
}
const span = Math.max(relativeEnd - relativeStart, 0);
const buffer = this[BUFFER];
const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
const blob = new Blob([], { type: arguments[2] });
blob[BUFFER] = slicedBuffer;
return blob;
}
};
Object.defineProperties(Blob.prototype, {
size: { enumerable: true },
type: { enumerable: true },
slice: { enumerable: true }
});
Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
value: "Blob",
writable: false,
enumerable: false,
configurable: true
});
function FetchError(message, type, systemError) {
Error.call(this, message);
this.message = message;
this.type = type;
if (systemError) {
this.code = this.errno = systemError.code;
}
Error.captureStackTrace(this, this.constructor);
}
FetchError.prototype = Object.create(Error.prototype);
FetchError.prototype.constructor = FetchError;
FetchError.prototype.name = "FetchError";
var convert;
try {
convert = require("encoding").convert;
} catch (e) {
}
var INTERNALS = Symbol("Body internals");
var PassThrough = Stream.PassThrough;
function Body(body) {
var _this = this;
var _ref = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, _ref$size = _ref.size;
let size = _ref$size === void 0 ? 0 : _ref$size;
var _ref$timeout = _ref.timeout;
let timeout = _ref$timeout === void 0 ? 0 : _ref$timeout;
if (body == null) {
body = null;
} else if (isURLSearchParams(body)) {
body = Buffer.from(body.toString());
} else if (isBlob(body))
;
else if (Buffer.isBuffer(body))
;
else if (Object.prototype.toString.call(body) === "[object ArrayBuffer]") {
body = Buffer.from(body);
} else if (ArrayBuffer.isView(body)) {
body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
} else if (body instanceof Stream)
;
else {
body = Buffer.from(String(body));
}
this[INTERNALS] = {
body,
disturbed: false,
error: null
};
this.size = size;
this.timeout = timeout;
if (body instanceof Stream) {
body.on("error", function(err) {
const error = err.name === "AbortError" ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, "system", err);
_this[INTERNALS].error = error;
});
}
}
Body.prototype = {
get body() {
return this[INTERNALS].body;
},
get bodyUsed() {
return this[INTERNALS].disturbed;
},
arrayBuffer() {
return consumeBody.call(this).then(function(buf) {
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
});
},
blob() {
let ct = this.headers && this.headers.get("content-type") || "";
return consumeBody.call(this).then(function(buf) {
return Object.assign(
new Blob([], {
type: ct.toLowerCase()
}),
{
[BUFFER]: buf
}
);
3 years ago
});
},
json() {
var _this2 = this;
return consumeBody.call(this).then(function(buffer) {
try {
return JSON.parse(buffer.toString());
} catch (err) {
return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, "invalid-json"));
}
});
},
text() {
return consumeBody.call(this).then(function(buffer) {
return buffer.toString();
});
},
buffer() {
return consumeBody.call(this);
},
textConverted() {
var _this3 = this;
return consumeBody.call(this).then(function(buffer) {
return convertBody(buffer, _this3.headers);
});
}
};
Object.defineProperties(Body.prototype, {
body: { enumerable: true },
bodyUsed: { enumerable: true },
arrayBuffer: { enumerable: true },
blob: { enumerable: true },
json: { enumerable: true },
text: { enumerable: true }
});
Body.mixIn = function(proto) {
for (const name of Object.getOwnPropertyNames(Body.prototype)) {
if (!(name in proto)) {
const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
Object.defineProperty(proto, name, desc);
}
}
};
function consumeBody() {
var _this4 = this;
if (this[INTERNALS].disturbed) {
return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
}
this[INTERNALS].disturbed = true;
if (this[INTERNALS].error) {
return Body.Promise.reject(this[INTERNALS].error);
}
let body = this.body;
if (body === null) {
return Body.Promise.resolve(Buffer.alloc(0));
}
if (isBlob(body)) {
body = body.stream();
}
if (Buffer.isBuffer(body)) {
return Body.Promise.resolve(body);
}
if (!(body instanceof Stream)) {
return Body.Promise.resolve(Buffer.alloc(0));
}
let accum = [];
let accumBytes = 0;
let abort = false;
return new Body.Promise(function(resolve, reject) {
let resTimeout;
if (_this4.timeout) {
resTimeout = setTimeout(function() {
abort = true;
reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, "body-timeout"));
}, _this4.timeout);
}
body.on("error", function(err) {
if (err.name === "AbortError") {
abort = true;
reject(err);
} else {
reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, "system", err));
}
});
body.on("data", function(chunk) {
if (abort || chunk === null) {
return;
}
if (_this4.size && accumBytes + chunk.length > _this4.size) {
abort = true;
reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, "max-size"));
return;
}
accumBytes += chunk.length;
accum.push(chunk);
});
body.on("end", function() {
if (abort) {
return;
}
clearTimeout(resTimeout);
try {
resolve(Buffer.concat(accum, accumBytes));
} catch (err) {
reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, "system", err));
}
});
});
}
function convertBody(buffer, headers) {
if (typeof convert !== "function") {
throw new Error("The package `encoding` must be installed to use the textConverted() function");
}
const ct = headers.get("content-type");
let charset = "utf-8";
let res, str;
if (ct) {
res = /charset=([^;]*)/i.exec(ct);
}
str = buffer.slice(0, 1024).toString();
if (!res && str) {
res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);
}
if (!res && str) {
res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);
if (!res) {
res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str);
if (res) {
res.pop();
}
}
if (res) {
res = /charset=(.*)/i.exec(res.pop());
}
}
if (!res && str) {
res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);
}
if (res) {
charset = res.pop();
if (charset === "gb2312" || charset === "gbk") {
charset = "gb18030";
}
}
return convert(buffer, "UTF-8", charset).toString();
}
function isURLSearchParams(obj) {
if (typeof obj !== "object" || typeof obj.append !== "function" || typeof obj.delete !== "function" || typeof obj.get !== "function" || typeof obj.getAll !== "function" || typeof obj.has !== "function" || typeof obj.set !== "function") {
return false;
}
return obj.constructor.name === "URLSearchParams" || Object.prototype.toString.call(obj) === "[object URLSearchParams]" || typeof obj.sort === "function";
}
function isBlob(obj) {
return typeof obj === "object" && typeof obj.arrayBuffer === "function" && typeof obj.type === "string" && typeof obj.stream === "function" && typeof obj.constructor === "function" && typeof obj.constructor.name === "string" && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);
}
function clone(instance) {
let p1, p2;
let body = instance.body;
if (instance.bodyUsed) {
throw new Error("cannot clone body after it is used");
}
if (body instanceof Stream && typeof body.getBoundary !== "function") {
p1 = new PassThrough();
p2 = new PassThrough();
body.pipe(p1);
body.pipe(p2);
instance[INTERNALS].body = p1;
body = p2;
}
return body;
}
function extractContentType(body) {
if (body === null) {
return null;
} else if (typeof body === "string") {
return "text/plain;charset=UTF-8";
} else if (isURLSearchParams(body)) {
return "application/x-www-form-urlencoded;charset=UTF-8";
} else if (isBlob(body)) {
return body.type || null;
} else if (Buffer.isBuffer(body)) {
return null;
} else if (Object.prototype.toString.call(body) === "[object ArrayBuffer]") {
return null;
} else if (ArrayBuffer.isView(body)) {
return null;
} else if (typeof body.getBoundary === "function") {
return `multipart/form-data;boundary=${body.getBoundary()}`;
} else if (body instanceof Stream) {
return null;
} else {
return "text/plain;charset=UTF-8";
}
}
function getTotalBytes(instance) {
const body = instance.body;
if (body === null) {
return 0;
} else if (isBlob(body)) {
return body.size;
} else if (Buffer.isBuffer(body)) {
return body.length;
} else if (body && typeof body.getLengthSync === "function") {
if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || body.hasKnownLength && body.hasKnownLength()) {
return body.getLengthSync();
}
return null;
} else {
return null;
}
}
function writeToStream(dest, instance) {
const body = instance.body;
if (body === null) {
dest.end();
} else if (isBlob(body)) {
body.stream().pipe(dest);
} else if (Buffer.isBuffer(body)) {
dest.write(body);
dest.end();
} else {
body.pipe(dest);
}
}
Body.Promise = global.Promise;
var invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
var invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
function validateName(name) {
name = `${name}`;
if (invalidTokenRegex.test(name) || name === "") {
throw new TypeError(`${name} is not a legal HTTP header name`);
}
}
function validateValue(value) {
value = `${value}`;
if (invalidHeaderCharRegex.test(value)) {
throw new TypeError(`${value} is not a legal HTTP header value`);
}
}
function find(map, name) {
name = name.toLowerCase();
for (const key in map) {
if (key.toLowerCase() === name) {
return key;
}
}
return void 0;
}
var MAP = Symbol("map");
var Headers = class {
constructor() {
let init = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : void 0;
this[MAP] = /* @__PURE__ */ Object.create(null);
if (init instanceof Headers) {
const rawHeaders = init.raw();
const headerNames = Object.keys(rawHeaders);
for (const headerName of headerNames) {
for (const value of rawHeaders[headerName]) {
this.append(headerName, value);
}
}
return;
}
if (init == null)
;
else if (typeof init === "object") {
const method = init[Symbol.iterator];
if (method != null) {
if (typeof method !== "function") {
throw new TypeError("Header pairs must be iterable");
}
const pairs = [];
for (const pair of init) {
if (typeof pair !== "object" || typeof pair[Symbol.iterator] !== "function") {
throw new TypeError("Each header pair must be iterable");
}
pairs.push(Array.from(pair));
}
for (const pair of pairs) {
if (pair.length !== 2) {
throw new TypeError("Each header pair must be a name/value tuple");
}
this.append(pair[0], pair[1]);
}
} else {
for (const key of Object.keys(init)) {
const value = init[key];
this.append(key, value);
}
}
} else {
throw new TypeError("Provided initializer must be an object");
}
}
get(name) {
name = `${name}`;
validateName(name);
const key = find(this[MAP], name);
if (key === void 0) {
return null;
}
return this[MAP][key].join(", ");
}
forEach(callback) {
let thisArg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : void 0;
let pairs = getHeaders(this);
let i = 0;
while (i < pairs.length) {
var _pairs$i = pairs[i];
const name = _pairs$i[0], value = _pairs$i[1];
callback.call(thisArg, value, name, this);
pairs = getHeaders(this);
i++;
}
}
set(name, value) {
name = `${name}`;
value = `${value}`;
validateName(name);
validateValue(value);
const key = find(this[MAP], name);
this[MAP][key !== void 0 ? key : name] = [value];
}
append(name, value) {
name = `${name}`;
value = `${value}`;
validateName(name);
validateValue(value);
const key = find(this[MAP], name);
if (key !== void 0) {
this[MAP][key].push(value);
} else {
this[MAP][name] = [value];
}
}
has(name) {
name = `${name}`;
validateName(name);
return find(this[MAP], name) !== void 0;
}
delete(name) {
name = `${name}`;
validateName(name);
const key = find(this[MAP], name);
if (key !== void 0) {
delete this[MAP][key];
}
}
raw() {
return this[MAP];
}
keys() {
return createHeadersIterator(this, "key");
}
values() {
return createHeadersIterator(this, "value");
}
[Symbol.iterator]() {
return createHeadersIterator(this, "key+value");
}
};
Headers.prototype.entries = Headers.prototype[Symbol.iterator];
Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
value: "Headers",
writable: false,
enumerable: false,
configurable: true
});
Object.defineProperties(Headers.prototype, {
get: { enumerable: true },
forEach: { enumerable: true },
set: { enumerable: true },
append: { enumerable: true },
has: { enumerable: true },
delete: { enumerable: true },
keys: { enumerable: true },
values: { enumerable: true },
entries: { enumerable: true }
});
function getHeaders(headers) {
let kind = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "key+value";
const keys = Object.keys(headers[MAP]).sort();
return keys.map(kind === "key" ? function(k) {
return k.toLowerCase();
} : kind === "value" ? function(k) {
return headers[MAP][k].join(", ");
} : function(k) {
return [k.toLowerCase(), headers[MAP][k].join(", ")];
});
}
var INTERNAL = Symbol("internal");
function createHeadersIterator(target, kind) {
const iterator = Object.create(HeadersIteratorPrototype);
iterator[INTERNAL] = {
target,
kind,
index: 0
};
return iterator;
}
var HeadersIteratorPrototype = Object.setPrototypeOf({
next() {
if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
throw new TypeError("Value of `this` is not a HeadersIterator");
}
var _INTERNAL = this[INTERNAL];
const target = _INTERNAL.target, kind = _INTERNAL.kind, index = _INTERNAL.index;
const values = getHeaders(target, kind);
const len = values.length;
if (index >= len) {
return {
value: void 0,
done: true
};
}
this[INTERNAL].index = index + 1;
return {
value: values[index],
done: false
};
}
}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
value: "HeadersIterator",
writable: false,
enumerable: false,
configurable: true
});
function exportNodeCompatibleHeaders(headers) {
const obj = Object.assign({ __proto__: null }, headers[MAP]);
const hostHeaderKey = find(headers[MAP], "Host");
if (hostHeaderKey !== void 0) {
obj[hostHeaderKey] = obj[hostHeaderKey][0];
}
return obj;
}
function createHeadersLenient(obj) {
const headers = new Headers();
for (const name of Object.keys(obj)) {
if (invalidTokenRegex.test(name)) {
continue;
}
if (Array.isArray(obj[name])) {
for (const val of obj[name]) {
if (invalidHeaderCharRegex.test(val)) {
continue;
}
if (headers[MAP][name] === void 0) {
headers[MAP][name] = [val];
} else {
headers[MAP][name].push(val);
}
}
} else if (!invalidHeaderCharRegex.test(obj[name])) {
headers[MAP][name] = [obj[name]];
}
}
return headers;
}
var INTERNALS$1 = Symbol("Response internals");
var STATUS_CODES = http.STATUS_CODES;
var Response = class {
constructor() {
let body = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : null;
let opts = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
Body.call(this, body, opts);
const status = opts.status || 200;
const headers = new Headers(opts.headers);
if (body != null && !headers.has("Content-Type")) {
const contentType = extractContentType(body);
if (contentType) {
headers.append("Content-Type", contentType);
}
}
this[INTERNALS$1] = {
url: opts.url,
status,
statusText: opts.statusText || STATUS_CODES[status],
headers,
counter: opts.counter
};
}
get url() {
return this[INTERNALS$1].url || "";
}
get status() {
return this[INTERNALS$1].status;
}
get ok() {
return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
}
get redirected() {
return this[INTERNALS$1].counter > 0;
}
get statusText() {
return this[INTERNALS$1].statusText;
}
get headers() {
return this[INTERNALS$1].headers;
}
clone() {
return new Response(clone(this), {
url: this.url,
status: this.status,
statusText: this.statusText,
headers: this.headers,
ok: this.ok,
redirected: this.redirected
});
}
};
Body.mixIn(Response.prototype);
Object.defineProperties(Response.prototype, {
url: { enumerable: true },
status: { enumerable: true },
ok: { enumerable: true },
redirected: { enumerable: true },
statusText: { enumerable: true },
headers: { enumerable: true },
clone: { enumerable: true }
});
Object.defineProperty(Response.prototype, Symbol.toStringTag, {
value: "Response",
writable: false,
enumerable: false,
configurable: true
});
var INTERNALS$2 = Symbol("Request internals");
var URL2 = Url.URL || whatwgUrl.URL;
var parse_url = Url.parse;
var format_url = Url.format;
function parseURL(urlStr) {
if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {
urlStr = new URL2(urlStr).toString();
}
return parse_url(urlStr);
}
var streamDestructionSupported = "destroy" in Stream.Readable.prototype;
function isRequest(input) {
return typeof input === "object" && typeof input[INTERNALS$2] === "object";
}
function isAbortSignal(signal) {
const proto = signal && typeof signal === "object" && Object.getPrototypeOf(signal);
return !!(proto && proto.constructor.name === "AbortSignal");
}
var Request = class {
constructor(input) {
let init = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
let parsedURL;
if (!isRequest(input)) {
if (input && input.href) {
parsedURL = parseURL(input.href);
} else {
parsedURL = parseURL(`${input}`);
}
input = {};
} else {
parsedURL = parseURL(input.url);
}
let method = init.method || input.method || "GET";
method = method.toUpperCase();
if ((init.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) {
throw new TypeError("Request with GET/HEAD method cannot have body");
}
let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
Body.call(this, inputBody, {
timeout: init.timeout || input.timeout || 0,
size: init.size || input.size || 0
});
const headers = new Headers(init.headers || input.headers || {});
if (inputBody != null && !headers.has("Content-Type")) {
const contentType = extractContentType(inputBody);
if (contentType) {
headers.append("Content-Type", contentType);
}
}
let signal = isRequest(input) ? input.signal : null;
if ("signal" in init)
signal = init.signal;
if (signal != null && !isAbortSignal(signal)) {
throw new TypeError("Expected signal to be an instanceof AbortSignal");
}
this[INTERNALS$2] = {
method,
redirect: init.redirect || input.redirect || "follow",
headers,
parsedURL,
signal
};
this.follow = init.follow !== void 0 ? init.follow : input.follow !== void 0 ? input.follow : 20;
this.compress = init.compress !== void 0 ? init.compress : input.compress !== void 0 ? input.compress : true;
this.counter = init.counter || input.counter || 0;
this.agent = init.agent || input.agent;
}
get method() {
return this[INTERNALS$2].method;
}
get url() {
return format_url(this[INTERNALS$2].parsedURL);
}
get headers() {
return this[INTERNALS$2].headers;
}
get redirect() {
return this[INTERNALS$2].redirect;
}
get signal() {
return this[INTERNALS$2].signal;
}
clone() {
return new Request(this);
}
};
Body.mixIn(Request.prototype);
Object.defineProperty(Request.prototype, Symbol.toStringTag, {
value: "Request",
writable: false,
enumerable: false,
configurable: true
});
Object.defineProperties(Request.prototype, {
method: { enumerable: true },
url: { enumerable: true },
headers: { enumerable: true },
redirect: { enumerable: true },
clone: { enumerable: true },
signal: { enumerable: true }
});
function getNodeRequestOptions(request) {
const parsedURL = request[INTERNALS$2].parsedURL;
const headers = new Headers(request[INTERNALS$2].headers);
if (!headers.has("Accept")) {
headers.set("Accept", "*/*");
}
if (!parsedURL.protocol || !parsedURL.hostname) {
throw new TypeError("Only absolute URLs are supported");
}
if (!/^https?:$/.test(parsedURL.protocol)) {
throw new TypeError("Only HTTP(S) protocols are supported");
}
if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
throw new Error("Cancellation of streamed requests with AbortSignal is not supported in node < 8");
}
let contentLengthValue = null;
if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
contentLengthValue = "0";
}
if (request.body != null) {
const totalBytes = getTotalBytes(request);
if (typeof totalBytes === "number") {
contentLengthValue = String(totalBytes);
}
}
if (contentLengthValue) {
headers.set("Content-Length", contentLengthValue);
}
if (!headers.has("User-Agent")) {
headers.set("User-Agent", "node-fetch/1.0 (+https://github.com/bitinn/node-fetch)");
}
if (request.compress && !headers.has("Accept-Encoding")) {
headers.set("Accept-Encoding", "gzip,deflate");
}
let agent = request.agent;
if (typeof agent === "function") {
agent = agent(parsedURL);
}
if (!headers.has("Connection") && !agent) {
headers.set("Connection", "close");
}
return Object.assign({}, parsedURL, {
method: request.method,
headers: exportNodeCompatibleHeaders(headers),
agent
});
}
function AbortError(message) {
Error.call(this, message);
this.type = "aborted";
this.message = message;
Error.captureStackTrace(this, this.constructor);
}
AbortError.prototype = Object.create(Error.prototype);
AbortError.prototype.constructor = AbortError;
AbortError.prototype.name = "AbortError";
var URL$1 = Url.URL || whatwgUrl.URL;
var PassThrough$1 = Stream.PassThrough;
var isDomainOrSubdomain = function isDomainOrSubdomain2(destination, original) {
const orig = new URL$1(original).hostname;
const dest = new URL$1(destination).hostname;
return orig === dest || orig[orig.length - dest.length - 1] === "." && orig.endsWith(dest);
};
function fetch2(url, opts) {
if (!fetch2.Promise) {
throw new Error("native promise missing, set fetch.Promise to your favorite alternative");
}
Body.Promise = fetch2.Promise;
return new fetch2.Promise(function(resolve, reject) {
const request = new Request(url, opts);
const options = getNodeRequestOptions(request);
const send = (options.protocol === "https:" ? https : http).request;
const signal = request.signal;
let response = null;
const abort = function abort2() {
let error = new AbortError("The user aborted a request.");
reject(error);
if (request.body && request.body instanceof Stream.Readable) {
request.body.destroy(error);
}
if (!response || !response.body)
return;
response.body.emit("error", error);
};
if (signal && signal.aborted) {
abort();
return;
}
const abortAndFinalize = function abortAndFinalize2() {
abort();
finalize();
};
const req = send(options);
let reqTimeout;
if (signal) {
signal.addEventListener("abort", abortAndFinalize);
}
function finalize() {
req.abort();
if (signal)
signal.removeEventListener("abort", abortAndFinalize);
clearTimeout(reqTimeout);
}
if (request.timeout) {
req.once("socket", function(socket) {
reqTimeout = setTimeout(function() {
reject(new FetchError(`network timeout at: ${request.url}`, "request-timeout"));
finalize();
}, request.timeout);
});
}
req.on("error", function(err) {
reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, "system", err));
finalize();
});
req.on("response", function(res) {
clearTimeout(reqTimeout);
const headers = createHeadersLenient(res.headers);
if (fetch2.isRedirect(res.statusCode)) {
const location = headers.get("Location");
let locationURL = null;
try {
locationURL = location === null ? null : new URL$1(location, request.url).toString();
} catch (err) {
if (request.redirect !== "manual") {
reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect"));
finalize();
return;
}
}
switch (request.redirect) {
case "error":
reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, "no-redirect"));
finalize();
return;
case "manual":
if (locationURL !== null) {
try {
headers.set("Location", locationURL);
} catch (err) {
reject(err);
}
}
break;
case "follow":
if (locationURL === null) {
break;
}
if (request.counter >= request.follow) {
reject(new FetchError(`maximum redirect reached at: ${request.url}`, "max-redirect"));
finalize();
return;
}
const requestOpts = {
headers: new Headers(request.headers),
follow: request.follow,
counter: request.counter + 1,
agent: request.agent,
compress: request.compress,
method: request.method,
body: request.body,
signal: request.signal,
timeout: request.timeout,
size: request.size
};
if (!isDomainOrSubdomain(request.url, locationURL)) {
for (const name of ["authorization", "www-authenticate", "cookie", "cookie2"]) {
requestOpts.headers.delete(name);
}
}
if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect"));
finalize();
return;
}
if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === "POST") {
requestOpts.method = "GET";
requestOpts.body = void 0;
requestOpts.headers.delete("content-length");
}
resolve(fetch2(new Request(locationURL, requestOpts)));
finalize();
return;
}
}
res.once("end", function() {
if (signal)
signal.removeEventListener("abort", abortAndFinalize);
});
let body = res.pipe(new PassThrough$1());
const response_options = {
url: request.url,
status: res.statusCode,
statusText: res.statusMessage,
headers,
size: request.size,
timeout: request.timeout,
counter: request.counter
};
const codings = headers.get("Content-Encoding");
if (!request.compress || request.method === "HEAD" || codings === null || res.statusCode === 204 || res.statusCode === 304) {
response = new Response(body, response_options);
resolve(response);
return;
}
const zlibOptions = {
flush: zlib.Z_SYNC_FLUSH,
finishFlush: zlib.Z_SYNC_FLUSH
};
if (codings == "gzip" || codings == "x-gzip") {
body = body.pipe(zlib.createGunzip(zlibOptions));
response = new Response(body, response_options);
resolve(response);
return;
}
if (codings == "deflate" || codings == "x-deflate") {
const raw = res.pipe(new PassThrough$1());
raw.once("data", function(chunk) {
if ((chunk[0] & 15) === 8) {
body = body.pipe(zlib.createInflate());
} else {
body = body.pipe(zlib.createInflateRaw());
}
response = new Response(body, response_options);
resolve(response);
});
return;
}
if (codings == "br" && typeof zlib.createBrotliDecompress === "function") {
body = body.pipe(zlib.createBrotliDecompress());
response = new Response(body, response_options);
resolve(response);
return;
}
response = new Response(body, response_options);
resolve(response);
});
writeToStream(req, request);
});
}
fetch2.isRedirect = function(code) {
return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
};
fetch2.Promise = global.Promise;
module2.exports = exports = fetch2;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = exports;
exports.Headers = Headers;
exports.Request = Request;
exports.Response = Response;
exports.FetchError = FetchError;
}
});
// node_modules/deprecation/dist-node/index.js
var require_dist_node3 = __commonJS({
"node_modules/deprecation/dist-node/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Deprecation = class extends Error {
constructor(message) {
super(message);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = "Deprecation";
}
};
exports.Deprecation = Deprecation;
}
});
// node_modules/wrappy/wrappy.js
var require_wrappy = __commonJS({
"node_modules/wrappy/wrappy.js"(exports, 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"(exports, 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/request-error/dist-node/index.js
var require_dist_node4 = __commonJS({
"node_modules/@octokit/request-error/dist-node/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function _interopDefault(ex) {
return ex && typeof ex === "object" && "default" in ex ? ex["default"] : ex;
}
var deprecation = require_dist_node3();
var once = _interopDefault(require_once());
var logOnceCode = once((deprecation2) => console.warn(deprecation2));
var logOnceHeaders = once((deprecation2) => console.warn(deprecation2));
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(/ .*$/, " [REDACTED]")
});
}
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 deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
return statusCode;
}
});
Object.defineProperty(this, "headers", {
get() {
logOnceHeaders(new deprecation.Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`."));
return headers || {};
}
});
}
};
exports.RequestError = RequestError;
}
});
// node_modules/@octokit/request/dist-node/index.js
var require_dist_node5 = __commonJS({
"node_modules/@octokit/request/dist-node/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function _interopDefault(ex) {
return ex && typeof ex === "object" && "default" in ex ? ex["default"] : ex;
}
var endpoint = require_dist_node2();
var universalUserAgent = require_dist_node();
var isPlainObject = require_is_plain_object();
var nodeFetch = _interopDefault(require_lib3());
3 years ago
var requestError = require_dist_node4();
var VERSION = "5.6.3";
function getBufferResponse(response) {
return response.arrayBuffer();
}
function fetchWrapper(requestOptions) {
const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console;
if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {
requestOptions.body = JSON.stringify(requestOptions.body);
}
let headers = {};
let status;
let url;
const fetch2 = requestOptions.request && requestOptions.request.fetch || nodeFetch;
return fetch2(requestOptions.url, Object.assign(
{
method: requestOptions.method,
body: requestOptions.body,
headers: requestOptions.headers,
redirect: requestOptions.redirect
},
requestOptions.request
)).then(async (response) => {
3 years ago
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 requestError.RequestError(response.statusText, status, {
response: {
url,
status,
headers,
data: void 0
},
request: requestOptions
});
}
if (status === 304) {
throw new requestError.RequestError("Not modified", status, {
response: {
url,
status,
headers,
data: await getResponseData(response)
},
request: requestOptions
});
}
if (status >= 400) {
const data = await getResponseData(response);
const error = new requestError.RequestError(toErrorMessage(data), status, {
response: {
url,
status,
headers,
data
},
request: requestOptions
});
throw error;
}
return getResponseData(response);
}).then((data) => {
return {
status,
url,
headers,
data
};
}).catch((error) => {
if (error instanceof requestError.RequestError)
throw error;
throw new requestError.RequestError(error.message, 500, {
request: requestOptions
});
});
}
async function getResponseData(response) {
const contentType = response.headers.get("content-type");
if (/application\/json/.test(contentType)) {
return response.json();
}
if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) {
return response.text();
}
return getBufferResponse(response);
}
function toErrorMessage(data) {
if (typeof data === "string")
return data;
if ("message" in data) {
if (Array.isArray(data.errors)) {
return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`;
}
return data.message;
}
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(endpoint.endpoint, {
headers: {
"user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}`
}
});
exports.request = request;
}
});
// node_modules/@octokit/graphql/dist-node/index.js
var require_dist_node6 = __commonJS({
"node_modules/@octokit/graphql/dist-node/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var request = require_dist_node5();
var universalUserAgent = require_dist_node();
var VERSION = "4.8.0";
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(request$1, newDefaults) {
const newRequest = request$1.defaults(newDefaults);
const newApi = (query, options) => {
return graphql(newRequest, query, options);
};
return Object.assign(newApi, {
defaults: withDefaults.bind(null, newRequest),
endpoint: request.request.endpoint
});
}
var graphql$1 = withDefaults(request.request, {
headers: {
"user-agent": `octokit-graphql.js/${VERSION} ${universalUserAgent.getUserAgent()}`
},
method: "POST",
url: "/graphql"
});
function withCustomRequest(customRequest) {
return withDefaults(customRequest, {
method: "POST",
url: "/graphql"
});
}
exports.GraphqlResponseError = GraphqlResponseError;
exports.graphql = graphql$1;
exports.withCustomRequest = withCustomRequest;
}
});
// node_modules/@octokit/auth-token/dist-node/index.js
var require_dist_node7 = __commonJS({
"node_modules/@octokit/auth-token/dist-node/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
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)
});
};
exports.createTokenAuth = createTokenAuth;
}
});
// node_modules/@octokit/core/dist-node/index.js
var require_dist_node8 = __commonJS({
"node_modules/@octokit/core/dist-node/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var universalUserAgent = require_dist_node();
var beforeAfterHook = require_before_after_hook();
var request = require_dist_node5();
var graphql = require_dist_node6();
var authToken = require_dist_node7();
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null)
return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0)
continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null)
return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0)
continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key))
continue;
target[key] = source[key];
}
}
return target;
}
var VERSION = "3.6.0";
var _excluded = ["authStrategy"];
var Octokit = class {
constructor(options = {}) {
const hook = new beforeAfterHook.Collection();
const requestDefaults = {
baseUrl: request.request.endpoint.DEFAULTS.baseUrl,
headers: {},
request: Object.assign({}, options.request, {
hook: hook.bind(null, "request")
}),
mediaType: {
previews: [],
format: ""
}
};
requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" ");
if (options.baseUrl) {
requestDefaults.baseUrl = options.baseUrl;
}
if (options.previews) {
requestDefaults.mediaType.previews = options.previews;
}
if (options.timeZone) {
requestDefaults.headers["time-zone"] = options.timeZone;
}
this.request = request.request.defaults(requestDefaults);
this.graphql = graphql.withCustomRequest(this.request).defaults(requestDefaults);
this.log = Object.assign({
debug: () => {
},
info: () => {
},
warn: console.warn.bind(console),
error: console.error.bind(console)
}, options.log);
this.hook = hook;
if (!options.authStrategy) {
if (!options.auth) {
this.auth = async () => ({
type: "unauthenticated"
});
} else {
const auth = authToken.createTokenAuth(options.auth);
hook.wrap("request", auth.hook);
this.auth = auth;
}
} else {
const {
authStrategy
} = options, otherOptions = _objectWithoutProperties(options, _excluded);
const auth = authStrategy(Object.assign({
request: this.request,
log: this.log,
octokit: this,
octokitOptions: otherOptions
}, options.auth));
hook.wrap("request", auth.hook);
this.auth = auth;
}
const classConstructor = this.constructor;
classConstructor.plugins.forEach((plugin) => {
Object.assign(this, plugin(this, options));
});
}
static defaults(defaults) {
const OctokitWithDefaults = class extends this {
constructor(...args) {
const options = args[0] || {};
if (typeof defaults === "function") {
super(defaults(options));
return;
}
super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? {
userAgent: `${options.userAgent} ${defaults.userAgent}`
} : null));
}
};
return OctokitWithDefaults;
}
static plugin(...newPlugins) {
var _a;
const currentPlugins = this.plugins;
const NewOctokit = (_a = class extends this {
}, _a.plugins = currentPlugins.concat(newPlugins.filter((plugin) => !currentPlugins.includes(plugin))), _a);
return NewOctokit;
}
};
Octokit.VERSION = VERSION;
Octokit.plugins = [];
exports.Octokit = Octokit;
}
});
// node_modules/@octokit/plugin-rest-endpoint-methods/dist-node/index.js
var require_dist_node9 = __commonJS({
"node_modules/@octokit/plugin-rest-endpoint-methods/dist-node/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function(key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var Endpoints = {
actions: {
addCustomLabelsToSelfHostedRunnerForOrg: ["POST /orgs/{org}/actions/runners/{runner_id}/labels"],
addCustomLabelsToSelfHostedRunnerForRepo: ["POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],
3 years ago
addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],
approveWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"],
cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"],
createOrUpdateEnvironmentSecret: ["PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"],
createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"],
createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"],
createRegistrationTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/registration-token"],
createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"],
createRemoveTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/remove-token"],
createWorkflowDispatch: ["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"],
deleteActionsCacheById: ["DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}"],
deleteActionsCacheByKey: ["DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}"],
3 years ago
deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],
deleteEnvironmentSecret: ["DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"],
deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"],
deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"],
deleteSelfHostedRunnerFromRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"],
deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"],
deleteWorkflowRunLogs: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],
disableSelectedRepositoryGithubActionsOrganization: ["DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"],
disableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"],
downloadArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"],
downloadJobLogsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"],
downloadWorkflowRunAttemptLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs"],
downloadWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],
enableSelectedRepositoryGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"],
enableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"],
getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"],
getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"],
getActionsCacheUsageByRepoForOrg: ["GET /orgs/{org}/actions/cache/usage-by-repository"],
getActionsCacheUsageForEnterprise: ["GET /enterprises/{enterprise}/actions/cache/usage"],
getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"],
3 years ago
getAllowedActionsOrganization: ["GET /orgs/{org}/actions/permissions/selected-actions"],
getAllowedActionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"],
getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],
getEnvironmentPublicKey: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key"],
getEnvironmentSecret: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"],
getGithubActionsDefaultWorkflowPermissionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/workflow"],
getGithubActionsDefaultWorkflowPermissionsOrganization: ["GET /orgs/{org}/actions/permissions/workflow"],
getGithubActionsDefaultWorkflowPermissionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions/workflow"],
3 years ago
getGithubActionsPermissionsOrganization: ["GET /orgs/{org}/actions/permissions"],
getGithubActionsPermissionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions"],
getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"],
getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"],
getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"],
getPendingDeploymentsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],
getRepoPermissions: ["GET /repos/{owner}/{repo}/actions/permissions", {}, {
renamed: ["actions", "getGithubActionsPermissionsRepository"]
}],
getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"],
getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
getReviewsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"],
getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"],
getSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"],
getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"],
getWorkflowAccessToRepository: ["GET /repos/{owner}/{repo}/actions/permissions/access"],
3 years ago
getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"],
getWorkflowRunAttempt: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"],
getWorkflowRunUsage: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"],
getWorkflowUsage: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"],
listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"],
listEnvironmentSecrets: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets"],
listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"],
listJobsForWorkflowRunAttempt: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"],
listLabelsForSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}/labels"],
listLabelsForSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],
3 years ago
listOrgSecrets: ["GET /orgs/{org}/actions/secrets"],
listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"],
listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"],
listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"],
listRunnerApplicationsForRepo: ["GET /repos/{owner}/{repo}/actions/runners/downloads"],
listSelectedReposForOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"],
listSelectedRepositoriesEnabledGithubActionsOrganization: ["GET /orgs/{org}/actions/permissions/repositories"],
listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"],
listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"],
listWorkflowRunArtifacts: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"],
listWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"],
listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"],
reRunJobForWorkflowRun: ["POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun"],
reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"],
reRunWorkflowFailedJobs: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs"],
removeAllCustomLabelsFromSelfHostedRunnerForOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}/labels"],
removeAllCustomLabelsFromSelfHostedRunnerForRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],
removeCustomLabelFromSelfHostedRunnerForOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}"],
removeCustomLabelFromSelfHostedRunnerForRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}"],
3 years ago
removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],
reviewPendingDeploymentsForRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],
setAllowedActionsOrganization: ["PUT /orgs/{org}/actions/permissions/selected-actions"],
setAllowedActionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"],
setCustomLabelsForSelfHostedRunnerForOrg: ["PUT /orgs/{org}/actions/runners/{runner_id}/labels"],
setCustomLabelsForSelfHostedRunnerForRepo: ["PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],
setGithubActionsDefaultWorkflowPermissionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/workflow"],
setGithubActionsDefaultWorkflowPermissionsOrganization: ["PUT /orgs/{org}/actions/permissions/workflow"],
setGithubActionsDefaultWorkflowPermissionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/workflow"],
3 years ago
setGithubActionsPermissionsOrganization: ["PUT /orgs/{org}/actions/permissions"],
setGithubActionsPermissionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions"],
setSelectedReposForOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"],
setSelectedRepositoriesEnabledGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories"],
setWorkflowAccessToRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/access"]
3 years ago
},
activity: {
checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"],
deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"],
deleteThreadSubscription: ["DELETE /notifications/threads/{thread_id}/subscription"],
getFeeds: ["GET /feeds"],
getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"],
getThread: ["GET /notifications/threads/{thread_id}"],
getThreadSubscriptionForAuthenticatedUser: ["GET /notifications/threads/{thread_id}/subscription"],
listEventsForAuthenticatedUser: ["GET /users/{username}/events"],
listNotificationsForAuthenticatedUser: ["GET /notifications"],
listOrgEventsForAuthenticatedUser: ["GET /users/{username}/events/orgs/{org}"],
listPublicEvents: ["GET /events"],
listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"],
listPublicEventsForUser: ["GET /users/{username}/events/public"],
listPublicOrgEvents: ["GET /orgs/{org}/events"],
listReceivedEventsForUser: ["GET /users/{username}/received_events"],
listReceivedPublicEventsForUser: ["GET /users/{username}/received_events/public"],
listRepoEvents: ["GET /repos/{owner}/{repo}/events"],
listRepoNotificationsForAuthenticatedUser: ["GET /repos/{owner}/{repo}/notifications"],
listReposStarredByAuthenticatedUser: ["GET /user/starred"],
listReposStarredByUser: ["GET /users/{username}/starred"],
listReposWatchedByUser: ["GET /users/{username}/subscriptions"],
listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"],
listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"],
listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"],
markNotificationsAsRead: ["PUT /notifications"],
markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"],
markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"],
setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"],
setThreadSubscription: ["PUT /notifications/threads/{thread_id}/subscription"],
starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"],
unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"]
},
apps: {
addRepoToInstallation: ["PUT /user/installations/{installation_id}/repositories/{repository_id}", {}, {
renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"]
}],
addRepoToInstallationForAuthenticatedUser: ["PUT /user/installations/{installation_id}/repositories/{repository_id}"],
checkToken: ["POST /applications/{client_id}/token"],
createFromManifest: ["POST /app-manifests/{code}/conversions"],
createInstallationAccessToken: ["POST /app/installations/{installation_id}/access_tokens"],
deleteAuthorization: ["DELETE /applications/{client_id}/grant"],
deleteInstallation: ["DELETE /app/installations/{installation_id}"],
deleteToken: ["DELETE /applications/{client_id}/token"],
getAuthenticated: ["GET /app"],
getBySlug: ["GET /apps/{app_slug}"],
getInstallation: ["GET /app/installations/{installation_id}"],
getOrgInstallation: ["GET /orgs/{org}/installation"],
getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"],
getSubscriptionPlanForAccount: ["GET /marketplace_listing/accounts/{account_id}"],
getSubscriptionPlanForAccountStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}"],
getUserInstallation: ["GET /users/{username}/installation"],
getWebhookConfigForApp: ["GET /app/hook/config"],
getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"],
listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"],
listAccountsForPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"],
listInstallationReposForAuthenticatedUser: ["GET /user/installations/{installation_id}/repositories"],
listInstallations: ["GET /app/installations"],
listInstallationsForAuthenticatedUser: ["GET /user/installations"],
listPlans: ["GET /marketplace_listing/plans"],
listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"],
listReposAccessibleToInstallation: ["GET /installation/repositories"],
listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"],
listSubscriptionsForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed"],
listWebhookDeliveries: ["GET /app/hook/deliveries"],
redeliverWebhookDelivery: ["POST /app/hook/deliveries/{delivery_id}/attempts"],
removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}", {}, {
renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"]
}],
removeRepoFromInstallationForAuthenticatedUser: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}"],
resetToken: ["PATCH /applications/{client_id}/token"],
revokeInstallationAccessToken: ["DELETE /installation/token"],
scopeToken: ["POST /applications/{client_id}/token/scoped"],
suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"],
unsuspendInstallation: ["DELETE /app/installations/{installation_id}/suspended"],
updateWebhookConfigForApp: ["PATCH /app/hook/config"]
},
billing: {
getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"],
getGithubActionsBillingUser: ["GET /users/{username}/settings/billing/actions"],
getGithubAdvancedSecurityBillingGhe: ["GET /enterprises/{enterprise}/settings/billing/advanced-security"],
getGithubAdvancedSecurityBillingOrg: ["GET /orgs/{org}/settings/billing/advanced-security"],
3 years ago
getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"],
getGithubPackagesBillingUser: ["GET /users/{username}/settings/billing/packages"],
getSharedStorageBillingOrg: ["GET /orgs/{org}/settings/billing/shared-storage"],
getSharedStorageBillingUser: ["GET /users/{username}/settings/billing/shared-storage"]
},
checks: {
create: ["POST /repos/{owner}/{repo}/check-runs"],
createSuite: ["POST /repos/{owner}/{repo}/check-suites"],
get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"],
getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"],
listAnnotations: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"],
listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"],
listForSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"],
listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"],
rerequestRun: ["POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest"],
rerequestSuite: ["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"],
setSuitesPreferences: ["PATCH /repos/{owner}/{repo}/check-suites/preferences"],
update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"]
},
codeScanning: {
deleteAnalysis: ["DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"],
getAlert: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", {}, {
renamedParameters: {
alert_id: "alert_number"
}
}],
getAnalysis: ["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"],
getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"],
listAlertInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"],
listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"],
3 years ago
listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"],
listAlertsInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", {}, {
renamed: ["codeScanning", "listAlertInstances"]
}],
listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"],
updateAlert: ["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"],
uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"]
},
codesOfConduct: {
getAllCodesOfConduct: ["GET /codes_of_conduct"],
getConductCode: ["GET /codes_of_conduct/{key}"]
},
codespaces: {
addRepositoryForSecretForAuthenticatedUser: ["PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],
codespaceMachinesForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}/machines"],
createForAuthenticatedUser: ["POST /user/codespaces"],
createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],
createOrUpdateSecretForAuthenticatedUser: ["PUT /user/codespaces/secrets/{secret_name}"],
createWithPrForAuthenticatedUser: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces"],
createWithRepoForAuthenticatedUser: ["POST /repos/{owner}/{repo}/codespaces"],
deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"],
deleteFromOrganization: ["DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}"],
deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],
deleteSecretForAuthenticatedUser: ["DELETE /user/codespaces/secrets/{secret_name}"],
exportForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/exports"],
getExportDetailsForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}/exports/{export_id}"],
getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"],
getPublicKeyForAuthenticatedUser: ["GET /user/codespaces/secrets/public-key"],
getRepoPublicKey: ["GET /repos/{owner}/{repo}/codespaces/secrets/public-key"],
getRepoSecret: ["GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],
getSecretForAuthenticatedUser: ["GET /user/codespaces/secrets/{secret_name}"],
listDevcontainersInRepositoryForAuthenticatedUser: ["GET /repos/{owner}/{repo}/codespaces/devcontainers"],
listForAuthenticatedUser: ["GET /user/codespaces"],
listInOrganization: ["GET /orgs/{org}/codespaces", {}, {
renamedParameters: {
org_id: "org"
}
}],
listInRepositoryForAuthenticatedUser: ["GET /repos/{owner}/{repo}/codespaces"],
listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"],
listRepositoriesForSecretForAuthenticatedUser: ["GET /user/codespaces/secrets/{secret_name}/repositories"],
listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"],
removeRepositoryForSecretForAuthenticatedUser: ["DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],
repoMachinesForAuthenticatedUser: ["GET /repos/{owner}/{repo}/codespaces/machines"],
setRepositoriesForSecretForAuthenticatedUser: ["PUT /user/codespaces/secrets/{secret_name}/repositories"],
startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"],
stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"],
stopInOrganization: ["POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop"],
updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"]
},
dependabot: {
addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],
createOrUpdateOrgSecret: ["PUT /orgs/{org}/dependabot/secrets/{secret_name}"],
createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],
deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"],
deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],
getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"],
getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"],
getRepoPublicKey: ["GET /repos/{owner}/{repo}/dependabot/secrets/public-key"],
getRepoSecret: ["GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],
listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"],
listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"],
listSelectedReposForOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories"],
removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],
setSelectedReposForOrgSecret: ["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories"]
},
dependencyGraph: {
createRepositorySnapshot: ["POST /repos/{owner}/{repo}/dependency-graph/snapshots"],
diffRange: ["GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}"]
},
3 years ago
emojis: {
get: ["GET /emojis"]
},
enterpriseAdmin: {
addCustomLabelsToSelfHostedRunnerForEnterprise: ["POST /enterprises/{enterprise}/actions/runners/{runner_id}/labels"],
3 years ago
disableSelectedOrganizationGithubActionsEnterprise: ["DELETE /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"],
enableSelectedOrganizationGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"],
getAllowedActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/selected-actions"],
getGithubActionsPermissionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions"],
getServerStatistics: ["GET /enterprise-installation/{enterprise_or_org}/server-statistics"],
listLabelsForSelfHostedRunnerForEnterprise: ["GET /enterprises/{enterprise}/actions/runners/{runner_id}/labels"],
3 years ago
listSelectedOrganizationsEnabledGithubActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/organizations"],
removeAllCustomLabelsFromSelfHostedRunnerForEnterprise: ["DELETE /enterprises/{enterprise}/actions/runners/{runner_id}/labels"],
removeCustomLabelFromSelfHostedRunnerForEnterprise: ["DELETE /enterprises/{enterprise}/actions/runners/{runner_id}/labels/{name}"],
3 years ago
setAllowedActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/selected-actions"],
setCustomLabelsForSelfHostedRunnerForEnterprise: ["PUT /enterprises/{enterprise}/actions/runners/{runner_id}/labels"],
3 years ago
setGithubActionsPermissionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions"],
setSelectedOrganizationsEnabledGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations"]
},
gists: {
checkIsStarred: ["GET /gists/{gist_id}/star"],
create: ["POST /gists"],
createComment: ["POST /gists/{gist_id}/comments"],
delete: ["DELETE /gists/{gist_id}"],
deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"],
fork: ["POST /gists/{gist_id}/forks"],
get: ["GET /gists/{gist_id}"],
getComment: ["GET /gists/{gist_id}/comments/{comment_id}"],
getRevision: ["GET /gists/{gist_id}/{sha}"],
list: ["GET /gists"],
listComments: ["GET /gists/{gist_id}/comments"],
listCommits: ["GET /gists/{gist_id}/commits"],
listForUser: ["GET /users/{username}/gists"],
listForks: ["GET /gists/{gist_id}/forks"],
listPublic: ["GET /gists/public"],
listStarred: ["GET /gists/starred"],
star: ["PUT /gists/{gist_id}/star"],
unstar: ["DELETE /gists/{gist_id}/star"],
update: ["PATCH /gists/{gist_id}"],
updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"]
},
git: {
createBlob: ["POST /repos/{owner}/{repo}/git/blobs"],
createCommit: ["POST /repos/{owner}/{repo}/git/commits"],
createRef: ["POST /repos/{owner}/{repo}/git/refs"],
createTag: ["POST /repos/{owner}/{repo}/git/tags"],
createTree: ["POST /repos/{owner}/{repo}/git/trees"],
deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"],
getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"],
getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"],
getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"],
getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"],
getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"],
listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"],
updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"]
},
gitignore: {
getAllTemplates: ["GET /gitignore/templates"],
getTemplate: ["GET /gitignore/templates/{name}"]
},
interactions: {
getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"],
getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"],
getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"],
getRestrictionsForYourPublicRepos: ["GET /user/interaction-limits", {}, {
renamed: ["interactions", "getRestrictionsForAuthenticatedUser"]
}],
removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"],
removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"],
removeRestrictionsForRepo: ["DELETE /repos/{owner}/{repo}/interaction-limits"],
removeRestrictionsForYourPublicRepos: ["DELETE /user/interaction-limits", {}, {
renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"]
}],
setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"],
setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"],
setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"],
setRestrictionsForYourPublicRepos: ["PUT /user/interaction-limits", {}, {
renamed: ["interactions", "setRestrictionsForAuthenticatedUser"]
}]
},
issues: {
addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"],
addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"],
checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"],
create: ["POST /repos/{owner}/{repo}/issues"],
createComment: ["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"],
createLabel: ["POST /repos/{owner}/{repo}/labels"],
createMilestone: ["POST /repos/{owner}/{repo}/milestones"],
deleteComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"],
deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"],
deleteMilestone: ["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"],
get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"],
getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"],
getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"],
getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"],
getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"],
list: ["GET /issues"],
listAssignees: ["GET /repos/{owner}/{repo}/assignees"],
listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"],
listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"],
listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"],
listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"],
listEventsForTimeline: ["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"],
listForAuthenticatedUser: ["GET /user/issues"],
listForOrg: ["GET /orgs/{org}/issues"],
listForRepo: ["GET /repos/{owner}/{repo}/issues"],
listLabelsForMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"],
listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"],
listLabelsOnIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"],
listMilestones: ["GET /repos/{owner}/{repo}/milestones"],
lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"],
removeAllLabels: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"],
removeAssignees: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"],
removeLabel: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"],
setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"],
unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"],
update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"],
updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"],
updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"],
updateMilestone: ["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"]
},
licenses: {
get: ["GET /licenses/{license}"],
getAllCommonlyUsed: ["GET /licenses"],
getForRepo: ["GET /repos/{owner}/{repo}/license"]
},
markdown: {
render: ["POST /markdown"],
renderRaw: ["POST /markdown/raw", {
headers: {
"content-type": "text/plain; charset=utf-8"
}
}]
},
meta: {
get: ["GET /meta"],
getOctocat: ["GET /octocat"],
getZen: ["GET /zen"],
root: ["GET /"]
},
migrations: {
cancelImport: ["DELETE /repos/{owner}/{repo}/import"],
deleteArchiveForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/archive"],
deleteArchiveForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/archive"],
downloadArchiveForOrg: ["GET /orgs/{org}/migrations/{migration_id}/archive"],
getArchiveForAuthenticatedUser: ["GET /user/migrations/{migration_id}/archive"],
getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"],
getImportStatus: ["GET /repos/{owner}/{repo}/import"],
getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"],
getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"],
getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"],
listForAuthenticatedUser: ["GET /user/migrations"],
listForOrg: ["GET /orgs/{org}/migrations"],
listReposForAuthenticatedUser: ["GET /user/migrations/{migration_id}/repositories"],
listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"],
listReposForUser: ["GET /user/migrations/{migration_id}/repositories", {}, {
renamed: ["migrations", "listReposForAuthenticatedUser"]
}],
mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"],
setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"],
startForAuthenticatedUser: ["POST /user/migrations"],
startForOrg: ["POST /orgs/{org}/migrations"],
startImport: ["PUT /repos/{owner}/{repo}/import"],
unlockRepoForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock"],
unlockRepoForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock"],
updateImport: ["PATCH /repos/{owner}/{repo}/import"]
},
orgs: {
blockUser: ["PUT /orgs/{org}/blocks/{username}"],
cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"],
checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"],
checkMembershipForUser: ["GET /orgs/{org}/members/{username}"],
checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"],
convertMemberToOutsideCollaborator: ["PUT /orgs/{org}/outside_collaborators/{username}"],
createInvitation: ["POST /orgs/{org}/invitations"],
createWebhook: ["POST /orgs/{org}/hooks"],
deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"],
get: ["GET /orgs/{org}"],
getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"],
getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"],
getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"],
getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"],
getWebhookDelivery: ["GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"],
list: ["GET /organizations"],
listAppInstallations: ["GET /orgs/{org}/installations"],
listBlockedUsers: ["GET /orgs/{org}/blocks"],
listCustomRoles: ["GET /organizations/{organization_id}/custom_roles"],
3 years ago
listFailedInvitations: ["GET /orgs/{org}/failed_invitations"],
listForAuthenticatedUser: ["GET /user/orgs"],
listForUser: ["GET /users/{username}/orgs"],
listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"],
listMembers: ["GET /orgs/{org}/members"],
listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"],
listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"],
listPendingInvitations: ["GET /orgs/{org}/invitations"],
listPublicMembers: ["GET /orgs/{org}/public_members"],
listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"],
listWebhooks: ["GET /orgs/{org}/hooks"],
pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"],
redeliverWebhookDelivery: ["POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],
removeMember: ["DELETE /orgs/{org}/members/{username}"],
removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"],
removeOutsideCollaborator: ["DELETE /orgs/{org}/outside_collaborators/{username}"],
removePublicMembershipForAuthenticatedUser: ["DELETE /orgs/{org}/public_members/{username}"],
setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"],
setPublicMembershipForAuthenticatedUser: ["PUT /orgs/{org}/public_members/{username}"],
unblockUser: ["DELETE /orgs/{org}/blocks/{username}"],
update: ["PATCH /orgs/{org}"],
updateMembershipForAuthenticatedUser: ["PATCH /user/memberships/orgs/{org}"],
updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"],
updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"]
},
packages: {
deletePackageForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}"],
deletePackageForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}"],
deletePackageForUser: ["DELETE /users/{username}/packages/{package_type}/{package_name}"],
deletePackageVersionForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],
deletePackageVersionForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
deletePackageVersionForUser: ["DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
getAllPackageVersionsForAPackageOwnedByAnOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions", {}, {
renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"]
}],
getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions", {}, {
renamed: ["packages", "getAllPackageVersionsForPackageOwnedByAuthenticatedUser"]
}],
getAllPackageVersionsForPackageOwnedByAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions"],
getAllPackageVersionsForPackageOwnedByOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"],
getAllPackageVersionsForPackageOwnedByUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions"],
getPackageForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}"],
getPackageForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}"],
getPackageForUser: ["GET /users/{username}/packages/{package_type}/{package_name}"],
getPackageVersionForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],
getPackageVersionForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
getPackageVersionForUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
listPackagesForAuthenticatedUser: ["GET /user/packages"],
listPackagesForOrganization: ["GET /orgs/{org}/packages"],
listPackagesForUser: ["GET /users/{username}/packages"],
restorePackageForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/restore{?token}"],
restorePackageForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"],
restorePackageForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}"],
restorePackageVersionForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],
restorePackageVersionForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],
restorePackageVersionForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"]
},
projects: {
addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"],
createCard: ["POST /projects/columns/{column_id}/cards"],
createColumn: ["POST /projects/{project_id}/columns"],
createForAuthenticatedUser: ["POST /user/projects"],
createForOrg: ["POST /orgs/{org}/projects"],
createForRepo: ["POST /repos/{owner}/{repo}/projects"],
delete: ["DELETE /projects/{project_id}"],
deleteCard: ["DELETE /projects/columns/cards/{card_id}"],
deleteColumn: ["DELETE /projects/columns/{column_id}"],
get: ["GET /projects/{project_id}"],
getCard: ["GET /projects/columns/cards/{card_id}"],
getColumn: ["GET /projects/columns/{column_id}"],
getPermissionForUser: ["GET /projects/{project_id}/collaborators/{username}/permission"],
listCards: ["GET /projects/columns/{column_id}/cards"],
listCollaborators: ["GET /projects/{project_id}/collaborators"],
listColumns: ["GET /projects/{project_id}/columns"],
listForOrg: ["GET /orgs/{org}/projects"],
listForRepo: ["GET /repos/{owner}/{repo}/projects"],
listForUser: ["GET /users/{username}/projects"],
moveCard: ["POST /projects/columns/cards/{card_id}/moves"],
moveColumn: ["POST /projects/columns/{column_id}/moves"],
removeCollaborator: ["DELETE /projects/{project_id}/collaborators/{username}"],
update: ["PATCH /projects/{project_id}"],
updateCard: ["PATCH /projects/columns/cards/{card_id}"],
updateColumn: ["PATCH /projects/columns/{column_id}"]
},
pulls: {
checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"],
create: ["POST /repos/{owner}/{repo}/pulls"],
createReplyForReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"],
createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],
createReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"],
deletePendingReview: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],
deleteReviewComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"],
dismissReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"],
get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"],
getReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],
getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"],
list: ["GET /repos/{owner}/{repo}/pulls"],
listCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"],
listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"],
listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"],
listRequestedReviewers: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],
listReviewComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"],
listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"],
listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],
merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"],
removeRequestedReviewers: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],
requestReviewers: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],
submitReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"],
update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"],
updateBranch: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch"],
updateReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],
updateReviewComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"]
},
rateLimit: {
get: ["GET /rate_limit"]
},
reactions: {
createForCommitComment: ["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions"],
createForIssue: ["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions"],
createForIssueComment: ["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],
createForPullRequestReviewComment: ["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],
createForRelease: ["POST /repos/{owner}/{repo}/releases/{release_id}/reactions"],
createForTeamDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],
createForTeamDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"],
deleteForCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}"],
deleteForIssue: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}"],
deleteForIssueComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}"],
deleteForPullRequestComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}"],
deleteForRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}"],
3 years ago
deleteForTeamDiscussion: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}"],
deleteForTeamDiscussionComment: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}"],
listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"],
listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"],
listForIssueComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],
listForPullRequestReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],
listForRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}/reactions"],
3 years ago
listForTeamDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],
listForTeamDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"]
},
repos: {
acceptInvitation: ["PATCH /user/repository_invitations/{invitation_id}", {}, {
renamed: ["repos", "acceptInvitationForAuthenticatedUser"]
}],
acceptInvitationForAuthenticatedUser: ["PATCH /user/repository_invitations/{invitation_id}"],
addAppAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, {
mapToData: "apps"
}],
addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"],
addStatusCheckContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, {
mapToData: "contexts"
}],
addTeamAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, {
mapToData: "teams"
}],
addUserAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, {
mapToData: "users"
}],
checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"],
checkVulnerabilityAlerts: ["GET /repos/{owner}/{repo}/vulnerability-alerts"],
codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"],
3 years ago
compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"],
compareCommitsWithBasehead: ["GET /repos/{owner}/{repo}/compare/{basehead}"],
createAutolink: ["POST /repos/{owner}/{repo}/autolinks"],
createCommitComment: ["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"],
createCommitSignatureProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],
createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"],
createDeployKey: ["POST /repos/{owner}/{repo}/keys"],
createDeployment: ["POST /repos/{owner}/{repo}/deployments"],
createDeploymentStatus: ["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],
createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"],
createForAuthenticatedUser: ["POST /user/repos"],
createFork: ["POST /repos/{owner}/{repo}/forks"],
createInOrg: ["POST /orgs/{org}/repos"],
createOrUpdateEnvironment: ["PUT /repos/{owner}/{repo}/environments/{environment_name}"],
createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"],
createPagesSite: ["POST /repos/{owner}/{repo}/pages"],
createRelease: ["POST /repos/{owner}/{repo}/releases"],
createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"],
3 years ago
createUsingTemplate: ["POST /repos/{template_owner}/{template_repo}/generate"],
createWebhook: ["POST /repos/{owner}/{repo}/hooks"],
declineInvitation: ["DELETE /user/repository_invitations/{invitation_id}", {}, {
renamed: ["repos", "declineInvitationForAuthenticatedUser"]
}],
declineInvitationForAuthenticatedUser: ["DELETE /user/repository_invitations/{invitation_id}"],
delete: ["DELETE /repos/{owner}/{repo}"],
deleteAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],
deleteAdminBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
deleteAnEnvironment: ["DELETE /repos/{owner}/{repo}/environments/{environment_name}"],
deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"],
deleteBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"],
deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"],
deleteCommitSignatureProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],
deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"],
deleteDeployment: ["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"],
deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"],
deleteInvitation: ["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"],
deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"],
deletePullRequestReviewProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],
deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"],
deleteReleaseAsset: ["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"],
deleteTagProtection: ["DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}"],
3 years ago
deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"],
disableAutomatedSecurityFixes: ["DELETE /repos/{owner}/{repo}/automated-security-fixes"],
disableLfsForRepo: ["DELETE /repos/{owner}/{repo}/lfs"],
disableVulnerabilityAlerts: ["DELETE /repos/{owner}/{repo}/vulnerability-alerts"],
downloadArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}", {}, {
renamed: ["repos", "downloadZipballArchive"]
}],
downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"],
downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"],
enableAutomatedSecurityFixes: ["PUT /repos/{owner}/{repo}/automated-security-fixes"],
enableLfsForRepo: ["PUT /repos/{owner}/{repo}/lfs"],
enableVulnerabilityAlerts: ["PUT /repos/{owner}/{repo}/vulnerability-alerts"],
generateReleaseNotes: ["POST /repos/{owner}/{repo}/releases/generate-notes"],
get: ["GET /repos/{owner}/{repo}"],
getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],
getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"],
getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"],
getAllTopics: ["GET /repos/{owner}/{repo}/topics"],
3 years ago
getAppsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"],
getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"],
getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"],
getBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection"],
getClones: ["GET /repos/{owner}/{repo}/traffic/clones"],
getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"],
getCollaboratorPermissionLevel: ["GET /repos/{owner}/{repo}/collaborators/{username}/permission"],
getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"],
getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"],
getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"],
getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"],
getCommitSignatureProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],
getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"],
getContent: ["GET /repos/{owner}/{repo}/contents/{path}"],
getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"],
getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"],
getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"],
getDeploymentStatus: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"],
getEnvironment: ["GET /repos/{owner}/{repo}/environments/{environment_name}"],
getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"],
getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"],
getPages: ["GET /repos/{owner}/{repo}/pages"],
getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"],
getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"],
getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"],
getPullRequestReviewProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],
getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"],
getReadme: ["GET /repos/{owner}/{repo}/readme"],
getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"],
getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"],
getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"],
getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"],
getStatusChecksProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],
getTeamsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"],
getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"],
getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"],
getUsersWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"],
getViews: ["GET /repos/{owner}/{repo}/traffic/views"],
getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"],
getWebhookConfigForRepo: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"],
getWebhookDelivery: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"],
listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"],
listBranches: ["GET /repos/{owner}/{repo}/branches"],
listBranchesForHeadCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"],
listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"],
listCommentsForCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"],
listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"],
listCommitStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses"],
listCommits: ["GET /repos/{owner}/{repo}/commits"],
listContributors: ["GET /repos/{owner}/{repo}/contributors"],
listDeployKeys: ["GET /repos/{owner}/{repo}/keys"],
listDeploymentStatuses: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],
listDeployments: ["GET /repos/{owner}/{repo}/deployments"],
listForAuthenticatedUser: ["GET /user/repos"],
listForOrg: ["GET /orgs/{org}/repos"],
listForUser: ["GET /users/{username}/repos"],
listForks: ["GET /repos/{owner}/{repo}/forks"],
listInvitations: ["GET /repos/{owner}/{repo}/invitations"],
listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"],
listLanguages: ["GET /repos/{owner}/{repo}/languages"],
listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"],
listPublic: ["GET /repositories"],
listPullRequestsAssociatedWithCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"],
listReleaseAssets: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets"],
listReleases: ["GET /repos/{owner}/{repo}/releases"],
listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"],
3 years ago
listTags: ["GET /repos/{owner}/{repo}/tags"],
listTeams: ["GET /repos/{owner}/{repo}/teams"],
listWebhookDeliveries: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"],
listWebhooks: ["GET /repos/{owner}/{repo}/hooks"],
merge: ["POST /repos/{owner}/{repo}/merges"],
mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"],
pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"],
redeliverWebhookDelivery: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],
removeAppAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, {
mapToData: "apps"
}],
removeCollaborator: ["DELETE /repos/{owner}/{repo}/collaborators/{username}"],
removeStatusCheckContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, {
mapToData: "contexts"
}],
removeStatusCheckProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],
removeTeamAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, {
mapToData: "teams"
}],
removeUserAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, {
mapToData: "users"
}],
renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"],
replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"],
3 years ago
requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"],
setAdminBranchProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
setAppAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, {
mapToData: "apps"
}],
setStatusCheckContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, {
mapToData: "contexts"
}],
setTeamAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, {
mapToData: "teams"
}],
setUserAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, {
mapToData: "users"
}],
testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"],
transfer: ["POST /repos/{owner}/{repo}/transfer"],
update: ["PATCH /repos/{owner}/{repo}"],
updateBranchProtection: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection"],
updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"],
updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"],
updateInvitation: ["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"],
updatePullRequestReviewProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],
updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"],
updateReleaseAsset: ["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"],
updateStatusCheckPotection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, {
renamed: ["repos", "updateStatusCheckProtection"]
}],
updateStatusCheckProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],
updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"],
updateWebhookConfigForRepo: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"],
uploadReleaseAsset: ["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", {
baseUrl: "https://uploads.github.com"
}]
},
search: {
code: ["GET /search/code"],
commits: ["GET /search/commits"],
issuesAndPullRequests: ["GET /search/issues"],
labels: ["GET /search/labels"],
repos: ["GET /search/repositories"],
topics: ["GET /search/topics"],
3 years ago
users: ["GET /search/users"]
},
secretScanning: {
getAlert: ["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"],
listAlertsForEnterprise: ["GET /enterprises/{enterprise}/secret-scanning/alerts"],
3 years ago
listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"],
listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"],
listLocationsForAlert: ["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations"],
3 years ago
updateAlert: ["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"]
},
teams: {
addOrUpdateMembershipForUserInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"],
addOrUpdateProjectPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}"],
addOrUpdateRepoPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],
checkPermissionsForProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}"],
checkPermissionsForRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],
create: ["POST /orgs/{org}/teams"],
createDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],
createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"],
deleteDiscussionCommentInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],
deleteDiscussionInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],
deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"],
getByName: ["GET /orgs/{org}/teams/{team_slug}"],
getDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],
getDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],
getMembershipForUserInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"],
list: ["GET /orgs/{org}/teams"],
listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"],
listDiscussionCommentsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],
listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"],
listForAuthenticatedUser: ["GET /user/teams"],
listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"],
listPendingInvitationsInOrg: ["GET /orgs/{org}/teams/{team_slug}/invitations"],
listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"],
listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"],
removeMembershipForUserInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"],
removeProjectInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"],
removeRepoInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],
updateDiscussionCommentInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],
updateDiscussionInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],
updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"]
},
users: {
addEmailForAuthenticated: ["POST /user/emails", {}, {
renamed: ["users", "addEmailForAuthenticatedUser"]
}],
addEmailForAuthenticatedUser: ["POST /user/emails"],
block: ["PUT /user/blocks/{username}"],
checkBlocked: ["GET /user/blocks/{username}"],
checkFollowingForUser: ["GET /users/{username}/following/{target_user}"],
checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"],
createGpgKeyForAuthenticated: ["POST /user/gpg_keys", {}, {
renamed: ["users", "createGpgKeyForAuthenticatedUser"]
}],
createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"],
createPublicSshKeyForAuthenticated: ["POST /user/keys", {}, {
renamed: ["users", "createPublicSshKeyForAuthenticatedUser"]
}],
createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"],
deleteEmailForAuthenticated: ["DELETE /user/emails", {}, {
renamed: ["users", "deleteEmailForAuthenticatedUser"]
}],
deleteEmailForAuthenticatedUser: ["DELETE /user/emails"],
deleteGpgKeyForAuthenticated: ["DELETE /user/gpg_keys/{gpg_key_id}", {}, {
renamed: ["users", "deleteGpgKeyForAuthenticatedUser"]
}],
deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"],
deletePublicSshKeyForAuthenticated: ["DELETE /user/keys/{key_id}", {}, {
renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"]
}],
deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"],
follow: ["PUT /user/following/{username}"],
getAuthenticated: ["GET /user"],
getByUsername: ["GET /users/{username}"],
getContextForUser: ["GET /users/{username}/hovercard"],
getGpgKeyForAuthenticated: ["GET /user/gpg_keys/{gpg_key_id}", {}, {
renamed: ["users", "getGpgKeyForAuthenticatedUser"]
}],
getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"],
getPublicSshKeyForAuthenticated: ["GET /user/keys/{key_id}", {}, {
renamed: ["users", "getPublicSshKeyForAuthenticatedUser"]
}],
getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"],
list: ["GET /users"],
listBlockedByAuthenticated: ["GET /user/blocks", {}, {
renamed: ["users", "listBlockedByAuthenticatedUser"]
}],
listBlockedByAuthenticatedUser: ["GET /user/blocks"],
listEmailsForAuthenticated: ["GET /user/emails", {}, {
renamed: ["users", "listEmailsForAuthenticatedUser"]
}],
listEmailsForAuthenticatedUser: ["GET /user/emails"],
listFollowedByAuthenticated: ["GET /user/following", {}, {
renamed: ["users", "listFollowedByAuthenticatedUser"]
}],
listFollowedByAuthenticatedUser: ["GET /user/following"],
listFollowersForAuthenticatedUser: ["GET /user/followers"],
listFollowersForUser: ["GET /users/{username}/followers"],
listFollowingForUser: ["GET /users/{username}/following"],
listGpgKeysForAuthenticated: ["GET /user/gpg_keys", {}, {
renamed: ["users", "listGpgKeysForAuthenticatedUser"]
}],
listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"],
listGpgKeysForUser: ["GET /users/{username}/gpg_keys"],
listPublicEmailsForAuthenticated: ["GET /user/public_emails", {}, {
renamed: ["users", "listPublicEmailsForAuthenticatedUser"]
}],
listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"],
listPublicKeysForUser: ["GET /users/{username}/keys"],
listPublicSshKeysForAuthenticated: ["GET /user/keys", {}, {
renamed: ["users", "listPublicSshKeysForAuthenticatedUser"]
}],
listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"],
setPrimaryEmailVisibilityForAuthenticated: ["PATCH /user/email/visibility", {}, {
renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"]
}],
setPrimaryEmailVisibilityForAuthenticatedUser: ["PATCH /user/email/visibility"],
unblock: ["DELETE /user/blocks/{username}"],
unfollow: ["DELETE /user/following/{username}"],
updateAuthenticated: ["PATCH /user"]
}
};
var VERSION = "5.16.2";
3 years ago
function endpointsToMethods(octokit, endpointsMap) {
const newMethods = {};
for (const [scope, endpoints] of Object.entries(endpointsMap)) {
for (const [methodName, endpoint] of Object.entries(endpoints)) {
const [route, defaults, decorations] = endpoint;
const [method, url] = route.split(/ /);
const endpointDefaults = Object.assign({
method,
url
}, defaults);
if (!newMethods[scope]) {
newMethods[scope] = {};
}
const scopeMethods = newMethods[scope];
if (decorations) {
scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations);
continue;
}
scopeMethods[methodName] = octokit.request.defaults(endpointDefaults);
}
}
return newMethods;
}
function decorate(octokit, scope, methodName, defaults, decorations) {
const requestWithDefaults = octokit.request.defaults(defaults);
function withDecorations(...args) {
let options = requestWithDefaults.endpoint.merge(...args);
if (decorations.mapToData) {
options = Object.assign({}, options, {
data: options[decorations.mapToData],
[decorations.mapToData]: void 0
});
return requestWithDefaults(options);
}
if (decorations.renamed) {
const [newScope, newMethodName] = decorations.renamed;
octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`);
}
if (decorations.deprecated) {
octokit.log.warn(decorations.deprecated);
}
if (decorations.renamedParameters) {
const options2 = requestWithDefaults.endpoint.merge(...args);
for (const [name, alias] of Object.entries(decorations.renamedParameters)) {
if (name in options2) {
octokit.log.warn(`"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`);
if (!(alias in options2)) {
options2[alias] = options2[name];
}
delete options2[name];
}
}
return requestWithDefaults(options2);
}
return requestWithDefaults(...args);
}
return Object.assign(withDecorations, requestWithDefaults);
}
function restEndpointMethods(octokit) {
const api = endpointsToMethods(octokit, Endpoints);
return {
rest: api
};
}
restEndpointMethods.VERSION = VERSION;
function legacyRestEndpointMethods(octokit) {
const api = endpointsToMethods(octokit, Endpoints);
return _objectSpread2(_objectSpread2({}, api), {}, {
rest: api
});
}
legacyRestEndpointMethods.VERSION = VERSION;
exports.legacyRestEndpointMethods = legacyRestEndpointMethods;
exports.restEndpointMethods = restEndpointMethods;
}
});
// node_modules/@octokit/plugin-paginate-rest/dist-node/index.js
var require_dist_node10 = __commonJS({
"node_modules/@octokit/plugin-paginate-rest/dist-node/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var VERSION = "2.21.3";
3 years ago
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
})), keys.push.apply(keys, symbols);
3 years ago
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), true).forEach(function(key) {
_defineProperty(target, key, source[key]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
3 years ago
}
return target;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function normalizePaginatedListResponse(response) {
if (!response.data) {
return _objectSpread2(_objectSpread2({}, response), {}, {
data: []
});
}
const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data);
if (!responseNeedsNormalization)
return response;
const incompleteResults = response.data.incomplete_results;
const repositorySelection = response.data.repository_selection;
const totalCount = response.data.total_count;
delete response.data.incomplete_results;
delete response.data.repository_selection;
delete response.data.total_count;
const namespaceKey = Object.keys(response.data)[0];
const data = response.data[namespaceKey];
response.data = data;
if (typeof incompleteResults !== "undefined") {
response.data.incomplete_results = incompleteResults;
}
if (typeof repositorySelection !== "undefined") {
response.data.repository_selection = repositorySelection;
}
response.data.total_count = totalCount;
return response;
}
function iterator(octokit, route, parameters) {
const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);
const requestMethod = typeof route === "function" ? route : octokit.request;
const method = options.method;
const headers = options.headers;
let url = options.url;
return {
[Symbol.asyncIterator]: () => ({
async next() {
if (!url)
return {
done: true
};
try {
const response = await requestMethod({
method,
url,
headers
});
const normalizedResponse = normalizePaginatedListResponse(response);
url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1];
return {
value: normalizedResponse
};
} catch (error) {
if (error.status !== 409)
throw error;
url = "";
return {
value: {
status: 200,
headers: {},
data: []
}
};
}
}
})
};
}
function paginate(octokit, route, parameters, mapFn) {
if (typeof parameters === "function") {
mapFn = parameters;
parameters = void 0;
}
return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn);
}
function gather(octokit, results, iterator2, mapFn) {
return iterator2.next().then((result) => {
if (result.done) {
return results;
}
let earlyExit = false;
function done() {
earlyExit = true;
}
results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data);
if (earlyExit) {
return results;
}
return gather(octokit, results, iterator2, mapFn);
});
}
var composePaginateRest = Object.assign(paginate, {
iterator
});
var paginatingEndpoints = ["GET /app/hook/deliveries", "GET /app/installations", "GET /applications/grants", "GET /authorizations", "GET /enterprises/{enterprise}/actions/permissions/organizations", "GET /enterprises/{enterprise}/actions/runner-groups", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners", "GET /enterprises/{enterprise}/actions/runners", "GET /enterprises/{enterprise}/audit-log", "GET /enterprises/{enterprise}/secret-scanning/alerts", "GET /enterprises/{enterprise}/settings/billing/advanced-security", "GET /events", "GET /gists", "GET /gists/public", "GET /gists/starred", "GET /gists/{gist_id}/comments", "GET /gists/{gist_id}/commits", "GET /gists/{gist_id}/forks", "GET /installation/repositories", "GET /issues", "GET /licenses", "GET /marketplace_listing/plans", "GET /marketplace_listing/plans/{plan_id}/accounts", "GET /marketplace_listing/stubbed/plans", "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", "GET /networks/{owner}/{repo}/events", "GET /notifications", "GET /organizations", "GET /orgs/{org}/actions/cache/usage-by-repository", "GET /orgs/{org}/actions/permissions/repositories", "GET /orgs/{org}/actions/runner-groups", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners", "GET /orgs/{org}/actions/runners", "GET /orgs/{org}/actions/secrets", "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", "GET /orgs/{org}/audit-log", "GET /orgs/{org}/blocks", "GET /orgs/{org}/code-scanning/alerts", "GET /orgs/{org}/codespaces", "GET /orgs/{org}/credential-authorizations", "GET /orgs/{org}/dependabot/secrets", "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", "GET /orgs/{org}/events", "GET /orgs/{org}/external-groups", "GET /orgs/{org}/failed_invitations", "GET /orgs/{org}/hooks", "GET /orgs/{org}/hooks/{hook_id}/deliveries", "GET /orgs/{org}/installations", "GET /orgs/{org}/invitations", "GET /orgs/{org}/invitations/{invitation_id}/teams", "GET /orgs/{org}/issues", "GET /orgs/{org}/members", "GET /orgs/{org}/migrations", "GET /orgs/{org}/migrations/{migration_id}/repositories", "GET /orgs/{org}/outside_collaborators", "GET /orgs/{org}/packages", "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", "GET /orgs/{org}/projects", "GET /orgs/{org}/public_members", "GET /orgs/{org}/repos", "GET /orgs/{org}/secret-scanning/alerts", "GET /orgs/{org}/settings/billing/advanced-security", "GET /orgs/{org}/team-sync/groups", "GET /orgs/{org}/teams", "GET /orgs/{org}/teams/{team_slug}/discussions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/invitations", "GET /orgs/{org}/teams/{team_slug}/members", "GET /orgs/{org}/teams/{team_slug}/projects", "GET /orgs/{org}/teams/{team_slug}/repos", "GET /orgs/{org}/teams/{team_slug}/teams", "GET /projects/columns/{column_id}/cards", "GET /projects/{project_id}/collaborators", "GET /projects/{project_id}/columns", "GET /repos/{owner}/{repo}/actions/artifacts", "GET /repos/{owner}/{repo}/actions/caches", "GET /repos/{owner}/{repo}/actions/runners", "GET /repos/{owner}/{repo}/actions/runs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", "GET /repos/{owner}/{repo}/actions/secrets", "GET /repos/{owner}/{repo}/actions/workflows", "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", "GET /repos/{owner}/{repo}/assignees", "GET /repos/{owner}/{repo}/branches", "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", "GET /repos/{owner}/{repo}/code-scanni
3 years ago
function isPaginatingEndpoint(arg) {
if (typeof arg === "string") {
return paginatingEndpoints.includes(arg);
} else {
return false;
}
}
function paginateRest(octokit) {
return {
paginate: Object.assign(paginate.bind(null, octokit), {
iterator: iterator.bind(null, octokit)
})
};
}
paginateRest.VERSION = VERSION;
exports.composePaginateRest = composePaginateRest;
exports.isPaginatingEndpoint = isPaginatingEndpoint;
exports.paginateRest = paginateRest;
exports.paginatingEndpoints = paginatingEndpoints;
}
});
// node_modules/@actions/github/lib/utils.js
var require_utils4 = __commonJS({
"node_modules/@actions/github/lib/utils.js"(exports) {
"use strict";
var __createBinding = exports && exports.__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 __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports && exports.__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))
__createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0;
3 years ago
var Context = __importStar(require_context());
var Utils = __importStar(require_utils2());
var core_1 = require_dist_node8();
var plugin_rest_endpoint_methods_1 = require_dist_node9();
var plugin_paginate_rest_1 = require_dist_node10();
exports.context = new Context.Context();
var baseUrl = Utils.getApiBaseUrl();
exports.defaults = {
3 years ago
baseUrl,
request: {
agent: Utils.getProxyAgent(baseUrl)
}
};
exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults);
3 years ago
function getOctokitOptions(token, options) {
const opts = Object.assign({}, options || {});
const auth = Utils.getAuthString(token, opts);
if (auth) {
opts.auth = auth;
}
return opts;
}
exports.getOctokitOptions = getOctokitOptions;
}
});
// node_modules/@actions/github/lib/github.js
var require_github = __commonJS({
"node_modules/@actions/github/lib/github.js"(exports) {
"use strict";
var __createBinding = exports && exports.__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 __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports && exports.__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))
__createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOctokit = exports.context = void 0;
var Context = __importStar(require_context());
var utils_1 = require_utils4();
exports.context = new Context.Context();
function getOctokit2(token, options, ...additionalPlugins) {
const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins);
return new GitHubWithPlugins(utils_1.getOctokitOptions(token, options));
3 years ago
}
exports.getOctokit = getOctokit2;
}
});
// node_modules/undici/lib/core/symbols.js
var require_symbols = __commonJS({
"node_modules/undici/lib/core/symbols.js"(exports, module2) {
module2.exports = {
kClose: Symbol("close"),
kDestroy: Symbol("destroy"),
kDispatch: Symbol("dispatch"),
kUrl: Symbol("url"),
kWriting: Symbol("writing"),
kResuming: Symbol("resuming"),
kQueue: Symbol("queue"),
kConnect: Symbol("connect"),
kConnecting: Symbol("connecting"),
kHeadersList: Symbol("headers list"),
kKeepAliveDefaultTimeout: Symbol("default keep alive timeout"),
kKeepAliveMaxTimeout: Symbol("max keep alive timeout"),
kKeepAliveTimeoutThreshold: Symbol("keep alive timeout threshold"),
kKeepAliveTimeoutValue: Symbol("keep alive timeout"),
kKeepAlive: Symbol("keep alive"),
kHeadersTimeout: Symbol("headers timeout"),
kBodyTimeout: Symbol("body timeout"),
kServerName: Symbol("server name"),
kHost: Symbol("host"),
kNoRef: Symbol("no ref"),
kBodyUsed: Symbol("used"),
kRunning: Symbol("running"),
kBlocking: Symbol("blocking"),
kPending: Symbol("pending"),
kSize: Symbol("size"),
kBusy: Symbol("busy"),
kQueued: Symbol("queued"),
kFree: Symbol("free"),
kConnected: Symbol("connected"),
kClosed: Symbol("closed"),
kNeedDrain: Symbol("need drain"),
kReset: Symbol("reset"),
kDestroyed: Symbol("destroyed"),
kMaxHeadersSize: Symbol("max headers size"),
kRunningIdx: Symbol("running index"),
kPendingIdx: Symbol("pending index"),
kError: Symbol("error"),
kClients: Symbol("clients"),
kClient: Symbol("client"),
kParser: Symbol("parser"),
kOnDestroyed: Symbol("destroy callbacks"),
kPipelining: Symbol("pipelinig"),
kSocket: Symbol("socket"),
kHostHeader: Symbol("host header"),
kConnector: Symbol("connector"),
kStrictContentLength: Symbol("strict content length"),
kMaxRedirections: Symbol("maxRedirections"),
kMaxRequests: Symbol("maxRequestsPerClient"),
kProxy: Symbol("proxy agent options"),
kCounter: Symbol("socket request counter"),
kInterceptors: Symbol("dispatch interceptors")
3 years ago
};
}
});
// node_modules/undici/lib/core/errors.js
var require_errors = __commonJS({
"node_modules/undici/lib/core/errors.js"(exports, module2) {
"use strict";
var UndiciError = class extends Error {
constructor(message) {
super(message);
this.name = "UndiciError";
this.code = "UND_ERR";
}
};
var ConnectTimeoutError = class extends UndiciError {
constructor(message) {
super(message);
Error.captureStackTrace(this, ConnectTimeoutError);
this.name = "ConnectTimeoutError";
this.message = message || "Connect Timeout Error";
this.code = "UND_ERR_CONNECT_TIMEOUT";
}
};
var HeadersTimeoutError = class extends UndiciError {
constructor(message) {
super(message);
Error.captureStackTrace(this, HeadersTimeoutError);
this.name = "HeadersTimeoutError";
this.message = message || "Headers Timeout Error";
this.code = "UND_ERR_HEADERS_TIMEOUT";
}
};
var HeadersOverflowError = class extends UndiciError {
constructor(message) {
super(message);
Error.captureStackTrace(this, HeadersOverflowError);
this.name = "HeadersOverflowError";
this.message = message || "Headers Overflow Error";
this.code = "UND_ERR_HEADERS_OVERFLOW";
}
};
var BodyTimeoutError = class extends UndiciError {
constructor(message) {
super(message);
Error.captureStackTrace(this, BodyTimeoutError);
this.name = "BodyTimeoutError";
this.message = message || "Body Timeout Error";
this.code = "UND_ERR_BODY_TIMEOUT";
}
};
var ResponseStatusCodeError = class extends UndiciError {
constructor(message, statusCode, headers, body) {
super(message);
Error.captureStackTrace(this, ResponseStatusCodeError);
this.name = "ResponseStatusCodeError";
this.message = message || "Response Status Code Error";
this.code = "UND_ERR_RESPONSE_STATUS_CODE";
this.body = body;
this.status = statusCode;
this.statusCode = statusCode;
this.headers = headers;
}
};
3 years ago
var InvalidArgumentError = class extends UndiciError {
constructor(message) {
super(message);
Error.captureStackTrace(this, InvalidArgumentError);
this.name = "InvalidArgumentError";
this.message = message || "Invalid Argument Error";
this.code = "UND_ERR_INVALID_ARG";
}
};
var InvalidReturnValueError = class extends UndiciError {
constructor(message) {
super(message);
Error.captureStackTrace(this, InvalidReturnValueError);
this.name = "InvalidReturnValueError";
this.message = message || "Invalid Return Value Error";
this.code = "UND_ERR_INVALID_RETURN_VALUE";
}
};
var RequestAbortedError = class extends UndiciError {
constructor(message) {
super(message);
Error.captureStackTrace(this, RequestAbortedError);
this.name = "AbortError";
this.message = message || "Request aborted";
this.code = "UND_ERR_ABORTED";
}
};
var InformationalError = class extends UndiciError {
constructor(message) {
super(message);
Error.captureStackTrace(this, InformationalError);
this.name = "InformationalError";
this.message = message || "Request information";
this.code = "UND_ERR_INFO";
}
};
var RequestContentLengthMismatchError = class extends UndiciError {
constructor(message) {
super(message);
Error.captureStackTrace(this, RequestContentLengthMismatchError);
this.name = "RequestContentLengthMismatchError";
this.message = message || "Request body length does not match content-length header";
this.code = "UND_ERR_REQ_CONTENT_LENGTH_MISMATCH";
}
};
var ResponseContentLengthMismatchError = class extends UndiciError {
constructor(message) {
super(message);
Error.captureStackTrace(this, ResponseContentLengthMismatchError);
this.name = "ResponseContentLengthMismatchError";
this.message = message || "Response body length does not match content-length header";
this.code = "UND_ERR_RES_CONTENT_LENGTH_MISMATCH";
}
};
var ClientDestroyedError = class extends UndiciError {
constructor(message) {
super(message);
Error.captureStackTrace(this, ClientDestroyedError);
this.name = "ClientDestroyedError";
this.message = message || "The client is destroyed";
this.code = "UND_ERR_DESTROYED";
}
};
var ClientClosedError = class extends UndiciError {
constructor(message) {
super(message);
Error.captureStackTrace(this, ClientClosedError);
this.name = "ClientClosedError";
this.message = message || "The client is closed";
this.code = "UND_ERR_CLOSED";
}
};
var SocketError = class extends UndiciError {
constructor(message, socket) {
super(message);
Error.captureStackTrace(this, SocketError);
this.name = "SocketError";
this.message = message || "Socket error";
this.code = "UND_ERR_SOCKET";
this.socket = socket;
}
};
var NotSupportedError = class extends UndiciError {
constructor(message) {
super(message);
Error.captureStackTrace(this, NotSupportedError);
this.name = "NotSupportedError";
this.message = message || "Not supported error";
this.code = "UND_ERR_NOT_SUPPORTED";
}
};
var BalancedPoolMissingUpstreamError = class extends UndiciError {
constructor(message) {
super(message);
Error.captureStackTrace(this, NotSupportedError);
this.name = "MissingUpstreamError";
this.message = message || "No upstream has been added to the BalancedPool";
this.code = "UND_ERR_BPL_MISSING_UPSTREAM";
}
};
var HTTPParserError = class extends Error {
constructor(message, code, data) {
super(message);
Error.captureStackTrace(this, HTTPParserError);
this.name = "HTTPParserError";
this.code = code ? `HPE_${code}` : void 0;
this.data = data ? data.toString() : void 0;
}
};
module2.exports = {
HTTPParserError,
UndiciError,
HeadersTimeoutError,
HeadersOverflowError,
BodyTimeoutError,
RequestContentLengthMismatchError,
ConnectTimeoutError,
ResponseStatusCodeError,
3 years ago
InvalidArgumentError,
InvalidReturnValueError,
RequestAbortedError,
ClientDestroyedError,
ClientClosedError,
InformationalError,
SocketError,
NotSupportedError,
ResponseContentLengthMismatchError,
BalancedPoolMissingUpstreamError
};
}
});
// node_modules/undici/lib/core/util.js
var require_util = __commonJS({
"node_modules/undici/lib/core/util.js"(exports, module2) {
"use strict";
var assert = require("assert");
var { kDestroyed, kBodyUsed } = require_symbols();
var { IncomingMessage } = require("http");
var stream = require("stream");
var net = require("net");
var { InvalidArgumentError } = require_errors();
var { Blob } = require("buffer");
var nodeUtil = require("util");
var { stringify } = require("querystring");
3 years ago
function nop() {
}
function isStream(obj) {
return obj && typeof obj.pipe === "function";
}
function isBlobLike(object) {
return Blob && object instanceof Blob || object && typeof object === "object" && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && /^(Blob|File)$/.test(object[Symbol.toStringTag]);
}
function buildURL(url, queryParams) {
if (url.includes("?") || url.includes("#")) {
throw new Error('Query params cannot be passed when url already contains "?" or "#".');
}
const stringified = stringify(queryParams);
if (stringified) {
url += "?" + stringified;
}
return url;
}
3 years ago
function parseURL(url) {
if (typeof url === "string") {
url = new URL(url);
}
if (!url || typeof url !== "object") {
throw new InvalidArgumentError("invalid url");
}
if (url.port != null && url.port !== "" && !Number.isFinite(parseInt(url.port))) {
throw new InvalidArgumentError("invalid port");
}
if (url.path != null && typeof url.path !== "string") {
throw new InvalidArgumentError("invalid path");
}
if (url.pathname != null && typeof url.pathname !== "string") {
throw new InvalidArgumentError("invalid pathname");
}
if (url.hostname != null && typeof url.hostname !== "string") {
throw new InvalidArgumentError("invalid hostname");
}
if (url.origin != null && typeof url.origin !== "string") {
throw new InvalidArgumentError("invalid origin");
}
if (!/^https?:/.test(url.origin || url.protocol)) {
throw new InvalidArgumentError("invalid protocol");
}
if (!(url instanceof URL)) {
const port = url.port != null ? url.port : url.protocol === "https:" ? 443 : 80;
let origin = url.origin != null ? url.origin : `${url.protocol}//${url.hostname}:${port}`;
let path3 = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`;
if (origin.endsWith("/")) {
origin = origin.substring(0, origin.length - 1);
}
if (path3 && !path3.startsWith("/")) {
path3 = `/${path3}`;
}
url = new URL(origin + path3);
3 years ago
}
return url;
}
function parseOrigin(url) {
url = parseURL(url);
if (url.pathname !== "/" || url.search || url.hash) {
throw new InvalidArgumentError("invalid url");
}
return url;
}
function getHostname(host) {
if (host[0] === "[") {
const idx2 = host.indexOf("]");
assert(idx2 !== -1);
return host.substr(1, idx2 - 1);
}
const idx = host.indexOf(":");
if (idx === -1)
return host;
return host.substr(0, idx);
}
function getServerName(host) {
if (!host) {
return null;
}
assert.strictEqual(typeof host, "string");
const servername = getHostname(host);
if (net.isIP(servername)) {
return "";
}
return servername;
}
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
function isAsyncIterable(obj) {
return !!(obj != null && typeof obj[Symbol.asyncIterator] === "function");
}
function isIterable(obj) {
return !!(obj != null && (typeof obj[Symbol.iterator] === "function" || typeof obj[Symbol.asyncIterator] === "function"));
}
function bodyLength(body) {
if (body == null) {
return 0;
} else if (isStream(body)) {
const state = body._readableState;
return state && state.ended === true && Number.isFinite(state.length) ? state.length : null;
} else if (isBlobLike(body)) {
return body.size != null ? body.size : null;
} else if (isBuffer(body)) {
return body.byteLength;
}
return null;
}
function isDestroyed(stream2) {
return !stream2 || !!(stream2.destroyed || stream2[kDestroyed]);
}
function isReadableAborted(stream2) {
const state = stream2 && stream2._readableState;
return isDestroyed(stream2) && state && !state.endEmitted;
}
function destroy(stream2, err) {
if (!isStream(stream2) || isDestroyed(stream2)) {
return;
}
if (typeof stream2.destroy === "function") {
if (Object.getPrototypeOf(stream2).constructor === IncomingMessage) {
stream2.socket = null;
}
stream2.destroy(err);
} else if (err) {
process.nextTick((stream3, err2) => {
stream3.emit("error", err2);
}, stream2, err);
}
if (stream2.destroyed !== true) {
stream2[kDestroyed] = true;
}
}
var KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/;
function parseKeepAliveTimeout(val) {
const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR);
return m ? parseInt(m[1], 10) * 1e3 : null;
}
function parseHeaders(headers, obj = {}) {
for (let i = 0; i < headers.length; i += 2) {
const key = headers[i].toString().toLowerCase();
let val = obj[key];
if (!val) {
if (Array.isArray(headers[i + 1])) {
obj[key] = headers[i + 1];
} else {
obj[key] = headers[i + 1].toString();
}
3 years ago
} else {
if (!Array.isArray(val)) {
val = [val];
obj[key] = val;
}
val.push(headers[i + 1].toString());
}
}
return obj;
}
function parseRawHeaders(headers) {
return headers.map((header) => header.toString());
}
function isBuffer(buffer) {
return buffer instanceof Uint8Array || Buffer.isBuffer(buffer);
}
function validateHandler(handler, method, upgrade) {
if (!handler || typeof handler !== "object") {
throw new InvalidArgumentError("handler must be an object");
}
if (typeof handler.onConnect !== "function") {
throw new InvalidArgumentError("invalid onConnect method");
}
if (typeof handler.onError !== "function") {
throw new InvalidArgumentError("invalid onError method");
}
if (typeof handler.onBodySent !== "function" && handler.onBodySent !== void 0) {
throw new InvalidArgumentError("invalid onBodySent method");
}
if (upgrade || method === "CONNECT") {
if (typeof handler.onUpgrade !== "function") {
throw new InvalidArgumentError("invalid onUpgrade method");
}
} else {
if (typeof handler.onHeaders !== "function") {
throw new InvalidArgumentError("invalid onHeaders method");
}
if (typeof handler.onData !== "function") {
throw new InvalidArgumentError("invalid onData method");
}
if (typeof handler.onComplete !== "function") {
throw new InvalidArgumentError("invalid onComplete method");
}
}
}
function isDisturbed(body) {
return !!(body && (stream.isDisturbed ? stream.isDisturbed(body) || body[kBodyUsed] : body[kBodyUsed] || body.readableDidRead || body._readableState && body._readableState.dataEmitted || isReadableAborted(body)));
}
function isErrored(body) {
return !!(body && (stream.isErrored ? stream.isErrored(body) : /state: 'errored'/.test(
nodeUtil.inspect(body)
)));
3 years ago
}
function isReadable(body) {
return !!(body && (stream.isReadable ? stream.isReadable(body) : /state: 'readable'/.test(
nodeUtil.inspect(body)
)));
3 years ago
}
function getSocketInfo(socket) {
return {
localAddress: socket.localAddress,
localPort: socket.localPort,
remoteAddress: socket.remoteAddress,
remotePort: socket.remotePort,
remoteFamily: socket.remoteFamily,
timeout: socket.timeout,
bytesWritten: socket.bytesWritten,
bytesRead: socket.bytesRead
};
}
var ReadableStream;
function ReadableStreamFrom(iterable) {
if (!ReadableStream) {
ReadableStream = require("stream/web").ReadableStream;
}
if (ReadableStream.from) {
return ReadableStream.from(iterable);
}
let iterator;
return new ReadableStream(
{
async start() {
iterator = iterable[Symbol.asyncIterator]();
},
async pull(controller) {
const { done, value } = await iterator.next();
if (done) {
queueMicrotask(() => {
controller.close();
});
} else {
const buf = Buffer.isBuffer(value) ? value : Buffer.from(value);
controller.enqueue(new Uint8Array(buf));
}
return controller.desiredSize > 0;
},
async cancel(reason) {
await iterator.return();
3 years ago
}
},
0
);
3 years ago
}
function isFormDataLike(chunk) {
return chunk && chunk.constructor && chunk.constructor.name === "FormData";
}
var kEnumerableProperty = /* @__PURE__ */ Object.create(null);
kEnumerableProperty.enumerable = true;
module2.exports = {
kEnumerableProperty,
nop,
isDisturbed,
isErrored,
isReadable,
toUSVString: nodeUtil.toUSVString || ((val) => `${val}`),
isReadableAborted,
isBlobLike,
parseOrigin,
parseURL,
getServerName,
isStream,
isIterable,
isAsyncIterable,
isDestroyed,
parseRawHeaders,
parseHeaders,
parseKeepAliveTimeout,
destroy,
bodyLength,
deepClone,
ReadableStreamFrom,
isBuffer,
validateHandler,
getSocketInfo,
isFormDataLike,
buildURL
3 years ago
};
}
});
// node_modules/busboy/lib/utils.js
var require_utils5 = __commonJS({
"node_modules/busboy/lib/utils.js"(exports, module2) {
3 years ago
"use strict";
function parseContentType(str) {
if (str.length === 0)
return;
const params = /* @__PURE__ */ Object.create(null);
let i = 0;
for (; i < str.length; ++i) {
const code = str.charCodeAt(i);
if (TOKEN[code] !== 1) {
if (code !== 47 || i === 0)
return;
break;
}
}
if (i === str.length)
return;
const type = str.slice(0, i).toLowerCase();
const subtypeStart = ++i;
for (; i < str.length; ++i) {
const code = str.charCodeAt(i);
if (TOKEN[code] !== 1) {
if (i === subtypeStart)
return;
if (parseContentTypeParams(str, i, params) === void 0)
return;
break;
}
}
if (i === subtypeStart)
return;
const subtype = str.slice(subtypeStart, i).toLowerCase();
return { type, subtype, params };
}
function parseContentTypeParams(str, i, params) {
while (i < str.length) {
for (; i < str.length; ++i) {
const code = str.charCodeAt(i);
if (code !== 32 && code !== 9)
break;
}
if (i === str.length)
break;
if (str.charCodeAt(i++) !== 59)
return;
for (; i < str.length; ++i) {
const code = str.charCodeAt(i);
if (code !== 32 && code !== 9)
break;
}
if (i === str.length)
return;
let name;
const nameStart = i;
for (; i < str.length; ++i) {
const code = str.charCodeAt(i);
if (TOKEN[code] !== 1) {
if (code !== 61)
return;
break;
}
}
if (i === str.length)
return;
name = str.slice(nameStart, i);
++i;
if (i === str.length)
return;
let value = "";
let valueStart;
if (str.charCodeAt(i) === 34) {
valueStart = ++i;
let escaping = false;
for (; i < str.length; ++i) {
const code = str.charCodeAt(i);
if (code === 92) {
if (escaping) {
valueStart = i;
escaping = false;
} else {
value += str.slice(valueStart, i);
escaping = true;
}
continue;
}
if (code === 34) {
if (escaping) {
valueStart = i;
escaping = false;
continue;
}
value += str.slice(valueStart, i);
break;
}
if (escaping) {
valueStart = i - 1;
escaping = false;
}
if (QDTEXT[code] !== 1)
return;
}
if (i === str.length)
return;
++i;
} else {
valueStart = i;
for (; i < str.length; ++i) {
const code = str.charCodeAt(i);
if (TOKEN[code] !== 1) {
if (i === valueStart)
return;
break;
}
}
value = str.slice(valueStart, i);
}
name = name.toLowerCase();
if (params[name] === void 0)
params[name] = value;
}
return params;
}
function parseDisposition(str, defDecoder) {
if (str.length === 0)
return;
const params = /* @__PURE__ */ Object.create(null);
let i = 0;
for (; i < str.length; ++i) {
const code = str.charCodeAt(i);
if (TOKEN[code] !== 1) {
if (parseDispositionParams(str, i, params, defDecoder) === void 0)
return;
break;
}
}
const type = str.slice(0, i).toLowerCase();
return { type, params };
}
function parseDispositionParams(str, i, params, defDecoder) {
while (i < str.length) {
for (; i < str.length; ++i) {
const code = str.charCodeAt(i);
if (code !== 32 && code !== 9)
break;
}
if (i === str.length)
break;
if (str.charCodeAt(i++) !== 59)
return;
for (; i < str.length; ++i) {
const code = str.charCodeAt(i);
if (code !== 32 && code !== 9)
break;
}
if (i === str.length)
return;
let name;
const nameStart = i;
for (; i < str.length; ++i) {
const code = str.charCodeAt(i);
if (TOKEN[code] !== 1) {
if (code === 61)
break;
return;
}
}
if (i === str.length)
return;
let value = "";
let valueStart;
let charset;
name = str.slice(nameStart, i);
if (name.charCodeAt(name.length - 1) === 42) {
const charsetStart = ++i;
for (; i < str.length; ++i) {
const code = str.charCodeAt(i);
if (CHARSET[code] !== 1) {
if (code !== 39)
return;
break;
}
}
if (i === str.length)
return;
charset = str.slice(charsetStart, i);
++i;
for (; i < str.length; ++i) {
const code = str.charCodeAt(i);
if (code === 39)
break;
}
if (i === str.length)
return;
++i;
if (i === str.length)
return;
valueStart = i;
let encode = 0;
for (; i < str.length; ++i) {
const code = str.charCodeAt(i);
if (EXTENDED_VALUE[code] !== 1) {
if (code === 37) {
let hexUpper;
let hexLower;
if (i + 2 < str.length && (hexUpper = HEX_VALUES[str.charCodeAt(i + 1)]) !== -1 && (hexLower = HEX_VALUES[str.charCodeAt(i + 2)]) !== -1) {
const byteVal = (hexUpper << 4) + hexLower;
value += str.slice(valueStart, i);
value += String.fromCharCode(byteVal);
i += 2;
valueStart = i + 1;
if (byteVal >= 128)
encode = 2;
else if (encode === 0)
encode = 1;
continue;
}
return;
}
break;
}
}
value += str.slice(valueStart, i);
value = convertToUTF8(value, charset, encode);
if (value === void 0)
return;
} else {
++i;
if (i === str.length)
return;
if (str.charCodeAt(i) === 34) {
valueStart = ++i;
let escaping = false;
for (; i < str.length; ++i) {
const code = str.charCodeAt(i);
if (code === 92) {
if (escaping) {
valueStart = i;
escaping = false;
} else {
value += str.slice(valueStart, i);
escaping = true;
}
continue;
}
if (code === 34) {
if (escaping) {
valueStart = i;
escaping = false;
continue;
}
value += str.slice(valueStart, i);
break;
}
if (escaping) {
valueStart = i - 1;
escaping = false;
}
if (QDTEXT[code] !== 1)
return;
}
if (i === str.length)
return;
++i;
} else {
valueStart = i;
for (; i < str.length; ++i) {
const code = str.charCodeAt(i);
if (TOKEN[code] !== 1) {
if (i === valueStart)
return;
break;
}
}
value = str.slice(valueStart, i);
}
value = defDecoder(value, 2);
if (value === void 0)
return;
}
name = name.toLowerCase();
if (params[name] === void 0)
params[name] = value;
}
return params;
}
function getDecoder(charset) {
let lc;
while (true) {
switch (charset) {
case "utf-8":
case "utf8":
return decoders.utf8;
case "latin1":
case "ascii":
case "us-ascii":
case "iso-8859-1":
case "iso8859-1":
case "iso88591":
case "iso_8859-1":
case "windows-1252":
case "iso_8859-1:1987":
case "cp1252":
case "x-cp1252":
return decoders.latin1;
case "utf16le":
case "utf-16le":
case "ucs2":
case "ucs-2":
return decoders.utf16le;
case "base64":
return decoders.base64;
default:
if (lc === void 0) {
lc = true;
charset = charset.toLowerCase();
continue;
}
return decoders.other.bind(charset);
}
}
}
var decoders = {
utf8: (data, hint) => {
if (data.length === 0)
return "";
if (typeof data === "string") {
if (hint < 2)
return data;
data = Buffer.from(data, "latin1");
}
return data.utf8Slice(0, data.length);
},
latin1: (data, hint) => {
if (data.length === 0)
return "";
if (typeof data === "string")
return data;
return data.latin1Slice(0, data.length);
},
utf16le: (data, hint) => {
if (data.length === 0)
return "";
if (typeof data === "string")
data = Buffer.from(data, "latin1");
return data.ucs2Slice(0, data.length);
},
base64: (data, hint) => {
if (data.length === 0)
return "";
if (typeof data === "string")
data = Buffer.from(data, "latin1");
return data.base64Slice(0, data.length);
},
other: (data, hint) => {
if (data.length === 0)
return "";
if (typeof data === "string")
data = Buffer.from(data, "latin1");
try {
const decoder = new TextDecoder(exports);
return decoder.decode(data);
} catch {
}
}
};
function convertToUTF8(data, charset, hint) {
const decode = getDecoder(charset);
if (decode)
return decode(data, hint);
}
function basename(path3) {
if (typeof path3 !== "string")
return "";
for (let i = path3.length - 1; i >= 0; --i) {
switch (path3.charCodeAt(i)) {
case 47:
case 92:
path3 = path3.slice(i + 1);
return path3 === ".." || path3 === "." ? "" : path3;
}
}
return path3 === ".." || path3 === "." ? "" : path3;
}
var TOKEN = [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
0,
1,
1,
1,
1,
1,
0,
0,
1,
1,
0,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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 QDTEXT = [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
];
var CHARSET = [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
0,
1,
1,
1,
1,
0,
0,
0,
0,
1,
0,
1,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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 EXTENDED_VALUE = [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
0,
1,
1,
0,
1,
0,
0,
0,
0,
1,
0,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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 HEX_VALUES = [
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
10,
11,
12,
13,
14,
15,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
10,
11,
12,
13,
14,
15,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1
];
module2.exports = {
basename,
convertToUTF8,
getDecoder,
parseContentType,
parseDisposition
};
}
});
// node_modules/streamsearch/lib/sbmh.js
var require_sbmh = __commonJS({
"node_modules/streamsearch/lib/sbmh.js"(exports, module2) {
"use strict";
function memcmp(buf1, pos1, buf2, pos2, num) {
for (let i = 0; i < num; ++i) {
if (buf1[pos1 + i] !== buf2[pos2 + i])
return false;
}
return true;
}
var SBMH = class {
constructor(needle, cb) {
if (typeof cb !== "function")
throw new Error("Missing match callback");
if (typeof needle === "string")
needle = Buffer.from(needle);
else if (!Buffer.isBuffer(needle))
throw new Error(`Expected Buffer for needle, got ${typeof needle}`);
const needleLen = needle.length;
this.maxMatches = Infinity;
this.matches = 0;
this._cb = cb;
this._lookbehindSize = 0;
this._needle = needle;
this._bufPos = 0;
this._lookbehind = Buffer.allocUnsafe(needleLen);
this._occ = [
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen,
needleLen
];
if (needleLen > 1) {
for (let i = 0; i < needleLen - 1; ++i)
this._occ[needle[i]] = needleLen - 1 - i;
}
}
reset() {
this.matches = 0;
this._lookbehindSize = 0;
this._bufPos = 0;
}
push(chunk, pos) {
let result;
if (!Buffer.isBuffer(chunk))
chunk = Buffer.from(chunk, "latin1");
const chunkLen = chunk.length;
this._bufPos = pos || 0;
while (result !== chunkLen && this.matches < this.maxMatches)
result = feed(this, chunk);
return result;
}
destroy() {
const lbSize = this._lookbehindSize;
if (lbSize)
this._cb(false, this._lookbehind, 0, lbSize, false);
this.reset();
}
};
function feed(self, data) {
const len = data.length;
const needle = self._needle;
const needleLen = needle.length;
let pos = -self._lookbehindSize;
const lastNeedleCharPos = needleLen - 1;
const lastNeedleChar = needle[lastNeedleCharPos];
const end = len - needleLen;
const occ = self._occ;
const lookbehind = self._lookbehind;
if (pos < 0) {
while (pos < 0 && pos <= end) {
const nextPos = pos + lastNeedleCharPos;
const ch = nextPos < 0 ? lookbehind[self._lookbehindSize + nextPos] : data[nextPos];
if (ch === lastNeedleChar && matchNeedle(self, data, pos, lastNeedleCharPos)) {
self._lookbehindSize = 0;
++self.matches;
if (pos > -self._lookbehindSize)
self._cb(true, lookbehind, 0, self._lookbehindSize + pos, false);
else
self._cb(true, void 0, 0, 0, true);
return self._bufPos = pos + needleLen;
}
pos += occ[ch];
}
while (pos < 0 && !matchNeedle(self, data, pos, len - pos))
++pos;
if (pos < 0) {
const bytesToCutOff = self._lookbehindSize + pos;
if (bytesToCutOff > 0) {
self._cb(false, lookbehind, 0, bytesToCutOff, false);
}
self._lookbehindSize -= bytesToCutOff;
lookbehind.copy(lookbehind, 0, bytesToCutOff, self._lookbehindSize);
lookbehind.set(data, self._lookbehindSize);
self._lookbehindSize += len;
self._bufPos = len;
return len;
}
self._cb(false, lookbehind, 0, self._lookbehindSize, false);
self._lookbehindSize = 0;
}
pos += self._bufPos;
const firstNeedleChar = needle[0];
while (pos <= end) {
const ch = data[pos + lastNeedleCharPos];
if (ch === lastNeedleChar && data[pos] === firstNeedleChar && memcmp(needle, 0, data, pos, lastNeedleCharPos)) {
++self.matches;
if (pos > 0)
self._cb(true, data, self._bufPos, pos, true);
else
self._cb(true, void 0, 0, 0, true);
return self._bufPos = pos + needleLen;
}
pos += occ[ch];
}
while (pos < len) {
if (data[pos] !== firstNeedleChar || !memcmp(data, pos, needle, 0, len - pos)) {
++pos;
continue;
}
data.copy(lookbehind, 0, pos, len);
self._lookbehindSize = len - pos;
break;
}
if (pos > 0)
self._cb(false, data, self._bufPos, pos < len ? pos : len, true);
self._bufPos = len;
return len;
}
function matchNeedle(self, data, pos, len) {
const lb = self._lookbehind;
const lbSize = self._lookbehindSize;
const needle = self._needle;
for (let i = 0; i < len; ++i, ++pos) {
const ch = pos < 0 ? lb[lbSize + pos] : data[pos];
if (ch !== needle[i])
return false;
}
return true;
}
module2.exports = SBMH;
}
});
// node_modules/busboy/lib/types/multipart.js
var require_multipart = __commonJS({
"node_modules/busboy/lib/types/multipart.js"(exports, module2) {
"use strict";
var { Readable, Writable } = require("stream");
var StreamSearch = require_sbmh();
var {
basename,
convertToUTF8,
getDecoder,
parseContentType,
parseDisposition
} = require_utils5();
var BUF_CRLF = Buffer.from("\r\n");
var BUF_CR = Buffer.from("\r");
var BUF_DASH = Buffer.from("-");
function noop() {
}
var MAX_HEADER_PAIRS = 2e3;
var MAX_HEADER_SIZE = 16 * 1024;
var HPARSER_NAME = 0;
var HPARSER_PRE_OWS = 1;
var HPARSER_VALUE = 2;
var HeaderParser = class {
constructor(cb) {
this.header = /* @__PURE__ */ Object.create(null);
this.pairCount = 0;
this.byteCount = 0;
this.state = HPARSER_NAME;
this.name = "";
this.value = "";
this.crlf = 0;
this.cb = cb;
}
reset() {
this.header = /* @__PURE__ */ Object.create(null);
this.pairCount = 0;
this.byteCount = 0;
this.state = HPARSER_NAME;
this.name = "";
this.value = "";
this.crlf = 0;
}
push(chunk, pos, end) {
let start = pos;
while (pos < end) {
switch (this.state) {
case HPARSER_NAME: {
let done = false;
for (; pos < end; ++pos) {
if (this.byteCount === MAX_HEADER_SIZE)
return -1;
++this.byteCount;
const code = chunk[pos];
if (TOKEN[code] !== 1) {
if (code !== 58)
return -1;
this.name += chunk.latin1Slice(start, pos);
if (this.name.length === 0)
return -1;
++pos;
done = true;
this.state = HPARSER_PRE_OWS;
break;
}
}
if (!done) {
this.name += chunk.latin1Slice(start, pos);
break;
}
}
case HPARSER_PRE_OWS: {
let done = false;
for (; pos < end; ++pos) {
if (this.byteCount === MAX_HEADER_SIZE)
return -1;
++this.byteCount;
const code = chunk[pos];
if (code !== 32 && code !== 9) {
start = pos;
done = true;
this.state = HPARSER_VALUE;
break;
}
}
if (!done)
break;
}
case HPARSER_VALUE:
switch (this.crlf) {
case 0:
for (; pos < end; ++pos) {
if (this.byteCount === MAX_HEADER_SIZE)
return -1;
++this.byteCount;
const code = chunk[pos];
if (FIELD_VCHAR[code] !== 1) {
if (code !== 13)
return -1;
++this.crlf;
break;
}
}
this.value += chunk.latin1Slice(start, pos++);
break;
case 1:
if (this.byteCount === MAX_HEADER_SIZE)
return -1;
++this.byteCount;
if (chunk[pos++] !== 10)
return -1;
++this.crlf;
break;
case 2: {
if (this.byteCount === MAX_HEADER_SIZE)
return -1;
++this.byteCount;
const code = chunk[pos];
if (code === 32 || code === 9) {
start = pos;
this.crlf = 0;
} else {
if (++this.pairCount < MAX_HEADER_PAIRS) {
this.name = this.name.toLowerCase();
if (this.header[this.name] === void 0)
this.header[this.name] = [this.value];
else
this.header[this.name].push(this.value);
}
if (code === 13) {
++this.crlf;
++pos;
} else {
start = pos;
this.crlf = 0;
this.state = HPARSER_NAME;
this.name = "";
this.value = "";
}
}
break;
}
case 3: {
if (this.byteCount === MAX_HEADER_SIZE)
return -1;
++this.byteCount;
if (chunk[pos++] !== 10)
return -1;
const header = this.header;
this.reset();
this.cb(header);
return pos;
}
}
break;
}
}
return pos;
}
};
var FileStream = class extends Readable {
constructor(opts, owner) {
super(opts);
this.truncated = false;
this._readcb = null;
this.once("end", () => {
this._read();
if (--owner._fileEndsLeft === 0 && owner._finalcb) {
const cb = owner._finalcb;
owner._finalcb = null;
process.nextTick(cb);
}
});
}
_read(n) {
const cb = this._readcb;
if (cb) {
this._readcb = null;
cb();
}
}
};
var ignoreData = {
push: (chunk, pos) => {
},
destroy: () => {
}
};
function callAndUnsetCb(self, err) {
const cb = self._writecb;
self._writecb = null;
if (err)
self.destroy(err);
else if (cb)
cb();
}
function nullDecoder(val, hint) {
return val;
}
var Multipart = class extends Writable {
constructor(cfg) {
const streamOpts = {
autoDestroy: true,
emitClose: true,
highWaterMark: typeof cfg.highWaterMark === "number" ? cfg.highWaterMark : void 0
};
super(streamOpts);
if (!cfg.conType.params || typeof cfg.conType.params.boundary !== "string")
throw new Error("Multipart: Boundary not found");
const boundary = cfg.conType.params.boundary;
const paramDecoder = typeof cfg.defParamCharset === "string" && cfg.defParamCharset ? getDecoder(cfg.defParamCharset) : nullDecoder;
const defCharset = cfg.defCharset || "utf8";
const preservePath = cfg.preservePath;
const fileOpts = {
autoDestroy: true,
emitClose: true,
highWaterMark: typeof cfg.fileHwm === "number" ? cfg.fileHwm : void 0
};
const limits = cfg.limits;
const fieldSizeLimit = limits && typeof limits.fieldSize === "number" ? limits.fieldSize : 1 * 1024 * 1024;
const fileSizeLimit = limits && typeof limits.fileSize === "number" ? limits.fileSize : Infinity;
const filesLimit = limits && typeof limits.files === "number" ? limits.files : Infinity;
const fieldsLimit = limits && typeof limits.fields === "number" ? limits.fields : Infinity;
const partsLimit = limits && typeof limits.parts === "number" ? limits.parts : Infinity;
let parts = -1;
let fields = 0;
let files = 0;
let skipPart = false;
this._fileEndsLeft = 0;
this._fileStream = void 0;
this._complete = false;
let fileSize = 0;
let field;
let fieldSize = 0;
let partCharset;
let partEncoding;
let partType;
let partName;
let partTruncated = false;
let hitFilesLimit = false;
let hitFieldsLimit = false;
this._hparser = null;
const hparser = new HeaderParser((header) => {
this._hparser = null;
skipPart = false;
partType = "text/plain";
partCharset = defCharset;
partEncoding = "7bit";
partName = void 0;
partTruncated = false;
let filename;
if (!header["content-disposition"]) {
skipPart = true;
return;
}
const disp = parseDisposition(
header["content-disposition"][0],
paramDecoder
);
if (!disp || disp.type !== "form-data") {
skipPart = true;
return;
}
if (disp.params) {
if (disp.params.name)
partName = disp.params.name;
if (disp.params["filename*"])
filename = disp.params["filename*"];
else if (disp.params.filename)
filename = disp.params.filename;
if (filename !== void 0 && !preservePath)
filename = basename(filename);
}
if (header["content-type"]) {
const conType = parseContentType(header["content-type"][0]);
if (conType) {
partType = `${conType.type}/${conType.subtype}`;
if (conType.params && typeof conType.params.charset === "string")
partCharset = conType.params.charset.toLowerCase();
}
}
if (header["content-transfer-encoding"])
partEncoding = header["content-transfer-encoding"][0].toLowerCase();
if (partType === "application/octet-stream" || filename !== void 0) {
if (files === filesLimit) {
if (!hitFilesLimit) {
hitFilesLimit = true;
this.emit("filesLimit");
}
skipPart = true;
return;
}
++files;
if (this.listenerCount("file") === 0) {
skipPart = true;
return;
}
fileSize = 0;
this._fileStream = new FileStream(fileOpts, this);
++this._fileEndsLeft;
this.emit(
"file",
partName,
this._fileStream,
{
filename,
encoding: partEncoding,
mimeType: partType
}
);
} else {
if (fields === fieldsLimit) {
if (!hitFieldsLimit) {
hitFieldsLimit = true;
this.emit("fieldsLimit");
}
skipPart = true;
return;
}
++fields;
if (this.listenerCount("field") === 0) {
skipPart = true;
return;
}
field = [];
fieldSize = 0;
}
});
let matchPostBoundary = 0;
const ssCb = (isMatch, data, start, end, isDataSafe) => {
retrydata:
while (data) {
if (this._hparser !== null) {
const ret = this._hparser.push(data, start, end);
if (ret === -1) {
this._hparser = null;
hparser.reset();
this.emit("error", new Error("Malformed part header"));
break;
}
start = ret;
}
if (start === end)
break;
if (matchPostBoundary !== 0) {
if (matchPostBoundary === 1) {
switch (data[start]) {
case 45:
matchPostBoundary = 2;
++start;
break;
case 13:
matchPostBoundary = 3;
++start;
break;
default:
matchPostBoundary = 0;
}
if (start === end)
return;
}
if (matchPostBoundary === 2) {
matchPostBoundary = 0;
if (data[start] === 45) {
this._complete = true;
this._bparser = ignoreData;
return;
}
const writecb = this._writecb;
this._writecb = noop;
ssCb(false, BUF_DASH, 0, 1, false);
this._writecb = writecb;
} else if (matchPostBoundary === 3) {
matchPostBoundary = 0;
if (data[start] === 10) {
++start;
if (parts >= partsLimit)
break;
this._hparser = hparser;
if (start === end)
break;
continue retrydata;
} else {
const writecb = this._writecb;
this._writecb = noop;
ssCb(false, BUF_CR, 0, 1, false);
this._writecb = writecb;
}
}
}
if (!skipPart) {
if (this._fileStream) {
let chunk;
const actualLen = Math.min(end - start, fileSizeLimit - fileSize);
if (!isDataSafe) {
chunk = Buffer.allocUnsafe(actualLen);
data.copy(chunk, 0, start, start + actualLen);
} else {
chunk = data.slice(start, start + actualLen);
}
fileSize += chunk.length;
if (fileSize === fileSizeLimit) {
if (chunk.length > 0)
this._fileStream.push(chunk);
this._fileStream.emit("limit");
this._fileStream.truncated = true;
skipPart = true;
} else if (!this._fileStream.push(chunk)) {
if (this._writecb)
this._fileStream._readcb = this._writecb;
this._writecb = null;
}
} else if (field !== void 0) {
let chunk;
const actualLen = Math.min(
end - start,
fieldSizeLimit - fieldSize
);
if (!isDataSafe) {
chunk = Buffer.allocUnsafe(actualLen);
data.copy(chunk, 0, start, start + actualLen);
} else {
chunk = data.slice(start, start + actualLen);
}
fieldSize += actualLen;
field.push(chunk);
if (fieldSize === fieldSizeLimit) {
skipPart = true;
partTruncated = true;
}
}
}
break;
}
if (isMatch) {
matchPostBoundary = 1;
if (this._fileStream) {
this._fileStream.push(null);
this._fileStream = null;
} else if (field !== void 0) {
let data2;
switch (field.length) {
case 0:
data2 = "";
break;
case 1:
data2 = convertToUTF8(field[0], partCharset, 0);
break;
default:
data2 = convertToUTF8(
Buffer.concat(field, fieldSize),
partCharset,
0
);
}
field = void 0;
fieldSize = 0;
this.emit(
"field",
partName,
data2,
{
nameTruncated: false,
valueTruncated: partTruncated,
encoding: partEncoding,
mimeType: partType
}
);
}
if (++parts === partsLimit)
this.emit("partsLimit");
}
};
this._bparser = new StreamSearch(`\r
--${boundary}`, ssCb);
this._writecb = null;
this._finalcb = null;
this.write(BUF_CRLF);
}
static detect(conType) {
return conType.type === "multipart" && conType.subtype === "form-data";
}
_write(chunk, enc, cb) {
this._writecb = cb;
this._bparser.push(chunk, 0);
if (this._writecb)
callAndUnsetCb(this);
}
_destroy(err, cb) {
this._hparser = null;
this._bparser = ignoreData;
if (!err)
err = checkEndState(this);
const fileStream = this._fileStream;
if (fileStream) {
this._fileStream = null;
fileStream.destroy(err);
}
cb(err);
}
_final(cb) {
this._bparser.destroy();
if (!this._complete)
return cb(new Error("Unexpected end of form"));
if (this._fileEndsLeft)
this._finalcb = finalcb.bind(null, this, cb);
else
finalcb(this, cb);
}
};
function finalcb(self, cb, err) {
if (err)
return cb(err);
err = checkEndState(self);
cb(err);
}
function checkEndState(self) {
if (self._hparser)
return new Error("Malformed part header");
const fileStream = self._fileStream;
if (fileStream) {
self._fileStream = null;
fileStream.destroy(new Error("Unexpected end of file"));
}
if (!self._complete)
return new Error("Unexpected end of form");
}
var TOKEN = [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
0,
1,
1,
1,
1,
1,
0,
0,
1,
1,
0,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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 FIELD_VCHAR = [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
];
module2.exports = Multipart;
}
});
// node_modules/busboy/lib/types/urlencoded.js
var require_urlencoded = __commonJS({
"node_modules/busboy/lib/types/urlencoded.js"(exports, module2) {
"use strict";
var { Writable } = require("stream");
var { getDecoder } = require_utils5();
var URLEncoded = class extends Writable {
constructor(cfg) {
const streamOpts = {
autoDestroy: true,
emitClose: true,
highWaterMark: typeof cfg.highWaterMark === "number" ? cfg.highWaterMark : void 0
};
super(streamOpts);
let charset = cfg.defCharset || "utf8";
if (cfg.conType.params && typeof cfg.conType.params.charset === "string")
charset = cfg.conType.params.charset;
this.charset = charset;
const limits = cfg.limits;
this.fieldSizeLimit = limits && typeof limits.fieldSize === "number" ? limits.fieldSize : 1 * 1024 * 1024;
this.fieldsLimit = limits && typeof limits.fields === "number" ? limits.fields : Infinity;
this.fieldNameSizeLimit = limits && typeof limits.fieldNameSize === "number" ? limits.fieldNameSize : 100;
this._inKey = true;
this._keyTrunc = false;
this._valTrunc = false;
this._bytesKey = 0;
this._bytesVal = 0;
this._fields = 0;
this._key = "";
this._val = "";
this._byte = -2;
this._lastPos = 0;
this._encode = 0;
this._decoder = getDecoder(charset);
}
static detect(conType) {
return conType.type === "application" && conType.subtype === "x-www-form-urlencoded";
}
_write(chunk, enc, cb) {
if (this._fields >= this.fieldsLimit)
return cb();
let i = 0;
const len = chunk.length;
this._lastPos = 0;
if (this._byte !== -2) {
i = readPctEnc(this, chunk, i, len);
if (i === -1)
return cb(new Error("Malformed urlencoded form"));
if (i >= len)
return cb();
if (this._inKey)
++this._bytesKey;
else
++this._bytesVal;
}
main:
while (i < len) {
if (this._inKey) {
i = skipKeyBytes(this, chunk, i, len);
while (i < len) {
switch (chunk[i]) {
case 61:
if (this._lastPos < i)
this._key += chunk.latin1Slice(this._lastPos, i);
this._lastPos = ++i;
this._key = this._decoder(this._key, this._encode);
this._encode = 0;
this._inKey = false;
continue main;
case 38:
if (this._lastPos < i)
this._key += chunk.latin1Slice(this._lastPos, i);
this._lastPos = ++i;
this._key = this._decoder(this._key, this._encode);
this._encode = 0;
if (this._bytesKey > 0) {
this.emit(
"field",
this._key,
"",
{
nameTruncated: this._keyTrunc,
valueTruncated: false,
encoding: this.charset,
mimeType: "text/plain"
}
);
}
this._key = "";
this._val = "";
this._keyTrunc = false;
this._valTrunc = false;
this._bytesKey = 0;
this._bytesVal = 0;
if (++this._fields >= this.fieldsLimit) {
this.emit("fieldsLimit");
return cb();
}
continue;
case 43:
if (this._lastPos < i)
this._key += chunk.latin1Slice(this._lastPos, i);
this._key += " ";
this._lastPos = i + 1;
break;
case 37:
if (this._encode === 0)
this._encode = 1;
if (this._lastPos < i)
this._key += chunk.latin1Slice(this._lastPos, i);
this._lastPos = i + 1;
this._byte = -1;
i = readPctEnc(this, chunk, i + 1, len);
if (i === -1)
return cb(new Error("Malformed urlencoded form"));
if (i >= len)
return cb();
++this._bytesKey;
i = skipKeyBytes(this, chunk, i, len);
continue;
}
++i;
++this._bytesKey;
i = skipKeyBytes(this, chunk, i, len);
}
if (this._lastPos < i)
this._key += chunk.latin1Slice(this._lastPos, i);
} else {
i = skipValBytes(this, chunk, i, len);
while (i < len) {
switch (chunk[i]) {
case 38:
if (this._lastPos < i)
this._val += chunk.latin1Slice(this._lastPos, i);
this._lastPos = ++i;
this._inKey = true;
this._val = this._decoder(this._val, this._encode);
this._encode = 0;
if (this._bytesKey > 0 || this._bytesVal > 0) {
this.emit(
"field",
this._key,
this._val,
{
nameTruncated: this._keyTrunc,
valueTruncated: this._valTrunc,
encoding: this.charset,
mimeType: "text/plain"
}
);
}
this._key = "";
this._val = "";
this._keyTrunc = false;
this._valTrunc = false;
this._bytesKey = 0;
this._bytesVal = 0;
if (++this._fields >= this.fieldsLimit) {
this.emit("fieldsLimit");
return cb();
}
continue main;
case 43:
if (this._lastPos < i)
this._val += chunk.latin1Slice(this._lastPos, i);
this._val += " ";
this._lastPos = i + 1;
break;
case 37:
if (this._encode === 0)
this._encode = 1;
if (this._lastPos < i)
this._val += chunk.latin1Slice(this._lastPos, i);
this._lastPos = i + 1;
this._byte = -1;
i = readPctEnc(this, chunk, i + 1, len);
if (i === -1)
return cb(new Error("Malformed urlencoded form"));
if (i >= len)
return cb();
++this._bytesVal;
i = skipValBytes(this, chunk, i, len);
continue;
}
++i;
++this._bytesVal;
i = skipValBytes(this, chunk, i, len);
}
if (this._lastPos < i)
this._val += chunk.latin1Slice(this._lastPos, i);
}
}
cb();
}
_final(cb) {
if (this._byte !== -2)
return cb(new Error("Malformed urlencoded form"));
if (!this._inKey || this._bytesKey > 0 || this._bytesVal > 0) {
if (this._inKey)
this._key = this._decoder(this._key, this._encode);
else
this._val = this._decoder(this._val, this._encode);
this.emit(
"field",
this._key,
this._val,
{
nameTruncated: this._keyTrunc,
valueTruncated: this._valTrunc,
encoding: this.charset,
mimeType: "text/plain"
}
);
}
cb();
}
};
function readPctEnc(self, chunk, pos, len) {
if (pos >= len)
return len;
if (self._byte === -1) {
const hexUpper = HEX_VALUES[chunk[pos++]];
if (hexUpper === -1)
return -1;
if (hexUpper >= 8)
self._encode = 2;
if (pos < len) {
const hexLower = HEX_VALUES[chunk[pos++]];
if (hexLower === -1)
return -1;
if (self._inKey)
self._key += String.fromCharCode((hexUpper << 4) + hexLower);
else
self._val += String.fromCharCode((hexUpper << 4) + hexLower);
self._byte = -2;
self._lastPos = pos;
} else {
self._byte = hexUpper;
}
} else {
const hexLower = HEX_VALUES[chunk[pos++]];
if (hexLower === -1)
return -1;
if (self._inKey)
self._key += String.fromCharCode((self._byte << 4) + hexLower);
else
self._val += String.fromCharCode((self._byte << 4) + hexLower);
self._byte = -2;
self._lastPos = pos;
}
return pos;
}
function skipKeyBytes(self, chunk, pos, len) {
if (self._bytesKey > self.fieldNameSizeLimit) {
if (!self._keyTrunc) {
if (self._lastPos < pos)
self._key += chunk.latin1Slice(self._lastPos, pos - 1);
}
self._keyTrunc = true;
for (; pos < len; ++pos) {
const code = chunk[pos];
if (code === 61 || code === 38)
break;
++self._bytesKey;
}
self._lastPos = pos;
}
return pos;
}
function skipValBytes(self, chunk, pos, len) {
if (self._bytesVal > self.fieldSizeLimit) {
if (!self._valTrunc) {
if (self._lastPos < pos)
self._val += chunk.latin1Slice(self._lastPos, pos - 1);
}
self._valTrunc = true;
for (; pos < len; ++pos) {
if (chunk[pos] === 38)
break;
++self._bytesVal;
}
self._lastPos = pos;
}
return pos;
}
var HEX_VALUES = [
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
10,
11,
12,
13,
14,
15,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
10,
11,
12,
13,
14,
15,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1
];
module2.exports = URLEncoded;
}
});
// node_modules/busboy/lib/index.js
var require_lib4 = __commonJS({
"node_modules/busboy/lib/index.js"(exports, module2) {
"use strict";
var { parseContentType } = require_utils5();
function getInstance(cfg) {
const headers = cfg.headers;
const conType = parseContentType(headers["content-type"]);
if (!conType)
throw new Error("Malformed content type");
for (const type of TYPES) {
const matched = type.detect(conType);
if (!matched)
continue;
const instanceCfg = {
limits: cfg.limits,
headers,
conType,
highWaterMark: void 0,
fileHwm: void 0,
defCharset: void 0,
defParamCharset: void 0,
preservePath: false
};
if (cfg.highWaterMark)
instanceCfg.highWaterMark = cfg.highWaterMark;
if (cfg.fileHwm)
instanceCfg.fileHwm = cfg.fileHwm;
instanceCfg.defCharset = cfg.defCharset;
instanceCfg.defParamCharset = cfg.defParamCharset;
instanceCfg.preservePath = cfg.preservePath;
return new type(instanceCfg);
}
throw new Error(`Unsupported content type: ${headers["content-type"]}`);
}
var TYPES = [
require_multipart(),
require_urlencoded()
].filter(function(typemod) {
return typeof typemod.detect === "function";
});
module2.exports = (cfg) => {
if (typeof cfg !== "object" || cfg === null)
cfg = {};
if (typeof cfg.headers !== "object" || cfg.headers === null || typeof cfg.headers["content-type"] !== "string") {
throw new Error("Missing Content-Type");
}
return getInstance(cfg);
};
}
});
// node_modules/undici/lib/fetch/constants.js
var require_constants = __commonJS({
"node_modules/undici/lib/fetch/constants.js"(exports, module2) {
"use strict";
var corsSafeListedMethods = ["GET", "HEAD", "POST"];
var nullBodyStatus = [101, 204, 205, 304];
var redirectStatus = [301, 302, 303, 307, 308];
var referrerPolicy = [
"",
"no-referrer",
"no-referrer-when-downgrade",
"same-origin",
"origin",
"strict-origin",
"origin-when-cross-origin",
"strict-origin-when-cross-origin",
"unsafe-url"
];
3 years ago
var requestRedirect = ["follow", "manual", "error"];
var safeMethods = ["GET", "HEAD", "OPTIONS", "TRACE"];
var requestMode = ["navigate", "same-origin", "no-cors", "cors"];
var requestCredentials = ["omit", "same-origin", "include"];
var requestCache = [
"default",
"no-store",
"reload",
"no-cache",
"force-cache",
"only-if-cached"
];
var requestBodyHeader = [
"content-encoding",
"content-language",
"content-location",
"content-type"
];
var forbiddenMethods = ["CONNECT", "TRACE", "TRACK"];
var subresource = [
"audio",
"audioworklet",
"font",
"image",
"manifest",
"paintworklet",
"script",
"style",
"track",
"video",
"xslt",
""
];
var DOMException = globalThis.DOMException ?? (() => {
try {
atob("~");
} catch (err) {
return Object.getPrototypeOf(err).constructor;
}
})();
3 years ago
module2.exports = {
DOMException,
3 years ago
subresource,
forbiddenMethods,
requestBodyHeader,
referrerPolicy,
requestRedirect,
requestMode,
requestCredentials,
requestCache,
redirectStatus,
corsSafeListedMethods,
nullBodyStatus,
safeMethods
};
}
});
// node_modules/undici/lib/fetch/util.js
var require_util2 = __commonJS({
"node_modules/undici/lib/fetch/util.js"(exports, module2) {
"use strict";
var { redirectStatus } = require_constants();
var { performance: performance2 } = require("perf_hooks");
3 years ago
var { isBlobLike, toUSVString, ReadableStreamFrom } = require_util();
var assert = require("assert");
var { isUint8Array } = require("util/types");
var crypto;
try {
crypto = require("crypto");
} catch {
}
3 years ago
var badPorts = [
"1",
"7",
"9",
"11",
"13",
"15",
"17",
"19",
"20",
"21",
"22",
"23",
"25",
"37",
"42",
"43",
"53",
"69",
"77",
"79",
"87",
"95",
"101",
"102",
"103",
"104",
"109",
"110",
"111",
"113",
"115",
"117",
"119",
"123",
"135",
"137",
"139",
"143",
"161",
"179",
"389",
"427",
"465",
"512",
"513",
"514",
"515",
"526",
"530",
"531",
"532",
"540",
"548",
"554",
"556",
"563",
"587",
"601",
"636",
"989",
"990",
"993",
"995",
"1719",
"1720",
"1723",
"2049",
"3659",
"4045",
"5060",
"5061",
"6000",
"6566",
"6665",
"6666",
"6667",
"6668",
"6669",
"6697",
"10080"
];
function responseURL(response) {
const urlList = response.urlList;
const length = urlList.length;
return length === 0 ? null : urlList[length - 1].toString();
}
function responseLocationURL(response, requestFragment) {
if (!redirectStatus.includes(response.status)) {
return null;
}
let location = response.headersList.get("location");
location = location ? new URL(location, responseURL(response)) : null;
if (location && !location.hash) {
location.hash = requestFragment;
}
return location;
}
function requestCurrentURL(request) {
return request.urlList[request.urlList.length - 1];
}
function requestBadPort(request) {
const url = requestCurrentURL(request);
if (/^https?:/.test(url.protocol) && badPorts.includes(url.port)) {
return "blocked";
}
return "allowed";
}
function isErrorLike(object) {
return object instanceof Error || (object?.constructor?.name === "Error" || object?.constructor?.name === "DOMException");
3 years ago
}
function isValidReasonPhrase(statusText) {
for (let i = 0; i < statusText.length; ++i) {
const c = statusText.charCodeAt(i);
if (!(c === 9 || c >= 32 && c <= 126 || c >= 128 && c <= 255)) {
return false;
}
}
return true;
}
function isTokenChar(c) {
return !(c >= 127 || c <= 32 || c === "(" || c === ")" || c === "<" || c === ">" || c === "@" || c === "," || c === ";" || c === ":" || c === "\\" || c === '"' || c === "/" || c === "[" || c === "]" || c === "?" || c === "=" || c === "{" || c === "}");
}
function isValidHTTPToken(characters) {
if (!characters || typeof characters !== "string") {
return false;
}
for (let i = 0; i < characters.length; ++i) {
const c = characters.charCodeAt(i);
if (c > 127 || !isTokenChar(c)) {
return false;
}
}
return true;
}
function isValidHeaderName(potentialValue) {
if (potentialValue.length === 0) {
return false;
}
for (const char of potentialValue) {
if (!isValidHTTPToken(char)) {
return false;
}
}
return true;
}
function isValidHeaderValue(potentialValue) {
if (potentialValue.startsWith(" ") || potentialValue.startsWith(" ") || potentialValue.endsWith(" ") || potentialValue.endsWith(" ")) {
return false;
}
if (potentialValue.includes("\0") || potentialValue.includes("\r") || potentialValue.includes("\n")) {
return false;
}
return true;
}
3 years ago
function setRequestReferrerPolicyOnRedirect(request, actualResponse) {
const policy = "";
if (policy !== "") {
request.referrerPolicy = policy;
}
}
function crossOriginResourcePolicyCheck() {
return "allowed";
}
function corsCheck() {
return "success";
}
function TAOCheck() {
return "success";
}
function appendFetchMetadata(httpRequest) {
let header = null;
header = httpRequest.mode;
httpRequest.headersList.set("sec-fetch-mode", header);
}
function appendRequestOriginHeader(request) {
let serializedOrigin = request.origin;
if (request.responseTainting === "cors" || request.mode === "websocket") {
if (serializedOrigin) {
request.headersList.append("Origin", serializedOrigin);
}
} else if (request.method !== "GET" && request.method !== "HEAD") {
switch (request.referrerPolicy) {
case "no-referrer":
serializedOrigin = null;
break;
case "no-referrer-when-downgrade":
case "strict-origin":
case "strict-origin-when-cross-origin":
if (/^https:/.test(request.origin) && !/^https:/.test(requestCurrentURL(request))) {
serializedOrigin = null;
}
break;
case "same-origin":
if (!sameOrigin(request, requestCurrentURL(request))) {
serializedOrigin = null;
}
break;
default:
}
if (serializedOrigin) {
request.headersList.append("Origin", serializedOrigin);
}
}
}
function coarsenedSharedCurrentTime(crossOriginIsolatedCapability) {
return performance2.now();
3 years ago
}
function createOpaqueTimingInfo(timingInfo) {
return {
startTime: timingInfo.startTime ?? 0,
redirectStartTime: 0,
redirectEndTime: 0,
postRedirectStartTime: timingInfo.startTime ?? 0,
finalServiceWorkerStartTime: 0,
finalNetworkResponseStartTime: 0,
finalNetworkRequestStartTime: 0,
endTime: 0,
encodedBodySize: 0,
decodedBodySize: 0,
finalConnectionTimingInfo: null
};
}
function makePolicyContainer() {
return {};
}
function clonePolicyContainer() {
return {};
}
function determineRequestsReferrer(request) {
const policy = request.referrerPolicy;
if (policy == null || policy === "" || policy === "no-referrer") {
return "no-referrer";
}
const environment = request.client;
let referrerSource = null;
if (request.referrer === "client") {
if (request.client?.globalObject?.constructor?.name === "Window") {
const origin = environment.globalObject.self?.origin ?? environment.globalObject.location?.origin;
if (origin == null || origin === "null")
return "no-referrer";
referrerSource = new URL(environment.globalObject.location.href);
} else {
if (environment?.globalObject?.location == null) {
return "no-referrer";
}
referrerSource = new URL(environment.globalObject.location.href);
}
} else if (request.referrer instanceof URL) {
referrerSource = request.referrer;
} else {
return "no-referrer";
}
const urlProtocol = referrerSource.protocol;
if (urlProtocol === "about:" || urlProtocol === "data:" || urlProtocol === "blob:") {
return "no-referrer";
}
let temp;
let referrerOrigin;
const referrerUrl = (temp = stripURLForReferrer(referrerSource)).length > 4096 ? referrerOrigin = stripURLForReferrer(referrerSource, true) : temp;
const areSameOrigin = sameOrigin(request, referrerUrl);
const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerUrl) && !isURLPotentiallyTrustworthy(request.url);
switch (policy) {
case "origin":
return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true);
case "unsafe-url":
return referrerUrl;
case "same-origin":
return areSameOrigin ? referrerOrigin : "no-referrer";
case "origin-when-cross-origin":
return areSameOrigin ? referrerUrl : referrerOrigin;
case "strict-origin-when-cross-origin":
if (areSameOrigin)
return referrerOrigin;
case "strict-origin":
case "no-referrer-when-downgrade":
default:
return isNonPotentiallyTrustWorthy ? "no-referrer" : referrerOrigin;
}
function stripURLForReferrer(url, originOnly = false) {
const urlObject = new URL(url.href);
urlObject.username = "";
urlObject.password = "";
urlObject.hash = "";
return originOnly ? urlObject.origin : urlObject.href;
}
}
function isURLPotentiallyTrustworthy(url) {
if (!(url instanceof URL)) {
return false;
}
if (url.href === "about:blank" || url.href === "about:srcdoc") {
return true;
}
if (url.protocol === "data:")
return true;
if (url.protocol === "file:")
return true;
return isOriginPotentiallyTrustworthy(url.origin);
function isOriginPotentiallyTrustworthy(origin) {
if (origin == null || origin === "null")
return false;
const originAsURL = new URL(origin);
if (originAsURL.protocol === "https:" || originAsURL.protocol === "wss:") {
return true;
}
if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || (originAsURL.hostname === "localhost" || originAsURL.hostname.includes("localhost.")) || originAsURL.hostname.endsWith(".localhost")) {
return true;
}
return false;
}
3 years ago
}
function bytesMatch(bytes, metadataList) {
if (crypto === void 0) {
return true;
}
const parsedMetadata = parseMetadata(metadataList);
if (parsedMetadata === "no metadata") {
return true;
}
if (parsedMetadata.length === 0) {
return true;
}
const metadata = parsedMetadata.sort((c, d) => d.algo.localeCompare(c.algo));
for (const item of metadata) {
const algorithm = item.algo;
const expectedValue = item.hash;
const actualValue = crypto.createHash(algorithm).update(bytes).digest("base64");
if (actualValue === expectedValue) {
return true;
}
}
3 years ago
return false;
}
var parseHashWithOptions = /((?<algo>sha256|sha384|sha512)-(?<hash>[A-z0-9+/]{1}.*={1,2}))( +[\x21-\x7e]?)?/i;
function parseMetadata(metadata) {
const result = [];
let empty = true;
const supportedHashes = crypto.getHashes();
for (const token of metadata.split(" ")) {
empty = false;
const parsedToken = parseHashWithOptions.exec(token);
if (parsedToken === null || parsedToken.groups === void 0) {
continue;
}
const algorithm = parsedToken.groups.algo;
if (supportedHashes.includes(algorithm.toLowerCase())) {
result.push(parsedToken.groups);
}
}
if (empty === true) {
return "no metadata";
}
return result;
}
3 years ago
function tryUpgradeRequestToAPotentiallyTrustworthyURL(request) {
}
function sameOrigin(A, B) {
if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {
return true;
}
return false;
}
function createDeferredPromise() {
let res;
let rej;
const promise = new Promise((resolve, reject) => {
res = resolve;
rej = reject;
});
return { promise, resolve: res, reject: rej };
}
function isAborted(fetchParams) {
return fetchParams.controller.state === "aborted";
}
function isCancelled(fetchParams) {
return fetchParams.controller.state === "aborted" || fetchParams.controller.state === "terminated";
}
function normalizeMethod(method) {
return /^(DELETE|GET|HEAD|OPTIONS|POST|PUT)$/i.test(method) ? method.toUpperCase() : method;
}
function serializeJavascriptValueToJSONString(value) {
const result = JSON.stringify(value);
if (result === void 0) {
throw new TypeError("Value is not JSON serializable");
}
assert(typeof result === "string");
return result;
}
var esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
function makeIterator(iterator, name) {
const i = {
next() {
if (Object.getPrototypeOf(this) !== i) {
throw new TypeError(
`'next' called on an object that does not implement interface ${name} Iterator.`
);
}
return iterator.next();
},
[Symbol.toStringTag]: `${name} Iterator`
};
Object.setPrototypeOf(i, esIteratorPrototype);
return Object.setPrototypeOf({}, i);
}
async function fullyReadBody(body, processBody, processBodyError) {
try {
const chunks = [];
let length = 0;
const reader = body.stream.getReader();
while (true) {
const { done, value } = await reader.read();
if (done === true) {
break;
}
assert(isUint8Array(value));
chunks.push(value);
length += value.byteLength;
}
const fulfilledSteps = (bytes) => queueMicrotask(() => {
processBody(bytes);
});
fulfilledSteps(Buffer.concat(chunks, length));
} catch (err) {
queueMicrotask(() => processBodyError(err));
}
}
var hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key));
3 years ago
module2.exports = {
isAborted,
isCancelled,
createDeferredPromise,
ReadableStreamFrom,
toUSVString,
tryUpgradeRequestToAPotentiallyTrustworthyURL,
coarsenedSharedCurrentTime,
determineRequestsReferrer,
makePolicyContainer,
clonePolicyContainer,
appendFetchMetadata,
appendRequestOriginHeader,
TAOCheck,
corsCheck,
crossOriginResourcePolicyCheck,
createOpaqueTimingInfo,
setRequestReferrerPolicyOnRedirect,
isValidHTTPToken,
requestBadPort,
requestCurrentURL,
responseURL,
responseLocationURL,
isBlobLike,
isURLPotentiallyTrustworthy,
3 years ago
isValidReasonPhrase,
sameOrigin,
normalizeMethod,
serializeJavascriptValueToJSONString,
makeIterator,
isValidHeaderName,
isValidHeaderValue,
hasOwn,
isErrorLike,
fullyReadBody,
bytesMatch
};
}
});
// node_modules/undici/lib/fetch/symbols.js
var require_symbols2 = __commonJS({
"node_modules/undici/lib/fetch/symbols.js"(exports, module2) {
"use strict";
module2.exports = {
kUrl: Symbol("url"),
kHeaders: Symbol("headers"),
kSignal: Symbol("signal"),
kState: Symbol("state"),
kGuard: Symbol("guard"),
kRealm: Symbol("realm")
};
}
});
// node_modules/undici/lib/fetch/webidl.js
var require_webidl = __commonJS({
"node_modules/undici/lib/fetch/webidl.js"(exports, module2) {
"use strict";
var { types } = require("util");
var { hasOwn, toUSVString } = require_util2();
var webidl = {};
webidl.converters = {};
webidl.util = {};
webidl.errors = {};
webidl.errors.exception = function(message) {
throw new TypeError(`${message.header}: ${message.message}`);
};
webidl.errors.conversionFailed = function(context2) {
const plural = context2.types.length === 1 ? "" : " one of";
const message = `${context2.argument} could not be converted to${plural}: ${context2.types.join(", ")}.`;
return webidl.errors.exception({
header: context2.prefix,
message
});
};
webidl.errors.invalidArgument = function(context2) {
return webidl.errors.exception({
header: context2.prefix,
message: `"${context2.value}" is an invalid ${context2.type}.`
});
};
webidl.util.Type = function(V) {
switch (typeof V) {
case "undefined":
return "Undefined";
case "boolean":
return "Boolean";
case "string":
return "String";
case "symbol":
return "Symbol";
case "number":
return "Number";
case "bigint":
return "BigInt";
case "function":
case "object": {
if (V === null) {
return "Null";
}
return "Object";
}
}
};
webidl.util.ConvertToInt = function(V, bitLength, signedness, opts = {}) {
let upperBound;
let lowerBound;
if (bitLength === 64) {
upperBound = Math.pow(2, 53) - 1;
if (signedness === "unsigned") {
lowerBound = 0;
} else {
lowerBound = Math.pow(-2, 53) + 1;
}
} else if (signedness === "unsigned") {
lowerBound = 0;
upperBound = Math.pow(2, bitLength) - 1;
} else {
lowerBound = Math.pow(-2, bitLength) - 1;
upperBound = Math.pow(2, bitLength - 1) - 1;
}
let x = Number(V);
if (Object.is(-0, x)) {
x = 0;
}
if (opts.enforceRange === true) {
if (Number.isNaN(x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY) {
webidl.errors.exception({
header: "Integer conversion",
message: `Could not convert ${V} to an integer.`
});
}
x = webidl.util.IntegerPart(x);
if (x < lowerBound || x > upperBound) {
webidl.errors.exception({
header: "Integer conversion",
message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`
});
}
return x;
}
if (!Number.isNaN(x) && opts.clamp === true) {
x = Math.min(Math.max(x, lowerBound), upperBound);
if (Math.floor(x) % 2 === 0) {
x = Math.floor(x);
} else {
x = Math.ceil(x);
}
return x;
}
if (Number.isNaN(x) || Object.is(0, x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY) {
return 0;
}
x = webidl.util.IntegerPart(x);
x = x % Math.pow(2, bitLength);
if (signedness === "signed" && x >= Math.pow(2, bitLength) - 1) {
return x - Math.pow(2, bitLength);
}
return x;
};
webidl.util.IntegerPart = function(n) {
const r = Math.floor(Math.abs(n));
if (n < 0) {
return -1 * r;
}
return r;
};
webidl.sequenceConverter = function(converter) {
return (V) => {
if (webidl.util.Type(V) !== "Object") {
webidl.errors.exception({
header: "Sequence",
message: `Value of type ${webidl.util.Type(V)} is not an Object.`
});
}
const method = V?.[Symbol.iterator]?.();
const seq = [];
if (method === void 0 || typeof method.next !== "function") {
webidl.errors.exception({
header: "Sequence",
message: "Object is not an iterator."
});
}
while (true) {
const { done, value } = method.next();
if (done) {
break;
}
seq.push(converter(value));
}
return seq;
};
};
webidl.recordConverter = function(keyConverter, valueConverter) {
return (V) => {
const record = {};
const type = webidl.util.Type(V);
if (type === "Undefined" || type === "Null") {
return record;
}
if (type !== "Object") {
webidl.errors.exception({
header: "Record",
message: `Expected ${V} to be an Object type.`
});
}
for (let [key, value] of Object.entries(V)) {
key = keyConverter(key);
value = valueConverter(value);
record[key] = value;
}
return record;
};
};
webidl.interfaceConverter = function(i) {
return (V, opts = {}) => {
if (opts.strict !== false && !(V instanceof i)) {
webidl.errors.exception({
header: i.name,
message: `Expected ${V} to be an instance of ${i.name}.`
});
}
return V;
};
};
webidl.dictionaryConverter = function(converters) {
return (dictionary) => {
const type = webidl.util.Type(dictionary);
const dict = {};
if (type !== "Null" && type !== "Undefined" && type !== "Object") {
webidl.errors.exception({
header: "Dictionary",
message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
});
}
for (const options of converters) {
const { key, defaultValue, required, converter } = options;
if (required === true) {
if (!hasOwn(dictionary, key)) {
webidl.errors.exception({
header: "Dictionary",
message: `Missing required key "${key}".`
});
}
}
let value = dictionary[key];
const hasDefault = hasOwn(options, "defaultValue");
if (hasDefault && value !== null) {
value = value ?? defaultValue;
}
if (required || hasDefault || value !== void 0) {
value = converter(value);
if (options.allowedValues && !options.allowedValues.includes(value)) {
webidl.errors.exception({
header: "Dictionary",
message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(", ")}.`
});
}
dict[key] = value;
}
}
return dict;
};
};
webidl.nullableConverter = function(converter) {
return (V) => {
if (V === null) {
return V;
}
return converter(V);
};
};
webidl.converters.DOMString = function(V, opts = {}) {
if (V === null && opts.legacyNullToEmptyString) {
return "";
}
if (typeof V === "symbol") {
throw new TypeError("Could not convert argument of type symbol to string.");
}
return String(V);
};
webidl.converters.ByteString = function(V) {
const x = webidl.converters.DOMString(V);
for (let index = 0; index < x.length; index++) {
const charCode = x.charCodeAt(index);
if (charCode > 255) {
throw new TypeError(
`Cannot convert argument to a ByteString because the character atindex ${index} has a value of ${charCode} which is greater than 255.`
);
}
}
return x;
};
webidl.converters.USVString = toUSVString;
webidl.converters.boolean = function(V) {
const x = Boolean(V);
return x;
};
webidl.converters.any = function(V) {
return V;
};
webidl.converters["long long"] = function(V, opts) {
const x = webidl.util.ConvertToInt(V, 64, "signed", opts);
return x;
};
webidl.converters["unsigned short"] = function(V) {
const x = webidl.util.ConvertToInt(V, 16, "unsigned");
return x;
};
webidl.converters.ArrayBuffer = function(V, opts = {}) {
if (webidl.util.Type(V) !== "Object" || !types.isAnyArrayBuffer(V)) {
webidl.errors.conversionFailed({
prefix: `${V}`,
argument: `${V}`,
types: ["ArrayBuffer"]
});
}
if (opts.allowShared === false && types.isSharedArrayBuffer(V)) {
webidl.errors.exception({
header: "ArrayBuffer",
message: "SharedArrayBuffer is not allowed."
});
}
return V;
};
webidl.converters.TypedArray = function(V, T, opts = {}) {
if (webidl.util.Type(V) !== "Object" || !types.isTypedArray(V) || V.constructor.name !== T.name) {
webidl.errors.conversionFailed({
prefix: `${T.name}`,
argument: `${V}`,
types: [T.name]
});
}
if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
webidl.errors.exception({
header: "ArrayBuffer",
message: "SharedArrayBuffer is not allowed."
});
}
return V;
};
webidl.converters.DataView = function(V, opts = {}) {
if (webidl.util.Type(V) !== "Object" || !types.isDataView(V)) {
webidl.errors.exception({
header: "DataView",
message: "Object is not a DataView."
});
}
if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
webidl.errors.exception({
header: "ArrayBuffer",
message: "SharedArrayBuffer is not allowed."
});
}
return V;
};
webidl.converters.BufferSource = function(V, opts = {}) {
if (types.isAnyArrayBuffer(V)) {
return webidl.converters.ArrayBuffer(V, opts);
}
if (types.isTypedArray(V)) {
return webidl.converters.TypedArray(V, V.constructor);
}
if (types.isDataView(V)) {
return webidl.converters.DataView(V, opts);
}
throw new TypeError(`Could not convert ${V} to a BufferSource.`);
};
webidl.converters["sequence<ByteString>"] = webidl.sequenceConverter(
webidl.converters.ByteString
);
webidl.converters["sequence<sequence<ByteString>>"] = webidl.sequenceConverter(
webidl.converters["sequence<ByteString>"]
);
webidl.converters["record<ByteString, ByteString>"] = webidl.recordConverter(
webidl.converters.ByteString,
webidl.converters.ByteString
);
module2.exports = {
webidl
};
}
});
// node_modules/undici/lib/fetch/file.js
var require_file = __commonJS({
"node_modules/undici/lib/fetch/file.js"(exports, module2) {
"use strict";
var { Blob } = require("buffer");
var { types } = require("util");
var { kState } = require_symbols2();
var { isBlobLike } = require_util2();
var { webidl } = require_webidl();
var File = class extends Blob {
constructor(fileBits, fileName, options = {}) {
if (arguments.length < 2) {
throw new TypeError("2 arguments required");
}
fileBits = webidl.converters["sequence<BlobPart>"](fileBits);
fileName = webidl.converters.USVString(fileName);
options = webidl.converters.FilePropertyBag(options);
const n = fileName;
const d = options.lastModified;
super(processBlobParts(fileBits, options), { type: options.type });
this[kState] = {
name: n,
lastModified: d
};
}
get name() {
if (!(this instanceof File)) {
throw new TypeError("Illegal invocation");
}
return this[kState].name;
}
get lastModified() {
if (!(this instanceof File)) {
throw new TypeError("Illegal invocation");
}
return this[kState].lastModified;
}
get [Symbol.toStringTag]() {
return this.constructor.name;
}
};
var FileLike = class {
constructor(blobLike, fileName, options = {}) {
const n = fileName;
const t = options.type;
const d = options.lastModified ?? Date.now();
this[kState] = {
blobLike,
name: n,
type: t,
lastModified: d
};
}
stream(...args) {
if (!(this instanceof FileLike)) {
throw new TypeError("Illegal invocation");
}
return this[kState].blobLike.stream(...args);
}
arrayBuffer(...args) {
if (!(this instanceof FileLike)) {
throw new TypeError("Illegal invocation");
}
return this[kState].blobLike.arrayBuffer(...args);
}
slice(...args) {
if (!(this instanceof FileLike)) {
throw new TypeError("Illegal invocation");
}
return this[kState].blobLike.slice(...args);
}
text(...args) {
if (!(this instanceof FileLike)) {
throw new TypeError("Illegal invocation");
}
return this[kState].blobLike.text(...args);
}
get size() {
if (!(this instanceof FileLike)) {
throw new TypeError("Illegal invocation");
}
return this[kState].blobLike.size;
}
get type() {
if (!(this instanceof FileLike)) {
throw new TypeError("Illegal invocation");
}
return this[kState].blobLike.type;
}
get name() {
if (!(this instanceof FileLike)) {
throw new TypeError("Illegal invocation");
}
return this[kState].name;
}
get lastModified() {
if (!(this instanceof FileLike)) {
throw new TypeError("Illegal invocation");
}
return this[kState].lastModified;
}
get [Symbol.toStringTag]() {
return "File";
}
};
webidl.converters.Blob = webidl.interfaceConverter(Blob);
webidl.converters.BlobPart = function(V, opts) {
if (webidl.util.Type(V) === "Object") {
if (isBlobLike(V)) {
return webidl.converters.Blob(V, { strict: false });
}
return webidl.converters.BufferSource(V, opts);
} else {
return webidl.converters.USVString(V, opts);
}
3 years ago
};
webidl.converters["sequence<BlobPart>"] = webidl.sequenceConverter(
webidl.converters.BlobPart
);
webidl.converters.FilePropertyBag = webidl.dictionaryConverter([
{
key: "lastModified",
converter: webidl.converters["long long"],
get defaultValue() {
return Date.now();
}
},
{
key: "type",
converter: webidl.converters.DOMString,
defaultValue: ""
},
{
key: "endings",
converter: (value) => {
value = webidl.converters.DOMString(value);
value = value.toLowerCase();
if (value !== "native") {
value = "transparent";
}
return value;
},
defaultValue: "transparent"
}
]);
function processBlobParts(parts, options) {
const bytes = [];
for (const element of parts) {
if (typeof element === "string") {
let s = element;
if (options.endings === "native") {
s = convertLineEndingsNative(s);
}
bytes.push(new TextEncoder().encode(s));
} else if (types.isAnyArrayBuffer(element) || types.isTypedArray(element)) {
if (!element.buffer) {
bytes.push(new Uint8Array(element));
} else {
bytes.push(
new Uint8Array(element.buffer, element.byteOffset, element.byteLength)
);
}
} else if (isBlobLike(element)) {
bytes.push(element);
}
}
return bytes;
}
function convertLineEndingsNative(s) {
let nativeLineEnding = "\n";
if (process.platform === "win32") {
nativeLineEnding = "\r\n";
}
return s.replace(/\r?\n/g, nativeLineEnding);
}
function isFileLike(object) {
return object instanceof File || object && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && object[Symbol.toStringTag] === "File";
}
module2.exports = { File, FileLike, isFileLike };
3 years ago
}
});
// node_modules/undici/lib/fetch/formdata.js
var require_formdata = __commonJS({
"node_modules/undici/lib/fetch/formdata.js"(exports, module2) {
"use strict";
var { isBlobLike, toUSVString, makeIterator } = require_util2();
3 years ago
var { kState } = require_symbols2();
var { File, FileLike, isFileLike } = require_file();
var { webidl } = require_webidl();
3 years ago
var { Blob } = require("buffer");
var _FormData = class {
constructor(form) {
if (arguments.length > 0 && form != null) {
webidl.errors.conversionFailed({
prefix: "FormData constructor",
argument: "Argument 1",
types: ["null"]
});
3 years ago
}
this[kState] = [];
}
append(name, value, filename = void 0) {
if (!(this instanceof _FormData)) {
3 years ago
throw new TypeError("Illegal invocation");
}
if (arguments.length < 2) {
throw new TypeError(
`Failed to execute 'append' on 'FormData': 2 arguments required, but only ${arguments.length} present.`
);
3 years ago
}
if (arguments.length === 3 && !isBlobLike(value)) {
throw new TypeError(
"Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'"
);
3 years ago
}
name = webidl.converters.USVString(name);
value = isBlobLike(value) ? webidl.converters.Blob(value, { strict: false }) : webidl.converters.USVString(value);
filename = arguments.length === 3 ? webidl.converters.USVString(filename) : void 0;
3 years ago
const entry = makeEntry(name, value, filename);
this[kState].push(entry);
}
delete(name) {
if (!(this instanceof _FormData)) {
3 years ago
throw new TypeError("Illegal invocation");
}
if (arguments.length < 1) {
throw new TypeError(
`Failed to execute 'delete' on 'FormData': 1 arguments required, but only ${arguments.length} present.`
);
3 years ago
}
name = webidl.converters.USVString(name);
3 years ago
const next = [];
for (const entry of this[kState]) {
if (entry.name !== name) {
next.push(entry);
}
}
this[kState] = next;
}
get(name) {
if (!(this instanceof _FormData)) {
3 years ago
throw new TypeError("Illegal invocation");
}
if (arguments.length < 1) {
throw new TypeError(
`Failed to execute 'get' on 'FormData': 1 arguments required, but only ${arguments.length} present.`
);
3 years ago
}
name = webidl.converters.USVString(name);
3 years ago
const idx = this[kState].findIndex((entry) => entry.name === name);
if (idx === -1) {
return null;
}
return this[kState][idx].value;
}
getAll(name) {
if (!(this instanceof _FormData)) {
3 years ago
throw new TypeError("Illegal invocation");
}
if (arguments.length < 1) {
throw new TypeError(
`Failed to execute 'getAll' on 'FormData': 1 arguments required, but only ${arguments.length} present.`
);
3 years ago
}
name = webidl.converters.USVString(name);
3 years ago
return this[kState].filter((entry) => entry.name === name).map((entry) => entry.value);
}
has(name) {
if (!(this instanceof _FormData)) {
3 years ago
throw new TypeError("Illegal invocation");
}
if (arguments.length < 1) {
throw new TypeError(
`Failed to execute 'has' on 'FormData': 1 arguments required, but only ${arguments.length} present.`
);
3 years ago
}
name = webidl.converters.USVString(name);
3 years ago
return this[kState].findIndex((entry) => entry.name === name) !== -1;
}
set(name, value, filename = void 0) {
if (!(this instanceof _FormData)) {
3 years ago
throw new TypeError("Illegal invocation");
}
if (arguments.length < 2) {
throw new TypeError(
`Failed to execute 'set' on 'FormData': 2 arguments required, but only ${arguments.length} present.`
);
3 years ago
}
if (arguments.length === 3 && !isBlobLike(value)) {
throw new TypeError(
"Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'"
);
3 years ago
}
name = webidl.converters.USVString(name);
value = isBlobLike(value) ? webidl.converters.Blob(value, { strict: false }) : webidl.converters.USVString(value);
filename = arguments.length === 3 ? toUSVString(filename) : void 0;
3 years ago
const entry = makeEntry(name, value, filename);
const idx = this[kState].findIndex((entry2) => entry2.name === name);
if (idx !== -1) {
this[kState] = [
...this[kState].slice(0, idx),
entry,
...this[kState].slice(idx + 1).filter((entry2) => entry2.name !== name)
];
} else {
this[kState].push(entry);
}
}
get [Symbol.toStringTag]() {
return this.constructor.name;
}
entries() {
if (!(this instanceof _FormData)) {
3 years ago
throw new TypeError("Illegal invocation");
}
return makeIterator(
makeIterable(this[kState], "entries"),
"FormData"
);
3 years ago
}
keys() {
if (!(this instanceof _FormData)) {
3 years ago
throw new TypeError("Illegal invocation");
}
return makeIterator(
makeIterable(this[kState], "keys"),
"FormData"
);
}
values() {
if (!(this instanceof _FormData)) {
throw new TypeError("Illegal invocation");
3 years ago
}
return makeIterator(
makeIterable(this[kState], "values"),
"FormData"
);
3 years ago
}
forEach(callbackFn, thisArg = globalThis) {
if (!(this instanceof _FormData)) {
3 years ago
throw new TypeError("Illegal invocation");
}
if (arguments.length < 1) {
throw new TypeError(
`Failed to execute 'forEach' on 'FormData': 1 argument required, but only ${arguments.length} present.`
);
3 years ago
}
if (typeof callbackFn !== "function") {
throw new TypeError(
"Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'."
);
}
for (const [key, value] of this) {
callbackFn.apply(thisArg, [value, key, this]);
3 years ago
}
}
};
var FormData = _FormData;
__publicField(FormData, "name", "FormData");
FormData.prototype[Symbol.iterator] = FormData.prototype.entries;
3 years ago
function makeEntry(name, value, filename) {
name = Buffer.from(name).toString("utf8");
if (typeof value === "string") {
value = Buffer.from(value).toString("utf8");
} else {
if (!isFileLike(value)) {
value = value instanceof Blob ? new File([value], "blob", { type: value.type }) : new FileLike(value, "blob", { type: value.type });
}
if (filename !== void 0) {
value = value instanceof File ? new File([value], filename, { type: value.type }) : new FileLike(value, filename, { type: value.type });
}
3 years ago
}
return { name, value };
}
function* makeIterable(entries, type) {
for (const { name, value } of entries) {
if (type === "entries") {
yield [name, value];
} else if (type === "values") {
yield value;
} else {
yield name;
}
3 years ago
}
}
module2.exports = { FormData };
3 years ago
}
});
// node_modules/undici/lib/fetch/body.js
var require_body = __commonJS({
"node_modules/undici/lib/fetch/body.js"(exports, module2) {
"use strict";
var Busboy = require_lib4();
3 years ago
var util = require_util();
var { ReadableStreamFrom, toUSVString, isBlobLike } = require_util2();
var { FormData } = require_formdata();
var { kState } = require_symbols2();
var { webidl } = require_webidl();
var { DOMException } = require_constants();
3 years ago
var { Blob } = require("buffer");
var { kBodyUsed } = require_symbols();
var assert = require("assert");
var { isErrored } = require_util();
var { isUint8Array, isArrayBuffer } = require("util/types");
var { File } = require_file();
3 years ago
var ReadableStream;
async function* blobGen(blob) {
yield* blob.stream();
3 years ago
}
function extractBody(object, keepalive = false) {
if (!ReadableStream) {
ReadableStream = require("stream/web").ReadableStream;
}
let stream = null;
let action = null;
let source = null;
let length = null;
let contentType = null;
if (object == null) {
} else if (object instanceof URLSearchParams) {
source = object.toString();
contentType = "application/x-www-form-urlencoded;charset=UTF-8";
} else if (isArrayBuffer(object)) {
source = new Uint8Array(object.slice());
} else if (ArrayBuffer.isView(object)) {
source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength));
3 years ago
} else if (util.isFormDataLike(object)) {
const boundary = "----formdata-undici-" + Math.random();
const prefix = `--${boundary}\r
Content-Disposition: form-data`;
const escape = (str) => str.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22");
const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, "\r\n");
action = async function* (object2) {
const enc = new TextEncoder();
for (const [name, value] of object2) {
if (typeof value === "string") {
yield enc.encode(
prefix + `; name="${escape(normalizeLinefeeds(name))}"\r
3 years ago
\r
${normalizeLinefeeds(value)}\r
`
);
3 years ago
} else {
yield enc.encode(
prefix + `; name="${escape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${escape(value.name)}"` : "") + `\r
3 years ago
Content-Type: ${value.type || "application/octet-stream"}\r
\r
`
);
3 years ago
yield* blobGen(value);
yield enc.encode("\r\n");
}
}
yield enc.encode(`--${boundary}--`);
};
source = object;
contentType = "multipart/form-data; boundary=" + boundary;
} else if (isBlobLike(object)) {
action = blobGen;
source = object;
length = object.size;
if (object.type) {
contentType = object.type;
}
} else if (typeof object[Symbol.asyncIterator] === "function") {
if (keepalive) {
throw new TypeError("keepalive");
}
if (util.isDisturbed(object) || object.locked) {
throw new TypeError(
"Response body object should not be disturbed or locked"
);
3 years ago
}
stream = object instanceof ReadableStream ? object : ReadableStreamFrom(object);
} else {
source = toUSVString(object);
contentType = "text/plain;charset=UTF-8";
}
if (typeof source === "string" || util.isBuffer(source)) {
length = Buffer.byteLength(source);
}
if (action != null) {
let iterator;
stream = new ReadableStream({
async start() {
iterator = action(object)[Symbol.asyncIterator]();
},
async pull(controller) {
const { value, done } = await iterator.next();
if (done) {
queueMicrotask(() => {
controller.close();
});
} else {
if (!isErrored(stream)) {
controller.enqueue(new Uint8Array(value));
}
}
return controller.desiredSize > 0;
},
async cancel(reason) {
await iterator.return();
}
});
} else if (!stream) {
stream = new ReadableStream({
async pull(controller) {
controller.enqueue(
typeof source === "string" ? new TextEncoder().encode(source) : source
);
3 years ago
queueMicrotask(() => {
controller.close();
});
}
});
}
const body = { stream, source, length };
return [body, contentType];
}
function safelyExtractBody(object, keepalive = false) {
if (!ReadableStream) {
ReadableStream = require("stream/web").ReadableStream;
}
if (object instanceof ReadableStream) {
assert(!util.isDisturbed(object), "The body has already been consumed.");
assert(!object.locked, "The stream is locked.");
3 years ago
}
return extractBody(object, keepalive);
}
function cloneBody(body) {
const [out1, out2] = body.stream.tee();
body.stream = out1;
return {
stream: out2,
length: body.length,
source: body.source
};
}
async function* consumeBody(body) {
if (body) {
if (isUint8Array(body)) {
yield body;
} else {
const stream = body.stream;
if (util.isDisturbed(stream)) {
throw new TypeError("The body has already been consumed.");
}
if (stream.locked) {
throw new TypeError("The stream is locked.");
}
stream[kBodyUsed] = true;
yield* stream;
}
}
}
function throwIfAborted(state) {
if (state.aborted) {
throw new DOMException("The operation was aborted.", "AbortError");
}
}
function bodyMixinMethods(instance) {
const methods = {
async blob() {
if (!(this instanceof instance)) {
throw new TypeError("Illegal invocation");
}
throwIfAborted(this[kState]);
const chunks = [];
for await (const chunk of consumeBody(this[kState].body)) {
if (!isUint8Array(chunk)) {
throw new TypeError("Expected Uint8Array chunk");
3 years ago
}
chunks.push(new Blob([chunk]));
}
return new Blob(chunks, { type: this.headers.get("Content-Type") || "" });
},
async arrayBuffer() {
if (!(this instanceof instance)) {
throw new TypeError("Illegal invocation");
}
throwIfAborted(this[kState]);
const contentLength = this.headers.get("content-length");
const encoded = this.headers.has("content-encoding");
if (!encoded && contentLength) {
const buffer2 = new Uint8Array(contentLength);
let offset2 = 0;
for await (const chunk of consumeBody(this[kState].body)) {
if (!isUint8Array(chunk)) {
throw new TypeError("Expected Uint8Array chunk");
}
buffer2.set(chunk, offset2);
offset2 += chunk.length;
3 years ago
}
return buffer2.buffer;
}
const chunks = [];
let size = 0;
for await (const chunk of consumeBody(this[kState].body)) {
if (!isUint8Array(chunk)) {
throw new TypeError("Expected Uint8Array chunk");
3 years ago
}
chunks.push(chunk);
size += chunk.byteLength;
3 years ago
}
const buffer = new Uint8Array(size);
let offset = 0;
for (const chunk of chunks) {
buffer.set(chunk, offset);
offset += chunk.byteLength;
3 years ago
}
return buffer.buffer;
},
async text() {
if (!(this instanceof instance)) {
throw new TypeError("Illegal invocation");
}
throwIfAborted(this[kState]);
let result = "";
const textDecoder = new TextDecoder();
for await (const chunk of consumeBody(this[kState].body)) {
if (!isUint8Array(chunk)) {
throw new TypeError("Expected Uint8Array chunk");
}
result += textDecoder.decode(chunk, { stream: true });
}
result += textDecoder.decode();
return result;
},
async json() {
if (!(this instanceof instance)) {
throw new TypeError("Illegal invocation");
}
throwIfAborted(this[kState]);
return JSON.parse(await this.text());
},
async formData() {
if (!(this instanceof instance)) {
throw new TypeError("Illegal invocation");
}
throwIfAborted(this[kState]);
const contentType = this.headers.get("Content-Type");
if (/multipart\/form-data/.test(contentType)) {
const headers = {};
for (const [key, value] of this.headers)
headers[key.toLowerCase()] = value;
const responseFormData = new FormData();
let busboy;
try {
busboy = Busboy({ headers });
} catch (err) {
throw Object.assign(new TypeError(), { cause: err });
}
busboy.on("field", (name, value) => {
responseFormData.append(name, value);
});
busboy.on("file", (name, value, info) => {
const { filename, encoding, mimeType } = info;
const chunks = [];
if (encoding.toLowerCase() === "base64") {
let base64chunk = "";
value.on("data", (chunk) => {
base64chunk += chunk.toString().replace(/[\r\n]/gm, "");
const end = base64chunk.length - base64chunk.length % 4;
chunks.push(Buffer.from(base64chunk.slice(0, end), "base64"));
base64chunk = base64chunk.slice(end);
});
value.on("end", () => {
chunks.push(Buffer.from(base64chunk, "base64"));
responseFormData.append(name, new File(chunks, filename, { type: mimeType }));
});
} else {
value.on("data", (chunk) => {
chunks.push(chunk);
});
value.on("end", () => {
responseFormData.append(name, new File(chunks, filename, { type: mimeType }));
});
}
});
const busboyResolve = new Promise((resolve, reject) => {
busboy.on("finish", resolve);
busboy.on("error", (err) => reject(err));
});
if (this.body !== null)
for await (const chunk of consumeBody(this[kState].body))
busboy.write(chunk);
busboy.end();
await busboyResolve;
return responseFormData;
} else if (/application\/x-www-form-urlencoded/.test(contentType)) {
let entries;
try {
let text = "";
const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true });
for await (const chunk of consumeBody(this[kState].body)) {
if (!isUint8Array(chunk)) {
throw new TypeError("Expected Uint8Array chunk");
}
text += textDecoder.decode(chunk, { stream: true });
}
text += textDecoder.decode();
entries = new URLSearchParams(text);
} catch (err) {
throw Object.assign(new TypeError(), { cause: err });
}
const formData = new FormData();
for (const [name, value] of entries) {
formData.append(name, value);
}
return formData;
} else {
await Promise.resolve();
throwIfAborted(this[kState]);
webidl.errors.exception({
header: `${instance.name}.formData`,
message: "Could not parse content as FormData."
});
3 years ago
}
}
};
return methods;
}
3 years ago
var properties = {
body: {
enumerable: true,
get() {
if (!this || !this[kState]) {
throw new TypeError("Illegal invocation");
}
3 years ago
return this[kState].body ? this[kState].body.stream : null;
}
},
bodyUsed: {
enumerable: true,
get() {
if (!this || !this[kState]) {
throw new TypeError("Illegal invocation");
}
3 years ago
return !!this[kState].body && util.isDisturbed(this[kState].body.stream);
}
}
};
function mixinBody(prototype) {
Object.assign(prototype.prototype, bodyMixinMethods(prototype));
Object.defineProperties(prototype.prototype, properties);
3 years ago
}
module2.exports = {
extractBody,
safelyExtractBody,
cloneBody,
mixinBody
};
}
});
// node_modules/undici/lib/core/request.js
var require_request = __commonJS({
"node_modules/undici/lib/core/request.js"(exports, module2) {
"use strict";
var {
InvalidArgumentError,
NotSupportedError
} = require_errors();
var assert = require("assert");
var util = require_util();
var tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/;
var headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
var invalidPathRegex = /[^\u0021-\u00ff]/;
3 years ago
var kHandler = Symbol("handler");
var channels = {};
var extractBody;
var nodeVersion = process.versions.node.split(".");
var nodeMajor = Number(nodeVersion[0]);
var nodeMinor = Number(nodeVersion[1]);
try {
const diagnosticsChannel = require("diagnostics_channel");
channels.create = diagnosticsChannel.channel("undici:request:create");
channels.bodySent = diagnosticsChannel.channel("undici:request:bodySent");
channels.headers = diagnosticsChannel.channel("undici:request:headers");
channels.trailers = diagnosticsChannel.channel("undici:request:trailers");
channels.error = diagnosticsChannel.channel("undici:request:error");
} catch {
channels.create = { hasSubscribers: false };
channels.bodySent = { hasSubscribers: false };
channels.headers = { hasSubscribers: false };
channels.trailers = { hasSubscribers: false };
channels.error = { hasSubscribers: false };
}
var Request = class {
constructor(origin, {
path: path3,
3 years ago
method,
body,
headers,
query,
3 years ago
idempotent,
blocking,
upgrade,
headersTimeout,
bodyTimeout,
throwOnError
3 years ago
}, handler) {
if (typeof path3 !== "string") {
3 years ago
throw new InvalidArgumentError("path must be a string");
} else if (path3[0] !== "/" && !(path3.startsWith("http://") || path3.startsWith("https://")) && method !== "CONNECT") {
3 years ago
throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
} else if (invalidPathRegex.exec(path3) !== null) {
throw new InvalidArgumentError("invalid request path");
3 years ago
}
if (typeof method !== "string") {
throw new InvalidArgumentError("method must be a string");
} else if (tokenRegExp.exec(method) === null) {
throw new InvalidArgumentError("invalid request method");
3 years ago
}
if (upgrade && typeof upgrade !== "string") {
throw new InvalidArgumentError("upgrade must be a string");
}
if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
throw new InvalidArgumentError("invalid headersTimeout");
}
if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
throw new InvalidArgumentError("invalid bodyTimeout");
}
this.headersTimeout = headersTimeout;
this.bodyTimeout = bodyTimeout;
this.throwOnError = throwOnError === true;
3 years ago
this.method = method;
if (body == null) {
this.body = null;
} else if (util.isStream(body)) {
this.body = body;
} else if (util.isBuffer(body)) {
this.body = body.byteLength ? body : null;
} else if (ArrayBuffer.isView(body)) {
this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null;
} else if (body instanceof ArrayBuffer) {
this.body = body.byteLength ? Buffer.from(body) : null;
3 years ago
} else if (typeof body === "string") {
this.body = body.length ? Buffer.from(body) : null;
} else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) {
this.body = body;
} else {
throw new InvalidArgumentError("body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable");
}
this.completed = false;
this.aborted = false;
this.upgrade = upgrade || null;
this.path = query ? util.buildURL(path3, query) : path3;
3 years ago
this.origin = origin;
this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
this.blocking = blocking == null ? false : blocking;
this.host = null;
this.contentLength = null;
this.contentType = null;
this.headers = "";
if (Array.isArray(headers)) {
if (headers.length % 2 !== 0) {
throw new InvalidArgumentError("headers array must be even");
}
for (let i = 0; i < headers.length; i += 2) {
processHeader(this, headers[i], headers[i + 1]);
}
} else if (headers && typeof headers === "object") {
const keys = Object.keys(headers);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
processHeader(this, key, headers[key]);
}
} else if (headers != null) {
throw new InvalidArgumentError("headers must be an object or an array");
}
if (util.isFormDataLike(this.body)) {
if (nodeMajor < 16 || nodeMajor === 16 && nodeMinor < 8) {
throw new InvalidArgumentError("Form-Data bodies are only supported in node v16.8 and newer.");
3 years ago
}
if (!extractBody) {
extractBody = require_body().extractBody;
}
const [bodyStream, contentType] = extractBody(body);
if (this.contentType == null) {
this.contentType = contentType;
this.headers += `content-type: ${contentType}\r
`;
}
this.body = bodyStream.stream;
} else if (util.isBlobLike(body) && this.contentType == null && body.type) {
this.contentType = body.type;
this.headers += `content-type: ${body.type}\r
`;
}
util.validateHandler(handler, method, upgrade);
this.servername = util.getServerName(this.host);
this[kHandler] = handler;
if (channels.create.hasSubscribers) {
channels.create.publish({ request: this });
}
}
onBodySent(chunk) {
if (this[kHandler].onBodySent) {
try {
this[kHandler].onBodySent(chunk);
} catch (err) {
this.onError(err);
}
}
}
onRequestSent() {
if (channels.bodySent.hasSubscribers) {
channels.bodySent.publish({ request: this });
}
}
onConnect(abort) {
assert(!this.aborted);
assert(!this.completed);
return this[kHandler].onConnect(abort);
}
onHeaders(statusCode, headers, resume, statusText) {
assert(!this.aborted);
assert(!this.completed);
if (channels.headers.hasSubscribers) {
channels.headers.publish({ request: this, response: { statusCode, headers, statusText } });
}
return this[kHandler].onHeaders(statusCode, headers, resume, statusText);
}
onData(chunk) {
assert(!this.aborted);
assert(!this.completed);
return this[kHandler].onData(chunk);
}
onUpgrade(statusCode, headers, socket) {
assert(!this.aborted);
assert(!this.completed);
return this[kHandler].onUpgrade(statusCode, headers, socket);
}
onComplete(trailers) {
assert(!this.aborted);
this.completed = true;
if (channels.trailers.hasSubscribers) {
channels.trailers.publish({ request: this, trailers });
}
return this[kHandler].onComplete(trailers);
}
onError(error) {
if (channels.error.hasSubscribers) {
channels.error.publish({ request: this, error });
}
if (this.aborted) {
return;
}
this.aborted = true;
return this[kHandler].onError(error);
}
addHeader(key, value) {
processHeader(this, key, value);
return this;
}
};
function processHeader(request, key, val) {
if (val && typeof val === "object") {
throw new InvalidArgumentError(`invalid ${key} header`);
} else if (val === void 0) {
return;
}
if (request.host === null && key.length === 4 && key.toLowerCase() === "host") {
request.host = val;
} else if (request.contentLength === null && key.length === 14 && key.toLowerCase() === "content-length") {
request.contentLength = parseInt(val, 10);
if (!Number.isFinite(request.contentLength)) {
throw new InvalidArgumentError("invalid content-length header");
}
} else if (request.contentType === null && key.length === 12 && key.toLowerCase() === "content-type" && headerCharRegex.exec(val) === null) {
3 years ago
request.contentType = val;
request.headers += `${key}: ${val}\r
`;
} else if (key.length === 17 && key.toLowerCase() === "transfer-encoding") {
throw new InvalidArgumentError("invalid transfer-encoding header");
} else if (key.length === 10 && key.toLowerCase() === "connection") {
throw new InvalidArgumentError("invalid connection header");
} else if (key.length === 10 && key.toLowerCase() === "keep-alive") {
throw new InvalidArgumentError("invalid keep-alive header");
} else if (key.length === 7 && key.toLowerCase() === "upgrade") {
throw new InvalidArgumentError("invalid upgrade header");
} else if (key.length === 6 && key.toLowerCase() === "expect") {
throw new NotSupportedError("expect header not supported");
} else if (tokenRegExp.exec(key) === null) {
throw new InvalidArgumentError("invalid header key");
} else if (headerCharRegex.exec(val) !== null) {
throw new InvalidArgumentError(`invalid ${key} header`);
3 years ago
} else {
request.headers += `${key}: ${val}\r
`;
}
}
module2.exports = Request;
}
});
// node_modules/undici/lib/dispatcher.js
var require_dispatcher = __commonJS({
"node_modules/undici/lib/dispatcher.js"(exports, module2) {
"use strict";
var EventEmitter = require("events");
var Dispatcher = class extends EventEmitter {
dispatch() {
throw new Error("not implemented");
}
close() {
throw new Error("not implemented");
}
destroy() {
throw new Error("not implemented");
}
};
module2.exports = Dispatcher;
}
});
// node_modules/undici/lib/dispatcher-base.js
var require_dispatcher_base = __commonJS({
"node_modules/undici/lib/dispatcher-base.js"(exports, module2) {
"use strict";
var Dispatcher = require_dispatcher();
var {
ClientDestroyedError,
ClientClosedError,
InvalidArgumentError
} = require_errors();
var { kDestroy, kClose, kDispatch, kInterceptors } = require_symbols();
3 years ago
var kDestroyed = Symbol("destroyed");
var kClosed = Symbol("closed");
var kOnDestroyed = Symbol("onDestroyed");
var kOnClosed = Symbol("onClosed");
var kInterceptedDispatch = Symbol("Intercepted Dispatch");
3 years ago
var DispatcherBase = class extends Dispatcher {
constructor() {
super();
this[kDestroyed] = false;
this[kOnDestroyed] = [];
this[kClosed] = false;
this[kOnClosed] = [];
}
get destroyed() {
return this[kDestroyed];
}
get closed() {
return this[kClosed];
}
get interceptors() {
return this[kInterceptors];
}
set interceptors(newInterceptors) {
if (newInterceptors) {
for (let i = newInterceptors.length - 1; i >= 0; i--) {
const interceptor = this[kInterceptors][i];
if (typeof interceptor !== "function") {
throw new InvalidArgumentError("interceptor must be an function");
}
}
}
this[kInterceptors] = newInterceptors;
}
3 years ago
close(callback) {
if (callback === void 0) {
return new Promise((resolve, reject) => {
this.close((err, data) => {
return err ? reject(err) : resolve(data);
});
});
}
if (typeof callback !== "function") {
throw new InvalidArgumentError("invalid callback");
}
if (this[kDestroyed]) {
queueMicrotask(() => callback(new ClientDestroyedError(), null));
return;
}
if (this[kClosed]) {
if (this[kOnClosed]) {
this[kOnClosed].push(callback);
} else {
queueMicrotask(() => callback(null, null));
}
return;
}
this[kClosed] = true;
this[kOnClosed].push(callback);
const onClosed = () => {
const callbacks = this[kOnClosed];
this[kOnClosed] = null;
for (let i = 0; i < callbacks.length; i++) {
callbacks[i](null, null);
}
};
this[kClose]().then(() => this.destroy()).then(() => {
queueMicrotask(onClosed);
});
}
destroy(err, callback) {
if (typeof err === "function") {
callback = err;
err = null;
3 years ago
}
if (callback === void 0) {
return new Promise((resolve, reject) => {
this.destroy(err, (err2, data) => {
return err2 ? reject(err2) : resolve(data);
});
});
3 years ago
}
if (typeof callback !== "function") {
throw new InvalidArgumentError("invalid callback");
3 years ago
}
if (this[kDestroyed]) {
if (this[kOnDestroyed]) {
this[kOnDestroyed].push(callback);
} else {
queueMicrotask(() => callback(null, null));
}
return;
3 years ago
}
if (!err) {
err = new ClientDestroyedError();
3 years ago
}
this[kDestroyed] = true;
this[kOnDestroyed].push(callback);
const onDestroyed = () => {
const callbacks = this[kOnDestroyed];
this[kOnDestroyed] = null;
for (let i = 0; i < callbacks.length; i++) {
callbacks[i](null, null);
}
};
this[kDestroy](err).then(() => {
queueMicrotask(onDestroyed);
});
3 years ago
}
[kInterceptedDispatch](opts, handler) {
if (!this[kInterceptors] || this[kInterceptors].length === 0) {
this[kInterceptedDispatch] = this[kDispatch];
return this[kDispatch](opts, handler);
3 years ago
}
let dispatch = this[kDispatch].bind(this);
for (let i = this[kInterceptors].length - 1; i >= 0; i--) {
dispatch = this[kInterceptors][i](dispatch);
3 years ago
}
this[kInterceptedDispatch] = dispatch;
return dispatch(opts, handler);
3 years ago
}
dispatch(opts, handler) {
if (!handler || typeof handler !== "object") {
throw new InvalidArgumentError("handler must be an object");
3 years ago
}
try {
if (!opts || typeof opts !== "object") {
throw new InvalidArgumentError("opts must be an object.");
}
if (this[kDestroyed]) {
throw new ClientDestroyedError();
}
if (this[kClosed]) {
throw new ClientClosedError();
3 years ago
}
return this[kInterceptedDispatch](opts, handler);
} catch (err) {
if (typeof handler.onError !== "function") {
throw new InvalidArgumentError("invalid onError method");
}
handler.onError(err);
return false;
3 years ago
}
}
};
module2.exports = DispatcherBase;
3 years ago
}
});
// node_modules/undici/lib/core/connect.js
var require_connect = __commonJS({
"node_modules/undici/lib/core/connect.js"(exports, module2) {
"use strict";
var net = require("net");
var assert = require("assert");
var util = require_util();
var { InvalidArgumentError, ConnectTimeoutError } = require_errors();
var tls;
function buildConnector({ maxCachedSessions, socketPath, timeout, ...opts }) {
if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
throw new InvalidArgumentError("maxCachedSessions must be a positive integer or zero");
}
const options = { path: socketPath, ...opts };
const sessionCache = /* @__PURE__ */ new Map();
timeout = timeout == null ? 1e4 : timeout;
maxCachedSessions = maxCachedSessions == null ? 100 : maxCachedSessions;
return function connect({ hostname, host, protocol, port, servername, httpSocket }, callback) {
3 years ago
let socket;
if (protocol === "https:") {
if (!tls) {
tls = require("tls");
}
servername = servername || options.servername || util.getServerName(host) || null;
const sessionKey = servername || hostname;
const session = sessionCache.get(sessionKey) || null;
assert(sessionKey);
socket = tls.connect({
highWaterMark: 16384,
...options,
servername,
session,
socket: httpSocket,
3 years ago
port: port || 443,
host: hostname
});
socket.on("session", function(session2) {
if (maxCachedSessions === 0) {
return;
}
if (sessionCache.size >= maxCachedSessions) {
const { value: oldestKey } = sessionCache.keys().next();
sessionCache.delete(oldestKey);
}
sessionCache.set(sessionKey, session2);
}).on("error", function(err) {
if (sessionKey && err.code !== "UND_ERR_INFO") {
sessionCache.delete(sessionKey);
}
});
} else {
assert(!httpSocket, "httpSocket can only be sent on TLS update");
3 years ago
socket = net.connect({
highWaterMark: 64 * 1024,
...options,
port: port || 80,
host: hostname
});
}
const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout);
3 years ago
socket.setNoDelay(true).once(protocol === "https:" ? "secureConnect" : "connect", function() {
cancelTimeout();
3 years ago
if (callback) {
const cb = callback;
callback = null;
cb(null, this);
}
}).on("error", function(err) {
cancelTimeout();
3 years ago
if (callback) {
const cb = callback;
callback = null;
cb(err);
}
});
return socket;
};
}
function setupTimeout(onConnectTimeout2, timeout) {
if (!timeout) {
return () => {
};
}
let s1 = null;
let s2 = null;
const timeoutId = setTimeout(() => {
s1 = setImmediate(() => {
if (process.platform === "win32") {
s2 = setImmediate(() => onConnectTimeout2());
} else {
onConnectTimeout2();
}
});
}, timeout);
return () => {
clearTimeout(timeoutId);
clearImmediate(s1);
clearImmediate(s2);
};
}
3 years ago
function onConnectTimeout(socket) {
util.destroy(socket, new ConnectTimeoutError());
}
module2.exports = buildConnector;
}
});
// node_modules/undici/lib/llhttp/utils.js
var require_utils6 = __commonJS({
3 years ago
"node_modules/undici/lib/llhttp/utils.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.enumToMap = void 0;
function enumToMap(obj) {
const res = {};
Object.keys(obj).forEach((key) => {
const value = obj[key];
if (typeof value === "number") {
res[key] = value;
}
});
return res;
}
exports.enumToMap = enumToMap;
}
});
// node_modules/undici/lib/llhttp/constants.js
var require_constants2 = __commonJS({
"node_modules/undici/lib/llhttp/constants.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;
var utils_1 = require_utils6();
3 years ago
var ERROR;
(function(ERROR2) {
ERROR2[ERROR2["OK"] = 0] = "OK";
ERROR2[ERROR2["INTERNAL"] = 1] = "INTERNAL";
ERROR2[ERROR2["STRICT"] = 2] = "STRICT";
ERROR2[ERROR2["LF_EXPECTED"] = 3] = "LF_EXPECTED";
ERROR2[ERROR2["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH";
ERROR2[ERROR2["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION";
ERROR2[ERROR2["INVALID_METHOD"] = 6] = "INVALID_METHOD";
ERROR2[ERROR2["INVALID_URL"] = 7] = "INVALID_URL";
ERROR2[ERROR2["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT";
ERROR2[ERROR2["INVALID_VERSION"] = 9] = "INVALID_VERSION";
ERROR2[ERROR2["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN";
ERROR2[ERROR2["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH";
ERROR2[ERROR2["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE";
ERROR2[ERROR2["INVALID_STATUS"] = 13] = "INVALID_STATUS";
ERROR2[ERROR2["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE";
ERROR2[ERROR2["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING";
ERROR2[ERROR2["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN";
ERROR2[ERROR2["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE";
ERROR2[ERROR2["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE";
ERROR2[ERROR2["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER";
ERROR2[ERROR2["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE";
ERROR2[ERROR2["PAUSED"] = 21] = "PAUSED";
ERROR2[ERROR2["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE";
ERROR2[ERROR2["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE";
ERROR2[ERROR2["USER"] = 24] = "USER";
})(ERROR = exports.ERROR || (exports.ERROR = {}));
var TYPE;
(function(TYPE2) {
TYPE2[TYPE2["BOTH"] = 0] = "BOTH";
TYPE2[TYPE2["REQUEST"] = 1] = "REQUEST";
TYPE2[TYPE2["RESPONSE"] = 2] = "RESPONSE";
})(TYPE = exports.TYPE || (exports.TYPE = {}));
var FLAGS;
(function(FLAGS2) {
FLAGS2[FLAGS2["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE";
FLAGS2[FLAGS2["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE";
FLAGS2[FLAGS2["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE";
FLAGS2[FLAGS2["CHUNKED"] = 8] = "CHUNKED";
FLAGS2[FLAGS2["UPGRADE"] = 16] = "UPGRADE";
FLAGS2[FLAGS2["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH";
FLAGS2[FLAGS2["SKIPBODY"] = 64] = "SKIPBODY";
FLAGS2[FLAGS2["TRAILING"] = 128] = "TRAILING";
FLAGS2[FLAGS2["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING";
})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));
var LENIENT_FLAGS;
(function(LENIENT_FLAGS2) {
LENIENT_FLAGS2[LENIENT_FLAGS2["HEADERS"] = 1] = "HEADERS";
LENIENT_FLAGS2[LENIENT_FLAGS2["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH";
LENIENT_FLAGS2[LENIENT_FLAGS2["KEEP_ALIVE"] = 4] = "KEEP_ALIVE";
})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {}));
var METHODS;
(function(METHODS2) {
METHODS2[METHODS2["DELETE"] = 0] = "DELETE";
METHODS2[METHODS2["GET"] = 1] = "GET";
METHODS2[METHODS2["HEAD"] = 2] = "HEAD";
METHODS2[METHODS2["POST"] = 3] = "POST";
METHODS2[METHODS2["PUT"] = 4] = "PUT";
METHODS2[METHODS2["CONNECT"] = 5] = "CONNECT";
METHODS2[METHODS2["OPTIONS"] = 6] = "OPTIONS";
METHODS2[METHODS2["TRACE"] = 7] = "TRACE";
METHODS2[METHODS2["COPY"] = 8] = "COPY";
METHODS2[METHODS2["LOCK"] = 9] = "LOCK";
METHODS2[METHODS2["MKCOL"] = 10] = "MKCOL";
METHODS2[METHODS2["MOVE"] = 11] = "MOVE";
METHODS2[METHODS2["PROPFIND"] = 12] = "PROPFIND";
METHODS2[METHODS2["PROPPATCH"] = 13] = "PROPPATCH";
METHODS2[METHODS2["SEARCH"] = 14] = "SEARCH";
METHODS2[METHODS2["UNLOCK"] = 15] = "UNLOCK";
METHODS2[METHODS2["BIND"] = 16] = "BIND";
METHODS2[METHODS2["REBIND"] = 17] = "REBIND";
METHODS2[METHODS2["UNBIND"] = 18] = "UNBIND";
METHODS2[METHODS2["ACL"] = 19] = "ACL";
METHODS2[METHODS2["REPORT"] = 20] = "REPORT";
METHODS2[METHODS2["MKACTIVITY"] = 21] = "MKACTIVITY";
METHODS2[METHODS2["CHECKOUT"] = 22] = "CHECKOUT";
METHODS2[METHODS2["MERGE"] = 23] = "MERGE";
METHODS2[METHODS2["M-SEARCH"] = 24] = "M-SEARCH";
METHODS2[METHODS2["NOTIFY"] = 25] = "NOTIFY";
METHODS2[METHODS2["SUBSCRIBE"] = 26] = "SUBSCRIBE";
METHODS2[METHODS2["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE";
METHODS2[METHODS2["PATCH"] = 28] = "PATCH";
METHODS2[METHODS2["PURGE"] = 29] = "PURGE";
METHODS2[METHODS2["MKCALENDAR"] = 30] = "MKCALENDAR";
METHODS2[METHODS2["LINK"] = 31] = "LINK";
METHODS2[METHODS2["UNLINK"] = 32] = "UNLINK";
METHODS2[METHODS2["SOURCE"] = 33] = "SOURCE";
METHODS2[METHODS2["PRI"] = 34] = "PRI";
METHODS2[METHODS2["DESCRIBE"] = 35] = "DESCRIBE";
METHODS2[METHODS2["ANNOUNCE"] = 36] = "ANNOUNCE";
METHODS2[METHODS2["SETUP"] = 37] = "SETUP";
METHODS2[METHODS2["PLAY"] = 38] = "PLAY";
METHODS2[METHODS2["PAUSE"] = 39] = "PAUSE";
METHODS2[METHODS2["TEARDOWN"] = 40] = "TEARDOWN";
METHODS2[METHODS2["GET_PARAMETER"] = 41] = "GET_PARAMETER";
METHODS2[METHODS2["SET_PARAMETER"] = 42] = "SET_PARAMETER";
METHODS2[METHODS2["REDIRECT"] = 43] = "REDIRECT";
METHODS2[METHODS2["RECORD"] = 44] = "RECORD";
METHODS2[METHODS2["FLUSH"] = 45] = "FLUSH";
})(METHODS = exports.METHODS || (exports.METHODS = {}));
exports.METHODS_HTTP = [
METHODS.DELETE,
METHODS.GET,
METHODS.HEAD,
METHODS.POST,
METHODS.PUT,
METHODS.CONNECT,
METHODS.OPTIONS,
METHODS.TRACE,
METHODS.COPY,
METHODS.LOCK,
METHODS.MKCOL,
METHODS.MOVE,
METHODS.PROPFIND,
METHODS.PROPPATCH,
METHODS.SEARCH,
METHODS.UNLOCK,
METHODS.BIND,
METHODS.REBIND,
METHODS.UNBIND,
METHODS.ACL,
METHODS.REPORT,
METHODS.MKACTIVITY,
METHODS.CHECKOUT,
METHODS.MERGE,
METHODS["M-SEARCH"],
METHODS.NOTIFY,
METHODS.SUBSCRIBE,
METHODS.UNSUBSCRIBE,
METHODS.PATCH,
METHODS.PURGE,
METHODS.MKCALENDAR,
METHODS.LINK,
METHODS.UNLINK,
METHODS.PRI,
METHODS.SOURCE
];
exports.METHODS_ICE = [
METHODS.SOURCE
];
exports.METHODS_RTSP = [
METHODS.OPTIONS,
METHODS.DESCRIBE,
METHODS.ANNOUNCE,
METHODS.SETUP,
METHODS.PLAY,
METHODS.PAUSE,
METHODS.TEARDOWN,
METHODS.GET_PARAMETER,
METHODS.SET_PARAMETER,
METHODS.REDIRECT,
METHODS.RECORD,
METHODS.FLUSH,
METHODS.GET,
METHODS.POST
];
exports.METHOD_MAP = utils_1.enumToMap(METHODS);
exports.H_METHOD_MAP = {};
Object.keys(exports.METHOD_MAP).forEach((key) => {
if (/^H/.test(key)) {
exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key];
}
});
var FINISH;
(function(FINISH2) {
FINISH2[FINISH2["SAFE"] = 0] = "SAFE";
FINISH2[FINISH2["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB";
FINISH2[FINISH2["UNSAFE"] = 2] = "UNSAFE";
})(FINISH = exports.FINISH || (exports.FINISH = {}));
exports.ALPHA = [];
for (let i = "A".charCodeAt(0); i <= "Z".charCodeAt(0); i++) {
exports.ALPHA.push(String.fromCharCode(i));
exports.ALPHA.push(String.fromCharCode(i + 32));
}
exports.NUM_MAP = {
0: 0,
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
7: 7,
8: 8,
9: 9
};
exports.HEX_MAP = {
0: 0,
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
7: 7,
8: 8,
9: 9,
A: 10,
B: 11,
C: 12,
D: 13,
E: 14,
F: 15,
a: 10,
b: 11,
c: 12,
d: 13,
e: 14,
f: 15
};
exports.NUM = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9"
];
exports.ALPHANUM = exports.ALPHA.concat(exports.NUM);
exports.MARK = ["-", "_", ".", "!", "~", "*", "'", "(", ")"];
exports.USERINFO_CHARS = exports.ALPHANUM.concat(exports.MARK).concat(["%", ";", ":", "&", "=", "+", "$", ","]);
exports.STRICT_URL_CHAR = [
"!",
'"',
"$",
"%",
"&",
"'",
"(",
")",
"*",
"+",
",",
"-",
".",
"/",
":",
";",
"<",
"=",
">",
"@",
"[",
"\\",
"]",
"^",
"_",
"`",
"{",
"|",
"}",
"~"
].concat(exports.ALPHANUM);
exports.URL_CHAR = exports.STRICT_URL_CHAR.concat([" ", "\f"]);
for (let i = 128; i <= 255; i++) {
exports.URL_CHAR.push(i);
}
exports.HEX = exports.NUM.concat(["a", "b", "c", "d", "e", "f", "A", "B", "C", "D", "E", "F"]);
exports.STRICT_TOKEN = [
"!",
"#",
"$",
"%",
"&",
"'",
"*",
"+",
"-",
".",
"^",
"_",
"`",
"|",
"~"
].concat(exports.ALPHANUM);
exports.TOKEN = exports.STRICT_TOKEN.concat([" "]);
exports.HEADER_CHARS = [" "];
for (let i = 32; i <= 255; i++) {
if (i !== 127) {
exports.HEADER_CHARS.push(i);
}
}
exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44);
exports.MAJOR = exports.NUM_MAP;
exports.MINOR = exports.MAJOR;
var HEADER_STATE;
(function(HEADER_STATE2) {
HEADER_STATE2[HEADER_STATE2["GENERAL"] = 0] = "GENERAL";
HEADER_STATE2[HEADER_STATE2["CONNECTION"] = 1] = "CONNECTION";
HEADER_STATE2[HEADER_STATE2["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH";
HEADER_STATE2[HEADER_STATE2["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING";
HEADER_STATE2[HEADER_STATE2["UPGRADE"] = 4] = "UPGRADE";
HEADER_STATE2[HEADER_STATE2["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE";
HEADER_STATE2[HEADER_STATE2["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE";
HEADER_STATE2[HEADER_STATE2["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE";
HEADER_STATE2[HEADER_STATE2["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED";
})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {}));
exports.SPECIAL_HEADERS = {
"connection": HEADER_STATE.CONNECTION,
"content-length": HEADER_STATE.CONTENT_LENGTH,
"proxy-connection": HEADER_STATE.CONNECTION,
"transfer-encoding": HEADER_STATE.TRANSFER_ENCODING,
"upgrade": HEADER_STATE.UPGRADE
};
}
});
// node_modules/undici/lib/handler/RedirectHandler.js
var require_RedirectHandler = __commonJS({
"node_modules/undici/lib/handler/RedirectHandler.js"(exports, module2) {
"use strict";
var util = require_util();
var { kBodyUsed } = require_symbols();
var assert = require("assert");
var { InvalidArgumentError } = require_errors();
var EE = require("events");
var redirectableStatusCodes = [300, 301, 302, 303, 307, 308];
var kBody = Symbol("body");
var BodyAsyncIterable = class {
constructor(body) {
this[kBody] = body;
this[kBodyUsed] = false;
}
async *[Symbol.asyncIterator]() {
assert(!this[kBodyUsed], "disturbed");
this[kBodyUsed] = true;
yield* this[kBody];
}
};
var RedirectHandler = class {
constructor(dispatch, maxRedirections, opts, handler) {
if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
throw new InvalidArgumentError("maxRedirections must be a positive number");
}
util.validateHandler(handler, opts.method, opts.upgrade);
this.dispatch = dispatch;
this.location = null;
this.abort = null;
this.opts = { ...opts, maxRedirections: 0 };
this.maxRedirections = maxRedirections;
this.handler = handler;
this.history = [];
if (util.isStream(this.opts.body)) {
if (util.bodyLength(this.opts.body) === 0) {
this.opts.body.on("data", function() {
assert(false);
});
}
if (typeof this.opts.body.readableDidRead !== "boolean") {
this.opts.body[kBodyUsed] = false;
EE.prototype.on.call(this.opts.body, "data", function() {
this[kBodyUsed] = true;
});
}
} else if (this.opts.body && typeof this.opts.body.pipeTo === "function") {
this.opts.body = new BodyAsyncIterable(this.opts.body);
} else if (this.opts.body && typeof this.opts.body !== "string" && !ArrayBuffer.isView(this.opts.body) && util.isIterable(this.opts.body)) {
this.opts.body = new BodyAsyncIterable(this.opts.body);
}
}
onConnect(abort) {
this.abort = abort;
this.handler.onConnect(abort, { history: this.history });
}
onUpgrade(statusCode, headers, socket) {
this.handler.onUpgrade(statusCode, headers, socket);
}
onError(error) {
this.handler.onError(error);
}
onHeaders(statusCode, headers, resume, statusText) {
this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) ? null : parseLocation(statusCode, headers);
if (this.opts.origin) {
this.history.push(new URL(this.opts.path, this.opts.origin));
}
if (!this.location) {
return this.handler.onHeaders(statusCode, headers, resume, statusText);
}
const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
const path3 = search ? `${pathname}${search}` : pathname;
this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
this.opts.path = path3;
this.opts.origin = origin;
this.opts.maxRedirections = 0;
if (statusCode === 303 && this.opts.method !== "HEAD") {
this.opts.method = "GET";
this.opts.body = null;
}
}
onData(chunk) {
if (this.location) {
} else {
return this.handler.onData(chunk);
}
}
onComplete(trailers) {
if (this.location) {
this.location = null;
this.abort = null;
this.dispatch(this.opts, this);
} else {
this.handler.onComplete(trailers);
}
}
onBodySent(chunk) {
if (this.handler.onBodySent) {
this.handler.onBodySent(chunk);
}
}
};
function parseLocation(statusCode, headers) {
if (redirectableStatusCodes.indexOf(statusCode) === -1) {
return null;
}
for (let i = 0; i < headers.length; i += 2) {
if (headers[i].toString().toLowerCase() === "location") {
return headers[i + 1];
}
}
}
function shouldRemoveHeader(header, removeContent, unknownOrigin) {
return header.length === 4 && header.toString().toLowerCase() === "host" || removeContent && header.toString().toLowerCase().indexOf("content-") === 0 || unknownOrigin && header.length === 13 && header.toString().toLowerCase() === "authorization" || unknownOrigin && header.length === 6 && header.toString().toLowerCase() === "cookie";
}
function cleanRequestHeaders(headers, removeContent, unknownOrigin) {
const ret = [];
if (Array.isArray(headers)) {
for (let i = 0; i < headers.length; i += 2) {
if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {
ret.push(headers[i], headers[i + 1]);
}
}
} else if (headers && typeof headers === "object") {
for (const key of Object.keys(headers)) {
if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
ret.push(key, headers[key]);
}
}
} else {
assert(headers == null, "headers must be an object or an array");
}
return ret;
}
module2.exports = RedirectHandler;
}
});
// node_modules/undici/lib/interceptor/redirectInterceptor.js
var require_redirectInterceptor = __commonJS({
"node_modules/undici/lib/interceptor/redirectInterceptor.js"(exports, module2) {
"use strict";
var RedirectHandler = require_RedirectHandler();
function createRedirectInterceptor({ maxRedirections: defaultMaxRedirections }) {
return (dispatch) => {
return function Intercept(opts, handler) {
const { maxRedirections = defaultMaxRedirections } = opts;
if (!maxRedirections) {
return dispatch(opts, handler);
}
const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler);
opts = { ...opts, maxRedirections: 0 };
return dispatch(opts, redirectHandler);
};
};
}
module2.exports = createRedirectInterceptor;
}
});
3 years ago
// node_modules/undici/lib/llhttp/llhttp.wasm.js
var require_llhttp_wasm = __commonJS({
"node_modules/undici/lib/llhttp/llhttp.wasm.js"(exports, module2) {
module2.exports = "AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAzk4AwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAYGAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAAMEBQFwAQ4OBQMBAAIGCAF/AUGAuAQLB/UEHwZtZW1vcnkCAAtfaW5pdGlhbGl6ZQAJGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtsbGh0dHBfaW5pdAAKGGxsaHR0cF9zaG91bGRfa2VlcF9hbGl2ZQA1DGxsaHR0cF9hbGxvYwAMBm1hbGxvYwA6C2xsaHR0cF9mcmVlAA0EZnJlZQA8D2xsaHR0cF9nZXRfdHlwZQAOFWxsaHR0cF9nZXRfaHR0cF9tYWpvcgAPFWxsaHR0cF9nZXRfaHR0cF9taW5vcgAQEWxsaHR0cF9nZXRfbWV0aG9kABEWbGxodHRwX2dldF9zdGF0dXNfY29kZQASEmxsaHR0cF9nZXRfdXBncmFkZQATDGxsaHR0cF9yZXNldAAUDmxsaHR0cF9leGVjdXRlABUUbGxodHRwX3NldHRpbmdzX2luaXQAFg1sbGh0dHBfZmluaXNoABcMbGxodHRwX3BhdXNlABgNbGxodHRwX3Jlc3VtZQAZG2xsaHR0cF9yZXN1bWVfYWZ0ZXJfdXBncmFkZQAaEGxsaHR0cF9nZXRfZXJybm8AGxdsbGh0dHBfZ2V0X2Vycm9yX3JlYXNvbgAcF2xsaHR0cF9zZXRfZXJyb3JfcmVhc29uAB0UbGxodHRwX2dldF9lcnJvcl9wb3MAHhFsbGh0dHBfZXJybm9fbmFtZQAfEmxsaHR0cF9tZXRob2RfbmFtZQAgGmxsaHR0cF9zZXRfbGVuaWVudF9oZWFkZXJzACEhbGxodHRwX3NldF9sZW5pZW50X2NodW5rZWRfbGVuZ3RoACIYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mADMJEwEAQQELDQECAwQFCwYHLiooJCYKxqgCOAIACwgAEIiAgIAACxkAIAAQtoCAgAAaIAAgAjYCNCAAIAE6ACgLHAAgACAALwEyIAAtAC4gABC1gICAABCAgICAAAspAQF/QTgQuoCAgAAiARC2gICAABogAUGAiICAADYCNCABIAA6ACggAQsKACAAELyAgIAACwcAIAAtACgLBwAgAC0AKgsHACAALQArCwcAIAAtACkLBwAgAC8BMgsHACAALQAuC0UBBH8gACgCGCEBIAAtAC0hAiAALQAoIQMgACgCNCEEIAAQtoCAgAAaIAAgBDYCNCAAIAM6ACggACACOgAtIAAgATYCGAsRACAAIAEgASACahC3gICAAAtFACAAQgA3AgAgAEEwakIANwIAIABBKGpCADcCACAAQSBqQgA3AgAgAEEYakIANwIAIABBEGpCADcCACAAQQhqQgA3AgALZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI0IgFFDQAgASgCHCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQv4CAgAAACyAAQf+RgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQYSUgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBGkkNABC/gICAAAALIABBAnRByJuAgABqKAIACyIAAkAgAEEuSQ0AEL+AgIAAAAsgAEECdEGwnICAAGooAgALFgAgACAALQAtQf4BcSABQQBHcjoALQsZACAAIAAtAC1B/QFxIAFBAEdBAXRyOgAtCy4BAn9BACEDAkAgACgCNCIERQ0AIAQoAgAiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI0IgRFDQAgBCgCBCIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZyOgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjQiBEUNACAEKAIoIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCNCIERQ0AIAQoAggiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEHSioCAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI0IgRFDQAgBCgCLCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjQiBEUNACAEKAIMIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB3ZOAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCNCIERQ0AIAQoAjAiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI0IgRFDQAgBCgCECIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQcOQgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjQiBEUNACAEKAI0IgRFDQAgACAEEYCAgIAAACEDCyADCy4BAn9BACEDAkAgACgCNCIERQ0AIAQoAhQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI0IgRFDQAgBCgCHCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjQiBEUNACAEKAIYIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB0oiAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCNCIERQ0AIAQoAiAiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI0IgRFDQAgBCgCJCIERQ0AIAAgBBGAgICAAAAhAwsgAwtFAQF/AkACQCAALwEwQRRxQRRHDQBBASEDIAAtAChBAUYNASAALwEyQeUARiEDDAELIAAtAClBBUYhAwsgACADOgAuQQAL8gEBA39BASEDAkAgAC8BMCIEQQhxDQAgACkDIEIAUiEDCwJAAkAgAC0ALkUNAEEBIQUgAC0AKUEFRg0BQQEhBSAEQcAAcUUgA3FBAUcNAQtBACEFIARBwABxDQBBAiEFIARBCHENAAJAIARBgARxRQ0AAkAgAC0AKEEBRw0AIAAtAC1BCnENAEEFDwtBBA8LAkAgBEEgcQ0AAkAgAC0AKEEBRg0AIAAvATIiAEGcf2pB5ABJDQAgAEHMAUYNACAAQbACRg0AQQQhBSAEQYgEcUGABEYNAiAEQShxRQ0CC0EADwtBAEEDIAApAyBQGyEFCyAFC10BAn9BACEBAkAgAC0AKEEBRg0AIAAvATIiAkGcf2pB5ABJDQAgAkHMAUYNACACQbACRg0AIAAvATAiAEHAAHENAEEBIQEgAEGIBHFBgARGDQAgAEEocUUhAQsgAQuiAQEDfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEDIAAvATAiBEECcUUNAQwCC0EAIQMgAC8BMCIEQQFxRQ0BC0EBIQMgAC0AKEEBRg0AIAAvATIiBUGcf2pB5ABJDQAgBUHMAUYNACAFQbACRg0AIARBwABxDQBBACEDIARBiARxQYAERg0AIARBKHFBAEchAwsgAEEAOwEwIABBADoALyADC5QBAQJ/AkACQAJAIAAtACpFDQAgAC0AK0UN
3 years ago
}
});
// node_modules/undici/lib/llhttp/llhttp_simd.wasm.js
var require_llhttp_simd_wasm = __commonJS({
"node_modules/undici/lib/llhttp/llhttp_simd.wasm.js"(exports, module2) {
module2.exports = "AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAzk4AwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAYGAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAAMEBQFwAQ4OBQMBAAIGCAF/AUGAuAQLB/UEHwZtZW1vcnkCAAtfaW5pdGlhbGl6ZQAJGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtsbGh0dHBfaW5pdAAKGGxsaHR0cF9zaG91bGRfa2VlcF9hbGl2ZQA1DGxsaHR0cF9hbGxvYwAMBm1hbGxvYwA6C2xsaHR0cF9mcmVlAA0EZnJlZQA8D2xsaHR0cF9nZXRfdHlwZQAOFWxsaHR0cF9nZXRfaHR0cF9tYWpvcgAPFWxsaHR0cF9nZXRfaHR0cF9taW5vcgAQEWxsaHR0cF9nZXRfbWV0aG9kABEWbGxodHRwX2dldF9zdGF0dXNfY29kZQASEmxsaHR0cF9nZXRfdXBncmFkZQATDGxsaHR0cF9yZXNldAAUDmxsaHR0cF9leGVjdXRlABUUbGxodHRwX3NldHRpbmdzX2luaXQAFg1sbGh0dHBfZmluaXNoABcMbGxodHRwX3BhdXNlABgNbGxodHRwX3Jlc3VtZQAZG2xsaHR0cF9yZXN1bWVfYWZ0ZXJfdXBncmFkZQAaEGxsaHR0cF9nZXRfZXJybm8AGxdsbGh0dHBfZ2V0X2Vycm9yX3JlYXNvbgAcF2xsaHR0cF9zZXRfZXJyb3JfcmVhc29uAB0UbGxodHRwX2dldF9lcnJvcl9wb3MAHhFsbGh0dHBfZXJybm9fbmFtZQAfEmxsaHR0cF9tZXRob2RfbmFtZQAgGmxsaHR0cF9zZXRfbGVuaWVudF9oZWFkZXJzACEhbGxodHRwX3NldF9sZW5pZW50X2NodW5rZWRfbGVuZ3RoACIYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mADMJEwEAQQELDQECAwQFCwYHLiooJCYKuKgCOAIACwgAEIiAgIAACxkAIAAQtoCAgAAaIAAgAjYCNCAAIAE6ACgLHAAgACAALwEyIAAtAC4gABC1gICAABCAgICAAAspAQF/QTgQuoCAgAAiARC2gICAABogAUGAiICAADYCNCABIAA6ACggAQsKACAAELyAgIAACwcAIAAtACgLBwAgAC0AKgsHACAALQArCwcAIAAtACkLBwAgAC8BMgsHACAALQAuC0UBBH8gACgCGCEBIAAtAC0hAiAALQAoIQMgACgCNCEEIAAQtoCAgAAaIAAgBDYCNCAAIAM6ACggACACOgAtIAAgATYCGAsRACAAIAEgASACahC3gICAAAs+AQF7IAD9DAAAAAAAAAAAAAAAAAAAAAAiAf0LAgAgAEEwakIANwIAIABBIGogAf0LAgAgAEEQaiAB/QsCAAtnAQF/QQAhAQJAIAAoAgwNAAJAAkACQAJAIAAtAC8OAwEAAwILIAAoAjQiAUUNACABKAIcIgFFDQAgACABEYCAgIAAACIBDQMLQQAPCxC/gICAAAALIABB/5GAgAA2AhBBDiEBCyABCx4AAkAgACgCDA0AIABBhJSAgAA2AhAgAEEVNgIMCwsWAAJAIAAoAgxBFUcNACAAQQA2AgwLCxYAAkAgACgCDEEWRw0AIABBADYCDAsLBwAgACgCDAsHACAAKAIQCwkAIAAgATYCEAsHACAAKAIUCyIAAkAgAEEaSQ0AEL+AgIAAAAsgAEECdEHIm4CAAGooAgALIgACQCAAQS5JDQAQv4CAgAAACyAAQQJ0QbCcgIAAaigCAAsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LLgECf0EAIQMCQCAAKAI0IgRFDQAgBCgCACIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjQiBEUNACAEKAIEIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABBnI6AgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCNCIERQ0AIAQoAigiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI0IgRFDQAgBCgCCCIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQdKKgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjQiBEUNACAEKAIsIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCNCIERQ0AIAQoAgwiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEHdk4CAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI0IgRFDQAgBCgCMCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjQiBEUNACAEKAIQIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABBw5CAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCNCIERQ0AIAQoAjQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI0IgRFDQAgBCgCFCIERQ0AIAAgBBGAgICAAAAhAwsgAwsuAQJ/QQAhAwJAIAAoAjQiBEUNACAEKAIcIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCNCIERQ0AIAQoAhgiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEHSiICAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI0IgRFDQAgBCgCICIERQ0AIAAgBBGAgICAAAAhAwsgAwsuAQJ/QQAhAwJAIAAoAjQiBEUNACAEKAIkIgRFDQAgACAEEYCAgIAAACEDCyADC0UBAX8CQAJAIAAvATBBFHFBFEcNAEEBIQMgAC0AKEEBRg0BIAAvATJB5QBGIQMMAQsgAC0AKUEFRiEDCyAAIAM6AC5BAAvyAQEDf0EBIQMCQCAALwEwIgRBCHENACAAKQMgQgBSIQMLAkACQCAALQAuRQ0AQQEhBSAALQApQQVGDQFBASEFIARBwABxRSADcUEBRw0BC0EAIQUgBEHAAHENAEECIQUgBEEIcQ0AAkAgBEGABHFFDQACQCAALQAoQQFHDQAgAC0ALUEKcQ0AQQUPC0EEDwsCQCAEQSBxDQACQCAALQAoQQFGDQAgAC8BMiIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQBBBCEFIARBiARxQYAERg0CIARBKHFFDQILQQAPC0EAQQMgACkDIFAbIQULIAULXQECf0EAIQECQCAALQAoQQFGDQAgAC8BMiICQZx/akHkAEkNACACQcwBRg0AIAJBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhASAAQYgEcUGABEYNACAAQShxRSEBCyABC6IBAQN/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMiIFQZx/akHkAEkNACAFQcwBRg0AIAVBsAJGDQAgBEHAAHENAEEAIQMgBEGIBHFBgARGDQAgBEEocUEARyEDCyAAQQA7ATAgAEEAOgAvIAMLlAEBAn8CQAJAAkAgAC0AKkUNACAALQArRQ0AQQAhASAA
3 years ago
}
});
// node_modules/undici/lib/client.js
var require_client = __commonJS({
"node_modules/undici/lib/client.js"(exports, module2) {
"use strict";
var assert = require("assert");
var net = require("net");
var util = require_util();
var Request = require_request();
var DispatcherBase = require_dispatcher_base();
var {
RequestContentLengthMismatchError,
ResponseContentLengthMismatchError,
InvalidArgumentError,
RequestAbortedError,
HeadersTimeoutError,
HeadersOverflowError,
SocketError,
InformationalError,
BodyTimeoutError,
HTTPParserError
} = require_errors();
var buildConnector = require_connect();
var {
kUrl,
kReset,
kServerName,
kClient,
kBusy,
kParser,
kConnect,
kBlocking,
kResuming,
kRunning,
kPending,
kSize,
kWriting,
kQueue,
kConnected,
kConnecting,
kNeedDrain,
kNoRef,
kKeepAliveDefaultTimeout,
kHostHeader,
kPendingIdx,
kRunningIdx,
kError,
kPipelining,
kSocket,
kKeepAliveTimeoutValue,
kMaxHeadersSize,
kKeepAliveMaxTimeout,
kKeepAliveTimeoutThreshold,
kHeadersTimeout,
kBodyTimeout,
kStrictContentLength,
kConnector,
kMaxRedirections,
kMaxRequests,
kCounter,
kClose,
kDestroy,
kDispatch,
kInterceptors
3 years ago
} = require_symbols();
var kClosedResolve = Symbol("kClosedResolve");
var channels = {};
try {
const diagnosticsChannel = require("diagnostics_channel");
channels.sendHeaders = diagnosticsChannel.channel("undici:client:sendHeaders");
channels.beforeConnect = diagnosticsChannel.channel("undici:client:beforeConnect");
channels.connectError = diagnosticsChannel.channel("undici:client:connectError");
channels.connected = diagnosticsChannel.channel("undici:client:connected");
} catch {
channels.sendHeaders = { hasSubscribers: false };
channels.beforeConnect = { hasSubscribers: false };
channels.connectError = { hasSubscribers: false };
channels.connected = { hasSubscribers: false };
}
var Client = class extends DispatcherBase {
constructor(url, {
interceptors,
3 years ago
maxHeaderSize,
headersTimeout,
socketTimeout,
requestTimeout,
connectTimeout,
bodyTimeout,
idleTimeout,
keepAlive,
keepAliveTimeout,
maxKeepAliveTimeout,
keepAliveMaxTimeout,
keepAliveTimeoutThreshold,
socketPath,
pipelining,
tls,
strictContentLength,
maxCachedSessions,
maxRedirections,
connect: connect2,
maxRequestsPerClient
} = {}) {
super();
if (keepAlive !== void 0) {
throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead");
}
if (socketTimeout !== void 0) {
throw new InvalidArgumentError("unsupported socketTimeout, use headersTimeout & bodyTimeout instead");
}
if (requestTimeout !== void 0) {
throw new InvalidArgumentError("unsupported requestTimeout, use headersTimeout & bodyTimeout instead");
}
if (idleTimeout !== void 0) {
throw new InvalidArgumentError("unsupported idleTimeout, use keepAliveTimeout instead");
}
if (maxKeepAliveTimeout !== void 0) {
throw new InvalidArgumentError("unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead");
}
if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) {
throw new InvalidArgumentError("invalid maxHeaderSize");
}
if (socketPath != null && typeof socketPath !== "string") {
throw new InvalidArgumentError("invalid socketPath");
}
if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
throw new InvalidArgumentError("invalid connectTimeout");
}
if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
throw new InvalidArgumentError("invalid keepAliveTimeout");
}
if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
throw new InvalidArgumentError("invalid keepAliveMaxTimeout");
}
if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
throw new InvalidArgumentError("invalid keepAliveTimeoutThreshold");
}
if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
throw new InvalidArgumentError("headersTimeout must be a positive integer or zero");
}
if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
throw new InvalidArgumentError("bodyTimeout must be a positive integer or zero");
}
if (connect2 != null && typeof connect2 !== "function" && typeof connect2 !== "object") {
throw new InvalidArgumentError("connect must be a function or an object");
}
if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
throw new InvalidArgumentError("maxRedirections must be a positive number");
}
if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
throw new InvalidArgumentError("maxRequestsPerClient must be a positive number");
}
if (typeof connect2 !== "function") {
connect2 = buildConnector({
...tls,
maxCachedSessions,
socketPath,
timeout: connectTimeout,
...connect2
});
}
this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client) ? interceptors.Client : [createRedirectInterceptor({ maxRedirections })];
3 years ago
this[kUrl] = util.parseOrigin(url);
this[kConnector] = connect2;
this[kSocket] = null;
this[kPipelining] = pipelining != null ? pipelining : 1;
this[kMaxHeadersSize] = maxHeaderSize || 16384;
this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout;
this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 6e5 : keepAliveMaxTimeout;
this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold;
this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout];
this[kServerName] = null;
this[kResuming] = 0;
this[kNeedDrain] = 0;
this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ""}\r
`;
this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 3e4;
this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 3e4;
this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength;
this[kMaxRedirections] = maxRedirections;
this[kMaxRequests] = maxRequestsPerClient;
this[kClosedResolve] = null;
this[kQueue] = [];
this[kRunningIdx] = 0;
this[kPendingIdx] = 0;
}
get pipelining() {
return this[kPipelining];
}
set pipelining(value) {
this[kPipelining] = value;
resume(this, true);
}
get [kPending]() {
return this[kQueue].length - this[kPendingIdx];
}
get [kRunning]() {
return this[kPendingIdx] - this[kRunningIdx];
}
get [kSize]() {
return this[kQueue].length - this[kRunningIdx];
}
get [kConnected]() {
return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed;
}
get [kBusy]() {
const socket = this[kSocket];
return socket && (socket[kReset] || socket[kWriting] || socket[kBlocking]) || this[kSize] >= (this[kPipelining] || 1) || this[kPending] > 0;
}
[kConnect](cb) {
connect(this);
this.once("connect", cb);
}
[kDispatch](opts, handler) {
const origin = opts.origin || this[kUrl].origin;
const request = new Request(origin, opts, handler);
this[kQueue].push(request);
if (this[kResuming]) {
} else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
this[kResuming] = 1;
process.nextTick(resume, this);
} else {
resume(this, true);
}
if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
this[kNeedDrain] = 2;
}
return this[kNeedDrain] < 2;
}
async [kClose]() {
return new Promise((resolve) => {
if (!this[kSize]) {
this.destroy(resolve);
} else {
this[kClosedResolve] = resolve;
}
});
}
async [kDestroy](err) {
return new Promise((resolve) => {
const requests = this[kQueue].splice(this[kPendingIdx]);
for (let i = 0; i < requests.length; i++) {
const request = requests[i];
errorRequest(this, request, err);
}
const callback = () => {
if (this[kClosedResolve]) {
this[kClosedResolve]();
this[kClosedResolve] = null;
}
resolve();
};
if (!this[kSocket]) {
queueMicrotask(callback);
} else {
util.destroy(this[kSocket].on("close", callback), err);
}
resume(this);
});
}
};
var constants = require_constants2();
var createRedirectInterceptor = require_redirectInterceptor();
3 years ago
var EMPTY_BUF = Buffer.alloc(0);
async function lazyllhttp() {
const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0;
let mod;
try {
mod = await WebAssembly.compile(Buffer.from(require_llhttp_simd_wasm(), "base64"));
} catch (e) {
mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || require_llhttp_wasm(), "base64"));
}
return await WebAssembly.instantiate(mod, {
env: {
wasm_on_url: (p, at, len) => {
return 0;
},
wasm_on_status: (p, at, len) => {
assert.strictEqual(currentParser.ptr, p);
const start = at - currentBufferPtr;
const end = start + len;
return currentParser.onStatus(currentBufferRef.slice(start, end)) || 0;
},
wasm_on_message_begin: (p) => {
assert.strictEqual(currentParser.ptr, p);
return currentParser.onMessageBegin() || 0;
},
wasm_on_header_field: (p, at, len) => {
assert.strictEqual(currentParser.ptr, p);
const start = at - currentBufferPtr;
const end = start + len;
return currentParser.onHeaderField(currentBufferRef.slice(start, end)) || 0;
},
wasm_on_header_value: (p, at, len) => {
assert.strictEqual(currentParser.ptr, p);
const start = at - currentBufferPtr;
const end = start + len;
return currentParser.onHeaderValue(currentBufferRef.slice(start, end)) || 0;
},
wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
assert.strictEqual(currentParser.ptr, p);
return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0;
},
wasm_on_body: (p, at, len) => {
assert.strictEqual(currentParser.ptr, p);
const start = at - currentBufferPtr;
const end = start + len;
return currentParser.onBody(currentBufferRef.slice(start, end)) || 0;
},
wasm_on_message_complete: (p) => {
assert.strictEqual(currentParser.ptr, p);
return currentParser.onMessageComplete() || 0;
}
}
});
}
var llhttpInstance = null;
var llhttpPromise = lazyllhttp().catch(() => {
});
var currentParser = null;
var currentBufferRef = null;
var currentBufferSize = 0;
var currentBufferPtr = null;
var TIMEOUT_HEADERS = 1;
var TIMEOUT_BODY = 2;
var TIMEOUT_IDLE = 3;
var Parser = class {
constructor(client, socket, { exports: exports2 }) {
assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0);
this.llhttp = exports2;
this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE);
this.client = client;
this.socket = socket;
this.timeout = null;
this.timeoutValue = null;
this.timeoutType = null;
this.statusCode = null;
this.statusText = "";
this.upgrade = false;
this.headers = [];
this.headersSize = 0;
this.headersMaxSize = client[kMaxHeadersSize];
this.shouldKeepAlive = false;
this.paused = false;
this.resume = this.resume.bind(this);
this.bytesRead = 0;
this.keepAlive = "";
this.contentLength = "";
}
setTimeout(value, type) {
this.timeoutType = type;
if (value !== this.timeoutValue) {
clearTimeout(this.timeout);
if (value) {
this.timeout = setTimeout(onParserTimeout, value, this);
if (this.timeout.unref) {
this.timeout.unref();
}
} else {
this.timeout = null;
}
this.timeoutValue = value;
} else if (this.timeout) {
if (this.timeout.refresh) {
this.timeout.refresh();
}
}
}
resume() {
if (this.socket.destroyed || !this.paused) {
return;
}
assert(this.ptr != null);
assert(currentParser == null);
this.llhttp.llhttp_resume(this.ptr);
assert(this.timeoutType === TIMEOUT_BODY);
if (this.timeout) {
if (this.timeout.refresh) {
this.timeout.refresh();
}
}
this.paused = false;
this.execute(this.socket.read() || EMPTY_BUF);
this.readMore();
}
readMore() {
while (!this.paused && this.ptr) {
const chunk = this.socket.read();
if (chunk === null) {
break;
}
this.execute(chunk);
}
}
execute(data) {
assert(this.ptr != null);
assert(currentParser == null);
assert(!this.paused);
const { socket, llhttp } = this;
if (data.length > currentBufferSize) {
if (currentBufferPtr) {
llhttp.free(currentBufferPtr);
}
currentBufferSize = Math.ceil(data.length / 4096) * 4096;
currentBufferPtr = llhttp.malloc(currentBufferSize);
}
new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data);
try {
let ret;
try {
currentBufferRef = data;
currentParser = this;
ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length);
} catch (err) {
throw err;
} finally {
currentParser = null;
currentBufferRef = null;
}
const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr;
if (ret === constants.ERROR.PAUSED_UPGRADE) {
this.onUpgrade(data.slice(offset));
} else if (ret === constants.ERROR.PAUSED) {
this.paused = true;
socket.unshift(data.slice(offset));
} else if (ret !== constants.ERROR.OK) {
const ptr = llhttp.llhttp_get_error_reason(this.ptr);
let message = "";
if (ptr) {
const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0);
message = Buffer.from(llhttp.memory.buffer, ptr, len).toString();
}
throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset));
}
} catch (err) {
util.destroy(socket, err);
}
}
finish() {
try {
try {
currentParser = this;
} finally {
currentParser = null;
}
} catch (err) {
util.destroy(this.socket, err);
}
}
destroy() {
assert(this.ptr != null);
assert(currentParser == null);
this.llhttp.llhttp_free(this.ptr);
this.ptr = null;
clearTimeout(this.timeout);
this.timeout = null;
this.timeoutValue = null;
this.timeoutType = null;
this.paused = false;
}
onStatus(buf) {
this.statusText = buf.toString();
}
onMessageBegin() {
const { socket, client } = this;
if (socket.destroyed) {
return -1;
}
const request = client[kQueue][client[kRunningIdx]];
if (!request) {
return -1;
}
}
onHeaderField(buf) {
const len = this.headers.length;
if ((len & 1) === 0) {
this.headers.push(buf);
} else {
this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]);
}
this.trackHeader(buf.length);
}
onHeaderValue(buf) {
let len = this.headers.length;
if ((len & 1) === 1) {
this.headers.push(buf);
len += 1;
} else {
this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]);
}
const key = this.headers[len - 2];
if (key.length === 10 && key.toString().toLowerCase() === "keep-alive") {
this.keepAlive += buf.toString();
} else if (key.length === 14 && key.toString().toLowerCase() === "content-length") {
this.contentLength += buf.toString();
}
this.trackHeader(buf.length);
}
trackHeader(len) {
this.headersSize += len;
if (this.headersSize >= this.headersMaxSize) {
util.destroy(this.socket, new HeadersOverflowError());
}
}
onUpgrade(head) {
const { upgrade, client, socket, headers, statusCode } = this;
assert(upgrade);
const request = client[kQueue][client[kRunningIdx]];
assert(request);
assert(!socket.destroyed);
assert(socket === client[kSocket]);
assert(!this.paused);
assert(request.upgrade || request.method === "CONNECT");
this.statusCode = null;
this.statusText = "";
this.shouldKeepAlive = null;
assert(this.headers.length % 2 === 0);
this.headers = [];
this.headersSize = 0;
socket.unshift(head);
socket[kParser].destroy();
socket[kParser] = null;
socket[kClient] = null;
socket[kError] = null;
socket.removeListener("error", onSocketError).removeListener("readable", onSocketReadable).removeListener("end", onSocketEnd).removeListener("close", onSocketClose);
client[kSocket] = null;
client[kQueue][client[kRunningIdx]++] = null;
client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade"));
try {
request.onUpgrade(statusCode, headers, socket);
} catch (err) {
util.destroy(socket, err);
}
resume(client);
}
onHeadersComplete(statusCode, upgrade, shouldKeepAlive) {
const { client, socket, headers, statusText } = this;
if (socket.destroyed) {
return -1;
}
const request = client[kQueue][client[kRunningIdx]];
if (!request) {
return -1;
}
assert(!this.upgrade);
assert(this.statusCode < 200);
if (statusCode === 100) {
util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket)));
return -1;
}
if (upgrade && !request.upgrade) {
util.destroy(socket, new SocketError("bad upgrade", util.getSocketInfo(socket)));
return -1;
}
assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS);
this.statusCode = statusCode;
this.shouldKeepAlive = shouldKeepAlive;
if (this.statusCode >= 200) {
const bodyTimeout = request.bodyTimeout != null ? request.bodyTimeout : client[kBodyTimeout];
this.setTimeout(bodyTimeout, TIMEOUT_BODY);
} else if (this.timeout) {
if (this.timeout.refresh) {
this.timeout.refresh();
}
}
if (request.method === "CONNECT") {
3 years ago
assert(client[kRunning] === 1);
this.upgrade = true;
return 2;
}
if (upgrade) {
assert(client[kRunning] === 1);
this.upgrade = true;
return 2;
}
assert(this.headers.length % 2 === 0);
this.headers = [];
this.headersSize = 0;
if (shouldKeepAlive && client[kPipelining]) {
const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null;
if (keepAliveTimeout != null) {
const timeout = Math.min(
keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
client[kKeepAliveMaxTimeout]
);
3 years ago
if (timeout <= 0) {
socket[kReset] = true;
} else {
client[kKeepAliveTimeoutValue] = timeout;
}
} else {
client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout];
}
} else {
socket[kReset] = true;
}
let pause;
try {
pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false;
} catch (err) {
util.destroy(socket, err);
return -1;
}
if (request.method === "HEAD") {
assert(socket[kReset]);
return 1;
}
if (statusCode < 200) {
return 1;
}
if (socket[kBlocking]) {
socket[kBlocking] = false;
resume(client);
}
return pause ? constants.ERROR.PAUSED : 0;
}
onBody(buf) {
const { client, socket, statusCode } = this;
if (socket.destroyed) {
return -1;
}
const request = client[kQueue][client[kRunningIdx]];
assert(request);
assert.strictEqual(this.timeoutType, TIMEOUT_BODY);
if (this.timeout) {
if (this.timeout.refresh) {
this.timeout.refresh();
}
}
assert(statusCode >= 200);
this.bytesRead += buf.length;
try {
if (request.onData(buf) === false) {
return constants.ERROR.PAUSED;
}
} catch (err) {
util.destroy(socket, err);
return -1;
}
}
onMessageComplete() {
const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this;
3 years ago
if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
return -1;
}
if (upgrade) {
return;
}
const request = client[kQueue][client[kRunningIdx]];
assert(request);
assert(statusCode >= 100);
this.statusCode = null;
this.statusText = "";
this.bytesRead = 0;
this.contentLength = "";
this.keepAlive = "";
assert(this.headers.length % 2 === 0);
this.headers = [];
this.headersSize = 0;
if (statusCode < 200) {
return;
}
if (request.method !== "HEAD" && contentLength && bytesRead !== parseInt(contentLength, 10)) {
util.destroy(socket, new ResponseContentLengthMismatchError());
return -1;
}
try {
request.onComplete(headers);
} catch (err) {
errorRequest(client, request, err);
}
client[kQueue][client[kRunningIdx]++] = null;
if (socket[kWriting]) {
assert.strictEqual(client[kRunning], 0);
util.destroy(socket, new InformationalError("reset"));
return constants.ERROR.PAUSED;
} else if (!shouldKeepAlive) {
util.destroy(socket, new InformationalError("reset"));
return constants.ERROR.PAUSED;
} else if (socket[kReset] && client[kRunning] === 0) {
util.destroy(socket, new InformationalError("reset"));
return constants.ERROR.PAUSED;
} else if (client[kPipelining] === 1) {
setImmediate(resume, client);
3 years ago
} else {
resume(client);
}
}
};
function onParserTimeout(parser2) {
const { socket, timeoutType, client } = parser2;
if (timeoutType === TIMEOUT_HEADERS) {
if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
3 years ago
assert(!parser2.paused, "cannot be paused while waiting for headers");
util.destroy(socket, new HeadersTimeoutError());
}
} else if (timeoutType === TIMEOUT_BODY) {
if (!parser2.paused) {
util.destroy(socket, new BodyTimeoutError());
}
} else if (timeoutType === TIMEOUT_IDLE) {
assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]);
util.destroy(socket, new InformationalError("socket idle timeout"));
}
}
function onSocketReadable() {
const { [kParser]: parser2 } = this;
parser2.readMore();
}
function onSocketError(err) {
const { [kParser]: parser2 } = this;
assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
if (err.code === "ECONNRESET" && parser2.statusCode && !parser2.shouldKeepAlive) {
parser2.finish();
return;
}
this[kError] = err;
onError(this[kClient], err);
}
function onError(client, err) {
if (client[kRunning] === 0 && err.code !== "UND_ERR_INFO" && err.code !== "UND_ERR_SOCKET") {
assert(client[kPendingIdx] === client[kRunningIdx]);
const requests = client[kQueue].splice(client[kRunningIdx]);
for (let i = 0; i < requests.length; i++) {
const request = requests[i];
errorRequest(client, request, err);
}
assert(client[kSize] === 0);
}
}
function onSocketEnd() {
const { [kParser]: parser2 } = this;
if (parser2.statusCode && !parser2.shouldKeepAlive) {
parser2.finish();
return;
}
util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this)));
}
function onSocketClose() {
const { [kClient]: client } = this;
this[kParser].destroy();
this[kParser] = null;
const err = this[kError] || new SocketError("closed", util.getSocketInfo(this));
client[kSocket] = null;
if (client.destroyed) {
assert(client[kPending] === 0);
const requests = client[kQueue].splice(client[kRunningIdx]);
for (let i = 0; i < requests.length; i++) {
const request = requests[i];
errorRequest(client, request, err);
}
} else if (client[kRunning] > 0 && err.code !== "UND_ERR_INFO") {
const request = client[kQueue][client[kRunningIdx]];
client[kQueue][client[kRunningIdx]++] = null;
errorRequest(client, request, err);
}
client[kPendingIdx] = client[kRunningIdx];
assert(client[kRunning] === 0);
client.emit("disconnect", client[kUrl], [client], err);
resume(client);
}
async function connect(client) {
assert(!client[kConnecting]);
assert(!client[kSocket]);
let { host, hostname, protocol, port } = client[kUrl];
if (hostname[0] === "[") {
const idx = hostname.indexOf("]");
assert(idx !== -1);
const ip = hostname.substr(1, idx - 1);
assert(net.isIP(ip));
hostname = ip;
}
client[kConnecting] = true;
if (channels.beforeConnect.hasSubscribers) {
channels.beforeConnect.publish({
connectParams: {
host,
hostname,
protocol,
port,
servername: client[kServerName]
},
connector: client[kConnector]
});
}
try {
const socket = await new Promise((resolve, reject) => {
client[kConnector]({
host,
hostname,
protocol,
port,
servername: client[kServerName]
}, (err, socket2) => {
if (err) {
reject(err);
} else {
resolve(socket2);
}
});
});
if (!llhttpInstance) {
llhttpInstance = await llhttpPromise;
llhttpPromise = null;
}
client[kConnecting] = false;
assert(socket);
client[kSocket] = socket;
socket[kNoRef] = false;
socket[kWriting] = false;
socket[kReset] = false;
socket[kBlocking] = false;
socket[kError] = null;
socket[kParser] = new Parser(client, socket, llhttpInstance);
socket[kClient] = client;
socket[kCounter] = 0;
socket[kMaxRequests] = client[kMaxRequests];
socket.on("error", onSocketError).on("readable", onSocketReadable).on("end", onSocketEnd).on("close", onSocketClose);
if (channels.connected.hasSubscribers) {
channels.connected.publish({
connectParams: {
host,
hostname,
protocol,
port,
servername: client[kServerName]
},
connector: client[kConnector],
socket
});
}
client.emit("connect", client[kUrl], [client]);
} catch (err) {
client[kConnecting] = false;
if (channels.connectError.hasSubscribers) {
channels.connectError.publish({
connectParams: {
host,
hostname,
protocol,
port,
servername: client[kServerName]
},
connector: client[kConnector],
error: err
});
}
if (err.code === "ERR_TLS_CERT_ALTNAME_INVALID") {
assert(client[kRunning] === 0);
while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
const request = client[kQueue][client[kPendingIdx]++];
errorRequest(client, request, err);
}
} else {
onError(client, err);
}
client.emit("connectionError", client[kUrl], [client], err);
}
resume(client);
}
function emitDrain(client) {
client[kNeedDrain] = 0;
client.emit("drain", client[kUrl], [client]);
}
function resume(client, sync) {
if (client[kResuming] === 2) {
return;
}
client[kResuming] = 2;
_resume(client, sync);
client[kResuming] = 0;
if (client[kRunningIdx] > 256) {
client[kQueue].splice(0, client[kRunningIdx]);
client[kPendingIdx] -= client[kRunningIdx];
client[kRunningIdx] = 0;
}
}
function _resume(client, sync) {
while (true) {
if (client.destroyed) {
assert(client[kPending] === 0);
return;
}
if (client.closed && !client[kSize]) {
client.destroy();
return;
}
const socket = client[kSocket];
if (socket) {
if (client[kSize] === 0) {
if (!socket[kNoRef] && socket.unref) {
socket.unref();
socket[kNoRef] = true;
}
} else if (socket[kNoRef] && socket.ref) {
socket.ref();
socket[kNoRef] = false;
}
if (client[kSize] === 0) {
if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {
socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE);
}
} else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
const request2 = client[kQueue][client[kRunningIdx]];
const headersTimeout = request2.headersTimeout != null ? request2.headersTimeout : client[kHeadersTimeout];
socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS);
}
}
}
if (client[kBusy]) {
client[kNeedDrain] = 2;
} else if (client[kNeedDrain] === 2) {
if (sync) {
client[kNeedDrain] = 1;
process.nextTick(emitDrain, client);
} else {
emitDrain(client);
}
continue;
}
if (client[kPending] === 0) {
return;
}
if (client[kRunning] >= (client[kPipelining] || 1)) {
return;
}
const request = client[kQueue][client[kPendingIdx]];
if (client[kUrl].protocol === "https:" && client[kServerName] !== request.servername) {
if (client[kRunning] > 0) {
return;
}
client[kServerName] = request.servername;
if (socket && socket.servername !== request.servername) {
util.destroy(socket, new InformationalError("servername changed"));
return;
}
}
if (client[kConnecting]) {
return;
}
if (!socket) {
connect(client);
continue;
}
if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) {
return;
}
if (client[kRunning] > 0 && !request.idempotent) {
return;
}
if (client[kRunning] > 0 && (request.upgrade || request.method === "CONNECT")) {
return;
}
if (util.isStream(request.body) && util.bodyLength(request.body) === 0) {
request.body.on("data", function() {
assert(false);
}).on("error", function(err) {
errorRequest(client, request, err);
}).on("end", function() {
util.destroy(this);
});
request.body = null;
}
if (client[kRunning] > 0 && (util.isStream(request.body) || util.isAsyncIterable(request.body))) {
return;
}
if (!request.aborted && write(client, request)) {
client[kPendingIdx]++;
} else {
client[kQueue].splice(client[kPendingIdx], 1);
}
}
}
function write(client, request) {
const { body, method, path: path3, host, upgrade, headers, blocking } = request;
3 years ago
const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
if (body && typeof body.read === "function") {
body.read(0);
}
let contentLength = util.bodyLength(body);
if (contentLength === null) {
contentLength = request.contentLength;
}
if (contentLength === 0 && !expectsPayload) {
contentLength = null;
}
if (request.contentLength !== null && request.contentLength !== contentLength) {
if (client[kStrictContentLength]) {
errorRequest(client, request, new RequestContentLengthMismatchError());
return false;
}
process.emitWarning(new RequestContentLengthMismatchError());
}
const socket = client[kSocket];
try {
request.onConnect((err) => {
if (request.aborted || request.completed) {
return;
}
errorRequest(client, request, err || new RequestAbortedError());
util.destroy(socket, new InformationalError("aborted"));
});
} catch (err) {
errorRequest(client, request, err);
}
if (request.aborted) {
return false;
}
if (method === "HEAD") {
socket[kReset] = true;
}
if (upgrade || method === "CONNECT") {
socket[kReset] = true;
}
if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
socket[kReset] = true;
}
if (blocking) {
socket[kBlocking] = true;
}
let header = `${method} ${path3} HTTP/1.1\r
3 years ago
`;
if (typeof host === "string") {
header += `host: ${host}\r
`;
} else {
header += client[kHostHeader];
}
if (upgrade) {
header += `connection: upgrade\r
upgrade: ${upgrade}\r
`;
} else if (client[kPipelining]) {
header += "connection: keep-alive\r\n";
} else {
header += "connection: close\r\n";
}
if (headers) {
header += headers;
}
if (channels.sendHeaders.hasSubscribers) {
channels.sendHeaders.publish({ request, headers: header, socket });
}
if (!body) {
if (contentLength === 0) {
socket.write(`${header}content-length: 0\r
\r
`, "ascii");
} else {
assert(contentLength === null, "no body must not have content length");
socket.write(`${header}\r
`, "ascii");
}
request.onRequestSent();
} else if (util.isBuffer(body)) {
assert(contentLength === body.byteLength, "buffer body must have content length");
socket.cork();
socket.write(`${header}content-length: ${contentLength}\r
\r
`, "ascii");
socket.write(body);
socket.uncork();
request.onBodySent(body);
request.onRequestSent();
if (!expectsPayload) {
socket[kReset] = true;
}
} else if (util.isBlobLike(body)) {
if (typeof body.stream === "function") {
writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload });
} else {
writeBlob({ body, client, request, socket, contentLength, header, expectsPayload });
}
} else if (util.isStream(body)) {
writeStream({ body, client, request, socket, contentLength, header, expectsPayload });
} else if (util.isIterable(body)) {
writeIterable({ body, client, request, socket, contentLength, header, expectsPayload });
} else {
assert(false);
}
return true;
}
function writeStream({ body, client, request, socket, contentLength, header, expectsPayload }) {
assert(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
let finished = false;
const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header });
const onData = function(chunk) {
try {
assert(!finished);
if (!writer.write(chunk) && this.pause) {
this.pause();
}
} catch (err) {
util.destroy(this, err);
}
};
const onDrain = function() {
assert(!finished);
if (body.resume) {
body.resume();
}
};
const onAbort = function() {
onFinished(new RequestAbortedError());
};
const onFinished = function(err) {
if (finished) {
return;
}
finished = true;
assert(socket.destroyed || socket[kWriting] && client[kRunning] <= 1);
socket.off("drain", onDrain).off("error", onFinished);
body.removeListener("data", onData).removeListener("end", onFinished).removeListener("error", onFinished).removeListener("close", onAbort);
if (!err) {
try {
writer.end();
} catch (er) {
err = er;
}
}
writer.destroy(err);
if (err && (err.code !== "UND_ERR_INFO" || err.message !== "reset")) {
util.destroy(body, err);
} else {
util.destroy(body);
}
};
body.on("data", onData).on("end", onFinished).on("error", onFinished).on("close", onAbort);
if (body.resume) {
body.resume();
}
socket.on("drain", onDrain).on("error", onFinished);
}
async function writeBlob({ body, client, request, socket, contentLength, header, expectsPayload }) {
assert(contentLength === body.size, "blob body must have content length");
try {
if (contentLength != null && contentLength !== body.size) {
throw new RequestContentLengthMismatchError();
}
const buffer = Buffer.from(await body.arrayBuffer());
socket.cork();
socket.write(`${header}content-length: ${contentLength}\r
\r
`, "ascii");
socket.write(buffer);
socket.uncork();
request.onBodySent(buffer);
request.onRequestSent();
if (!expectsPayload) {
socket[kReset] = true;
}
resume(client);
} catch (err) {
util.destroy(socket, err);
}
}
async function writeIterable({ body, client, request, socket, contentLength, header, expectsPayload }) {
assert(contentLength !== 0 || client[kRunning] === 0, "iterator body cannot be pipelined");
let callback = null;
function onDrain() {
if (callback) {
const cb = callback;
callback = null;
cb();
}
}
const waitForDrain = () => new Promise((resolve, reject) => {
assert(callback === null);
if (socket[kError]) {
reject(socket[kError]);
} else {
callback = resolve;
}
});
socket.on("close", onDrain).on("drain", onDrain);
const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header });
try {
for await (const chunk of body) {
if (socket[kError]) {
throw socket[kError];
}
if (!writer.write(chunk)) {
await waitForDrain();
}
}
writer.end();
} catch (err) {
writer.destroy(err);
} finally {
socket.off("close", onDrain).off("drain", onDrain);
}
}
var AsyncWriter = class {
constructor({ socket, request, contentLength, client, expectsPayload, header }) {
this.socket = socket;
this.request = request;
this.contentLength = contentLength;
this.client = client;
this.bytesWritten = 0;
this.expectsPayload = expectsPayload;
this.header = header;
socket[kWriting] = true;
}
write(chunk) {
const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this;
if (socket[kError]) {
throw socket[kError];
}
if (socket.destroyed) {
return false;
}
const len = Buffer.byteLength(chunk);
if (!len) {
return true;
}
if (contentLength !== null && bytesWritten + len > contentLength) {
if (client[kStrictContentLength]) {
throw new RequestContentLengthMismatchError();
}
process.emitWarning(new RequestContentLengthMismatchError());
}
if (bytesWritten === 0) {
if (!expectsPayload) {
socket[kReset] = true;
}
if (contentLength === null) {
socket.write(`${header}transfer-encoding: chunked\r
`, "ascii");
} else {
socket.write(`${header}content-length: ${contentLength}\r
\r
`, "ascii");
}
}
if (contentLength === null) {
socket.write(`\r
${len.toString(16)}\r
`, "ascii");
}
this.bytesWritten += len;
const ret = socket.write(chunk);
request.onBodySent(chunk);
if (!ret) {
if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
if (socket[kParser].timeout.refresh) {
socket[kParser].timeout.refresh();
}
}
}
3 years ago
return ret;
}
end() {
const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this;
request.onRequestSent();
socket[kWriting] = false;
if (socket[kError]) {
throw socket[kError];
}
if (socket.destroyed) {
return;
}
if (bytesWritten === 0) {
if (expectsPayload) {
socket.write(`${header}content-length: 0\r
\r
`, "ascii");
} else {
socket.write(`${header}\r
`, "ascii");
}
} else if (contentLength === null) {
socket.write("\r\n0\r\n\r\n", "ascii");
}
if (contentLength !== null && bytesWritten !== contentLength) {
if (client[kStrictContentLength]) {
throw new RequestContentLengthMismatchError();
} else {
process.emitWarning(new RequestContentLengthMismatchError());
}
}
if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
if (socket[kParser].timeout.refresh) {
socket[kParser].timeout.refresh();
}
}
resume(client);
}
destroy(err) {
const { socket, client } = this;
socket[kWriting] = false;
if (err) {
assert(client[kRunning] <= 1, "pipeline should only contain this request");
util.destroy(socket, err);
}
}
};
function errorRequest(client, request, err) {
try {
request.onError(err);
assert(request.aborted);
} catch (err2) {
client.emit("error", err2);
}
}
module2.exports = Client;
}
});
// node_modules/undici/lib/node/fixed-queue.js
var require_fixed_queue = __commonJS({
"node_modules/undici/lib/node/fixed-queue.js"(exports, module2) {
"use strict";
var kSize = 2048;
var kMask = kSize - 1;
var FixedCircularBuffer = class {
constructor() {
this.bottom = 0;
this.top = 0;
this.list = new Array(kSize);
this.next = null;
}
isEmpty() {
return this.top === this.bottom;
}
isFull() {
return (this.top + 1 & kMask) === this.bottom;
}
push(data) {
this.list[this.top] = data;
this.top = this.top + 1 & kMask;
}
shift() {
const nextItem = this.list[this.bottom];
if (nextItem === void 0)
return null;
this.list[this.bottom] = void 0;
this.bottom = this.bottom + 1 & kMask;
return nextItem;
}
};
module2.exports = class FixedQueue {
constructor() {
this.head = this.tail = new FixedCircularBuffer();
}
isEmpty() {
return this.head.isEmpty();
}
push(data) {
if (this.head.isFull()) {
this.head = this.head.next = new FixedCircularBuffer();
}
this.head.push(data);
}
shift() {
const tail = this.tail;
const next = tail.shift();
if (tail.isEmpty() && tail.next !== null) {
this.tail = tail.next;
}
return next;
}
};
}
});
// node_modules/undici/lib/pool-stats.js
var require_pool_stats = __commonJS({
"node_modules/undici/lib/pool-stats.js"(exports, module2) {
var { kFree, kConnected, kPending, kQueued, kRunning, kSize } = require_symbols();
var kPool = Symbol("pool");
var PoolStats = class {
constructor(pool) {
this[kPool] = pool;
}
get connected() {
return this[kPool][kConnected];
}
get free() {
return this[kPool][kFree];
}
get pending() {
return this[kPool][kPending];
}
get queued() {
return this[kPool][kQueued];
}
get running() {
return this[kPool][kRunning];
}
get size() {
return this[kPool][kSize];
}
};
module2.exports = PoolStats;
}
});
// node_modules/undici/lib/pool-base.js
var require_pool_base = __commonJS({
"node_modules/undici/lib/pool-base.js"(exports, module2) {
"use strict";
var DispatcherBase = require_dispatcher_base();
var FixedQueue = require_fixed_queue();
var { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require_symbols();
var PoolStats = require_pool_stats();
var kClients = Symbol("clients");
var kNeedDrain = Symbol("needDrain");
var kQueue = Symbol("queue");
var kClosedResolve = Symbol("closed resolve");
var kOnDrain = Symbol("onDrain");
var kOnConnect = Symbol("onConnect");
var kOnDisconnect = Symbol("onDisconnect");
var kOnConnectionError = Symbol("onConnectionError");
var kGetDispatcher = Symbol("get dispatcher");
var kAddClient = Symbol("add client");
var kRemoveClient = Symbol("remove client");
var kStats = Symbol("stats");
var PoolBase = class extends DispatcherBase {
constructor() {
super();
this[kQueue] = new FixedQueue();
this[kClients] = [];
this[kQueued] = 0;
const pool = this;
this[kOnDrain] = function onDrain(origin, targets) {
const queue = pool[kQueue];
let needDrain = false;
while (!needDrain) {
const item = queue.shift();
if (!item) {
break;
}
pool[kQueued]--;
needDrain = !this.dispatch(item.opts, item.handler);
}
this[kNeedDrain] = needDrain;
if (!this[kNeedDrain] && pool[kNeedDrain]) {
pool[kNeedDrain] = false;
pool.emit("drain", origin, [pool, ...targets]);
}
if (pool[kClosedResolve] && queue.isEmpty()) {
Promise.all(pool[kClients].map((c) => c.close())).then(pool[kClosedResolve]);
}
};
this[kOnConnect] = (origin, targets) => {
pool.emit("connect", origin, [pool, ...targets]);
};
this[kOnDisconnect] = (origin, targets, err) => {
pool.emit("disconnect", origin, [pool, ...targets], err);
};
this[kOnConnectionError] = (origin, targets, err) => {
pool.emit("connectionError", origin, [pool, ...targets], err);
};
this[kStats] = new PoolStats(this);
}
get [kBusy]() {
return this[kNeedDrain];
}
get [kConnected]() {
return this[kClients].filter((client) => client[kConnected]).length;
}
get [kFree]() {
return this[kClients].filter((client) => client[kConnected] && !client[kNeedDrain]).length;
}
get [kPending]() {
let ret = this[kQueued];
for (const { [kPending]: pending } of this[kClients]) {
ret += pending;
}
return ret;
}
get [kRunning]() {
let ret = 0;
for (const { [kRunning]: running } of this[kClients]) {
ret += running;
}
return ret;
}
get [kSize]() {
let ret = this[kQueued];
for (const { [kSize]: size } of this[kClients]) {
ret += size;
}
return ret;
}
get stats() {
return this[kStats];
}
async [kClose]() {
if (this[kQueue].isEmpty()) {
return Promise.all(this[kClients].map((c) => c.close()));
} else {
return new Promise((resolve) => {
this[kClosedResolve] = resolve;
});
}
}
async [kDestroy](err) {
while (true) {
const item = this[kQueue].shift();
if (!item) {
break;
}
item.handler.onError(err);
}
return Promise.all(this[kClients].map((c) => c.destroy(err)));
}
[kDispatch](opts, handler) {
const dispatcher = this[kGetDispatcher]();
if (!dispatcher) {
this[kNeedDrain] = true;
this[kQueue].push({ opts, handler });
this[kQueued]++;
} else if (!dispatcher.dispatch(opts, handler)) {
dispatcher[kNeedDrain] = true;
this[kNeedDrain] = !this[kGetDispatcher]();
}
return !this[kNeedDrain];
}
[kAddClient](client) {
client.on("drain", this[kOnDrain]).on("connect", this[kOnConnect]).on("disconnect", this[kOnDisconnect]).on("connectionError", this[kOnConnectionError]);
this[kClients].push(client);
if (this[kNeedDrain]) {
process.nextTick(() => {
if (this[kNeedDrain]) {
this[kOnDrain](client[kUrl], [this, client]);
}
});
}
return this;
}
[kRemoveClient](client) {
client.close(() => {
const idx = this[kClients].indexOf(client);
if (idx !== -1) {
this[kClients].splice(idx, 1);
}
});
this[kNeedDrain] = this[kClients].some((dispatcher) => !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true);
}
};
module2.exports = {
PoolBase,
kClients,
kNeedDrain,
kAddClient,
kRemoveClient,
kGetDispatcher
};
}
});
// node_modules/undici/lib/pool.js
var require_pool = __commonJS({
"node_modules/undici/lib/pool.js"(exports, module2) {
"use strict";
var {
PoolBase,
kClients,
kNeedDrain,
kAddClient,
kGetDispatcher
} = require_pool_base();
var Client = require_client();
var {
InvalidArgumentError
} = require_errors();
var util = require_util();
var { kUrl, kInterceptors } = require_symbols();
3 years ago
var buildConnector = require_connect();
var kOptions = Symbol("options");
var kConnections = Symbol("connections");
var kFactory = Symbol("factory");
function defaultFactory(origin, opts) {
return new Client(origin, opts);
}
var Pool = class extends PoolBase {
constructor(origin, {
connections,
factory = defaultFactory,
connect,
connectTimeout,
tls,
maxCachedSessions,
socketPath,
...options
} = {}) {
super();
if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
throw new InvalidArgumentError("invalid connections");
}
if (typeof factory !== "function") {
throw new InvalidArgumentError("factory must be a function.");
}
if (connect != null && typeof connect !== "function" && typeof connect !== "object") {
throw new InvalidArgumentError("connect must be a function or an object");
}
if (typeof connect !== "function") {
connect = buildConnector({
...tls,
maxCachedSessions,
socketPath,
timeout: connectTimeout == null ? 1e4 : connectTimeout,
...connect
});
}
this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : [];
3 years ago
this[kConnections] = connections || null;
this[kUrl] = util.parseOrigin(origin);
this[kOptions] = { ...util.deepClone(options), connect };
this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : void 0;
3 years ago
this[kFactory] = factory;
}
[kGetDispatcher]() {
let dispatcher = this[kClients].find((dispatcher2) => !dispatcher2[kNeedDrain]);
if (dispatcher) {
return dispatcher;
}
if (!this[kConnections] || this[kClients].length < this[kConnections]) {
dispatcher = this[kFactory](this[kUrl], this[kOptions]);
this[kAddClient](dispatcher);
}
return dispatcher;
}
};
module2.exports = Pool;
}
});
// node_modules/undici/lib/balanced-pool.js
var require_balanced_pool = __commonJS({
"node_modules/undici/lib/balanced-pool.js"(exports, module2) {
"use strict";
var {
BalancedPoolMissingUpstreamError,
InvalidArgumentError
} = require_errors();
var {
PoolBase,
kClients,
kNeedDrain,
kAddClient,
kRemoveClient,
kGetDispatcher
} = require_pool_base();
var Pool = require_pool();
var { kUrl, kInterceptors } = require_symbols();
3 years ago
var { parseOrigin } = require_util();
var kFactory = Symbol("factory");
var kOptions = Symbol("options");
var kGreatestCommonDivisor = Symbol("kGreatestCommonDivisor");
var kCurrentWeight = Symbol("kCurrentWeight");
var kIndex = Symbol("kIndex");
var kWeight = Symbol("kWeight");
var kMaxWeightPerServer = Symbol("kMaxWeightPerServer");
var kErrorPenalty = Symbol("kErrorPenalty");
function getGreatestCommonDivisor(a, b) {
if (b === 0)
return a;
return getGreatestCommonDivisor(b, a % b);
}
3 years ago
function defaultFactory(origin, opts) {
return new Pool(origin, opts);
}
var BalancedPool = class extends PoolBase {
constructor(upstreams = [], { factory = defaultFactory, ...opts } = {}) {
super();
this[kOptions] = opts;
this[kIndex] = -1;
this[kCurrentWeight] = 0;
this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100;
this[kErrorPenalty] = this[kOptions].errorPenalty || 15;
3 years ago
if (!Array.isArray(upstreams)) {
upstreams = [upstreams];
}
if (typeof factory !== "function") {
throw new InvalidArgumentError("factory must be a function.");
}
this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) ? opts.interceptors.BalancedPool : [];
3 years ago
this[kFactory] = factory;
for (const upstream of upstreams) {
this.addUpstream(upstream);
}
this._updateBalancedPoolStats();
3 years ago
}
addUpstream(upstream) {
const upstreamOrigin = parseOrigin(upstream).origin;
if (this[kClients].find((pool2) => pool2[kUrl].origin === upstreamOrigin && pool2.closed !== true && pool2.destroyed !== true)) {
3 years ago
return this;
}
const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]));
this[kAddClient](pool);
pool.on("connect", () => {
pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]);
});
pool.on("connectionError", () => {
pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]);
this._updateBalancedPoolStats();
});
pool.on("disconnect", (...args) => {
const err = args[2];
if (err && err.code === "UND_ERR_SOCKET") {
pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]);
this._updateBalancedPoolStats();
}
});
for (const client of this[kClients]) {
client[kWeight] = this[kMaxWeightPerServer];
}
this._updateBalancedPoolStats();
3 years ago
return this;
}
_updateBalancedPoolStats() {
this[kGreatestCommonDivisor] = this[kClients].map((p) => p[kWeight]).reduce(getGreatestCommonDivisor, 0);
}
3 years ago
removeUpstream(upstream) {
const upstreamOrigin = parseOrigin(upstream).origin;
const pool = this[kClients].find((pool2) => pool2[kUrl].origin === upstreamOrigin && pool2.closed !== true && pool2.destroyed !== true);
if (pool) {
this[kRemoveClient](pool);
}
return this;
}
get upstreams() {
return this[kClients].filter((dispatcher) => dispatcher.closed !== true && dispatcher.destroyed !== true).map((p) => p[kUrl].origin);
}
[kGetDispatcher]() {
if (this[kClients].length === 0) {
throw new BalancedPoolMissingUpstreamError();
}
const dispatcher = this[kClients].find((dispatcher2) => !dispatcher2[kNeedDrain] && dispatcher2.closed !== true && dispatcher2.destroyed !== true);
if (!dispatcher) {
return;
}
const allClientsBusy = this[kClients].map((pool) => pool[kNeedDrain]).reduce((a, b) => a && b, true);
if (allClientsBusy) {
return;
}
let counter = 0;
let maxWeightIndex = this[kClients].findIndex((pool) => !pool[kNeedDrain]);
while (counter++ < this[kClients].length) {
this[kIndex] = (this[kIndex] + 1) % this[kClients].length;
const pool = this[kClients][this[kIndex]];
if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
maxWeightIndex = this[kIndex];
}
if (this[kIndex] === 0) {
this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor];
if (this[kCurrentWeight] <= 0) {
this[kCurrentWeight] = this[kMaxWeightPerServer];
}
}
if (pool[kWeight] >= this[kCurrentWeight] && !pool[kNeedDrain]) {
return pool;
}
}
this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight];
this[kIndex] = maxWeightIndex;
return this[kClients][maxWeightIndex];
3 years ago
}
};
module2.exports = BalancedPool;
}
});
// node_modules/undici/lib/compat/dispatcher-weakref.js
var require_dispatcher_weakref = __commonJS({
"node_modules/undici/lib/compat/dispatcher-weakref.js"(exports, module2) {
"use strict";
var { kConnected, kSize } = require_symbols();
var CompatWeakRef = class {
constructor(value) {
this.value = value;
}
deref() {
return this.value[kConnected] === 0 && this.value[kSize] === 0 ? void 0 : this.value;
}
};
var CompatFinalizer = class {
constructor(finalizer) {
this.finalizer = finalizer;
}
register(dispatcher, key) {
dispatcher.on("disconnect", () => {
if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
this.finalizer(key);
}
});
}
};
module2.exports = function() {
return {
WeakRef: global.WeakRef || CompatWeakRef,
FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer
};
};
}
});
// node_modules/undici/lib/agent.js
var require_agent = __commonJS({
"node_modules/undici/lib/agent.js"(exports, module2) {
"use strict";
var { InvalidArgumentError } = require_errors();
var { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require_symbols();
3 years ago
var DispatcherBase = require_dispatcher_base();
var Pool = require_pool();
var Client = require_client();
var util = require_util();
var createRedirectInterceptor = require_redirectInterceptor();
var { WeakRef, FinalizationRegistry } = require_dispatcher_weakref()();
3 years ago
var kOnConnect = Symbol("onConnect");
var kOnDisconnect = Symbol("onDisconnect");
var kOnConnectionError = Symbol("onConnectionError");
var kMaxRedirections = Symbol("maxRedirections");
var kOnDrain = Symbol("onDrain");
var kFactory = Symbol("factory");
var kFinalizer = Symbol("finalizer");
var kOptions = Symbol("options");
function defaultFactory(origin, opts) {
return opts && opts.connections === 1 ? new Client(origin, opts) : new Pool(origin, opts);
}
var Agent = class extends DispatcherBase {
constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
super();
if (typeof factory !== "function") {
throw new InvalidArgumentError("factory must be a function.");
}
if (connect != null && typeof connect !== "function" && typeof connect !== "object") {
throw new InvalidArgumentError("connect must be a function or an object");
}
if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {
throw new InvalidArgumentError("maxRedirections must be a positive number");
}
if (connect && typeof connect !== "function") {
connect = { ...connect };
}
this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) ? options.interceptors.Agent : [createRedirectInterceptor({ maxRedirections })];
3 years ago
this[kOptions] = { ...util.deepClone(options), connect };
this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : void 0;
3 years ago
this[kMaxRedirections] = maxRedirections;
this[kFactory] = factory;
this[kClients] = /* @__PURE__ */ new Map();
this[kFinalizer] = new FinalizationRegistry((key) => {
3 years ago
const ref = this[kClients].get(key);
if (ref !== void 0 && ref.deref() === void 0) {
this[kClients].delete(key);
}
});
const agent = this;
this[kOnDrain] = (origin, targets) => {
agent.emit("drain", origin, [agent, ...targets]);
};
this[kOnConnect] = (origin, targets) => {
agent.emit("connect", origin, [agent, ...targets]);
};
this[kOnDisconnect] = (origin, targets, err) => {
agent.emit("disconnect", origin, [agent, ...targets], err);
};
this[kOnConnectionError] = (origin, targets, err) => {
agent.emit("connectionError", origin, [agent, ...targets], err);
};
}
get [kRunning]() {
let ret = 0;
for (const ref of this[kClients].values()) {
const client = ref.deref();
if (client) {
ret += client[kRunning];
}
}
return ret;
}
[kDispatch](opts, handler) {
let key;
if (opts.origin && (typeof opts.origin === "string" || opts.origin instanceof URL)) {
key = String(opts.origin);
} else {
throw new InvalidArgumentError("opts.origin must be a non-empty string or URL.");
}
const ref = this[kClients].get(key);
let dispatcher = ref ? ref.deref() : null;
if (!dispatcher) {
dispatcher = this[kFactory](opts.origin, this[kOptions]).on("drain", this[kOnDrain]).on("connect", this[kOnConnect]).on("disconnect", this[kOnDisconnect]).on("connectionError", this[kOnConnectionError]);
this[kClients].set(key, new WeakRef(dispatcher));
this[kFinalizer].register(dispatcher, key);
}
return dispatcher.dispatch(opts, handler);
}
async [kClose]() {
const closePromises = [];
for (const ref of this[kClients].values()) {
const client = ref.deref();
if (client) {
closePromises.push(client.close());
}
}
await Promise.all(closePromises);
}
async [kDestroy](err) {
const destroyPromises = [];
for (const ref of this[kClients].values()) {
const client = ref.deref();
if (client) {
destroyPromises.push(client.destroy(err));
}
}
await Promise.all(destroyPromises);
}
};
module2.exports = Agent;
}
});
// node_modules/undici/lib/api/readable.js
var require_readable = __commonJS({
"node_modules/undici/lib/api/readable.js"(exports, module2) {
"use strict";
var assert = require("assert");
var { Readable } = require("stream");
var { RequestAbortedError, NotSupportedError } = require_errors();
var util = require_util();
var { ReadableStreamFrom, toUSVString } = require_util();
var Blob;
var kConsume = Symbol("kConsume");
var kReading = Symbol("kReading");
var kBody = Symbol("kBody");
var kAbort = Symbol("abort");
var kContentType = Symbol("kContentType");
module2.exports = class BodyReadable extends Readable {
constructor(resume, abort, contentType = "") {
super({
autoDestroy: true,
read: resume,
highWaterMark: 64 * 1024
});
this._readableState.dataEmitted = false;
this[kAbort] = abort;
this[kConsume] = null;
this[kBody] = null;
this[kContentType] = contentType;
this[kReading] = false;
}
destroy(err) {
if (this.destroyed) {
return this;
}
if (!err && !this._readableState.endEmitted) {
err = new RequestAbortedError();
}
if (err) {
this[kAbort]();
}
return super.destroy(err);
}
emit(ev, ...args) {
if (ev === "data") {
this._readableState.dataEmitted = true;
} else if (ev === "error") {
this._readableState.errorEmitted = true;
}
return super.emit(ev, ...args);
}
on(ev, ...args) {
if (ev === "data" || ev === "readable") {
this[kReading] = true;
}
return super.on(ev, ...args);
}
addListener(ev, ...args) {
return this.on(ev, ...args);
}
off(ev, ...args) {
const ret = super.off(ev, ...args);
if (ev === "data" || ev === "readable") {
this[kReading] = this.listenerCount("data") > 0 || this.listenerCount("readable") > 0;
}
return ret;
}
removeListener(ev, ...args) {
return this.off(ev, ...args);
}
push(chunk) {
if (this[kConsume] && chunk !== null && this.readableLength === 0) {
3 years ago
consumePush(this[kConsume], chunk);
return this[kReading] ? super.push(chunk) : true;
}
return super.push(chunk);
}
async text() {
return consume(this, "text");
}
async json() {
return consume(this, "json");
}
async blob() {
return consume(this, "blob");
}
async arrayBuffer() {
return consume(this, "arrayBuffer");
}
async formData() {
throw new NotSupportedError();
}
get bodyUsed() {
return util.isDisturbed(this);
}
get body() {
if (!this[kBody]) {
this[kBody] = ReadableStreamFrom(this);
if (this[kConsume]) {
this[kBody].getReader();
assert(this[kBody].locked);
}
}
return this[kBody];
}
async dump(opts) {
let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144;
try {
for await (const chunk of this) {
limit -= Buffer.byteLength(chunk);
if (limit < 0) {
return;
}
}
} catch {
}
}
};
function isLocked(self) {
return self[kBody] && self[kBody].locked === true || self[kConsume];
}
function isUnusable(self) {
return util.isDisturbed(self) || isLocked(self);
}
async function consume(stream, type) {
if (isUnusable(stream)) {
throw new TypeError("unusable");
}
assert(!stream[kConsume]);
return new Promise((resolve, reject) => {
stream[kConsume] = {
type,
stream,
resolve,
reject,
length: 0,
body: []
};
stream.on("error", function(err) {
consumeFinish(this[kConsume], err);
}).on("close", function() {
if (this[kConsume].body !== null) {
consumeFinish(this[kConsume], new RequestAbortedError());
}
});
process.nextTick(consumeStart, stream[kConsume]);
});
}
function consumeStart(consume2) {
if (consume2.body === null) {
return;
}
const { _readableState: state } = consume2.stream;
for (const chunk of state.buffer) {
consumePush(consume2, chunk);
}
if (state.endEmitted) {
consumeEnd(this[kConsume]);
} else {
consume2.stream.on("end", function() {
consumeEnd(this[kConsume]);
});
}
consume2.stream.resume();
while (consume2.stream.read() != null) {
}
}
function consumeEnd(consume2) {
const { type, body, resolve, stream, length } = consume2;
try {
if (type === "text") {
resolve(toUSVString(Buffer.concat(body)));
} else if (type === "json") {
resolve(JSON.parse(Buffer.concat(body)));
} else if (type === "arrayBuffer") {
const dst = new Uint8Array(length);
let pos = 0;
for (const buf of body) {
dst.set(buf, pos);
pos += buf.byteLength;
}
resolve(dst);
} else if (type === "blob") {
if (!Blob) {
Blob = require("buffer").Blob;
}
resolve(new Blob(body, { type: stream[kContentType] }));
}
consumeFinish(consume2);
} catch (err) {
stream.destroy(err);
}
}
function consumePush(consume2, chunk) {
consume2.length += chunk.length;
consume2.body.push(chunk);
}
function consumeFinish(consume2, err) {
if (consume2.body === null) {
return;
}
if (err) {
consume2.reject(err);
} else {
consume2.resolve();
}
consume2.type = null;
consume2.stream = null;
consume2.resolve = null;
consume2.reject = null;
consume2.length = 0;
consume2.body = null;
}
}
});
// node_modules/undici/lib/api/abort-signal.js
var require_abort_signal = __commonJS({
"node_modules/undici/lib/api/abort-signal.js"(exports, module2) {
var { RequestAbortedError } = require_errors();
var kListener = Symbol("kListener");
var kSignal = Symbol("kSignal");
function abort(self) {
if (self.abort) {
self.abort();
} else {
self.onError(new RequestAbortedError());
}
}
function addSignal(self, signal) {
self[kSignal] = null;
self[kListener] = null;
if (!signal) {
return;
}
if (signal.aborted) {
abort(self);
return;
}
self[kSignal] = signal;
self[kListener] = () => {
abort(self);
};
if ("addEventListener" in self[kSignal]) {
self[kSignal].addEventListener("abort", self[kListener]);
} else {
self[kSignal].addListener("abort", self[kListener]);
}
}
function removeSignal(self) {
if (!self[kSignal]) {
return;
}
if ("removeEventListener" in self[kSignal]) {
self[kSignal].removeEventListener("abort", self[kListener]);
} else {
self[kSignal].removeListener("abort", self[kListener]);
}
self[kSignal] = null;
self[kListener] = null;
}
module2.exports = {
addSignal,
removeSignal
};
}
});
// node_modules/undici/lib/api/api-request.js
var require_api_request = __commonJS({
"node_modules/undici/lib/api/api-request.js"(exports, module2) {
"use strict";
var Readable = require_readable();
var {
InvalidArgumentError,
RequestAbortedError,
ResponseStatusCodeError
3 years ago
} = require_errors();
var util = require_util();
var { AsyncResource } = require("async_hooks");
var { addSignal, removeSignal } = require_abort_signal();
var RequestHandler = class extends AsyncResource {
constructor(opts, callback) {
if (!opts || typeof opts !== "object") {
throw new InvalidArgumentError("invalid opts");
}
const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts;
3 years ago
try {
if (typeof callback !== "function") {
throw new InvalidArgumentError("invalid callback");
}
if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
}
if (method === "CONNECT") {
throw new InvalidArgumentError("invalid method");
}
if (onInfo && typeof onInfo !== "function") {
throw new InvalidArgumentError("invalid onInfo callback");
}
super("UNDICI_REQUEST");
} catch (err) {
if (util.isStream(body)) {
util.destroy(body.on("error", util.nop), err);
}
throw err;
}
this.responseHeaders = responseHeaders || null;
this.opaque = opaque || null;
this.callback = callback;
this.res = null;
this.abort = null;
this.body = body;
this.trailers = {};
this.context = null;
this.onInfo = onInfo || null;
this.throwOnError = throwOnError;
3 years ago
if (util.isStream(body)) {
body.on("error", (err) => {
this.onError(err);
});
}
addSignal(this, signal);
}
onConnect(abort, context2) {
if (!this.callback) {
throw new RequestAbortedError();
}
this.abort = abort;
this.context = context2;
}
onHeaders(statusCode, rawHeaders, resume, statusMessage) {
3 years ago
const { callback, opaque, abort, context: context2 } = this;
if (statusCode < 200) {
if (this.onInfo) {
const headers2 = this.responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders);
this.onInfo({ statusCode, headers: headers2 });
}
return;
}
const parsedHeaders = util.parseHeaders(rawHeaders);
const contentType = parsedHeaders["content-type"];
const body = new Readable(resume, abort, contentType);
3 years ago
this.callback = null;
this.res = body;
const headers = this.responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders);
if (callback !== null) {
if (this.throwOnError && statusCode >= 400) {
this.runInAsyncScope(
getResolveErrorBodyCallback,
null,
{ callback, body, contentType, statusCode, statusMessage, headers }
);
return;
}
3 years ago
this.runInAsyncScope(callback, null, null, {
statusCode,
headers,
trailers: this.trailers,
opaque,
body,
context: context2
});
}
}
onData(chunk) {
const { res } = this;
return res.push(chunk);
}
onComplete(trailers) {
const { res } = this;
removeSignal(this);
util.parseHeaders(trailers, this.trailers);
res.push(null);
}
onError(err) {
const { res, callback, body, opaque } = this;
removeSignal(this);
if (callback) {
this.callback = null;
queueMicrotask(() => {
this.runInAsyncScope(callback, null, err, { opaque });
});
}
if (res) {
this.res = null;
queueMicrotask(() => {
util.destroy(res, err);
});
}
if (body) {
this.body = null;
util.destroy(body, err);
}
}
};
async function getResolveErrorBodyCallback({ callback, body, contentType, statusCode, statusMessage, headers }) {
if (statusCode === 204 || !contentType) {
body.dump();
process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ""}`, statusCode, headers));
return;
}
try {
if (contentType.startsWith("application/json")) {
const payload = await body.json();
process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ""}`, statusCode, headers, payload));
return;
}
if (contentType.startsWith("text/")) {
const payload = await body.text();
process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ""}`, statusCode, headers, payload));
return;
}
} catch (err) {
}
body.dump();
process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ""}`, statusCode, headers));
}
3 years ago
function request(opts, callback) {
if (callback === void 0) {
return new Promise((resolve, reject) => {
request.call(this, opts, (err, data) => {
return err ? reject(err) : resolve(data);
});
});
}
try {
this.dispatch(opts, new RequestHandler(opts, callback));
} catch (err) {
if (typeof callback !== "function") {
throw err;
}
const opaque = opts && opts.opaque;
queueMicrotask(() => callback(err, { opaque }));
}
}
module2.exports = request;
}
});
// node_modules/undici/lib/api/api-stream.js
var require_api_stream = __commonJS({
"node_modules/undici/lib/api/api-stream.js"(exports, module2) {
"use strict";
var { finished } = require("stream");
var {
InvalidArgumentError,
InvalidReturnValueError,
RequestAbortedError
} = require_errors();
var util = require_util();
var { AsyncResource } = require("async_hooks");
var { addSignal, removeSignal } = require_abort_signal();
var StreamHandler = class extends AsyncResource {
constructor(opts, factory, callback) {
if (!opts || typeof opts !== "object") {
throw new InvalidArgumentError("invalid opts");
}
const { signal, method, opaque, body, onInfo, responseHeaders } = opts;
try {
if (typeof callback !== "function") {
throw new InvalidArgumentError("invalid callback");
}
if (typeof factory !== "function") {
throw new InvalidArgumentError("invalid factory");
}
if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
}
if (method === "CONNECT") {
throw new InvalidArgumentError("invalid method");
}
if (onInfo && typeof onInfo !== "function") {
throw new InvalidArgumentError("invalid onInfo callback");
}
super("UNDICI_STREAM");
} catch (err) {
if (util.isStream(body)) {
util.destroy(body.on("error", util.nop), err);
}
throw err;
}
this.responseHeaders = responseHeaders || null;
this.opaque = opaque || null;
this.factory = factory;
this.callback = callback;
this.res = null;
this.abort = null;
this.context = null;
this.trailers = null;
this.body = body;
this.onInfo = onInfo || null;
if (util.isStream(body)) {
body.on("error", (err) => {
this.onError(err);
});
}
addSignal(this, signal);
}
onConnect(abort, context2) {
if (!this.callback) {
throw new RequestAbortedError();
}
this.abort = abort;
this.context = context2;
}
onHeaders(statusCode, rawHeaders, resume) {
const { factory, opaque, context: context2 } = this;
if (statusCode < 200) {
if (this.onInfo) {
const headers2 = this.responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders);
this.onInfo({ statusCode, headers: headers2 });
}
return;
}
this.factory = null;
const headers = this.responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders);
const res = this.runInAsyncScope(factory, null, {
statusCode,
headers,
opaque,
context: context2
});
if (!res || typeof res.write !== "function" || typeof res.end !== "function" || typeof res.on !== "function") {
throw new InvalidReturnValueError("expected Writable");
}
res.on("drain", resume);
finished(res, { readable: false }, (err) => {
const { callback, res: res2, opaque: opaque2, trailers, abort } = this;
this.res = null;
if (err || !res2.readable) {
util.destroy(res2, err);
}
this.callback = null;
this.runInAsyncScope(callback, null, err || null, { opaque: opaque2, trailers });
if (err) {
abort();
}
});
this.res = res;
const needDrain = res.writableNeedDrain !== void 0 ? res.writableNeedDrain : res._writableState && res._writableState.needDrain;
return needDrain !== true;
}
onData(chunk) {
const { res } = this;
return res.write(chunk);
}
onComplete(trailers) {
const { res } = this;
removeSignal(this);
this.trailers = util.parseHeaders(trailers);
res.end();
}
onError(err) {
const { res, callback, opaque, body } = this;
removeSignal(this);
this.factory = null;
if (res) {
this.res = null;
util.destroy(res, err);
} else if (callback) {
this.callback = null;
queueMicrotask(() => {
this.runInAsyncScope(callback, null, err, { opaque });
});
}
if (body) {
this.body = null;
util.destroy(body, err);
}
}
};
function stream(opts, factory, callback) {
if (callback === void 0) {
return new Promise((resolve, reject) => {
stream.call(this, opts, factory, (err, data) => {
return err ? reject(err) : resolve(data);
});
});
}
try {
this.dispatch(opts, new StreamHandler(opts, factory, callback));
} catch (err) {
if (typeof callback !== "function") {
throw err;
}
const opaque = opts && opts.opaque;
queueMicrotask(() => callback(err, { opaque }));
}
}
module2.exports = stream;
}
});
// node_modules/undici/lib/api/api-pipeline.js
var require_api_pipeline = __commonJS({
"node_modules/undici/lib/api/api-pipeline.js"(exports, module2) {
"use strict";
var {
Readable,
Duplex,
PassThrough
} = require("stream");
var {
InvalidArgumentError,
InvalidReturnValueError,
RequestAbortedError
} = require_errors();
var util = require_util();
var { AsyncResource } = require("async_hooks");
var { addSignal, removeSignal } = require_abort_signal();
var assert = require("assert");
var kResume = Symbol("resume");
var PipelineRequest = class extends Readable {
constructor() {
super({ autoDestroy: true });
this[kResume] = null;
}
_read() {
const { [kResume]: resume } = this;
if (resume) {
this[kResume] = null;
resume();
}
}
_destroy(err, callback) {
this._read();
callback(err);
}
};
var PipelineResponse = class extends Readable {
constructor(resume) {
super({ autoDestroy: true });
this[kResume] = resume;
}
_read() {
this[kResume]();
}
_destroy(err, callback) {
if (!err && !this._readableState.endEmitted) {
err = new RequestAbortedError();
}
callback(err);
}
};
var PipelineHandler = class extends AsyncResource {
constructor(opts, handler) {
if (!opts || typeof opts !== "object") {
throw new InvalidArgumentError("invalid opts");
}
if (typeof handler !== "function") {
throw new InvalidArgumentError("invalid handler");
}
const { signal, method, opaque, onInfo, responseHeaders } = opts;
if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
}
if (method === "CONNECT") {
throw new InvalidArgumentError("invalid method");
}
if (onInfo && typeof onInfo !== "function") {
throw new InvalidArgumentError("invalid onInfo callback");
}
super("UNDICI_PIPELINE");
this.opaque = opaque || null;
this.responseHeaders = responseHeaders || null;
this.handler = handler;
this.abort = null;
this.context = null;
this.onInfo = onInfo || null;
this.req = new PipelineRequest().on("error", util.nop);
this.ret = new Duplex({
readableObjectMode: opts.objectMode,
autoDestroy: true,
read: () => {
const { body } = this;
if (body && body.resume) {
body.resume();
}
},
write: (chunk, encoding, callback) => {
const { req } = this;
if (req.push(chunk, encoding) || req._readableState.destroyed) {
callback();
} else {
req[kResume] = callback;
}
},
destroy: (err, callback) => {
const { body, req, res, ret, abort } = this;
if (!err && !ret._readableState.endEmitted) {
err = new RequestAbortedError();
}
if (abort && err) {
abort();
}
util.destroy(body, err);
util.destroy(req, err);
util.destroy(res, err);
removeSignal(this);
callback(err);
}
}).on("prefinish", () => {
const { req } = this;
req.push(null);
});
this.res = null;
addSignal(this, signal);
}
onConnect(abort, context2) {
const { ret, res } = this;
assert(!res, "pipeline cannot be retried");
if (ret.destroyed) {
throw new RequestAbortedError();
}
this.abort = abort;
this.context = context2;
}
onHeaders(statusCode, rawHeaders, resume) {
const { opaque, handler, context: context2 } = this;
if (statusCode < 200) {
if (this.onInfo) {
const headers = this.responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders);
this.onInfo({ statusCode, headers });
}
return;
}
this.res = new PipelineResponse(resume);
let body;
try {
this.handler = null;
const headers = this.responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders);
body = this.runInAsyncScope(handler, null, {
statusCode,
headers,
opaque,
body: this.res,
context: context2
});
} catch (err) {
this.res.on("error", util.nop);
throw err;
}
if (!body || typeof body.on !== "function") {
throw new InvalidReturnValueError("expected Readable");
}
body.on("data", (chunk) => {
const { ret, body: body2 } = this;
if (!ret.push(chunk) && body2.pause) {
body2.pause();
}
}).on("error", (err) => {
const { ret } = this;
util.destroy(ret, err);
}).on("end", () => {
const { ret } = this;
ret.push(null);
}).on("close", () => {
const { ret } = this;
if (!ret._readableState.ended) {
util.destroy(ret, new RequestAbortedError());
}
});
this.body = body;
}
onData(chunk) {
const { res } = this;
return res.push(chunk);
}
onComplete(trailers) {
const { res } = this;
res.push(null);
}
onError(err) {
const { ret } = this;
this.handler = null;
util.destroy(ret, err);
}
};
function pipeline(opts, handler) {
try {
const pipelineHandler = new PipelineHandler(opts, handler);
this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler);
return pipelineHandler.ret;
} catch (err) {
return new PassThrough().destroy(err);
}
}
module2.exports = pipeline;
}
});
// node_modules/undici/lib/api/api-upgrade.js
var require_api_upgrade = __commonJS({
"node_modules/undici/lib/api/api-upgrade.js"(exports, module2) {
"use strict";
var { InvalidArgumentError, RequestAbortedError, SocketError } = require_errors();
var { AsyncResource } = require("async_hooks");
var util = require_util();
var { addSignal, removeSignal } = require_abort_signal();
var assert = require("assert");
var UpgradeHandler = class extends AsyncResource {
constructor(opts, callback) {
if (!opts || typeof opts !== "object") {
throw new InvalidArgumentError("invalid opts");
}
if (typeof callback !== "function") {
throw new InvalidArgumentError("invalid callback");
}
const { signal, opaque, responseHeaders } = opts;
if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
}
super("UNDICI_UPGRADE");
this.responseHeaders = responseHeaders || null;
this.opaque = opaque || null;
this.callback = callback;
this.abort = null;
this.context = null;
addSignal(this, signal);
}
onConnect(abort, context2) {
if (!this.callback) {
throw new RequestAbortedError();
}
this.abort = abort;
this.context = null;
}
onHeaders() {
throw new SocketError("bad upgrade", null);
}
onUpgrade(statusCode, rawHeaders, socket) {
const { callback, opaque, context: context2 } = this;
assert.strictEqual(statusCode, 101);
removeSignal(this);
this.callback = null;
const headers = this.responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders);
this.runInAsyncScope(callback, null, null, {
headers,
socket,
opaque,
context: context2
});
}
onError(err) {
const { callback, opaque } = this;
removeSignal(this);
if (callback) {
this.callback = null;
queueMicrotask(() => {
this.runInAsyncScope(callback, null, err, { opaque });
});
}
}
};
function upgrade(opts, callback) {
if (callback === void 0) {
return new Promise((resolve, reject) => {
upgrade.call(this, opts, (err, data) => {
return err ? reject(err) : resolve(data);
});
});
}
try {
const upgradeHandler = new UpgradeHandler(opts, callback);
this.dispatch({
...opts,
method: opts.method || "GET",
upgrade: opts.protocol || "Websocket"
}, upgradeHandler);
} catch (err) {
if (typeof callback !== "function") {
throw err;
}
const opaque = opts && opts.opaque;
queueMicrotask(() => callback(err, { opaque }));
}
}
module2.exports = upgrade;
}
});
// node_modules/undici/lib/api/api-connect.js
var require_api_connect = __commonJS({
"node_modules/undici/lib/api/api-connect.js"(exports, module2) {
"use strict";
var { InvalidArgumentError, RequestAbortedError, SocketError } = require_errors();
var { AsyncResource } = require("async_hooks");
var util = require_util();
var { addSignal, removeSignal } = require_abort_signal();
var ConnectHandler = class extends AsyncResource {
constructor(opts, callback) {
if (!opts || typeof opts !== "object") {
throw new InvalidArgumentError("invalid opts");
}
if (typeof callback !== "function") {
throw new InvalidArgumentError("invalid callback");
}
const { signal, opaque, responseHeaders } = opts;
if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
}
super("UNDICI_CONNECT");
this.opaque = opaque || null;
this.responseHeaders = responseHeaders || null;
this.callback = callback;
this.abort = null;
addSignal(this, signal);
}
onConnect(abort, context2) {
if (!this.callback) {
throw new RequestAbortedError();
}
this.abort = abort;
this.context = context2;
}
onHeaders() {
throw new SocketError("bad connect", null);
}
onUpgrade(statusCode, rawHeaders, socket) {
const { callback, opaque, context: context2 } = this;
removeSignal(this);
this.callback = null;
const headers = this.responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders);
this.runInAsyncScope(callback, null, null, {
statusCode,
headers,
socket,
opaque,
context: context2
});
}
onError(err) {
const { callback, opaque } = this;
removeSignal(this);
if (callback) {
this.callback = null;
queueMicrotask(() => {
this.runInAsyncScope(callback, null, err, { opaque });
});
}
}
};
function connect(opts, callback) {
if (callback === void 0) {
return new Promise((resolve, reject) => {
connect.call(this, opts, (err, data) => {
return err ? reject(err) : resolve(data);
});
});
}
try {
const connectHandler = new ConnectHandler(opts, callback);
this.dispatch({ ...opts, method: "CONNECT" }, connectHandler);
} catch (err) {
if (typeof callback !== "function") {
throw err;
}
const opaque = opts && opts.opaque;
queueMicrotask(() => callback(err, { opaque }));
}
}
module2.exports = connect;
}
});
// node_modules/undici/lib/api/index.js
var require_api = __commonJS({
"node_modules/undici/lib/api/index.js"(exports, module2) {
"use strict";
module2.exports.request = require_api_request();
module2.exports.stream = require_api_stream();
module2.exports.pipeline = require_api_pipeline();
module2.exports.upgrade = require_api_upgrade();
module2.exports.connect = require_api_connect();
}
});
// node_modules/undici/lib/mock/mock-errors.js
var require_mock_errors = __commonJS({
"node_modules/undici/lib/mock/mock-errors.js"(exports, module2) {
"use strict";
var { UndiciError } = require_errors();
var MockNotMatchedError = class extends UndiciError {
constructor(message) {
super(message);
Error.captureStackTrace(this, MockNotMatchedError);
this.name = "MockNotMatchedError";
this.message = message || "The request does not match any registered mock dispatches";
this.code = "UND_MOCK_ERR_MOCK_NOT_MATCHED";
}
};
module2.exports = {
MockNotMatchedError
};
}
});
// node_modules/undici/lib/mock/mock-symbols.js
var require_mock_symbols = __commonJS({
"node_modules/undici/lib/mock/mock-symbols.js"(exports, module2) {
"use strict";
module2.exports = {
kAgent: Symbol("agent"),
kOptions: Symbol("options"),
kFactory: Symbol("factory"),
kDispatches: Symbol("dispatches"),
kDispatchKey: Symbol("dispatch key"),
kDefaultHeaders: Symbol("default headers"),
kDefaultTrailers: Symbol("default trailers"),
kContentLength: Symbol("content length"),
kMockAgent: Symbol("mock agent"),
kMockAgentSet: Symbol("mock agent set"),
kMockAgentGet: Symbol("mock agent get"),
kMockDispatch: Symbol("mock dispatch"),
kClose: Symbol("close"),
kOriginalClose: Symbol("original agent close"),
kOrigin: Symbol("origin"),
kIsMockActive: Symbol("is mock active"),
kNetConnect: Symbol("net connect"),
kGetNetConnect: Symbol("get net connect"),
kConnected: Symbol("connected")
};
}
});
// node_modules/undici/lib/mock/mock-utils.js
var require_mock_utils = __commonJS({
"node_modules/undici/lib/mock/mock-utils.js"(exports, module2) {
"use strict";
var { MockNotMatchedError } = require_mock_errors();
var {
kDispatches,
kMockAgent,
kOriginalDispatch,
kOrigin,
kGetNetConnect
} = require_mock_symbols();
var { buildURL, nop } = require_util();
var { STATUS_CODES } = require("http");
3 years ago
function matchValue(match, value) {
if (typeof match === "string") {
return match === value;
}
if (match instanceof RegExp) {
return match.test(value);
}
if (typeof match === "function") {
return match(value) === true;
}
return false;
}
function lowerCaseEntries(headers) {
return Object.fromEntries(
Object.entries(headers).map(([headerName, headerValue]) => {
return [headerName.toLocaleLowerCase(), headerValue];
})
);
3 years ago
}
function getHeaderByName(headers, key) {
if (Array.isArray(headers)) {
for (let i = 0; i < headers.length; i += 2) {
if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {
3 years ago
return headers[i + 1];
}
}
return void 0;
} else if (typeof headers.get === "function") {
return headers.get(key);
} else {
return lowerCaseEntries(headers)[key.toLocaleLowerCase()];
}
}
function buildHeadersFromArray(headers) {
const clone = headers.slice();
const entries = [];
for (let index = 0; index < clone.length; index += 2) {
entries.push([clone[index], clone[index + 1]]);
3 years ago
}
return Object.fromEntries(entries);
3 years ago
}
function matchHeaders(mockDispatch2, headers) {
if (typeof mockDispatch2.headers === "function") {
if (Array.isArray(headers)) {
headers = buildHeadersFromArray(headers);
3 years ago
}
return mockDispatch2.headers(headers ? lowerCaseEntries(headers) : {});
}
if (typeof mockDispatch2.headers === "undefined") {
return true;
}
if (typeof headers !== "object" || typeof mockDispatch2.headers !== "object") {
return false;
}
for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch2.headers)) {
const headerValue = getHeaderByName(headers, matchHeaderName);
if (!matchValue(matchHeaderValue, headerValue)) {
return false;
}
}
return true;
}
function safeUrl(path3) {
if (typeof path3 !== "string") {
return path3;
}
const pathSegments = path3.split("?");
if (pathSegments.length !== 2) {
return path3;
}
const qp = new URLSearchParams(pathSegments.pop());
qp.sort();
return [...pathSegments, qp.toString()].join("?");
}
function matchKey(mockDispatch2, { path: path3, method, body, headers }) {
const pathMatch = matchValue(mockDispatch2.path, path3);
3 years ago
const methodMatch = matchValue(mockDispatch2.method, method);
const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
const headersMatch = matchHeaders(mockDispatch2, headers);
return pathMatch && methodMatch && bodyMatch && headersMatch;
}
function getResponseData(data) {
if (Buffer.isBuffer(data)) {
return data;
} else if (typeof data === "object") {
return JSON.stringify(data);
} else {
return data.toString();
}
}
function getMockDispatch(mockDispatches, key) {
const basePath = key.query ? buildURL(key.path, key.query) : key.path;
const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path3 }) => matchValue(safeUrl(path3), resolvedPath));
3 years ago
if (matchedMockDispatches.length === 0) {
throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
3 years ago
}
matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method));
if (matchedMockDispatches.length === 0) {
throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`);
}
matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== "undefined" ? matchValue(body, key.body) : true);
if (matchedMockDispatches.length === 0) {
throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`);
}
matchedMockDispatches = matchedMockDispatches.filter((mockDispatch2) => matchHeaders(mockDispatch2, key.headers));
if (matchedMockDispatches.length === 0) {
throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === "object" ? JSON.stringify(key.headers) : key.headers}'`);
}
return matchedMockDispatches[0];
}
function addMockDispatch(mockDispatches, key, data) {
const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false };
const replyData = typeof data === "function" ? { callback: data } : { ...data };
const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } };
mockDispatches.push(newMockDispatch);
return newMockDispatch;
}
function deleteMockDispatch(mockDispatches, key) {
const index = mockDispatches.findIndex((dispatch) => {
if (!dispatch.consumed) {
return false;
}
return matchKey(dispatch, key);
});
if (index !== -1) {
mockDispatches.splice(index, 1);
}
}
function buildKey(opts) {
const { path: path3, method, body, headers, query } = opts;
3 years ago
return {
path: path3,
3 years ago
method,
body,
headers,
query
3 years ago
};
}
function generateKeyValues(data) {
return Object.entries(data).reduce((keyValuePairs, [key, value]) => [...keyValuePairs, key, value], []);
}
function getStatusText(statusCode) {
return STATUS_CODES[statusCode] || "unknown";
3 years ago
}
async function getResponse(body) {
const buffers = [];
for await (const data of body) {
buffers.push(data);
}
return Buffer.concat(buffers).toString("utf8");
}
function mockDispatch(opts, handler) {
const key = buildKey(opts);
const mockDispatch2 = getMockDispatch(this[kDispatches], key);
mockDispatch2.timesInvoked++;
if (mockDispatch2.data.callback) {
mockDispatch2.data = { ...mockDispatch2.data, ...mockDispatch2.data.callback(opts) };
}
const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch2;
const { timesInvoked, times } = mockDispatch2;
mockDispatch2.consumed = !persist && timesInvoked >= times;
mockDispatch2.pending = timesInvoked < times;
if (error !== null) {
deleteMockDispatch(this[kDispatches], key);
handler.onError(error);
return true;
}
if (typeof delay === "number" && delay > 0) {
setTimeout(() => {
handleReply(this[kDispatches]);
}, delay);
} else {
handleReply(this[kDispatches]);
}
function handleReply(mockDispatches) {
const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers;
const responseData = getResponseData(
typeof data === "function" ? data({ ...opts, headers: optsHeaders }) : data
);
3 years ago
const responseHeaders = generateKeyValues(headers);
const responseTrailers = generateKeyValues(trailers);
handler.abort = nop;
3 years ago
handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode));
handler.onData(Buffer.from(responseData));
handler.onComplete(responseTrailers);
deleteMockDispatch(mockDispatches, key);
}
function resume() {
}
return true;
}
function buildMockDispatch() {
const agent = this[kMockAgent];
const origin = this[kOrigin];
const originalDispatch = this[kOriginalDispatch];
return function dispatch(opts, handler) {
if (agent.isMockActive) {
3 years ago
try {
mockDispatch.call(this, opts, handler);
} catch (error) {
if (error instanceof MockNotMatchedError) {
const netConnect = agent[kGetNetConnect]();
if (netConnect === false) {
throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`);
}
if (checkNetConnect(netConnect, origin)) {
originalDispatch.call(this, opts, handler);
} else {
throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`);
}
} else {
throw error;
}
}
} else {
originalDispatch.call(this, opts, handler);
}
};
}
function checkNetConnect(netConnect, origin) {
const url = new URL(origin);
if (netConnect === true) {
return true;
} else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) {
return true;
}
return false;
}
function buildMockOptions(opts) {
if (opts) {
const { agent, ...mockOptions } = opts;
return mockOptions;
}
}
module2.exports = {
getResponseData,
getMockDispatch,
addMockDispatch,
deleteMockDispatch,
buildKey,
generateKeyValues,
matchValue,
getResponse,
getStatusText,
mockDispatch,
buildMockDispatch,
checkNetConnect,
buildMockOptions,
getHeaderByName
};
}
});
// node_modules/undici/lib/mock/mock-interceptor.js
var require_mock_interceptor = __commonJS({
"node_modules/undici/lib/mock/mock-interceptor.js"(exports, module2) {
"use strict";
var { getResponseData, buildKey, addMockDispatch } = require_mock_utils();
var {
kDispatches,
kDispatchKey,
kDefaultHeaders,
kDefaultTrailers,
kContentLength,
kMockDispatch
} = require_mock_symbols();
var { InvalidArgumentError } = require_errors();
var { buildURL } = require_util();
3 years ago
var MockScope = class {
constructor(mockDispatch) {
this[kMockDispatch] = mockDispatch;
}
delay(waitInMs) {
if (typeof waitInMs !== "number" || !Number.isInteger(waitInMs) || waitInMs <= 0) {
throw new InvalidArgumentError("waitInMs must be a valid integer > 0");
}
this[kMockDispatch].delay = waitInMs;
return this;
}
persist() {
this[kMockDispatch].persist = true;
return this;
}
times(repeatTimes) {
if (typeof repeatTimes !== "number" || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {
throw new InvalidArgumentError("repeatTimes must be a valid integer > 0");
}
this[kMockDispatch].times = repeatTimes;
return this;
}
};
var MockInterceptor = class {
constructor(opts, mockDispatches) {
if (typeof opts !== "object") {
throw new InvalidArgumentError("opts must be an object");
}
if (typeof opts.path === "undefined") {
throw new InvalidArgumentError("opts.path must be defined");
}
if (typeof opts.method === "undefined") {
opts.method = "GET";
}
if (typeof opts.path === "string") {
if (opts.query) {
opts.path = buildURL(opts.path, opts.query);
} else {
const parsedURL = new URL(opts.path, "data://");
opts.path = parsedURL.pathname + parsedURL.search;
}
3 years ago
}
if (typeof opts.method === "string") {
opts.method = opts.method.toUpperCase();
}
this[kDispatchKey] = buildKey(opts);
this[kDispatches] = mockDispatches;
this[kDefaultHeaders] = {};
this[kDefaultTrailers] = {};
this[kContentLength] = false;
}
createMockScopeDispatchData(statusCode, data, responseOptions = {}) {
const responseData = getResponseData(data);
const contentLength = this[kContentLength] ? { "content-length": responseData.length } : {};
const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers };
const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers };
return { statusCode, data, headers, trailers };
}
validateReplyParameters(statusCode, data, responseOptions) {
if (typeof statusCode === "undefined") {
throw new InvalidArgumentError("statusCode must be defined");
}
if (typeof data === "undefined") {
throw new InvalidArgumentError("data must be defined");
}
if (typeof responseOptions !== "object") {
throw new InvalidArgumentError("responseOptions must be an object");
}
}
reply(replyData) {
if (typeof replyData === "function") {
const wrappedDefaultsCallback = (opts) => {
const resolvedData = replyData(opts);
if (typeof resolvedData !== "object") {
throw new InvalidArgumentError("reply options callback must return an object");
}
const { statusCode: statusCode2, data: data2 = "", responseOptions: responseOptions2 = {} } = resolvedData;
3 years ago
this.validateReplyParameters(statusCode2, data2, responseOptions2);
return {
...this.createMockScopeDispatchData(statusCode2, data2, responseOptions2)
};
};
const newMockDispatch2 = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback);
return new MockScope(newMockDispatch2);
}
const [statusCode, data = "", responseOptions = {}] = [...arguments];
3 years ago
this.validateReplyParameters(statusCode, data, responseOptions);
const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions);
const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData);
return new MockScope(newMockDispatch);
}
replyWithError(error) {
if (typeof error === "undefined") {
throw new InvalidArgumentError("error must be defined");
}
const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error });
return new MockScope(newMockDispatch);
}
defaultReplyHeaders(headers) {
if (typeof headers === "undefined") {
throw new InvalidArgumentError("headers must be defined");
}
this[kDefaultHeaders] = headers;
return this;
}
defaultReplyTrailers(trailers) {
if (typeof trailers === "undefined") {
throw new InvalidArgumentError("trailers must be defined");
}
this[kDefaultTrailers] = trailers;
return this;
}
replyContentLength() {
this[kContentLength] = true;
return this;
}
};
module2.exports.MockInterceptor = MockInterceptor;
module2.exports.MockScope = MockScope;
}
});
// node_modules/undici/lib/mock/mock-client.js
var require_mock_client = __commonJS({
"node_modules/undici/lib/mock/mock-client.js"(exports, module2) {
"use strict";
var { promisify } = require("util");
var Client = require_client();
var { buildMockDispatch } = require_mock_utils();
var {
kDispatches,
kMockAgent,
kClose,
kOriginalClose,
kOrigin,
kOriginalDispatch,
kConnected
} = require_mock_symbols();
var { MockInterceptor } = require_mock_interceptor();
var Symbols = require_symbols();
var { InvalidArgumentError } = require_errors();
var MockClient = class extends Client {
constructor(origin, opts) {
super(origin, opts);
if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") {
throw new InvalidArgumentError("Argument opts.agent must implement Agent");
}
this[kMockAgent] = opts.agent;
this[kOrigin] = origin;
this[kDispatches] = [];
this[kConnected] = 1;
this[kOriginalDispatch] = this.dispatch;
this[kOriginalClose] = this.close.bind(this);
this.dispatch = buildMockDispatch.call(this);
this.close = this[kClose];
}
get [Symbols.kConnected]() {
return this[kConnected];
}
intercept(opts) {
return new MockInterceptor(opts, this[kDispatches]);
}
async [kClose]() {
await promisify(this[kOriginalClose])();
this[kConnected] = 0;
this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
}
};
module2.exports = MockClient;
}
});
// node_modules/undici/lib/mock/mock-pool.js
var require_mock_pool = __commonJS({
"node_modules/undici/lib/mock/mock-pool.js"(exports, module2) {
"use strict";
var { promisify } = require("util");
var Pool = require_pool();
var { buildMockDispatch } = require_mock_utils();
var {
kDispatches,
kMockAgent,
kClose,
kOriginalClose,
kOrigin,
kOriginalDispatch,
kConnected
} = require_mock_symbols();
var { MockInterceptor } = require_mock_interceptor();
var Symbols = require_symbols();
var { InvalidArgumentError } = require_errors();
var MockPool = class extends Pool {
constructor(origin, opts) {
super(origin, opts);
if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") {
throw new InvalidArgumentError("Argument opts.agent must implement Agent");
}
this[kMockAgent] = opts.agent;
this[kOrigin] = origin;
this[kDispatches] = [];
this[kConnected] = 1;
this[kOriginalDispatch] = this.dispatch;
this[kOriginalClose] = this.close.bind(this);
this.dispatch = buildMockDispatch.call(this);
this.close = this[kClose];
}
get [Symbols.kConnected]() {
return this[kConnected];
}
intercept(opts) {
return new MockInterceptor(opts, this[kDispatches]);
}
async [kClose]() {
await promisify(this[kOriginalClose])();
this[kConnected] = 0;
this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
}
};
module2.exports = MockPool;
}
});
// node_modules/undici/lib/mock/pluralizer.js
var require_pluralizer = __commonJS({
"node_modules/undici/lib/mock/pluralizer.js"(exports, module2) {
"use strict";
var singulars = {
pronoun: "it",
is: "is",
was: "was",
this: "this"
};
var plurals = {
pronoun: "they",
is: "are",
was: "were",
this: "these"
};
module2.exports = class Pluralizer {
constructor(singular, plural) {
this.singular = singular;
this.plural = plural;
}
pluralize(count) {
const one = count === 1;
const keys = one ? singulars : plurals;
const noun = one ? this.singular : this.plural;
return { ...keys, count, noun };
}
};
}
});
// node_modules/undici/lib/mock/pending-interceptors-formatter.js
var require_pending_interceptors_formatter = __commonJS({
"node_modules/undici/lib/mock/pending-interceptors-formatter.js"(exports, module2) {
"use strict";
var { Transform } = require("stream");
var { Console } = require("console");
module2.exports = class PendingInterceptorsFormatter {
constructor({ disableColors } = {}) {
this.transform = new Transform({
transform(chunk, _enc, cb) {
cb(null, chunk);
}
});
this.logger = new Console({
stdout: this.transform,
inspectOptions: {
colors: !disableColors && !process.env.CI
}
});
}
format(pendingInterceptors) {
const withPrettyHeaders = pendingInterceptors.map(
({ method, path: path3, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
Method: method,
Origin: origin,
Path: path3,
"Status code": statusCode,
Persistent: persist ? "\u2705" : "\u274C",
Invocations: timesInvoked,
Remaining: persist ? Infinity : times - timesInvoked
})
);
3 years ago
this.logger.table(withPrettyHeaders);
return this.transform.read().toString();
}
};
}
});
// node_modules/undici/lib/mock/mock-agent.js
var require_mock_agent = __commonJS({
"node_modules/undici/lib/mock/mock-agent.js"(exports, module2) {
"use strict";
var { kClients } = require_symbols();
var Agent = require_agent();
var {
kAgent,
kMockAgentSet,
kMockAgentGet,
kDispatches,
kIsMockActive,
kNetConnect,
kGetNetConnect,
kOptions,
kFactory
} = require_mock_symbols();
var MockClient = require_mock_client();
var MockPool = require_mock_pool();
var { matchValue, buildMockOptions } = require_mock_utils();
var { InvalidArgumentError, UndiciError } = require_errors();
var Dispatcher = require_dispatcher();
var Pluralizer = require_pluralizer();
var PendingInterceptorsFormatter = require_pending_interceptors_formatter();
var FakeWeakRef = class {
constructor(value) {
this.value = value;
}
deref() {
return this.value;
}
};
var MockAgent = class extends Dispatcher {
constructor(opts) {
super(opts);
this[kNetConnect] = true;
this[kIsMockActive] = true;
if (opts && opts.agent && typeof opts.agent.dispatch !== "function") {
throw new InvalidArgumentError("Argument opts.agent must implement Agent");
}
const agent = opts && opts.agent ? opts.agent : new Agent(opts);
this[kAgent] = agent;
this[kClients] = agent[kClients];
this[kOptions] = buildMockOptions(opts);
}
get(origin) {
let dispatcher = this[kMockAgentGet](origin);
if (!dispatcher) {
dispatcher = this[kFactory](origin);
this[kMockAgentSet](origin, dispatcher);
}
return dispatcher;
}
dispatch(opts, handler) {
this.get(opts.origin);
return this[kAgent].dispatch(opts, handler);
}
async close() {
await this[kAgent].close();
this[kClients].clear();
}
deactivate() {
this[kIsMockActive] = false;
}
activate() {
this[kIsMockActive] = true;
}
enableNetConnect(matcher) {
if (typeof matcher === "string" || typeof matcher === "function" || matcher instanceof RegExp) {
if (Array.isArray(this[kNetConnect])) {
this[kNetConnect].push(matcher);
} else {
this[kNetConnect] = [matcher];
}
} else if (typeof matcher === "undefined") {
this[kNetConnect] = true;
} else {
throw new InvalidArgumentError("Unsupported matcher. Must be one of String|Function|RegExp.");
}
}
disableNetConnect() {
this[kNetConnect] = false;
}
get isMockActive() {
return this[kIsMockActive];
}
3 years ago
[kMockAgentSet](origin, dispatcher) {
this[kClients].set(origin, new FakeWeakRef(dispatcher));
}
[kFactory](origin) {
const mockOptions = Object.assign({ agent: this }, this[kOptions]);
return this[kOptions] && this[kOptions].connections === 1 ? new MockClient(origin, mockOptions) : new MockPool(origin, mockOptions);
}
[kMockAgentGet](origin) {
const ref = this[kClients].get(origin);
if (ref) {
return ref.deref();
}
if (typeof origin !== "string") {
const dispatcher = this[kFactory]("http://localhost:9999");
this[kMockAgentSet](origin, dispatcher);
return dispatcher;
}
for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) {
const nonExplicitDispatcher = nonExplicitRef.deref();
if (nonExplicitDispatcher && typeof keyMatcher !== "string" && matchValue(keyMatcher, origin)) {
const dispatcher = this[kFactory](origin);
this[kMockAgentSet](origin, dispatcher);
dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches];
return dispatcher;
}
}
}
[kGetNetConnect]() {
return this[kNetConnect];
}
pendingInterceptors() {
const mockAgentClients = this[kClients];
return Array.from(mockAgentClients.entries()).flatMap(([origin, scope]) => scope.deref()[kDispatches].map((dispatch) => ({ ...dispatch, origin }))).filter(({ pending }) => pending);
}
assertNoPendingInterceptors({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
const pending = this.pendingInterceptors();
if (pending.length === 0) {
return;
}
const pluralizer = new Pluralizer("interceptor", "interceptors").pluralize(pending.length);
throw new UndiciError(`
${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:
${pendingInterceptorsFormatter.format(pending)}
`.trim());
}
};
module2.exports = MockAgent;
}
});
// node_modules/undici/lib/proxy-agent.js
var require_proxy_agent = __commonJS({
"node_modules/undici/lib/proxy-agent.js"(exports, module2) {
"use strict";
var { kProxy, kClose, kDestroy, kInterceptors } = require_symbols();
3 years ago
var { URL: URL2 } = require("url");
var Agent = require_agent();
var Client = require_client();
3 years ago
var DispatcherBase = require_dispatcher_base();
var { InvalidArgumentError, RequestAbortedError } = require_errors();
var buildConnector = require_connect();
3 years ago
var kAgent = Symbol("proxy agent");
var kClient = Symbol("proxy client");
var kProxyHeaders = Symbol("proxy headers");
var kRequestTls = Symbol("request tls settings");
var kProxyTls = Symbol("proxy tls settings");
var kConnectEndpoint = Symbol("connect endpoint function");
function defaultProtocolPort(protocol) {
return protocol === "https:" ? 443 : 80;
}
function buildProxyOptions(opts) {
if (typeof opts === "string") {
opts = { uri: opts };
}
if (!opts || !opts.uri) {
throw new InvalidArgumentError("Proxy opts.uri is mandatory");
}
return {
uri: opts.uri,
protocol: opts.protocol || "https"
};
}
3 years ago
var ProxyAgent = class extends DispatcherBase {
constructor(opts) {
super(opts);
this[kProxy] = buildProxyOptions(opts);
this[kAgent] = new Agent(opts);
this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) ? opts.interceptors.ProxyAgent : [];
if (typeof opts === "string") {
opts = { uri: opts };
}
if (!opts || !opts.uri) {
throw new InvalidArgumentError("Proxy opts.uri is mandatory");
}
this[kRequestTls] = opts.requestTls;
this[kProxyTls] = opts.proxyTls;
this[kProxyHeaders] = {};
if (opts.auth) {
this[kProxyHeaders]["proxy-authorization"] = `Basic ${opts.auth}`;
}
const resolvedUrl = new URL2(opts.uri);
const { origin, port, host } = resolvedUrl;
const connect = buildConnector({ ...opts.proxyTls });
this[kConnectEndpoint] = buildConnector({ ...opts.requestTls });
this[kClient] = new Client(resolvedUrl, { connect });
this[kAgent] = new Agent({
...opts,
connect: async (opts2, callback) => {
let requestedHost = opts2.host;
if (!opts2.port) {
requestedHost += `:${defaultProtocolPort(opts2.protocol)}`;
}
try {
const { socket, statusCode } = await this[kClient].connect({
origin,
port,
path: requestedHost,
signal: opts2.signal,
headers: {
...this[kProxyHeaders],
host
}
});
if (statusCode !== 200) {
socket.on("error", () => {
}).destroy();
callback(new RequestAbortedError("Proxy response !== 200 when HTTP Tunneling"));
}
if (opts2.protocol !== "https:") {
callback(null, socket);
return;
}
let servername;
if (this[kRequestTls]) {
servername = this[kRequestTls].servername;
} else {
servername = opts2.servername;
}
this[kConnectEndpoint]({ ...opts2, servername, httpSocket: socket }, callback);
} catch (err) {
callback(err);
}
}
});
3 years ago
}
dispatch(opts, handler) {
const { host } = new URL2(opts.origin);
const headers = buildHeaders(opts.headers);
throwIfProxyAuthIsSent(headers);
return this[kAgent].dispatch(
{
...opts,
headers: {
...headers,
host
}
},
handler
);
3 years ago
}
async [kClose]() {
await this[kAgent].close();
await this[kClient].close();
3 years ago
}
async [kDestroy]() {
await this[kAgent].destroy();
await this[kClient].destroy();
3 years ago
}
};
function buildHeaders(headers) {
if (Array.isArray(headers)) {
const headersPair = {};
for (let i = 0; i < headers.length; i += 2) {
headersPair[headers[i]] = headers[i + 1];
}
return headersPair;
}
return headers;
}
function throwIfProxyAuthIsSent(headers) {
const existProxyAuth = headers && Object.keys(headers).find((key) => key.toLowerCase() === "proxy-authorization");
if (existProxyAuth) {
throw new InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor");
}
}
3 years ago
module2.exports = ProxyAgent;
}
});
// node_modules/undici/lib/global.js
var require_global = __commonJS({
"node_modules/undici/lib/global.js"(exports, module2) {
"use strict";
var globalDispatcher = Symbol.for("undici.globalDispatcher.1");
var { InvalidArgumentError } = require_errors();
var Agent = require_agent();
if (getGlobalDispatcher() === void 0) {
setGlobalDispatcher(new Agent());
}
function setGlobalDispatcher(agent) {
if (!agent || typeof agent.dispatch !== "function") {
throw new InvalidArgumentError("Argument agent must implement Agent");
}
Object.defineProperty(globalThis, globalDispatcher, {
value: agent,
writable: true,
enumerable: false,
configurable: false
});
}
function getGlobalDispatcher() {
return globalThis[globalDispatcher];
}
module2.exports = {
setGlobalDispatcher,
getGlobalDispatcher
};
}
});
// node_modules/undici/lib/handler/DecoratorHandler.js
var require_DecoratorHandler = __commonJS({
"node_modules/undici/lib/handler/DecoratorHandler.js"(exports, module2) {
"use strict";
module2.exports = class DecoratorHandler {
constructor(handler) {
this.handler = handler;
}
onConnect(...args) {
return this.handler.onConnect(...args);
}
onError(...args) {
return this.handler.onError(...args);
}
onUpgrade(...args) {
return this.handler.onUpgrade(...args);
}
onHeaders(...args) {
return this.handler.onHeaders(...args);
}
onData(...args) {
return this.handler.onData(...args);
}
onComplete(...args) {
return this.handler.onComplete(...args);
}
onBodySent(...args) {
return this.handler.onBodySent(...args);
}
};
}
});
3 years ago
// node_modules/undici/lib/fetch/headers.js
var require_headers = __commonJS({
"node_modules/undici/lib/fetch/headers.js"(exports, module2) {
"use strict";
var { kHeadersList } = require_symbols();
var { kGuard } = require_symbols2();
var { kEnumerableProperty } = require_util();
var {
makeIterator,
isValidHeaderName,
isValidHeaderValue
} = require_util2();
var { webidl } = require_webidl();
3 years ago
var kHeadersMap = Symbol("headers map");
var kHeadersSortedMap = Symbol("headers map sorted");
function headerValueNormalize(potentialValue) {
return potentialValue.replace(
/^[\r\n\t ]+|[\r\n\t ]+$/g,
""
);
3 years ago
}
function fill(headers, object) {
if (Array.isArray(object)) {
for (const header of object) {
3 years ago
if (header.length !== 2) {
webidl.errors.exception({
header: "Headers constructor",
message: `expected name/value pair to be length 2, found ${header.length}.`
});
3 years ago
}
headers.append(header[0], header[1]);
}
} else if (typeof object === "object" && object !== null) {
for (const [key, value] of Object.entries(object)) {
headers.append(key, value);
3 years ago
}
} else {
webidl.errors.conversionFailed({
prefix: "Headers constructor",
argument: "Argument 1",
types: ["sequence<sequence<ByteString>>", "record<ByteString, ByteString>"]
});
3 years ago
}
}
var HeadersList = class {
constructor(init) {
if (init instanceof HeadersList) {
this[kHeadersMap] = new Map(init[kHeadersMap]);
this[kHeadersSortedMap] = init[kHeadersSortedMap];
} else {
this[kHeadersMap] = new Map(init);
this[kHeadersSortedMap] = null;
}
}
contains(name) {
name = name.toLowerCase();
return this[kHeadersMap].has(name);
}
clear() {
this[kHeadersMap].clear();
this[kHeadersSortedMap] = null;
}
3 years ago
append(name, value) {
this[kHeadersSortedMap] = null;
name = name.toLowerCase();
const exists = this[kHeadersMap].get(name);
3 years ago
if (exists) {
this[kHeadersMap].set(name, `${exists}, ${value}`);
3 years ago
} else {
this[kHeadersMap].set(name, `${value}`);
3 years ago
}
}
set(name, value) {
this[kHeadersSortedMap] = null;
name = name.toLowerCase();
return this[kHeadersMap].set(name, value);
3 years ago
}
delete(name) {
this[kHeadersSortedMap] = null;
name = name.toLowerCase();
return this[kHeadersMap].delete(name);
3 years ago
}
get(name) {
name = name.toLowerCase();
if (!this.contains(name)) {
return null;
}
return this[kHeadersMap].get(name) ?? null;
3 years ago
}
has(name) {
name = name.toLowerCase();
return this[kHeadersMap].has(name);
3 years ago
}
keys() {
return this[kHeadersMap].keys();
}
values() {
return this[kHeadersMap].values();
}
entries() {
return this[kHeadersMap].entries();
}
[Symbol.iterator]() {
return this[kHeadersMap][Symbol.iterator]();
}
};
var Headers = class {
constructor(init = void 0) {
3 years ago
this[kHeadersList] = new HeadersList();
this[kGuard] = "none";
if (init !== void 0) {
init = webidl.converters.HeadersInit(init);
fill(this, init);
}
3 years ago
}
get [Symbol.toStringTag]() {
return this.constructor.name;
}
append(name, value) {
3 years ago
if (!(this instanceof Headers)) {
throw new TypeError("Illegal invocation");
}
if (arguments.length < 2) {
throw new TypeError(
`Failed to execute 'append' on 'Headers': 2 arguments required, but only ${arguments.length} present.`
);
}
name = webidl.converters.ByteString(name);
value = webidl.converters.ByteString(value);
value = headerValueNormalize(value);
if (!isValidHeaderName(name)) {
webidl.errors.invalidArgument({
prefix: "Headers.append",
value: name,
type: "header name"
});
} else if (!isValidHeaderValue(value)) {
webidl.errors.invalidArgument({
prefix: "Headers.append",
value,
type: "header value"
});
3 years ago
}
if (this[kGuard] === "immutable") {
throw new TypeError("immutable");
} else if (this[kGuard] === "request-no-cors") {
}
return this[kHeadersList].append(name, value);
3 years ago
}
delete(name) {
3 years ago
if (!(this instanceof Headers)) {
throw new TypeError("Illegal invocation");
}
if (arguments.length < 1) {
throw new TypeError(
`Failed to execute 'delete' on 'Headers': 1 argument required, but only ${arguments.length} present.`
);
}
name = webidl.converters.ByteString(name);
if (!isValidHeaderName(name)) {
webidl.errors.invalidArgument({
prefix: "Headers.delete",
value: name,
type: "header name"
});
3 years ago
}
if (this[kGuard] === "immutable") {
throw new TypeError("immutable");
} else if (this[kGuard] === "request-no-cors") {
}
if (!this[kHeadersList].contains(name)) {
3 years ago
return;
}
return this[kHeadersList].delete(name);
3 years ago
}
get(name) {
3 years ago
if (!(this instanceof Headers)) {
throw new TypeError("Illegal invocation");
}
if (arguments.length < 1) {
throw new TypeError(
`Failed to execute 'get' on 'Headers': 1 argument required, but only ${arguments.length} present.`
);
}
name = webidl.converters.ByteString(name);
if (!isValidHeaderName(name)) {
webidl.errors.invalidArgument({
prefix: "Headers.get",
value: name,
type: "header name"
});
3 years ago
}
return this[kHeadersList].get(name);
3 years ago
}
has(name) {
3 years ago
if (!(this instanceof Headers)) {
throw new TypeError("Illegal invocation");
}
if (arguments.length < 1) {
throw new TypeError(
`Failed to execute 'has' on 'Headers': 1 argument required, but only ${arguments.length} present.`
);
}
name = webidl.converters.ByteString(name);
if (!isValidHeaderName(name)) {
webidl.errors.invalidArgument({
prefix: "Headers.has",
value: name,
type: "header name"
});
3 years ago
}
return this[kHeadersList].contains(name);
3 years ago
}
set(name, value) {
3 years ago
if (!(this instanceof Headers)) {
throw new TypeError("Illegal invocation");
}
if (arguments.length < 2) {
throw new TypeError(
`Failed to execute 'set' on 'Headers': 2 arguments required, but only ${arguments.length} present.`
);
}
name = webidl.converters.ByteString(name);
value = webidl.converters.ByteString(value);
value = headerValueNormalize(value);
if (!isValidHeaderName(name)) {
webidl.errors.invalidArgument({
prefix: "Headers.set",
value: name,
type: "header name"
});
} else if (!isValidHeaderValue(value)) {
webidl.errors.invalidArgument({
prefix: "Headers.set",
value,
type: "header value"
});
3 years ago
}
if (this[kGuard] === "immutable") {
throw new TypeError("immutable");
} else if (this[kGuard] === "request-no-cors") {
}
return this[kHeadersList].set(name, value);
3 years ago
}
get [kHeadersSortedMap]() {
if (!this[kHeadersList][kHeadersSortedMap]) {
this[kHeadersList][kHeadersSortedMap] = new Map([...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1));
}
3 years ago
return this[kHeadersList][kHeadersSortedMap];
}
keys() {
if (!(this instanceof Headers)) {
throw new TypeError("Illegal invocation");
}
return makeIterator(this[kHeadersSortedMap].keys(), "Headers");
3 years ago
}
values() {
if (!(this instanceof Headers)) {
throw new TypeError("Illegal invocation");
}
return makeIterator(this[kHeadersSortedMap].values(), "Headers");
3 years ago
}
entries() {
if (!(this instanceof Headers)) {
throw new TypeError("Illegal invocation");
}
return makeIterator(this[kHeadersSortedMap].entries(), "Headers");
3 years ago
}
forEach(callbackFn, thisArg = globalThis) {
3 years ago
if (!(this instanceof Headers)) {
throw new TypeError("Illegal invocation");
}
if (arguments.length < 1) {
throw new TypeError(
`Failed to execute 'forEach' on 'Headers': 1 argument required, but only ${arguments.length} present.`
);
3 years ago
}
if (typeof callbackFn !== "function") {
throw new TypeError(
"Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'."
);
3 years ago
}
for (const [key, value] of this) {
callbackFn.apply(thisArg, [value, key, this]);
3 years ago
}
}
[Symbol.for("nodejs.util.inspect.custom")]() {
if (!(this instanceof Headers)) {
throw new TypeError("Illegal invocation");
}
return this[kHeadersList];
}
};
Headers.prototype[Symbol.iterator] = Headers.prototype.entries;
Object.defineProperties(Headers.prototype, {
append: kEnumerableProperty,
delete: kEnumerableProperty,
get: kEnumerableProperty,
has: kEnumerableProperty,
set: kEnumerableProperty,
keys: kEnumerableProperty,
values: kEnumerableProperty,
entries: kEnumerableProperty,
forEach: kEnumerableProperty
});
webidl.converters.HeadersInit = function(V) {
if (webidl.util.Type(V) === "Object") {
if (V[Symbol.iterator]) {
return webidl.converters["sequence<sequence<ByteString>>"](V);
}
return webidl.converters["record<ByteString, ByteString>"](V);
}
webidl.errors.conversionFailed({
prefix: "Headers constructor",
argument: "Argument 1",
types: ["sequence<sequence<ByteString>>", "record<ByteString, ByteString>"]
});
};
3 years ago
module2.exports = {
fill,
Headers,
HeadersList
};
}
});
// node_modules/undici/lib/fetch/global.js
var require_global2 = __commonJS({
"node_modules/undici/lib/fetch/global.js"(exports, module2) {
"use strict";
var globalOrigin = Symbol.for("undici.globalOrigin.1");
function getGlobalOrigin() {
return globalThis[globalOrigin];
}
function setGlobalOrigin(newOrigin) {
if (newOrigin !== void 0 && typeof newOrigin !== "string" && !(newOrigin instanceof URL)) {
throw new Error("Invalid base url");
}
if (newOrigin === void 0) {
Object.defineProperty(globalThis, globalOrigin, {
value: void 0,
writable: true,
enumerable: false,
configurable: false
});
return;
}
const parsedURL = new URL(newOrigin);
if (parsedURL.protocol !== "http:" && parsedURL.protocol !== "https:") {
throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`);
}
Object.defineProperty(globalThis, globalOrigin, {
value: parsedURL,
writable: true,
enumerable: false,
configurable: false
});
}
module2.exports = {
getGlobalOrigin,
setGlobalOrigin
3 years ago
};
}
});
// node_modules/undici/lib/fetch/response.js
var require_response = __commonJS({
"node_modules/undici/lib/fetch/response.js"(exports, module2) {
"use strict";
var { Headers, HeadersList, fill } = require_headers();
var { extractBody, cloneBody, mixinBody } = require_body();
var util = require_util();
var { kEnumerableProperty } = util;
var {
responseURL,
isValidReasonPhrase,
isCancelled,
isAborted,
isBlobLike,
serializeJavascriptValueToJSONString,
isErrorLike
} = require_util2();
3 years ago
var {
redirectStatus,
nullBodyStatus,
DOMException
3 years ago
} = require_constants();
var { kState, kHeaders, kGuard, kRealm } = require_symbols2();
var { webidl } = require_webidl();
var { FormData } = require_formdata();
var { getGlobalOrigin } = require_global2();
3 years ago
var { kHeadersList } = require_symbols();
var assert = require("assert");
var { types } = require("util");
var ReadableStream = globalThis.ReadableStream || require("stream/web").ReadableStream;
3 years ago
var Response = class {
static error() {
const relevantRealm = { settingsObject: {} };
const responseObject = new Response();
responseObject[kState] = makeNetworkError();
responseObject[kRealm] = relevantRealm;
responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList;
responseObject[kHeaders][kGuard] = "immutable";
responseObject[kHeaders][kRealm] = relevantRealm;
return responseObject;
}
static json(data, init = {}) {
if (arguments.length === 0) {
throw new TypeError(
"Failed to execute 'json' on 'Response': 1 argument required, but 0 present."
);
}
if (init !== null) {
init = webidl.converters.ResponseInit(init);
}
const bytes = new TextEncoder("utf-8").encode(
serializeJavascriptValueToJSONString(data)
);
const body = extractBody(bytes);
const relevantRealm = { settingsObject: {} };
const responseObject = new Response();
responseObject[kRealm] = relevantRealm;
responseObject[kHeaders][kGuard] = "response";
responseObject[kHeaders][kRealm] = relevantRealm;
initializeResponse(responseObject, init, { body: body[0], type: "application/json" });
return responseObject;
}
static redirect(url, status = 302) {
3 years ago
const relevantRealm = { settingsObject: {} };
if (arguments.length < 1) {
throw new TypeError(
`Failed to execute 'redirect' on 'Response': 1 argument required, but only ${arguments.length} present.`
);
3 years ago
}
url = webidl.converters.USVString(url);
status = webidl.converters["unsigned short"](status);
3 years ago
let parsedURL;
try {
parsedURL = new URL(url, getGlobalOrigin());
3 years ago
} catch (err) {
throw Object.assign(new TypeError("Failed to parse URL from " + url), {
cause: err
});
}
if (!redirectStatus.includes(status)) {
throw new RangeError("Invalid status code");
}
const responseObject = new Response();
responseObject[kRealm] = relevantRealm;
responseObject[kHeaders][kGuard] = "immutable";
responseObject[kHeaders][kRealm] = relevantRealm;
responseObject[kState].status = status;
const value = parsedURL.toString();
responseObject[kState].headersList.append("location", value);
return responseObject;
}
constructor(body = null, init = {}) {
if (body !== null) {
body = webidl.converters.BodyInit(body);
3 years ago
}
init = webidl.converters.ResponseInit(init);
3 years ago
this[kRealm] = { settingsObject: {} };
this[kState] = makeResponse({});
this[kHeaders] = new Headers();
this[kHeaders][kGuard] = "response";
this[kHeaders][kHeadersList] = this[kState].headersList;
this[kHeaders][kRealm] = this[kRealm];
let bodyWithType = null;
3 years ago
if (body != null) {
const [extractedBody, type] = extractBody(body);
bodyWithType = { body: extractedBody, type };
3 years ago
}
initializeResponse(this, init, bodyWithType);
3 years ago
}
get [Symbol.toStringTag]() {
return this.constructor.name;
}
get type() {
if (!(this instanceof Response)) {
throw new TypeError("Illegal invocation");
}
return this[kState].type;
}
get url() {
if (!(this instanceof Response)) {
throw new TypeError("Illegal invocation");
}
let url = responseURL(this[kState]);
if (url == null) {
return "";
}
if (url.hash) {
url = new URL(url);
url.hash = "";
}
return url.toString();
}
get redirected() {
if (!(this instanceof Response)) {
throw new TypeError("Illegal invocation");
}
return this[kState].urlList.length > 1;
}
get status() {
if (!(this instanceof Response)) {
throw new TypeError("Illegal invocation");
}
return this[kState].status;
}
get ok() {
if (!(this instanceof Response)) {
throw new TypeError("Illegal invocation");
}
return this[kState].status >= 200 && this[kState].status <= 299;
}
get statusText() {
if (!(this instanceof Response)) {
throw new TypeError("Illegal invocation");
}
return this[kState].statusText;
}
get headers() {
if (!(this instanceof Response)) {
throw new TypeError("Illegal invocation");
}
return this[kHeaders];
}
clone() {
if (!(this instanceof Response)) {
throw new TypeError("Illegal invocation");
}
if (this.bodyUsed || this.body && this.body.locked) {
webidl.errors.exception({
header: "Response.clone",
message: "Body has already been consumed."
});
3 years ago
}
const clonedResponse = cloneResponse(this[kState]);
const clonedResponseObject = new Response();
clonedResponseObject[kState] = clonedResponse;
clonedResponseObject[kRealm] = this[kRealm];
clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList;
clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard];
clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm];
return clonedResponseObject;
}
};
mixinBody(Response);
3 years ago
Object.defineProperties(Response.prototype, {
type: kEnumerableProperty,
url: kEnumerableProperty,
status: kEnumerableProperty,
ok: kEnumerableProperty,
redirected: kEnumerableProperty,
statusText: kEnumerableProperty,
headers: kEnumerableProperty,
clone: kEnumerableProperty
});
function cloneResponse(response) {
if (response.internalResponse) {
return filterResponse(
cloneResponse(response.internalResponse),
response.type
);
3 years ago
}
const newResponse = makeResponse({ ...response, body: null });
if (response.body != null) {
newResponse.body = cloneBody(response.body);
}
return newResponse;
}
function makeResponse(init) {
return {
aborted: false,
rangeRequested: false,
timingAllowPassed: false,
requestIncludesCredentials: false,
type: "default",
status: 200,
timingInfo: null,
cacheState: "",
statusText: "",
...init,
headersList: init.headersList ? new HeadersList(init.headersList) : new HeadersList(),
urlList: init.urlList ? [...init.urlList] : []
};
}
function makeNetworkError(reason) {
const isError = isErrorLike(reason);
3 years ago
return makeResponse({
type: "error",
status: 0,
error: isError ? reason : new Error(reason ? String(reason) : reason, {
cause: isError ? reason : void 0
3 years ago
}),
aborted: reason && reason.name === "AbortError"
});
}
function makeFilteredResponse(response, state) {
state = {
internalResponse: response,
...state
};
return new Proxy(response, {
get(target, p) {
return p in state ? state[p] : target[p];
},
set(target, p, value) {
assert(!(p in state));
target[p] = value;
return true;
}
});
}
function filterResponse(response, type) {
if (type === "basic") {
return makeFilteredResponse(response, {
type: "basic",
headersList: response.headersList
3 years ago
});
} else if (type === "cors") {
return makeFilteredResponse(response, {
type: "cors",
headersList: response.headersList
3 years ago
});
} else if (type === "opaque") {
return makeFilteredResponse(response, {
type: "opaque",
urlList: Object.freeze([]),
status: 0,
statusText: "",
body: null
});
} else if (type === "opaqueredirect") {
return makeFilteredResponse(response, {
type: "opaqueredirect",
status: 0,
statusText: "",
headersList: [],
3 years ago
body: null
});
} else {
assert(false);
}
}
function makeAppropriateNetworkError(fetchParams) {
assert(isCancelled(fetchParams));
return isAborted(fetchParams) ? makeNetworkError(new DOMException("The operation was aborted.", "AbortError")) : makeNetworkError(fetchParams.controller.terminated.reason);
}
function initializeResponse(response, init, body) {
if (init.status !== null && (init.status < 200 || init.status > 599)) {
throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.');
}
if ("statusText" in init && init.statusText != null) {
if (!isValidReasonPhrase(String(init.statusText))) {
throw new TypeError("Invalid statusText");
}
}
if ("status" in init && init.status != null) {
response[kState].status = init.status;
}
if ("statusText" in init && init.statusText != null) {
response[kState].statusText = init.statusText;
}
if ("headers" in init && init.headers != null) {
fill(response[kState].headersList, init.headers);
}
if (body) {
if (nullBodyStatus.includes(response.status)) {
webidl.errors.exception({
header: "Response constructor",
message: "Invalid response status code."
});
}
response[kState].body = body.body;
if (body.type != null && !response[kState].headersList.has("Content-Type")) {
response[kState].headersList.append("content-type", body.type);
}
}
3 years ago
}
webidl.converters.ReadableStream = webidl.interfaceConverter(
ReadableStream
);
webidl.converters.FormData = webidl.interfaceConverter(
FormData
);
webidl.converters.URLSearchParams = webidl.interfaceConverter(
URLSearchParams
);
webidl.converters.XMLHttpRequestBodyInit = function(V) {
if (typeof V === "string") {
return webidl.converters.USVString(V);
}
if (isBlobLike(V)) {
return webidl.converters.Blob(V, { strict: false });
}
if (types.isAnyArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) {
return webidl.converters.BufferSource(V);
}
if (util.isFormDataLike(V)) {
return webidl.converters.FormData(V, { strict: false });
}
if (V instanceof URLSearchParams) {
return webidl.converters.URLSearchParams(V);
}
return webidl.converters.DOMString(V);
};
webidl.converters.BodyInit = function(V) {
if (V instanceof ReadableStream) {
return webidl.converters.ReadableStream(V);
}
if (V?.[Symbol.asyncIterator]) {
return V;
}
return webidl.converters.XMLHttpRequestBodyInit(V);
};
webidl.converters.ResponseInit = webidl.dictionaryConverter([
{
key: "status",
converter: webidl.converters["unsigned short"],
defaultValue: 200
},
{
key: "statusText",
converter: webidl.converters.ByteString,
defaultValue: ""
},
{
key: "headers",
converter: webidl.converters.HeadersInit
}
]);
3 years ago
module2.exports = {
makeNetworkError,
makeResponse,
makeAppropriateNetworkError,
filterResponse,
Response
};
}
});
// node_modules/undici/lib/fetch/request.js
var require_request2 = __commonJS({
"node_modules/undici/lib/fetch/request.js"(exports, module2) {
"use strict";
var { extractBody, mixinBody, cloneBody } = require_body();
var { Headers, fill: fillHeaders, HeadersList } = require_headers();
var { FinalizationRegistry } = require_dispatcher_weakref()();
3 years ago
var util = require_util();
var {
isValidHTTPToken,
sameOrigin,
normalizeMethod
} = require_util2();
var {
forbiddenMethods,
corsSafeListedMethods,
referrerPolicy,
requestRedirect,
requestMode,
requestCredentials,
requestCache
} = require_constants();
var { kEnumerableProperty } = util;
var { kHeaders, kSignal, kState, kGuard, kRealm } = require_symbols2();
var { webidl } = require_webidl();
var { getGlobalOrigin } = require_global2();
3 years ago
var { kHeadersList } = require_symbols();
var assert = require("assert");
var TransformStream;
var kInit = Symbol("init");
var requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
signal.removeEventListener("abort", abort);
});
var Request = class {
constructor(input, init = {}) {
if (input === kInit) {
3 years ago
return;
}
if (arguments.length < 1) {
throw new TypeError(
`Failed to construct 'Request': 1 argument required, but only ${arguments.length} present.`
);
3 years ago
}
input = webidl.converters.RequestInfo(input);
init = webidl.converters.RequestInit(init);
this[kRealm] = {
settingsObject: {
baseUrl: getGlobalOrigin()
}
};
3 years ago
let request = null;
let fallbackMode = null;
const baseUrl = this[kRealm].settingsObject.baseUrl;
let signal = null;
if (typeof input === "string") {
let parsedURL;
try {
parsedURL = new URL(input, baseUrl);
} catch (err) {
throw new TypeError("Failed to parse URL from " + input, { cause: err });
}
if (parsedURL.username || parsedURL.password) {
throw new TypeError(
"Request cannot be constructed from a URL that includes credentials: " + input
);
3 years ago
}
request = makeRequest({ urlList: [parsedURL] });
fallbackMode = "cors";
} else {
assert(input instanceof Request);
request = input[kState];
signal = input[kSignal];
}
const origin = this[kRealm].settingsObject.origin;
let window = "client";
if (request.window?.constructor?.name === "EnvironmentSettingsObject" && sameOrigin(request.window, origin)) {
window = request.window;
}
if (init.window !== void 0 && init.window != null) {
throw new TypeError(`'window' option '${window}' must be null`);
}
if (init.window !== void 0) {
window = "no-window";
}
request = makeRequest({
method: request.method,
headersList: request.headersList,
unsafeRequest: request.unsafeRequest,
client: this[kRealm].settingsObject,
window,
priority: request.priority,
origin: request.origin,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
mode: request.mode,
credentials: request.credentials,
cache: request.cache,
redirect: request.redirect,
integrity: request.integrity,
keepalive: request.keepalive,
reloadNavigation: request.reloadNavigation,
historyNavigation: request.historyNavigation,
urlList: [...request.urlList]
});
if (Object.keys(init).length > 0) {
if (request.mode === "navigate") {
request.mode = "same-origin";
}
request.reloadNavigation = false;
request.historyNavigation = false;
request.origin = "client";
request.referrer = "client";
request.referrerPolicy = "";
request.url = request.urlList[request.urlList.length - 1];
request.urlList = [request.url];
}
if (init.referrer !== void 0) {
const referrer = init.referrer;
if (referrer === "") {
request.referrer = "no-referrer";
} else {
let parsedReferrer;
try {
parsedReferrer = new URL(referrer, baseUrl);
} catch (err) {
throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err });
}
request.referrer = parsedReferrer;
}
}
if (init.referrerPolicy !== void 0) {
request.referrerPolicy = init.referrerPolicy;
if (!referrerPolicy.includes(request.referrerPolicy)) {
throw new TypeError(
`Failed to construct 'Request': The provided value '${request.referrerPolicy}' is not a valid enum value of type ReferrerPolicy.`
);
3 years ago
}
}
let mode;
if (init.mode !== void 0) {
mode = init.mode;
if (!requestMode.includes(mode)) {
throw new TypeError(
`Failed to construct 'Request': The provided value '${request.mode}' is not a valid enum value of type RequestMode.`
);
3 years ago
}
} else {
mode = fallbackMode;
}
if (mode === "navigate") {
webidl.errors.exception({
header: "Request constructor",
message: "invalid request mode navigate."
});
3 years ago
}
if (mode != null) {
request.mode = mode;
}
if (init.credentials !== void 0) {
request.credentials = init.credentials;
if (!requestCredentials.includes(request.credentials)) {
throw new TypeError(
`Failed to construct 'Request': The provided value '${request.credentials}' is not a valid enum value of type RequestCredentials.`
);
3 years ago
}
}
if (init.cache !== void 0) {
request.cache = init.cache;
if (!requestCache.includes(request.cache)) {
throw new TypeError(
`Failed to construct 'Request': The provided value '${request.cache}' is not a valid enum value of type RequestCache.`
);
3 years ago
}
}
if (request.cache === "only-if-cached" && request.mode !== "same-origin") {
throw new TypeError(
"'only-if-cached' can be set only with 'same-origin' mode"
);
3 years ago
}
if (init.redirect !== void 0) {
request.redirect = init.redirect;
if (!requestRedirect.includes(request.redirect)) {
throw new TypeError(
`Failed to construct 'Request': The provided value '${request.redirect}' is not a valid enum value of type RequestRedirect.`
);
3 years ago
}
}
if (init.integrity !== void 0 && init.integrity != null) {
request.integrity = String(init.integrity);
}
if (init.keepalive !== void 0) {
request.keepalive = Boolean(init.keepalive);
}
if (init.method !== void 0) {
let method = init.method;
if (!isValidHTTPToken(init.method)) {
throw TypeError(`'${init.method}' is not a valid HTTP method.`);
}
if (forbiddenMethods.indexOf(method.toUpperCase()) !== -1) {
throw TypeError(`'${init.method}' HTTP method is unsupported.`);
}
method = normalizeMethod(init.method);
request.method = method;
}
if (init.signal !== void 0) {
signal = init.signal;
}
this[kState] = request;
const ac = new AbortController();
this[kSignal] = ac.signal;
this[kSignal][kRealm] = this[kRealm];
if (signal != null) {
if (!signal || typeof signal.aborted !== "boolean" || typeof signal.addEventListener !== "function") {
throw new TypeError(
"Failed to construct 'Request': member signal is not of type AbortSignal."
);
3 years ago
}
if (signal.aborted) {
ac.abort(signal.reason);
3 years ago
} else {
const abort = () => ac.abort(signal.reason);
3 years ago
signal.addEventListener("abort", abort, { once: true });
requestFinalizer.register(this, { signal, abort });
}
}
this[kHeaders] = new Headers();
this[kHeaders][kHeadersList] = request.headersList;
this[kHeaders][kGuard] = "request";
3 years ago
this[kHeaders][kRealm] = this[kRealm];
if (mode === "no-cors") {
if (!corsSafeListedMethods.includes(request.method)) {
throw new TypeError(
`'${request.method} is unsupported in no-cors mode.`
);
3 years ago
}
this[kHeaders][kGuard] = "request-no-cors";
}
if (Object.keys(init).length !== 0) {
let headers = new Headers(this[kHeaders]);
3 years ago
if (init.headers !== void 0) {
headers = init.headers;
}
this[kHeaders][kHeadersList].clear();
if (headers.constructor.name === "Headers") {
for (const [key, val] of headers) {
this[kHeaders].append(key, val);
}
3 years ago
} else {
fillHeaders(this[kHeaders], headers);
3 years ago
}
}
const inputBody = input instanceof Request ? input[kState].body : null;
if ((init.body !== void 0 && init.body != null || inputBody != null) && (request.method === "GET" || request.method === "HEAD")) {
throw new TypeError("Request with GET/HEAD method cannot have body.");
}
let initBody = null;
if (init.body !== void 0 && init.body != null) {
const [extractedBody, contentType] = extractBody(
init.body,
request.keepalive
);
3 years ago
initBody = extractedBody;
if (contentType && !this[kHeaders].has("content-type")) {
this[kHeaders].append("content-type", contentType);
}
}
const inputOrInitBody = initBody ?? inputBody;
if (inputOrInitBody != null && inputOrInitBody.source == null) {
if (request.mode !== "same-origin" && request.mode !== "cors") {
throw new TypeError(
'If request is made from ReadableStream, mode should be "same-origin" or "cors"'
);
3 years ago
}
request.useCORSPreflightFlag = true;
}
let finalBody = inputOrInitBody;
if (initBody == null && inputBody != null) {
if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) {
throw new TypeError(
"Cannot construct a Request with a Request object that has already been used."
);
3 years ago
}
if (!TransformStream) {
TransformStream = require("stream/web").TransformStream;
}
const identityTransform = new TransformStream();
inputBody.stream.pipeThrough(identityTransform);
finalBody = {
source: inputBody.source,
length: inputBody.length,
stream: identityTransform.readable
};
}
this[kState].body = finalBody;
}
get [Symbol.toStringTag]() {
return this.constructor.name;
}
get method() {
if (!(this instanceof Request)) {
throw new TypeError("Illegal invocation");
}
return this[kState].method;
}
get url() {
if (!(this instanceof Request)) {
throw new TypeError("Illegal invocation");
}
return this[kState].url.toString();
}
get headers() {
if (!(this instanceof Request)) {
throw new TypeError("Illegal invocation");
}
return this[kHeaders];
}
get destination() {
if (!(this instanceof Request)) {
throw new TypeError("Illegal invocation");
}
return this[kState].destination;
}
get referrer() {
if (!(this instanceof Request)) {
throw new TypeError("Illegal invocation");
}
if (this[kState].referrer === "no-referrer") {
return "";
}
if (this[kState].referrer === "client") {
return "about:client";
}
return this[kState].referrer.toString();
}
get referrerPolicy() {
if (!(this instanceof Request)) {
throw new TypeError("Illegal invocation");
}
return this[kState].referrerPolicy;
}
get mode() {
if (!(this instanceof Request)) {
throw new TypeError("Illegal invocation");
}
return this[kState].mode;
}
get credentials() {
return this[kState].credentials;
}
get cache() {
if (!(this instanceof Request)) {
throw new TypeError("Illegal invocation");
}
return this[kState].cache;
}
get redirect() {
if (!(this instanceof Request)) {
throw new TypeError("Illegal invocation");
}
return this[kState].redirect;
}
get integrity() {
if (!(this instanceof Request)) {
throw new TypeError("Illegal invocation");
}
return this[kState].integrity;
}
get keepalive() {
if (!(this instanceof Request)) {
throw new TypeError("Illegal invocation");
}
return this[kState].keepalive;
}
get isReloadNavigation() {
if (!(this instanceof Request)) {
throw new TypeError("Illegal invocation");
}
return this[kState].reloadNavigation;
}
get isHistoryNavigation() {
if (!(this instanceof Request)) {
throw new TypeError("Illegal invocation");
}
return this[kState].historyNavigation;
}
get signal() {
if (!(this instanceof Request)) {
throw new TypeError("Illegal invocation");
}
return this[kSignal];
}
clone() {
if (!(this instanceof Request)) {
throw new TypeError("Illegal invocation");
}
if (this.bodyUsed || this.body?.locked) {
throw new TypeError("unusable");
}
const clonedRequest = cloneRequest(this[kState]);
const clonedRequestObject = new Request(kInit);
clonedRequestObject[kState] = clonedRequest;
clonedRequestObject[kRealm] = this[kRealm];
clonedRequestObject[kHeaders] = new Headers();
clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList;
clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard];
clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm];
const ac = new AbortController();
if (this.signal.aborted) {
ac.abort(this.signal.reason);
3 years ago
} else {
this.signal.addEventListener(
"abort",
() => {
ac.abort(this.signal.reason);
},
{ once: true }
);
3 years ago
}
clonedRequestObject[kSignal] = ac.signal;
return clonedRequestObject;
}
};
mixinBody(Request);
3 years ago
function makeRequest(init) {
const request = {
method: "GET",
localURLsOnly: false,
unsafeRequest: false,
body: null,
client: null,
reservedClient: null,
replacesClientId: "",
window: "client",
keepalive: false,
serviceWorkers: "all",
initiator: "",
destination: "",
priority: null,
origin: "client",
policyContainer: "client",
referrer: "client",
referrerPolicy: "",
mode: "no-cors",
useCORSPreflightFlag: false,
credentials: "same-origin",
useCredentials: false,
cache: "default",
redirect: "follow",
integrity: "",
cryptoGraphicsNonceMetadata: "",
parserMetadata: "",
reloadNavigation: false,
historyNavigation: false,
userActivation: false,
taintedOrigin: false,
redirectCount: 0,
responseTainting: "basic",
preventNoCacheCacheControlHeaderModification: false,
done: false,
timingAllowFailed: false,
...init,
headersList: init.headersList ? new HeadersList(init.headersList) : new HeadersList()
};
request.url = request.urlList[0];
return request;
}
function cloneRequest(request) {
const newRequest = makeRequest({ ...request, body: null });
if (request.body != null) {
newRequest.body = cloneBody(request.body);
}
return newRequest;
}
Object.defineProperties(Request.prototype, {
method: kEnumerableProperty,
url: kEnumerableProperty,
headers: kEnumerableProperty,
redirect: kEnumerableProperty,
clone: kEnumerableProperty,
signal: kEnumerableProperty
});
webidl.converters.Request = webidl.interfaceConverter(
Request
);
webidl.converters.RequestInfo = function(V) {
if (typeof V === "string") {
return webidl.converters.USVString(V);
}
if (V instanceof Request) {
return webidl.converters.Request(V);
}
return webidl.converters.USVString(V);
};
webidl.converters.AbortSignal = webidl.interfaceConverter(
AbortSignal
);
webidl.converters.RequestInit = webidl.dictionaryConverter([
{
key: "method",
converter: webidl.converters.ByteString
},
{
key: "headers",
converter: webidl.converters.HeadersInit
},
{
key: "body",
converter: webidl.nullableConverter(
webidl.converters.BodyInit
)
},
{
key: "referrer",
converter: webidl.converters.USVString
},
{
key: "referrerPolicy",
converter: webidl.converters.DOMString,
allowedValues: [
"",
"no-referrer",
"no-referrer-when-downgrade",
"same-origin",
"origin",
"strict-origin",
"origin-when-cross-origin",
"strict-origin-when-cross-origin",
"unsafe-url"
]
},
{
key: "mode",
converter: webidl.converters.DOMString,
allowedValues: [
"same-origin",
"cors",
"no-cors",
"navigate",
"websocket"
]
},
{
key: "credentials",
converter: webidl.converters.DOMString,
allowedValues: [
"omit",
"same-origin",
"include"
]
},
{
key: "cache",
converter: webidl.converters.DOMString,
allowedValues: [
"default",
"no-store",
"reload",
"no-cache",
"force-cache",
"only-if-cached"
]
},
{
key: "redirect",
converter: webidl.converters.DOMString,
allowedValues: [
"follow",
"error",
"manual"
]
},
{
key: "integrity",
converter: webidl.converters.DOMString
},
{
key: "keepalive",
converter: webidl.converters.boolean
},
{
key: "signal",
converter: webidl.nullableConverter(
(signal) => webidl.converters.AbortSignal(
signal,
{ strict: false }
)
)
},
{
key: "window",
converter: webidl.converters.any
}
]);
3 years ago
module2.exports = { Request, makeRequest };
}
});
// node_modules/undici/lib/fetch/dataURL.js
var require_dataURL = __commonJS({
"node_modules/undici/lib/fetch/dataURL.js"(exports, module2) {
var assert = require("assert");
var { atob: atob2 } = require("buffer");
var { isValidHTTPToken } = require_util2();
3 years ago
var encoder = new TextEncoder();
function dataURLProcessor(dataURL) {
assert(dataURL.protocol === "data:");
let input = URLSerializer(dataURL, true);
input = input.slice(5);
const position = { position: 0 };
let mimeType = collectASequenceOfCodePoints(
(char) => char !== ",",
input,
position
);
3 years ago
const mimeTypeLength = mimeType.length;
mimeType = mimeType.replace(/^(\u0020)+|(\u0020)+$/g, "");
if (position.position >= input.length) {
return "failure";
}
position.position++;
const encodedBody = input.slice(mimeTypeLength + 1);
let body = stringPercentDecode(encodedBody);
if (/;(\u0020){0,}base64$/i.test(mimeType)) {
const stringBody = decodeURIComponent(new TextDecoder("utf-8").decode(body));
body = forgivingBase64(stringBody);
if (body === "failure") {
return "failure";
}
mimeType = mimeType.slice(0, -6);
mimeType = mimeType.replace(/(\u0020)+$/, "");
mimeType = mimeType.slice(0, -1);
}
if (mimeType.startsWith(";")) {
mimeType = "text/plain" + mimeType;
}
let mimeTypeRecord = parseMIMEType(mimeType);
if (mimeTypeRecord === "failure") {
mimeTypeRecord = parseMIMEType("text/plain;charset=US-ASCII");
}
return { mimeType: mimeTypeRecord, body };
}
function URLSerializer(url, excludeFragment = false) {
let output = url.protocol;
if (url.host.length > 0) {
output += "//";
if (url.username.length > 0 || url.password.length > 0) {
output += url.username;
if (url.password.length > 0) {
output += ":" + url.password;
}
output += "@";
}
output += decodeURIComponent(url.host);
if (url.port.length > 0) {
output += ":" + url.port;
}
}
if (url.host.length === 0 && url.pathname.length > 1 && url.href.slice(url.protocol.length + 1)[0] === ".") {
output += "/.";
}
output += url.pathname;
if (url.search.length > 0) {
output += url.search;
}
if (excludeFragment === false && url.hash.length > 0) {
output += url.hash;
}
return output;
}
function collectASequenceOfCodePoints(condition, input, position) {
let result = "";
while (position.position < input.length && condition(input[position.position])) {
result += input[position.position];
position.position++;
}
return result;
}
function stringPercentDecode(input) {
const bytes = encoder.encode(input);
return percentDecode(bytes);
}
function percentDecode(input) {
const output = [];
for (let i = 0; i < input.length; i++) {
const byte = input[i];
if (byte !== 37) {
output.push(byte);
} else if (byte === 37 && !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2]))) {
output.push(37);
} else {
const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2]);
const bytePoint = Number.parseInt(nextTwoBytes, 16);
output.push(bytePoint);
i += 2;
}
}
return Uint8Array.from(output);
3 years ago
}
function parseMIMEType(input) {
input = input.trim();
const position = { position: 0 };
const type = collectASequenceOfCodePoints(
(char) => char !== "/",
input,
position
);
3 years ago
if (type.length === 0 || !/^[!#$%&'*+-.^_|~A-z0-9]+$/.test(type)) {
return "failure";
}
if (position.position > input.length) {
return "failure";
}
position.position++;
let subtype = collectASequenceOfCodePoints(
(char) => char !== ";",
input,
position
);
3 years ago
subtype = subtype.trim();
if (subtype.length === 0 || !/^[!#$%&'*+-.^_|~A-z0-9]+$/.test(subtype)) {
return "failure";
}
const mimeType = {
type: type.toLowerCase(),
subtype: subtype.toLowerCase(),
parameters: /* @__PURE__ */ new Map()
};
while (position.position < input.length) {
position.position++;
collectASequenceOfCodePoints(
(char) => /(\u000A|\u000D|\u0009|\u0020)/.test(char),
input,
position
);
let parameterName = collectASequenceOfCodePoints(
(char) => char !== ";" && char !== "=",
input,
position
);
3 years ago
parameterName = parameterName.toLowerCase();
if (position.position < input.length) {
if (input[position.position] === ";") {
continue;
}
position.position++;
}
if (position.position > input.length) {
break;
}
let parameterValue = null;
if (input[position.position] === '"') {
parameterValue = collectAnHTTPQuotedString(input, position, true);
collectASequenceOfCodePoints(
(char) => char !== ";",
input,
position
);
3 years ago
} else {
parameterValue = collectASequenceOfCodePoints(
(char) => char !== ";",
input,
position
);
parameterValue = parameterValue.trimEnd();
3 years ago
if (parameterValue.length === 0) {
continue;
}
}
if (parameterName.length !== 0 && /^[!#$%&'*+-.^_|~A-z0-9]+$/.test(parameterName) && !/^(\u0009|\x{0020}-\x{007E}|\x{0080}-\x{00FF})+$/.test(parameterValue) && !mimeType.parameters.has(parameterName)) {
mimeType.parameters.set(parameterName, parameterValue);
}
}
return mimeType;
}
function forgivingBase64(data) {
data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, "");
if (data.length % 4 === 0) {
data = data.replace(/=?=$/, "");
}
if (data.length % 4 === 1) {
return "failure";
}
if (/[^+/0-9A-Za-z]/.test(data)) {
return "failure";
}
const binary = atob2(data);
3 years ago
const bytes = new Uint8Array(binary.length);
for (let byte = 0; byte < binary.length; byte++) {
bytes[byte] = binary.charCodeAt(byte);
}
return bytes;
}
function collectAnHTTPQuotedString(input, position, extractValue) {
const positionStart = position.position;
let value = "";
assert(input[position.position] === '"');
position.position++;
while (true) {
value += collectASequenceOfCodePoints(
(char) => char !== '"' && char !== "\\",
input,
position
);
3 years ago
if (position.position >= input.length) {
break;
}
const quoteOrBackslash = input[position.position];
position.position++;
if (quoteOrBackslash === "\\") {
if (position.position >= input.length) {
value += "\\";
break;
}
value += input[position.position];
position.position++;
} else {
assert(quoteOrBackslash === '"');
break;
}
}
if (extractValue) {
return value;
}
return input.slice(positionStart, position.position);
}
function serializeAMimeType(mimeType) {
assert(mimeType !== "failure");
const { type, subtype, parameters } = mimeType;
let serialization = `${type}/${subtype}`;
for (let [name, value] of parameters.entries()) {
serialization += ";";
serialization += name;
serialization += "=";
if (!isValidHTTPToken(value)) {
value = value.replace(/(\\|")/g, "\\$1");
value = '"' + value;
value += '"';
}
serialization += value;
}
return serialization;
}
3 years ago
module2.exports = {
dataURLProcessor,
URLSerializer,
collectASequenceOfCodePoints,
stringPercentDecode,
parseMIMEType,
collectAnHTTPQuotedString,
serializeAMimeType
3 years ago
};
}
});
// node_modules/undici/lib/fetch/index.js
var require_fetch = __commonJS({
"node_modules/undici/lib/fetch/index.js"(exports, module2) {
"use strict";
var {
Response,
makeNetworkError,
makeAppropriateNetworkError,
filterResponse,
makeResponse
} = require_response();
var { Headers } = require_headers();
var { Request, makeRequest } = require_request2();
var zlib = require("zlib");
var {
bytesMatch,
3 years ago
makePolicyContainer,
clonePolicyContainer,
requestBadPort,
TAOCheck,
appendRequestOriginHeader,
responseLocationURL,
requestCurrentURL,
setRequestReferrerPolicyOnRedirect,
tryUpgradeRequestToAPotentiallyTrustworthyURL,
createOpaqueTimingInfo,
appendFetchMetadata,
corsCheck,
crossOriginResourcePolicyCheck,
determineRequestsReferrer,
coarsenedSharedCurrentTime,
createDeferredPromise,
isBlobLike,
sameOrigin,
isCancelled,
isAborted,
isErrorLike,
fullyReadBody
3 years ago
} = require_util2();
var { kState, kHeaders, kGuard, kRealm } = require_symbols2();
var assert = require("assert");
var { safelyExtractBody, extractBody } = require_body();
var {
redirectStatus,
nullBodyStatus,
safeMethods,
requestBodyHeader,
subresource,
DOMException
3 years ago
} = require_constants();
var { kHeadersList } = require_symbols();
var EE = require("events");
var { Readable, pipeline } = require("stream");
var { isErrored, isReadable } = require_util();
var { dataURLProcessor, serializeAMimeType } = require_dataURL();
3 years ago
var { TransformStream } = require("stream/web");
var resolveObjectURL;
var ReadableStream;
var nodeVersion = process.versions.node.split(".");
var nodeMajor = Number(nodeVersion[0]);
var nodeMinor = Number(nodeVersion[1]);
3 years ago
var Fetch = class extends EE {
constructor(dispatcher) {
super();
this.dispatcher = dispatcher;
this.connection = null;
this.dump = false;
this.state = "ongoing";
}
terminate(reason) {
if (this.state !== "ongoing") {
return;
}
this.state = "terminated";
this.connection?.destroy(reason);
this.emit("terminated", reason);
}
abort() {
if (this.state !== "ongoing") {
return;
}
const reason = new DOMException("The operation was aborted.", "AbortError");
3 years ago
this.state = "aborted";
this.connection?.destroy(reason);
this.emit("terminated", reason);
}
};
async function fetch2(input, init = {}) {
if (arguments.length < 1) {
throw new TypeError(
`Failed to execute 'fetch' on 'Window': 1 argument required, but only ${arguments.length} present.`
);
3 years ago
}
const p = createDeferredPromise();
let requestObject;
try {
requestObject = new Request(input, init);
} catch (e) {
p.reject(e);
return p.promise;
}
3 years ago
const request = requestObject[kState];
if (requestObject.signal.aborted) {
abortFetch(p, request, null);
return p.promise;
}
const globalObject = request.client.globalObject;
if (globalObject?.constructor?.name === "ServiceWorkerGlobalScope") {
request.serviceWorkers = "none";
}
let responseObject = null;
const relevantRealm = null;
let locallyAborted = false;
let controller = null;
requestObject.signal.addEventListener(
"abort",
() => {
locallyAborted = true;
abortFetch(p, request, responseObject);
if (controller != null) {
controller.abort();
}
},
{ once: true }
);
3 years ago
const handleFetchDone = (response) => finalizeAndReportTiming(response, "fetch");
const processResponse = (response) => {
if (locallyAborted) {
return;
}
if (response.aborted) {
abortFetch(p, request, responseObject);
return;
}
if (response.type === "error") {
p.reject(
Object.assign(new TypeError("fetch failed"), { cause: response.error })
);
3 years ago
return;
}
responseObject = new Response();
responseObject[kState] = response;
responseObject[kRealm] = relevantRealm;
responseObject[kHeaders][kHeadersList] = response.headersList;
responseObject[kHeaders][kGuard] = "immutable";
responseObject[kHeaders][kRealm] = relevantRealm;
p.resolve(responseObject);
};
controller = fetching({
request,
processResponseEndOfBody: handleFetchDone,
processResponse,
dispatcher: this
});
return p.promise;
}
function finalizeAndReportTiming(response, initiatorType = "other") {
if (response.type === "error" && response.aborted) {
return;
}
if (!response.urlList?.length) {
return;
}
const originalURL = response.urlList[0];
let timingInfo = response.timingInfo;
let cacheState = response.cacheState;
if (!/^https?:/.test(originalURL.protocol)) {
return;
}
if (timingInfo === null) {
return;
}
if (!timingInfo.timingAllowPassed) {
timingInfo = createOpaqueTimingInfo({
startTime: timingInfo.startTime
});
cacheState = "";
}
response.timingInfo.endTime = coarsenedSharedCurrentTime();
response.timingInfo = timingInfo;
markResourceTiming(
timingInfo,
originalURL,
initiatorType,
globalThis,
cacheState
);
3 years ago
}
function markResourceTiming(timingInfo, originalURL, initiatorType, globalThis2, cacheState) {
if (nodeMajor >= 18 && nodeMinor >= 2) {
performance.markResourceTiming(timingInfo, originalURL, initiatorType, globalThis2, cacheState);
}
3 years ago
}
function abortFetch(p, request, responseObject) {
const error = new DOMException("The operation was aborted.", "AbortError");
3 years ago
p.reject(error);
if (request.body != null && isReadable(request.body?.stream)) {
request.body.stream.cancel(error).catch((err) => {
if (err.code === "ERR_INVALID_STATE") {
return;
}
throw err;
});
}
if (responseObject == null) {
return;
}
const response = responseObject[kState];
if (response.body != null && isReadable(response.body?.stream)) {
response.body.stream.cancel(error).catch((err) => {
if (err.code === "ERR_INVALID_STATE") {
return;
}
throw err;
});
}
}
function fetching({
request,
processRequestBodyChunkLength,
processRequestEndOfBody,
processResponse,
processResponseEndOfBody,
processResponseConsumeBody,
useParallelQueue = false,
dispatcher
}) {
let taskDestination = null;
let crossOriginIsolatedCapability = false;
if (request.client != null) {
taskDestination = request.client.globalObject;
crossOriginIsolatedCapability = request.client.crossOriginIsolatedCapability;
}
const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability);
const timingInfo = createOpaqueTimingInfo({
startTime: currenTime
});
const fetchParams = {
controller: new Fetch(dispatcher),
request,
timingInfo,
processRequestBodyChunkLength,
processRequestEndOfBody,
processResponse,
processResponseConsumeBody,
processResponseEndOfBody,
taskDestination,
crossOriginIsolatedCapability
};
assert(!request.body || request.body.stream);
if (request.window === "client") {
request.window = request.client?.globalObject?.constructor?.name === "Window" ? request.client : "no-window";
}
if (request.origin === "client") {
request.origin = request.client?.origin;
}
if (request.policyContainer === "client") {
if (request.client != null) {
request.policyContainer = clonePolicyContainer(
request.client.policyContainer
);
3 years ago
} else {
request.policyContainer = makePolicyContainer();
}
}
if (!request.headersList.has("accept")) {
const value = "*/*";
request.headersList.append("accept", value);
}
if (!request.headersList.has("accept-language")) {
request.headersList.append("accept-language", "*");
}
if (request.priority === null) {
}
if (subresource.includes(request.destination)) {
}
mainFetch(fetchParams).catch((err) => {
fetchParams.controller.terminate(err);
});
return fetchParams.controller;
}
async function mainFetch(fetchParams, recursive = false) {
const request = fetchParams.request;
let response = null;
if (request.localURLsOnly && !/^(about|blob|data):/.test(requestCurrentURL(request).protocol)) {
response = makeNetworkError("local URLs only");
}
tryUpgradeRequestToAPotentiallyTrustworthyURL(request);
if (requestBadPort(request) === "blocked") {
response = makeNetworkError("bad port");
}
if (request.referrerPolicy === "") {
request.referrerPolicy = request.policyContainer.referrerPolicy;
}
if (request.referrer !== "no-referrer") {
request.referrer = determineRequestsReferrer(request);
}
if (response === null) {
response = await (async () => {
const currentURL = requestCurrentURL(request);
if (sameOrigin(currentURL, request.url) && request.responseTainting === "basic" || currentURL.protocol === "data:" || (request.mode === "navigate" || request.mode === "websocket")) {
request.responseTainting = "basic";
return await schemeFetch(fetchParams);
}
if (request.mode === "same-origin") {
return makeNetworkError('request mode cannot be "same-origin"');
}
if (request.mode === "no-cors") {
if (request.redirect !== "follow") {
return makeNetworkError(
'redirect mode cannot be "follow" for "no-cors" request'
);
3 years ago
}
request.responseTainting = "opaque";
return await schemeFetch(fetchParams);
3 years ago
}
if (!/^https?:/.test(requestCurrentURL(request).protocol)) {
return makeNetworkError("URL scheme must be a HTTP(S) scheme");
}
request.responseTainting = "cors";
return await httpFetch(fetchParams);
})();
}
if (recursive) {
return response;
}
if (response.status !== 0 && !response.internalResponse) {
if (request.responseTainting === "cors") {
}
if (request.responseTainting === "basic") {
response = filterResponse(response, "basic");
} else if (request.responseTainting === "cors") {
response = filterResponse(response, "cors");
} else if (request.responseTainting === "opaque") {
response = filterResponse(response, "opaque");
} else {
assert(false);
}
}
let internalResponse = response.status === 0 ? response : response.internalResponse;
if (internalResponse.urlList.length === 0) {
internalResponse.urlList.push(...request.urlList);
}
if (!request.timingAllowFailed) {
response.timingAllowPassed = true;
}
if (response.type === "opaque" && internalResponse.status === 206 && internalResponse.rangeRequested && !request.headers.has("range")) {
response = internalResponse = makeNetworkError();
}
if (response.status !== 0 && (request.method === "HEAD" || request.method === "CONNECT" || nullBodyStatus.includes(internalResponse.status))) {
internalResponse.body = null;
fetchParams.controller.dump = true;
}
if (request.integrity) {
const processBodyError = (reason) => fetchFinale(fetchParams, makeNetworkError(reason));
if (request.responseTainting === "opaque" || response.body == null) {
processBodyError(response.error);
return;
}
const processBody = (bytes) => {
if (!bytesMatch(bytes, request.integrity)) {
3 years ago
processBodyError("integrity mismatch");
return;
}
response.body = safelyExtractBody(bytes)[0];
fetchFinale(fetchParams, response);
};
await fullyReadBody(response.body, processBody, processBodyError);
3 years ago
} else {
fetchFinale(fetchParams, response);
}
}
async function schemeFetch(fetchParams) {
const { request } = fetchParams;
const {
protocol: scheme,
pathname: path3
3 years ago
} = requestCurrentURL(request);
switch (scheme) {
case "about:": {
if (path3 === "blank") {
3 years ago
const resp = makeResponse({
statusText: "OK",
headersList: [
["content-type", "text/html;charset=utf-8"]
]
});
resp.urlList = [new URL("about:blank")];
return resp;
}
return makeNetworkError("invalid path called");
}
case "blob:": {
resolveObjectURL = resolveObjectURL || require("buffer").resolveObjectURL;
const currentURL = requestCurrentURL(request);
if (currentURL.search.length !== 0) {
return makeNetworkError("NetworkError when attempting to fetch resource.");
}
const blob = resolveObjectURL(currentURL.toString());
if (request.method !== "GET" || !isBlobLike(blob)) {
return makeNetworkError("invalid method");
}
const response = makeResponse({ statusText: "OK", urlList: [currentURL] });
response.headersList.set("content-length", `${blob.size}`);
response.headersList.set("content-type", blob.type);
response.body = extractBody(blob)[0];
return response;
}
case "data:": {
const currentURL = requestCurrentURL(request);
const dataURLStruct = dataURLProcessor(currentURL);
if (dataURLStruct === "failure") {
return makeNetworkError("failed to fetch the data URL");
}
const mimeType = serializeAMimeType(dataURLStruct.mimeType);
3 years ago
return makeResponse({
statusText: "OK",
headersList: [
["content-type", mimeType]
3 years ago
],
body: extractBody(dataURLStruct.body)[0]
});
}
case "file:": {
return makeNetworkError("not implemented... yet...");
}
case "http:":
case "https:": {
return await httpFetch(fetchParams).catch((err) => makeNetworkError(err));
}
default: {
return makeNetworkError("unknown scheme");
}
}
}
function finalizeResponse(fetchParams, response) {
fetchParams.request.done = true;
if (fetchParams.processResponseDone != null) {
queueMicrotask(() => fetchParams.processResponseDone(response));
}
}
async function fetchFinale(fetchParams, response) {
if (response.type === "error") {
response.urlList = [fetchParams.request.urlList[0]];
response.timingInfo = createOpaqueTimingInfo({
startTime: fetchParams.timingInfo.startTime
});
}
const processResponseEndOfBody = () => {
fetchParams.request.done = true;
if (fetchParams.processResponseEndOfBody != null) {
queueMicrotask(() => fetchParams.processResponseEndOfBody(response));
}
};
if (fetchParams.processResponse != null) {
queueMicrotask(() => fetchParams.processResponse(response));
}
if (response.body == null) {
processResponseEndOfBody();
} else {
const identityTransformAlgorithm = (chunk, controller) => {
controller.enqueue(chunk);
};
const transformStream = new TransformStream({
start() {
},
transform: identityTransformAlgorithm,
flush: processResponseEndOfBody
});
response.body = { stream: response.body.stream.pipeThrough(transformStream) };
}
if (fetchParams.processResponseConsumeBody != null) {
const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes);
const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure);
if (response.body == null) {
queueMicrotask(() => processBody(null));
} else {
await fullyReadBody(response.body, processBody, processBodyError);
3 years ago
}
}
}
async function httpFetch(fetchParams) {
const request = fetchParams.request;
let response = null;
let actualResponse = null;
const timingInfo = fetchParams.timingInfo;
if (request.serviceWorkers === "all") {
}
if (response === null) {
if (request.redirect === "follow") {
request.serviceWorkers = "none";
}
actualResponse = response = await httpNetworkOrCacheFetch(fetchParams);
if (request.responseTainting === "cors" && corsCheck(request, response) === "failure") {
return makeNetworkError("cors failure");
}
if (TAOCheck(request, response) === "failure") {
request.timingAllowFailed = true;
}
}
if ((request.responseTainting === "opaque" || response.type === "opaque") && crossOriginResourcePolicyCheck(
request.origin,
request.client,
request.destination,
actualResponse
) === "blocked") {
3 years ago
return makeNetworkError("blocked");
}
if (redirectStatus.includes(actualResponse.status)) {
if (request.redirect !== "manual") {
fetchParams.controller.connection.destroy();
}
3 years ago
if (request.redirect === "error") {
response = makeNetworkError("unexpected redirect");
3 years ago
} else if (request.redirect === "manual") {
response = actualResponse;
} else if (request.redirect === "follow") {
response = await httpRedirectFetch(fetchParams, response);
} else {
assert(false);
}
}
response.timingInfo = timingInfo;
return response;
}
async function httpRedirectFetch(fetchParams, response) {
const request = fetchParams.request;
const actualResponse = response.internalResponse ? response.internalResponse : response;
let locationURL;
try {
locationURL = responseLocationURL(
actualResponse,
requestCurrentURL(request).hash
);
3 years ago
if (locationURL == null) {
return response;
}
} catch (err) {
return makeNetworkError(err);
}
if (!/^https?:/.test(locationURL.protocol)) {
return makeNetworkError("URL scheme must be a HTTP(S) scheme");
}
if (request.redirectCount === 20) {
return makeNetworkError("redirect count exceeded");
}
request.redirectCount += 1;
if (request.mode === "cors" && (locationURL.username || locationURL.password) && !sameOrigin(request, locationURL)) {
return makeNetworkError('cross origin not allowed for request mode "cors"');
}
if (request.responseTainting === "cors" && (locationURL.username || locationURL.password)) {
return makeNetworkError(
'URL cannot contain credentials for request mode "cors"'
);
3 years ago
}
if (actualResponse.status !== 303 && request.body != null && request.body.source == null) {
return makeNetworkError();
}
if ([301, 302].includes(actualResponse.status) && request.method === "POST" || actualResponse.status === 303 && !["GET", "HEAD"].includes(request.method)) {
3 years ago
request.method = "GET";
request.body = null;
for (const headerName of requestBodyHeader) {
request.headersList.delete(headerName);
}
}
if (request.body != null) {
assert(request.body.source);
request.body = safelyExtractBody(request.body.source)[0];
}
const timingInfo = fetchParams.timingInfo;
timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
if (timingInfo.redirectStartTime === 0) {
timingInfo.redirectStartTime = timingInfo.startTime;
}
request.urlList.push(locationURL);
setRequestReferrerPolicyOnRedirect(request, actualResponse);
return mainFetch(fetchParams, true);
}
async function httpNetworkOrCacheFetch(fetchParams, isAuthenticationFetch = false, isNewConnectionFetch = false) {
const request = fetchParams.request;
let httpFetchParams = null;
let httpRequest = null;
let response = null;
const httpCache = null;
const revalidatingFlag = false;
if (request.window === "no-window" && request.redirect === "error") {
httpFetchParams = fetchParams;
httpRequest = request;
} else {
httpRequest = makeRequest(request);
httpFetchParams = { ...fetchParams };
httpFetchParams.request = httpRequest;
}
const includeCredentials = request.credentials === "include" || request.credentials === "same-origin" && request.responseTainting === "basic";
const contentLength = httpRequest.body ? httpRequest.body.length : null;
let contentLengthHeaderValue = null;
if (httpRequest.body == null && ["POST", "PUT"].includes(httpRequest.method)) {
contentLengthHeaderValue = "0";
}
if (contentLength != null) {
contentLengthHeaderValue = String(contentLength);
}
if (contentLengthHeaderValue != null) {
httpRequest.headersList.append("content-length", contentLengthHeaderValue);
}
if (contentLength != null && httpRequest.keepalive) {
}
if (httpRequest.referrer instanceof URL) {
httpRequest.headersList.append("referer", httpRequest.referrer.href);
}
appendRequestOriginHeader(httpRequest);
appendFetchMetadata(httpRequest);
if (!httpRequest.headersList.has("user-agent")) {
httpRequest.headersList.append("user-agent", "undici");
}
if (httpRequest.cache === "default" && (httpRequest.headersList.has("if-modified-since") || httpRequest.headersList.has("if-none-match") || httpRequest.headersList.has("if-unmodified-since") || httpRequest.headersList.has("if-match") || httpRequest.headersList.has("if-range"))) {
httpRequest.cache = "no-store";
}
if (httpRequest.cache === "no-cache" && !httpRequest.preventNoCacheCacheControlHeaderModification && !httpRequest.headersList.has("cache-control")) {
httpRequest.headersList.append("cache-control", "max-age=0");
}
if (httpRequest.cache === "no-store" || httpRequest.cache === "reload") {
if (!httpRequest.headersList.has("pragma")) {
httpRequest.headersList.append("pragma", "no-cache");
}
if (!httpRequest.headersList.has("cache-control")) {
httpRequest.headersList.append("cache-control", "no-cache");
}
}
if (httpRequest.headersList.has("range")) {
httpRequest.headersList.append("accept-encoding", "identity");
}
if (!httpRequest.headersList.has("accept-encoding")) {
if (/^https:/.test(requestCurrentURL(httpRequest).protocol)) {
httpRequest.headersList.append("accept-encoding", "br, gzip, deflate");
} else {
httpRequest.headersList.append("accept-encoding", "gzip, deflate");
}
}
if (includeCredentials) {
}
if (httpCache == null) {
httpRequest.cache = "no-store";
}
if (httpRequest.mode !== "no-store" && httpRequest.mode !== "reload") {
}
if (response == null) {
if (httpRequest.mode === "only-if-cached") {
return makeNetworkError("only if cached");
}
const forwardResponse = await httpNetworkFetch(
httpFetchParams,
includeCredentials,
isNewConnectionFetch
);
3 years ago
if (!safeMethods.includes(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399) {
}
if (revalidatingFlag && forwardResponse.status === 304) {
}
if (response == null) {
response = forwardResponse;
}
}
response.urlList = [...httpRequest.urlList];
if (httpRequest.headersList.has("range")) {
response.rangeRequested = true;
}
response.requestIncludesCredentials = includeCredentials;
if (response.status === 407) {
if (request.window === "no-window") {
return makeNetworkError();
}
if (isCancelled(fetchParams)) {
return makeAppropriateNetworkError(fetchParams);
}
return makeNetworkError("proxy authentication required");
}
if (response.status === 421 && !isNewConnectionFetch && (request.body == null || request.body.source != null)) {
if (isCancelled(fetchParams)) {
return makeAppropriateNetworkError(fetchParams);
}
fetchParams.controller.connection.destroy();
response = await httpNetworkOrCacheFetch(
fetchParams,
isAuthenticationFetch,
true
);
3 years ago
}
if (isAuthenticationFetch) {
}
return response;
}
async function httpNetworkFetch(fetchParams, includeCredentials = false, forceNewConnection = false) {
assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed);
fetchParams.controller.connection = {
abort: null,
destroyed: false,
destroy(err) {
if (!this.destroyed) {
this.destroyed = true;
this.abort?.(err ?? new DOMException("The operation was aborted.", "AbortError"));
3 years ago
}
}
};
const request = fetchParams.request;
let response = null;
const timingInfo = fetchParams.timingInfo;
const httpCache = null;
if (httpCache == null) {
request.cache = "no-store";
}
const newConnection = forceNewConnection ? "yes" : "no";
if (request.mode === "websocket") {
} else {
}
let requestBody = null;
if (request.body == null && fetchParams.processRequestEndOfBody) {
queueMicrotask(() => fetchParams.processRequestEndOfBody());
} else if (request.body != null) {
const processBodyChunk = async function* (bytes) {
if (isCancelled(fetchParams)) {
return;
}
yield bytes;
fetchParams.processRequestBodyChunkLength?.(bytes.byteLength);
};
const processEndOfBody = () => {
if (isCancelled(fetchParams)) {
return;
}
if (fetchParams.processRequestEndOfBody) {
fetchParams.processRequestEndOfBody();
}
};
const processBodyError = (e) => {
if (isCancelled(fetchParams)) {
return;
}
if (e.name === "AbortError") {
fetchParams.controller.abort();
} else {
fetchParams.controller.terminate(e);
}
};
requestBody = async function* () {
try {
for await (const bytes of request.body.stream) {
yield* processBodyChunk(bytes);
}
processEndOfBody();
} catch (err) {
processBodyError(err);
}
}();
}
try {
const { body, status, statusText, headersList } = await dispatch({ body: requestBody });
const iterator = body[Symbol.asyncIterator]();
fetchParams.controller.next = () => iterator.next();
response = makeResponse({ status, statusText, headersList });
} catch (err) {
if (err.name === "AbortError") {
fetchParams.controller.connection.destroy();
return makeAppropriateNetworkError(fetchParams);
}
return makeNetworkError(err);
}
const pullAlgorithm = () => {
fetchParams.controller.resume();
};
const cancelAlgorithm = () => {
fetchParams.controller.abort();
};
if (!ReadableStream) {
ReadableStream = require("stream/web").ReadableStream;
}
const stream = new ReadableStream(
{
async start(controller) {
fetchParams.controller.controller = controller;
},
async pull(controller) {
await pullAlgorithm(controller);
},
async cancel(reason) {
await cancelAlgorithm(reason);
}
3 years ago
},
{ highWaterMark: 0 }
);
3 years ago
response.body = { stream };
fetchParams.controller.on("terminated", onAborted);
fetchParams.controller.resume = async () => {
while (true) {
let bytes;
try {
const { done, value } = await fetchParams.controller.next();
if (isAborted(fetchParams)) {
break;
}
3 years ago
bytes = done ? void 0 : value;
} catch (err) {
if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
bytes = void 0;
} else {
bytes = err;
}
}
if (bytes === void 0) {
try {
fetchParams.controller.controller.close();
} catch (err) {
if (!/Controller is already closed/.test(err)) {
throw err;
}
}
finalizeResponse(fetchParams, response);
return;
}
timingInfo.decodedBodySize += bytes?.byteLength ?? 0;
if (isErrorLike(bytes)) {
3 years ago
fetchParams.controller.terminate(bytes);
return;
}
fetchParams.controller.controller.enqueue(new Uint8Array(bytes));
if (isErrored(stream)) {
fetchParams.controller.terminate();
return;
}
if (!fetchParams.controller.controller.desiredSize) {
return;
}
}
};
function onAborted(reason) {
if (isAborted(fetchParams)) {
response.aborted = true;
if (isReadable(stream)) {
fetchParams.controller.controller.error(
new DOMException("The operation was aborted.", "AbortError")
);
3 years ago
}
} else {
if (isReadable(stream)) {
fetchParams.controller.controller.error(new TypeError("terminated", {
cause: isErrorLike(reason) ? reason : void 0
3 years ago
}));
}
}
fetchParams.controller.connection.destroy();
}
return response;
async function dispatch({ body }) {
const url = requestCurrentURL(request);
return new Promise((resolve, reject) => fetchParams.controller.dispatcher.dispatch(
{
path: url.pathname + url.search,
origin: url.origin,
method: request.method,
body: fetchParams.controller.dispatcher.isMockActive ? request.body && request.body.source : body,
headers: [...request.headersList].flat(),
maxRedirections: 0,
bodyTimeout: 3e5,
headersTimeout: 3e5
3 years ago
},
{
body: null,
abort: null,
onConnect(abort) {
const { connection } = fetchParams.controller;
if (connection.destroyed) {
abort(new DOMException("The operation was aborted.", "AbortError"));
} else {
fetchParams.controller.on("terminated", abort);
this.abort = connection.abort = abort;
3 years ago
}
},
onHeaders(status, headersList, resume, statusText) {
if (status < 200) {
return;
}
let codings = [];
let location = "";
const headers = new Headers();
for (let n = 0; n < headersList.length; n += 2) {
const key = headersList[n + 0].toString("latin1");
const val = headersList[n + 1].toString("latin1");
if (key.toLowerCase() === "content-encoding") {
codings = val.split(",").map((x) => x.trim());
} else if (key.toLowerCase() === "location") {
location = val;
3 years ago
}
headers.append(key, val);
3 years ago
}
this.body = new Readable({ read: resume });
const decoders = [];
const willFollow = request.redirect === "follow" && location && redirectStatus.includes(status);
if (request.method !== "HEAD" && request.method !== "CONNECT" && !nullBodyStatus.includes(status) && !willFollow) {
for (const coding of codings) {
if (/(x-)?gzip/.test(coding)) {
decoders.push(zlib.createGunzip());
} else if (/(x-)?deflate/.test(coding)) {
decoders.push(zlib.createInflate());
} else if (coding === "br") {
decoders.push(zlib.createBrotliDecompress());
} else {
decoders.length = 0;
break;
}
}
}
resolve({
status,
statusText,
headersList: headers[kHeadersList],
body: decoders.length ? pipeline(this.body, ...decoders, () => {
}) : this.body.on("error", () => {
})
});
return true;
},
onData(chunk) {
if (fetchParams.controller.dump) {
return;
}
const bytes = chunk;
timingInfo.encodedBodySize += bytes.byteLength;
return this.body.push(bytes);
},
onComplete() {
if (this.abort) {
fetchParams.controller.off("terminated", this.abort);
}
fetchParams.controller.ended = true;
this.body.push(null);
},
onError(error) {
if (this.abort) {
fetchParams.controller.off("terminated", this.abort);
}
this.body?.destroy(error);
fetchParams.controller.terminate(error);
reject(error);
3 years ago
}
}
));
3 years ago
}
}
module2.exports = {
fetch: fetch2,
Fetch,
fetching,
finalizeAndReportTiming
};
3 years ago
}
});
// node_modules/undici/index.js
var require_undici = __commonJS({
"node_modules/undici/index.js"(exports, module2) {
"use strict";
var Client = require_client();
var Dispatcher = require_dispatcher();
var errors = require_errors();
var Pool = require_pool();
var BalancedPool = require_balanced_pool();
var Agent = require_agent();
var util = require_util();
var { InvalidArgumentError } = errors;
var api = require_api();
var buildConnector = require_connect();
var MockClient = require_mock_client();
var MockAgent = require_mock_agent();
var MockPool = require_mock_pool();
var mockErrors = require_mock_errors();
var ProxyAgent = require_proxy_agent();
var { getGlobalDispatcher, setGlobalDispatcher } = require_global();
var DecoratorHandler = require_DecoratorHandler();
var RedirectHandler = require_RedirectHandler();
var createRedirectInterceptor = require_redirectInterceptor();
3 years ago
var nodeVersion = process.versions.node.split(".");
var nodeMajor = Number(nodeVersion[0]);
var nodeMinor = Number(nodeVersion[1]);
Object.assign(Dispatcher.prototype, api);
module2.exports.Dispatcher = Dispatcher;
module2.exports.Client = Client;
module2.exports.Pool = Pool;
module2.exports.BalancedPool = BalancedPool;
module2.exports.Agent = Agent;
module2.exports.ProxyAgent = ProxyAgent;
module2.exports.DecoratorHandler = DecoratorHandler;
module2.exports.RedirectHandler = RedirectHandler;
module2.exports.createRedirectInterceptor = createRedirectInterceptor;
3 years ago
module2.exports.buildConnector = buildConnector;
module2.exports.errors = errors;
function makeDispatcher(fn) {
return (url, opts, handler) => {
if (typeof opts === "function") {
handler = opts;
opts = null;
}
if (!url || typeof url !== "string" && typeof url !== "object" && !(url instanceof URL)) {
throw new InvalidArgumentError("invalid url");
}
if (opts != null && typeof opts !== "object") {
throw new InvalidArgumentError("invalid opts");
}
if (opts && opts.path != null) {
if (typeof opts.path !== "string") {
throw new InvalidArgumentError("invalid opts.path");
}
let path3 = opts.path;
if (!opts.path.startsWith("/")) {
path3 = `/${path3}`;
}
url = new URL(util.parseOrigin(url).origin + path3);
3 years ago
} else {
if (!opts) {
opts = typeof url === "object" ? url : {};
}
url = util.parseURL(url);
}
const { agent, dispatcher = getGlobalDispatcher() } = opts;
if (agent) {
throw new InvalidArgumentError("unsupported opts.agent. Did you mean opts.client?");
}
return fn.call(dispatcher, {
...opts,
origin: url.origin,
path: url.search ? `${url.pathname}${url.search}` : url.pathname,
method: opts.method || (opts.body ? "PUT" : "GET")
}, handler);
};
}
module2.exports.setGlobalDispatcher = setGlobalDispatcher;
module2.exports.getGlobalDispatcher = getGlobalDispatcher;
if (nodeMajor > 16 || nodeMajor === 16 && nodeMinor >= 8) {
3 years ago
let fetchImpl = null;
module2.exports.fetch = async function fetch2(resource) {
if (!fetchImpl) {
fetchImpl = require_fetch().fetch;
}
const dispatcher = arguments[1] && arguments[1].dispatcher || getGlobalDispatcher();
try {
return await fetchImpl.apply(dispatcher, arguments);
} catch (err) {
Error.captureStackTrace(err, this);
throw err;
3 years ago
}
};
module2.exports.Headers = require_headers().Headers;
module2.exports.Response = require_response().Response;
module2.exports.Request = require_request2().Request;
module2.exports.FormData = require_formdata().FormData;
module2.exports.File = require_file().File;
const { setGlobalOrigin, getGlobalOrigin } = require_global2();
module2.exports.setGlobalOrigin = setGlobalOrigin;
module2.exports.getGlobalOrigin = getGlobalOrigin;
3 years ago
}
module2.exports.request = makeDispatcher(api.request);
module2.exports.stream = makeDispatcher(api.stream);
module2.exports.pipeline = makeDispatcher(api.pipeline);
module2.exports.connect = makeDispatcher(api.connect);
module2.exports.upgrade = makeDispatcher(api.upgrade);
module2.exports.MockClient = MockClient;
module2.exports.MockPool = MockPool;
module2.exports.MockAgent = MockAgent;
module2.exports.mockErrors = mockErrors;
}
});
// src/index.ts
var import_core = __toESM(require_core());
var import_github = __toESM(require_github());
// node_modules/shellac/dist/index.js
3 years ago
var import_child_process = __toESM(require("child_process"), 1);
var import_path = __toESM(require("path"), 1);
// node_modules/reghex/dist/reghex-core.mjs
var isStickySupported = typeof /./g.sticky === "boolean";
var _pattern = function(input) {
if (typeof input === "function") {
return input;
}
var source = typeof input !== "string" ? input.source : input;
return isStickySupported ? new RegExp(source, "y") : new RegExp("^(?:" + source + ")", "g");
};
var _substr = function(state, pattern) {
var end = state.index + pattern.length;
var sub = state.input.slice(state.index, end);
if (sub === pattern) {
state.index = end;
return sub;
}
};
var _exec = function(state, pattern) {
if (typeof pattern === "function") {
return pattern();
}
var match;
if (isStickySupported) {
pattern.lastIndex = state.index;
match = pattern.exec(state.input);
state.index = pattern.lastIndex;
} else {
pattern.lastIndex = 0;
match = pattern.exec(state.input.slice(state.input));
state.index += pattern.lastIndex;
}
return match && match[0];
};
var tag = function(array, tag2) {
array.tag = tag2;
return array;
};
var parse = function(pattern) {
return function(input) {
var state = {
input,
index: 0
};
return pattern(state);
};
};
// node_modules/shellac/dist/index.js
var __defProp2 = Object.defineProperty;
var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField2 = (obj, key, value) => {
__defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
3 years ago
var Shell = class {
constructor(env_passthrough = ["PATH"]) {
__publicField(this, "process");
const env2 = { PS1: "" };
3 years ago
env_passthrough.forEach((key) => {
env2[key] = process.env[key];
3 years ago
});
this.process = import_child_process.default.spawn("bash", ["--noprofile", "--norc"], {
env: env2,
3 years ago
detached: true
});
this.process.stdout.setEncoding("utf8");
}
getStdin() {
return this.process.stdin;
}
getStdout() {
return this.process.stdout;
}
getStderr() {
return this.process.stderr;
}
exit() {
this.process.kill("SIGINT");
}
};
__publicField2(Shell, "logger", (...args) => process.stdout.write(args.map((a) => a.toString()).join("\n")));
3 years ago
var LF = "\n";
var CR = "\r";
var trimFinalNewline = (input) => {
if (input[input.length - 1] === LF) {
input = input.slice(0, input.length - 1);
}
if (input[input.length - 1] === CR) {
input = input.slice(0, input.length - 1);
}
return input;
};
var Command = class {
constructor({
cwd,
shell,
cmd,
interactive,
pipe_logs = false,
exit_expected = false
}) {
__publicField(this, "shell");
__publicField(this, "cmd");
__publicField(this, "cwd");
__publicField(this, "interactive");
__publicField(this, "exec");
__publicField(this, "runningState");
__publicField(this, "pipe_logs");
__publicField(this, "exit_expected");
__publicField(this, "retCode");
__publicField(this, "promiseResolve");
__publicField(this, "promiseReject");
__publicField(this, "promise");
__publicField(this, "timer");
__publicField(this, "stdout");
__publicField(this, "stderr");
__publicField(this, "handleStdoutData", (data) => {
3 years ago
const lines = trimFinalNewline(data).split(/\r?\n/);
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const match = line.match(/__END_OF_COMMAND_\[(\d+)\]__/);
if (match) {
this.retCode = parseInt(match[1]);
setImmediate(this.finish);
return;
} else {
if (this.pipe_logs)
process.stdout.write(line + "\n");
this.stdout += line + "\n";
}
if (this.interactive) {
this.interactive(line, this.handleStdinData);
}
}
});
__publicField(this, "handleStderrData", (data) => {
3 years ago
if (this.pipe_logs)
process.stderr.write(data);
this.stderr += data;
});
__publicField(this, "handleStdinData", (data) => {
3 years ago
this.shell.getStdin().write(`${data}
`);
});
__publicField(this, "run", () => {
3 years ago
let promiseResolve, promiseReject;
const promise = new Promise((resolve, reject) => {
promiseResolve = resolve;
promiseReject = reject;
});
this.promiseResolve = promiseResolve;
this.promiseReject = promiseReject;
this.promise = promise;
this.runningState = 1;
3 years ago
this.shell.getStdin().write(this.exec);
this.timer = setTimeout(() => {
if (this.runningState !== 2) {
3 years ago
const obj = {
retCode: -1,
cmd: this.cmd,
stdout: this.stdout,
stderr: this.stderr
};
this.promiseReject(obj);
}
}, 864e5);
return promise.then(() => this, (e) => {
this.log(`
SHELLAC COMMAND FAILED!
Executing: ${this.cmd} in ${this.cwd}
STDOUT:
`);
this.log(`${this.stdout}
`);
this.log(`STDERR:
${this.stderr}
`);
this.shell.exit();
throw e;
});
});
__publicField(this, "finish", () => {
this.runningState = 2;
3 years ago
clearTimeout(this.timer);
this.shell.getStdout().removeListener("data", this.handleStdoutData);
this.shell.getStderr().removeListener("data", this.handleStderrData);
const obj = {
retCode: this.retCode,
cmd: this.cmd,
stdout: this.stdout,
stderr: this.stderr
};
const matching_exit_code = this.retCode === this.exit_expected;
if (!matching_exit_code) {
if (this.exit_expected === true) {
if (this.retCode === 0) {
this.log("NO EXIT WHEN EXPECTED");
return this.promiseReject(obj);
}
} else if (this.exit_expected === false) {
if (this.retCode !== 0) {
this.log("EXIT WHEN NOT EXPECTED");
return this.promiseReject(obj);
}
} else {
this.log(`EXIT CODE DIDN'T MATCH`);
return this.promiseReject(obj);
}
}
return this.promiseResolve(obj);
});
__publicField(this, "log", Shell.logger);
3 years ago
this.shell = shell;
this.cmd = cmd;
this.cwd = cwd;
this.interactive = interactive;
this.exit_expected = exit_expected;
this.exec = `cd "${cwd}" &&
${this.cmd};echo __END_OF_COMMAND_[$?]__
`;
this.shell.process.on("exit", this.finish);
this.shell.getStdout().on("data", this.handleStdoutData);
this.shell.getStderr().on("data", this.handleStderrData);
this.runningState = 0;
3 years ago
this.pipe_logs = pipe_logs;
this.stdout = "";
this.stderr = "";
}
};
async function IfStatement(chunk, context2) {
const { interps, last_cmd } = context2;
const [[val_type, val_id], if_clause, else_clause] = chunk;
if (val_type !== "VALUE")
throw new Error("If statements only accept value interpolations, not functions.");
if (interps[val_id]) {
return execute(if_clause, context2);
} else if (else_clause) {
return execute(else_clause, context2);
} else {
return last_cmd;
}
}
async function Command2(chunk, context2) {
const { interps, cwd, shell, exit_expected } = context2;
const [str] = chunk;
const split_cmd = str.split(/#__(?:FUNCTION|VALUE)_(\d+)__#/g);
let cmd = "";
let i = 0;
for (const token of split_cmd) {
if (i++ % 2 === 0) {
cmd += token;
} else {
const interp = interps[token];
cmd += await (typeof interp === "function" ? interp() : interp);
}
}
const command = new Command({
cwd,
shell,
cmd,
pipe_logs: chunk.tag === "logged_command",
exit_expected
});
return command.run();
}
async function InStatement(chunk, context2) {
const { interps } = context2;
const [arg, in_clause] = chunk;
if (typeof arg === "string") {
throw new Error("IN statements need an argument token.");
}
let new_cwd;
if (arg.tag === "identifier") {
const [val_type, val_id] = arg;
if (val_type !== "VALUE")
throw new Error("IN statements only accept value interpolations, not functions.");
new_cwd = interps[val_id];
} else if (arg.tag === "string_arg") {
new_cwd = arg[0].replace(/^"|"$/g, "");
} else {
throw new Error(`Unknown argument token for IN statement: ${arg.tag}`);
}
if (!new_cwd || typeof new_cwd !== "string")
throw new Error(`IN statements need a string value to set as the current working dir`);
return execute(in_clause, {
...context2,
cwd: import_path.default.resolve(context2.cwd, new_cwd)
});
}
async function Grammar(chunk, context2) {
const { last_cmd } = context2;
let new_last_cmd = last_cmd;
for (const sub of chunk) {
new_last_cmd = await execute(sub, {
...context2,
last_cmd: new_last_cmd
});
}
return new_last_cmd;
}
async function Await(chunk, context2) {
const { interps, last_cmd } = context2;
const [[val_type, val_id]] = chunk;
if (val_type !== "FUNCTION")
throw new Error("IN statements only accept function interpolations, not values.");
await interps[val_id]();
return last_cmd;
}
async function Stdout(chunk, context2) {
const { interps, last_cmd, captures } = context2;
const [out_or_err, second] = chunk;
if (!(out_or_err === "stdout" || out_or_err === "stderr"))
throw new Error(`Expected only 'stdout' or 'stderr', got: ${out_or_err}`);
const capture = trimFinalNewline((last_cmd == null ? void 0 : last_cmd[out_or_err]) || "");
3 years ago
const tag2 = second.tag;
if (tag2 === "identifier") {
const [val_type, val_id] = second;
if (val_type !== "FUNCTION")
throw new Error("STDOUT/STDERR statements only accept function interpolations, not values.");
await interps[val_id](capture);
} else if (tag2 === "variable_name") {
captures[second[0]] = capture;
} else {
throw new Error("STDOUT/STDERR statements expect a variable name or an interpolation function.");
}
return last_cmd;
}
async function Exitcode(chunk, context2) {
const { interps, last_cmd } = context2;
const [exitcode, second] = chunk;
if (exitcode !== "exitcode")
throw new Error(`Expected only 'exitcode', got: ${exitcode}`);
const capture = (last_cmd == null ? void 0 : last_cmd.retCode) || 0;
3 years ago
const tag2 = second.tag;
if (tag2 === "identifier") {
const [val_type, val_id] = second;
if (val_type !== "FUNCTION")
throw new Error("exitcode statements only accept function interpolations, not values.");
await interps[val_id](capture);
} else {
throw new Error("exitcode statements expect an interpolation function.");
}
return last_cmd;
}
async function ExitsStatement(chunk, context2) {
const [exit_expected, block] = chunk.length > 1 ? [Number(chunk[0][0]), chunk[1]] : [true, chunk[0]];
return execute(block, {
...context2,
exit_expected
});
}
var execute = async (chunk, context2) => {
if (Array.isArray(chunk)) {
if (chunk.tag === "command_line" || chunk.tag === "logged_command") {
return Command2(chunk, context2);
} else if (chunk.tag === "if_statement") {
return IfStatement(chunk, context2);
} else if (chunk.tag === "in_statement") {
return InStatement(chunk, context2);
} else if (chunk.tag === "grammar") {
return await Grammar(chunk, context2);
} else if (chunk.tag === "await_statement") {
return await Await(chunk, context2);
} else if (chunk.tag === "stdout_statement") {
return await Stdout(chunk, context2);
} else if (chunk.tag === "exitcode_statement") {
return await Exitcode(chunk, context2);
} else if (chunk.tag === "exits_statement") {
return await ExitsStatement(chunk, context2);
} else {
return context2.last_cmd;
}
}
return null;
};
var _ignored_expression = _pattern(/([\s,]|#[^\n\r]+)+/);
var ignored = function _ignored(state) {
var last_index = state.index;
var match, node = [];
if (match = _exec(state, _ignored_expression)) {
node.push(match);
} else {
state.index = last_index;
return;
}
return tag(node, "ignored");
};
var _comment_line_expression = _pattern(/\/\/\s+/);
var _comment_line_expression2 = _pattern(/[^\n\r]*/);
var comment_line = function _comment_line(state) {
var last_index = state.index;
var match, node = [];
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (!_exec(state, _comment_line_expression)) {
state.index = last_index;
return;
}
if (match = _exec(state, _comment_line_expression2)) {
node.push(match);
} else {
state.index = last_index;
return;
}
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
return tag(node, "comment_line");
};
var _command_line_expression = _pattern(/\$\s+/);
var _command_line_expression2 = _pattern(/.*/);
var command_line = function _command_line(state) {
var last_index = state.index;
var match, node = [];
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (!_exec(state, _command_line_expression)) {
state.index = last_index;
return;
}
if (match = _exec(state, _command_line_expression2)) {
node.push(match);
} else {
state.index = last_index;
return;
}
return tag(node, "command_line");
};
var _logged_command_expression = _pattern(/\$\$\s+/);
var _logged_command_expression2 = _pattern(/.*/);
var logged_command = function _logged_command(state) {
var last_index = state.index;
var match, node = [];
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (!_exec(state, _logged_command_expression)) {
state.index = last_index;
return;
}
if (match = _exec(state, _logged_command_expression2)) {
node.push(match);
} else {
state.index = last_index;
return;
}
return tag(node, "logged_command");
};
var _identifier_expression = _pattern(/VALUE|FUNCTION/);
var _identifier_expression2 = _pattern(/\d+/);
var identifier = function _identifier(state) {
var last_index = state.index;
var match, node = [];
if (!_substr(state, "#__")) {
state.index = last_index;
return;
}
if (match = _exec(state, _identifier_expression)) {
node.push(match);
} else {
state.index = last_index;
return;
}
if (!_substr(state, "_")) {
state.index = last_index;
return;
}
if (match = _exec(state, _identifier_expression2)) {
node.push(match);
} else {
state.index = last_index;
return;
}
if (!_substr(state, "__#")) {
state.index = last_index;
return;
}
return tag(node, "identifier");
};
var _integer_argument_expression = _pattern(/\d+/);
var integer_argument = function _integer_argument(state) {
var last_index = state.index;
var match, node = [];
if (!_substr(state, "(")) {
state.index = last_index;
return;
}
if (match = _exec(state, _integer_argument_expression)) {
node.push(match);
} else {
state.index = last_index;
return;
}
if (!_substr(state, ")")) {
state.index = last_index;
return;
}
return tag(node, "integer_argument");
};
var _variable_name_expression = _pattern(/\S+/);
var variable_name = function _variable_name(state) {
var last_index = state.index;
var match, node = [];
if (match = _exec(state, _variable_name_expression)) {
node.push(match);
} else {
state.index = last_index;
return;
}
return tag(node, "variable_name");
};
var _string_arg_expression = _pattern(/"[^"]*"/);
var _string_arg_expression2 = _pattern(/\S+/);
var string_arg = function _string_arg(state) {
var last_index = state.index;
var match, node = [];
block_0: {
var index_0 = state.index;
if (match = _exec(state, _string_arg_expression)) {
node.push(match);
} else {
state.index = index_0;
break block_0;
}
return tag(node, "string_arg");
}
if (match = _exec(state, _string_arg_expression2)) {
node.push(match);
} else {
state.index = last_index;
return;
}
return tag(node, "string_arg");
};
var _if_statement_expression = _pattern(/if\s+/);
var if_statement = function _if_statement(state) {
var last_index = state.index;
var match, node = [];
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (!_exec(state, _if_statement_expression)) {
state.index = last_index;
return;
}
if (match = identifier(state)) {
node.push(match);
} else {
state.index = last_index;
return;
}
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (!_substr(state, "{")) {
state.index = last_index;
return;
}
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (match = grammar(state)) {
node.push(match);
} else {
state.index = last_index;
return;
}
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (!_substr(state, "}")) {
state.index = last_index;
return;
}
var index_0 = state.index;
var length_0 = node.length;
var index_2 = state.index;
if (!ignored(state)) {
state.index = index_2;
}
if (!_substr(state, "else")) {
state.index = index_0;
}
var index_2 = state.index;
if (!ignored(state)) {
state.index = index_2;
}
if (!_substr(state, "{")) {
state.index = index_0;
}
var index_2 = state.index;
if (!ignored(state)) {
state.index = index_2;
}
if (match = grammar(state)) {
node.push(match);
} else {
state.index = index_0;
}
var index_2 = state.index;
if (!ignored(state)) {
state.index = index_2;
}
if (!_substr(state, "}")) {
state.index = index_0;
}
return tag(node, "if_statement");
};
var _in_statement_expression = _pattern(/in\s+/);
var in_statement = function _in_statement(state) {
var last_index = state.index;
var match, node = [];
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (!_exec(state, _in_statement_expression)) {
state.index = last_index;
return;
}
var length_0 = node.length;
alternation_1: {
block_1: {
var index_1 = state.index;
if (match = identifier(state)) {
node.push(match);
} else {
node.length = length_0;
state.index = index_1;
break block_1;
}
break alternation_1;
}
if (match = string_arg(state)) {
node.push(match);
} else {
node.length = length_0;
state.index = last_index;
return;
}
}
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (!_substr(state, "{")) {
state.index = last_index;
return;
}
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (match = grammar(state)) {
node.push(match);
} else {
state.index = last_index;
return;
}
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (!_substr(state, "}")) {
state.index = last_index;
return;
}
return tag(node, "in_statement");
};
var _await_statement_expression = _pattern(/await\s+/);
var await_statement = function _await_statement(state) {
var last_index = state.index;
var match, node = [];
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (!_exec(state, _await_statement_expression)) {
state.index = last_index;
return;
}
if (match = identifier(state)) {
node.push(match);
} else {
state.index = last_index;
return;
}
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
return tag(node, "await_statement");
};
var _stdout_statement_expression = _pattern(/std(out|err)/);
var _stdout_statement_expression2 = _pattern(/\s+>>\s+/);
var stdout_statement = function _stdout_statement(state) {
var last_index = state.index;
var match, node = [];
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (match = _exec(state, _stdout_statement_expression)) {
node.push(match);
} else {
state.index = last_index;
return;
}
if (!_exec(state, _stdout_statement_expression2)) {
state.index = last_index;
return;
}
var length_0 = node.length;
alternation_1: {
block_1: {
var index_1 = state.index;
if (match = identifier(state)) {
node.push(match);
} else {
node.length = length_0;
state.index = index_1;
break block_1;
}
break alternation_1;
}
if (match = variable_name(state)) {
node.push(match);
} else {
node.length = length_0;
state.index = last_index;
return;
}
}
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
return tag(node, "stdout_statement");
};
var _exitcode_statement_expression = _pattern(/\s+>>\s+/);
var exitcode_statement = function _exitcode_statement(state) {
var last_index = state.index;
var match, node = [];
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (match = _substr(state, "exitcode")) {
node.push(match);
} else {
state.index = last_index;
return;
}
if (!_exec(state, _exitcode_statement_expression)) {
state.index = last_index;
return;
}
var length_0 = node.length;
if (match = identifier(state)) {
node.push(match);
} else {
node.length = length_0;
state.index = last_index;
return;
}
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
return tag(node, "exitcode_statement");
};
var exits_statement = function _exits_statement(state) {
var last_index = state.index;
var match, node = [];
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (!_substr(state, "exits")) {
state.index = last_index;
return;
}
var index_0 = state.index;
var length_0 = node.length;
if (match = integer_argument(state)) {
node.push(match);
} else {
state.index = index_0;
}
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (!_substr(state, "{")) {
state.index = last_index;
return;
}
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (match = grammar(state)) {
node.push(match);
} else {
state.index = last_index;
return;
}
var index_1 = state.index;
if (!ignored(state)) {
state.index = index_1;
}
if (!_substr(state, "}")) {
state.index = last_index;
return;
}
return tag(node, "exits_statement");
};
var grammar = function _grammar(state) {
var last_index = state.index;
var match, node = [];
loop_0:
for (var iter_0 = 0; true; iter_0++) {
var index_0 = state.index;
var length_0 = node.length;
alternation_1: {
block_1: {
var index_1 = state.index;
if (!ignored(state)) {
node.length = length_0;
state.index = index_1;
break block_1;
}
break alternation_1;
}
block_1: {
var index_1 = state.index;
if (match = comment_line(state)) {
node.push(match);
} else {
node.length = length_0;
state.index = index_1;
break block_1;
}
break alternation_1;
}
block_1: {
var index_1 = state.index;
if (match = command_line(state)) {
node.push(match);
} else {
node.length = length_0;
state.index = index_1;
break block_1;
}
break alternation_1;
}
block_1: {
var index_1 = state.index;
if (match = logged_command(state)) {
node.push(match);
} else {
node.length = length_0;
state.index = index_1;
break block_1;
}
break alternation_1;
}
block_1: {
var index_1 = state.index;
if (match = if_statement(state)) {
node.push(match);
} else {
node.length = length_0;
state.index = index_1;
break block_1;
}
break alternation_1;
}
block_1: {
var index_1 = state.index;
if (match = in_statement(state)) {
node.push(match);
} else {
node.length = length_0;
state.index = index_1;
break block_1;
}
break alternation_1;
}
block_1: {
var index_1 = state.index;
if (match = await_statement(state)) {
node.push(match);
} else {
node.length = length_0;
state.index = index_1;
break block_1;
}
break alternation_1;
}
block_1: {
var index_1 = state.index;
if (match = stdout_statement(state)) {
node.push(match);
} else {
node.length = length_0;
state.index = index_1;
break block_1;
}
break alternation_1;
}
block_1: {
var index_1 = state.index;
if (match = exitcode_statement(state)) {
node.push(match);
} else {
node.length = length_0;
state.index = index_1;
break block_1;
}
break alternation_1;
}
if (match = exits_statement(state)) {
node.push(match);
} else {
if (iter_0) {
state.index = index_0;
break loop_0;
}
node.length = length_0;
state.index = last_index;
return;
}
}
}
return tag(node, "grammar");
};
var grammar_default = parse(grammar);
var parser = (str) => grammar_default(str.trim());
var lazyCreateShell = async () => new Shell();
var _shellac = (cwd, lazyShell) => async (s, ...interps) => {
let str = s[0];
for (let i = 0; i < interps.length; i++) {
const is_fn = typeof interps[i] === "function";
const interp_placeholder = `#__${is_fn ? "FUNCTION_" : "VALUE_"}${i}__#`;
str += interp_placeholder + s[i + 1];
}
if (str.length === 0)
throw new Error("Must provide statements");
const parsed = parser(str);
if (!parsed || typeof parsed === "string")
throw new Error("Parsing error!");
const captures = {};
const shell = await lazyShell();
const last_cmd = await execute(parsed, {
interps,
last_cmd: null,
cwd,
captures,
shell,
exit_expected: false
});
shell.exit();
return {
stdout: trimFinalNewline((last_cmd == null ? void 0 : last_cmd.stdout) || ""),
stderr: trimFinalNewline((last_cmd == null ? void 0 : last_cmd.stderr) || ""),
3 years ago
...captures
};
};
var bgShellac = async (s, ...interps) => {
const shell = await lazyCreateShell();
return {
process: shell.process,
pid: shell.process.pid,
promise: _shellac(process.cwd(), async () => shell)(s, ...interps),
kill: () => shell.exit()
};
};
var shellac = Object.assign(_shellac(process.cwd(), lazyCreateShell), {
in: (cwd) => _shellac(cwd, lazyCreateShell),
bg: bgShellac
});
var src_default = shellac;
3 years ago
// src/index.ts
var import_undici = __toESM(require_undici());
var import_process = require("process");
var import_node_path = __toESM(require("path"));
3 years ago
try {
const apiToken = (0, import_core.getInput)("apiToken", { required: true });
const accountId = (0, import_core.getInput)("accountId", { required: true });
const projectName = (0, import_core.getInput)("projectName", { required: true });
const directory = (0, import_core.getInput)("directory", { required: true });
const gitHubToken = (0, import_core.getInput)("gitHubToken", { required: false });
const branch = (0, import_core.getInput)("branch", { required: false });
const workingDirectory = (0, import_core.getInput)("workingDirectory", { required: false });
const getProject = async () => {
const response = await (0, import_undici.fetch)(
`https://api.cloudflare.com/client/v4/accounts/${accountId}/pages/projects/${projectName}`,
{ headers: { Authorization: `Bearer ${apiToken}` } }
);
const { result } = await response.json();
return result;
};
3 years ago
const createPagesDeployment = async () => {
await src_default.in(import_node_path.default.join(process.cwd(), workingDirectory))`
3 years ago
$ export CLOUDFLARE_API_TOKEN="${apiToken}"
if ${accountId} {
$ export CLOUDFLARE_ACCOUNT_ID="${accountId}"
}
$$ npx wrangler@2 pages publish "${directory}" --project-name="${projectName}" --branch="${branch}"
3 years ago
`;
const response = await (0, import_undici.fetch)(
`https://api.cloudflare.com/client/v4/accounts/${accountId}/pages/projects/${projectName}/deployments`,
{ headers: { Authorization: `Bearer ${apiToken}` } }
);
3 years ago
const {
result: [deployment]
} = await response.json();
return deployment;
};
const createGitHubDeployment = async (octokit, productionEnvironment, environment) => {
3 years ago
const deployment = await octokit.rest.repos.createDeployment({
owner: import_github.context.repo.owner,
repo: import_github.context.repo.repo,
ref: import_github.context.ref,
auto_merge: false,
description: "Cloudflare Pages",
required_contexts: [],
environment,
production_environment: productionEnvironment
3 years ago
});
if (deployment.status === 201) {
return deployment.data;
}
};
const createGitHubDeploymentStatus = async ({
id,
url,
deploymentId,
3 years ago
environmentName,
productionEnvironment,
octokit
3 years ago
}) => {
await octokit.rest.repos.createDeploymentStatus({
owner: import_github.context.repo.owner,
repo: import_github.context.repo.repo,
deployment_id: id,
environment: environmentName,
environment_url: url,
production_environment: productionEnvironment,
log_url: `https://dash.cloudflare.com/${accountId}/pages/view/${projectName}/${deploymentId}`,
3 years ago
description: "Cloudflare Pages",
state: "success"
});
};
const createJobSummary = async ({ deployment, aliasUrl }) => {
const deployStage = deployment.stages.find((stage) => stage.name === "deploy");
let status = "\u26A1\uFE0F Deployment in progress...";
if (deployStage?.status === "success") {
status = "\u2705 Deploy successful!";
} else if (deployStage?.status === "failure") {
status = "\u{1F6AB} Deployment failed";
}
await import_core.summary.addRaw(
`
# Deploying with Cloudflare Pages
| Name | Result |
| ----------------------- | - |
| **Last commit:** | \`${deployment.deployment_trigger.metadata.commit_hash.substring(0, 8)}\` |
| **Status**: | ${status} |
| **Preview URL**: | ${deployment.url} |
| **Branch Preview URL**: | ${aliasUrl} |
`
).write();
};
3 years ago
(async () => {
const project = await getProject();
if (!project)
throw new Error("Unable to find pages project");
const githubBranch = import_process.env.GITHUB_REF_NAME;
const productionEnvironment = githubBranch === project.production_branch;
const environmentName = productionEnvironment ? "Production" : `Preview: (${githubBranch})`;
let gitHubDeployment;
if (gitHubToken && gitHubToken.length) {
const octokit = (0, import_github.getOctokit)(gitHubToken);
gitHubDeployment = await createGitHubDeployment(octokit, productionEnvironment, environmentName);
}
3 years ago
const pagesDeployment = await createPagesDeployment();
(0, import_core.setOutput)("id", pagesDeployment.id);
(0, import_core.setOutput)("url", pagesDeployment.url);
(0, import_core.setOutput)("environment", pagesDeployment.environment);
let alias = pagesDeployment.url;
if (!productionEnvironment && pagesDeployment.aliases && pagesDeployment.aliases.length > 0) {
alias = pagesDeployment.aliases[0];
}
(0, import_core.setOutput)("alias", alias);
await createJobSummary({ deployment: pagesDeployment, aliasUrl: alias });
3 years ago
if (gitHubDeployment) {
const octokit = (0, import_github.getOctokit)(gitHubToken);
3 years ago
await createGitHubDeploymentStatus({
id: gitHubDeployment.id,
url: pagesDeployment.url,
deploymentId: pagesDeployment.id,
3 years ago
environmentName,
productionEnvironment,
octokit
3 years ago
});
}
})();
} catch (thrown) {
(0, import_core.setFailed)(thrown.message);
}
/*!
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
/*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */