mirror of
https://github.com/peter-evans/dockerhub-description.git
synced 2024-11-22 12:09:33 +01:00
3618 lines
No EOL
108 KiB
JavaScript
3618 lines
No EOL
108 KiB
JavaScript
/******/ (() => { // webpackBootstrap
|
|
/******/ var __webpack_modules__ = ({
|
|
|
|
/***/ 812:
|
|
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
|
|
|
|
"use strict";
|
|
|
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
|
}) : (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
}));
|
|
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
}) : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = (this && this.__importStar) || function (mod) {
|
|
if (mod && mod.__esModule) return mod;
|
|
var result = {};
|
|
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
var __awaiter = (this && this.__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.updateRepositoryDescription = exports.getToken = void 0;
|
|
const core = __importStar(__nccwpck_require__(186));
|
|
const fetch = __importStar(__nccwpck_require__(467));
|
|
const DESCRIPTION_MAX_CHARS = 100;
|
|
function getToken(username, password) {
|
|
return __awaiter(this, void 0, void 0, function* () {
|
|
const body = {
|
|
username: username,
|
|
password: password
|
|
};
|
|
const response = yield fetch('https://hub.docker.com/v2/users/login', {
|
|
method: 'post',
|
|
body: JSON.stringify(body),
|
|
headers: { 'Content-Type': 'application/json' }
|
|
});
|
|
if (!response.ok) {
|
|
throw new Error(`Unexpected response: ${response.status} ${response.statusText}`);
|
|
}
|
|
const json = yield response.json();
|
|
core.setSecret(json['token']);
|
|
return json['token'];
|
|
});
|
|
}
|
|
exports.getToken = getToken;
|
|
function updateRepositoryDescription(token, repository, description, fullDescription) {
|
|
return __awaiter(this, void 0, void 0, function* () {
|
|
const body = {
|
|
full_description: fullDescription
|
|
};
|
|
if (description) {
|
|
body['description'] = description.slice(0, DESCRIPTION_MAX_CHARS);
|
|
}
|
|
yield fetch(`https://hub.docker.com/v2/repositories/${repository}`, {
|
|
method: 'patch',
|
|
body: JSON.stringify(body),
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Authorization: `JWT ${token}`
|
|
}
|
|
}).then(res => {
|
|
if (!res.ok) {
|
|
throw new Error(res.statusText);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
exports.updateRepositoryDescription = updateRepositoryDescription;
|
|
|
|
|
|
/***/ }),
|
|
|
|
/***/ 480:
|
|
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
|
|
|
|
"use strict";
|
|
|
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
|
}) : (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
}));
|
|
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
}) : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = (this && this.__importStar) || function (mod) {
|
|
if (mod && mod.__esModule) return mod;
|
|
var result = {};
|
|
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
exports.validateInputs = exports.getInputs = void 0;
|
|
const core = __importStar(__nccwpck_require__(186));
|
|
const README_FILEPATH_DEFAULT = './README.md';
|
|
function getInputs() {
|
|
const inputs = {
|
|
username: core.getInput('username'),
|
|
password: core.getInput('password'),
|
|
repository: core.getInput('repository'),
|
|
shortDescription: core.getInput('short-description'),
|
|
readmeFilepath: core.getInput('readme-filepath')
|
|
};
|
|
// Environment variable input alternatives and their aliases
|
|
if (!inputs.username && process.env['DOCKERHUB_USERNAME']) {
|
|
inputs.username = process.env['DOCKERHUB_USERNAME'];
|
|
}
|
|
if (!inputs.username && process.env['DOCKER_USERNAME']) {
|
|
inputs.username = process.env['DOCKER_USERNAME'];
|
|
}
|
|
if (!inputs.password && process.env['DOCKERHUB_PASSWORD']) {
|
|
inputs.password = process.env['DOCKERHUB_PASSWORD'];
|
|
}
|
|
if (!inputs.password && process.env['DOCKER_PASSWORD']) {
|
|
inputs.password = process.env['DOCKER_PASSWORD'];
|
|
}
|
|
if (!inputs.repository && process.env['DOCKERHUB_REPOSITORY']) {
|
|
inputs.repository = process.env['DOCKERHUB_REPOSITORY'];
|
|
}
|
|
if (!inputs.repository && process.env['DOCKER_REPOSITORY']) {
|
|
inputs.repository = process.env['DOCKER_REPOSITORY'];
|
|
}
|
|
if (!inputs.shortDescription && process.env['SHORT_DESCRIPTION']) {
|
|
inputs.shortDescription = process.env['SHORT_DESCRIPTION'];
|
|
}
|
|
if (!inputs.readmeFilepath && process.env['README_FILEPATH']) {
|
|
inputs.readmeFilepath = process.env['README_FILEPATH'];
|
|
}
|
|
// Set defaults
|
|
if (!inputs.readmeFilepath) {
|
|
inputs.readmeFilepath = README_FILEPATH_DEFAULT;
|
|
}
|
|
if (!inputs.repository && process.env['GITHUB_REPOSITORY']) {
|
|
inputs.repository = process.env['GITHUB_REPOSITORY'];
|
|
}
|
|
// Docker repositories must be all lower case
|
|
inputs.repository = inputs.repository.toLowerCase();
|
|
return inputs;
|
|
}
|
|
exports.getInputs = getInputs;
|
|
function checkRequiredInput(input, name) {
|
|
if (!input) {
|
|
throw new Error(`Required input '${name}' is missing.`);
|
|
}
|
|
}
|
|
function validateInputs(inputs) {
|
|
checkRequiredInput(inputs.username, 'username');
|
|
checkRequiredInput(inputs.password, 'password');
|
|
}
|
|
exports.validateInputs = validateInputs;
|
|
|
|
|
|
/***/ }),
|
|
|
|
/***/ 109:
|
|
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
|
|
|
|
"use strict";
|
|
|
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
|
}) : (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
}));
|
|
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
}) : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = (this && this.__importStar) || function (mod) {
|
|
if (mod && mod.__esModule) return mod;
|
|
var result = {};
|
|
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
var __awaiter = (this && this.__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 }));
|
|
const core = __importStar(__nccwpck_require__(186));
|
|
const inputHelper = __importStar(__nccwpck_require__(480));
|
|
const dockerhubHelper = __importStar(__nccwpck_require__(812));
|
|
const fs = __importStar(__nccwpck_require__(747));
|
|
const util_1 = __nccwpck_require__(669);
|
|
const MAX_BYTES = 25000;
|
|
function run() {
|
|
return __awaiter(this, void 0, void 0, function* () {
|
|
try {
|
|
const inputs = inputHelper.getInputs();
|
|
core.debug(`Inputs: ${(0, util_1.inspect)(inputs)}`);
|
|
inputHelper.validateInputs(inputs);
|
|
// Fetch the readme content
|
|
const readmeContent = yield fs.promises.readFile(inputs.readmeFilepath, {
|
|
encoding: 'utf8'
|
|
});
|
|
const byteLength = new util_1.TextEncoder().encode(readmeContent).length;
|
|
if (byteLength > MAX_BYTES) {
|
|
throw new Error(`File size exceeds the maximum allowed ${MAX_BYTES} bytes`);
|
|
}
|
|
// Acquire a token for the Docker Hub API
|
|
core.info('Acquiring token');
|
|
const token = yield dockerhubHelper.getToken(inputs.username, inputs.password);
|
|
// Send a PATCH request to update the description of the repository
|
|
core.info('Sending PATCH request');
|
|
yield dockerhubHelper.updateRepositoryDescription(token, inputs.repository, inputs.shortDescription, readmeContent);
|
|
core.info('Request successful');
|
|
}
|
|
catch (error) {
|
|
core.debug((0, util_1.inspect)(error));
|
|
core.setFailed(error.message);
|
|
}
|
|
});
|
|
}
|
|
run();
|
|
|
|
|
|
/***/ }),
|
|
|
|
/***/ 351:
|
|
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
|
|
|
|
"use strict";
|
|
|
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
|
}) : (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
}));
|
|
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
}) : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = (this && this.__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;
|
|
const os = __importStar(__nccwpck_require__(87));
|
|
const utils_1 = __nccwpck_require__(278);
|
|
/**
|
|
* Commands
|
|
*
|
|
* Command Format:
|
|
* ::name key=value,key=value::message
|
|
*
|
|
* Examples:
|
|
* ::warning::This is the message
|
|
* ::set-env name=MY_VAR::some value
|
|
*/
|
|
function issueCommand(command, properties, message) {
|
|
const cmd = new Command(command, properties, message);
|
|
process.stdout.write(cmd.toString() + os.EOL);
|
|
}
|
|
exports.issueCommand = issueCommand;
|
|
function issue(name, message = '') {
|
|
issueCommand(name, {}, message);
|
|
}
|
|
exports.issue = issue;
|
|
const CMD_STRING = '::';
|
|
class Command {
|
|
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');
|
|
}
|
|
//# sourceMappingURL=command.js.map
|
|
|
|
/***/ }),
|
|
|
|
/***/ 186:
|
|
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
|
|
|
|
"use strict";
|
|
|
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
|
}) : (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
}));
|
|
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
}) : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = (this && this.__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 = (this && this.__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;
|
|
const command_1 = __nccwpck_require__(351);
|
|
const file_command_1 = __nccwpck_require__(717);
|
|
const utils_1 = __nccwpck_require__(278);
|
|
const os = __importStar(__nccwpck_require__(87));
|
|
const path = __importStar(__nccwpck_require__(622));
|
|
const oidc_utils_1 = __nccwpck_require__(41);
|
|
/**
|
|
* The code to exit an action
|
|
*/
|
|
var ExitCode;
|
|
(function (ExitCode) {
|
|
/**
|
|
* A code indicating that the action was successful
|
|
*/
|
|
ExitCode[ExitCode["Success"] = 0] = "Success";
|
|
/**
|
|
* A code indicating that the action was a failure
|
|
*/
|
|
ExitCode[ExitCode["Failure"] = 1] = "Failure";
|
|
})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));
|
|
//-----------------------------------------------------------------------
|
|
// Variables
|
|
//-----------------------------------------------------------------------
|
|
/**
|
|
* Sets env variable for this action and future actions in the job
|
|
* @param name the name of the variable to set
|
|
* @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify
|
|
*/
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
function exportVariable(name, val) {
|
|
const convertedVal = utils_1.toCommandValue(val);
|
|
process.env[name] = convertedVal;
|
|
const filePath = process.env['GITHUB_ENV'] || '';
|
|
if (filePath) {
|
|
const delimiter = '_GitHubActionsFileCommandDelimeter_';
|
|
const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`;
|
|
file_command_1.issueCommand('ENV', commandValue);
|
|
}
|
|
else {
|
|
command_1.issueCommand('set-env', { name }, convertedVal);
|
|
}
|
|
}
|
|
exports.exportVariable = exportVariable;
|
|
/**
|
|
* Registers a secret which will get masked from logs
|
|
* @param secret value of the secret
|
|
*/
|
|
function setSecret(secret) {
|
|
command_1.issueCommand('add-mask', {}, secret);
|
|
}
|
|
exports.setSecret = setSecret;
|
|
/**
|
|
* Prepends inputPath to the PATH (for this action and future actions)
|
|
* @param inputPath
|
|
*/
|
|
function addPath(inputPath) {
|
|
const filePath = process.env['GITHUB_PATH'] || '';
|
|
if (filePath) {
|
|
file_command_1.issueCommand('PATH', inputPath);
|
|
}
|
|
else {
|
|
command_1.issueCommand('add-path', {}, inputPath);
|
|
}
|
|
process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;
|
|
}
|
|
exports.addPath = addPath;
|
|
/**
|
|
* Gets the value of an input.
|
|
* Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.
|
|
* Returns an empty string if the value is not defined.
|
|
*
|
|
* @param name name of the input to get
|
|
* @param options optional. See InputOptions.
|
|
* @returns string
|
|
*/
|
|
function getInput(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 = getInput;
|
|
/**
|
|
* Gets the values of an multiline input. Each value is also trimmed.
|
|
*
|
|
* @param name name of the input to get
|
|
* @param options optional. See InputOptions.
|
|
* @returns string[]
|
|
*
|
|
*/
|
|
function getMultilineInput(name, options) {
|
|
const inputs = getInput(name, options)
|
|
.split('\n')
|
|
.filter(x => x !== '');
|
|
return inputs;
|
|
}
|
|
exports.getMultilineInput = getMultilineInput;
|
|
/**
|
|
* Gets the input value of the boolean type in the YAML 1.2 "core schema" specification.
|
|
* Support boolean input list: `true | True | TRUE | false | False | FALSE` .
|
|
* The return value is also in boolean type.
|
|
* ref: https://yaml.org/spec/1.2/spec.html#id2804923
|
|
*
|
|
* @param name name of the input to get
|
|
* @param options optional. See InputOptions.
|
|
* @returns boolean
|
|
*/
|
|
function getBooleanInput(name, options) {
|
|
const trueValue = ['true', 'True', 'TRUE'];
|
|
const falseValue = ['false', 'False', 'FALSE'];
|
|
const val = getInput(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}\n` +
|
|
`Support boolean input list: \`true | True | TRUE | false | False | FALSE\``);
|
|
}
|
|
exports.getBooleanInput = getBooleanInput;
|
|
/**
|
|
* Sets the value of an output.
|
|
*
|
|
* @param name name of the output to set
|
|
* @param value value to store. Non-string values will be converted to a string via JSON.stringify
|
|
*/
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
function setOutput(name, value) {
|
|
process.stdout.write(os.EOL);
|
|
command_1.issueCommand('set-output', { name }, value);
|
|
}
|
|
exports.setOutput = setOutput;
|
|
/**
|
|
* Enables or disables the echoing of commands into stdout for the rest of the step.
|
|
* Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.
|
|
*
|
|
*/
|
|
function setCommandEcho(enabled) {
|
|
command_1.issue('echo', enabled ? 'on' : 'off');
|
|
}
|
|
exports.setCommandEcho = setCommandEcho;
|
|
//-----------------------------------------------------------------------
|
|
// Results
|
|
//-----------------------------------------------------------------------
|
|
/**
|
|
* Sets the action status to failed.
|
|
* When the action exits it will be with an exit code of 1
|
|
* @param message add error issue message
|
|
*/
|
|
function setFailed(message) {
|
|
process.exitCode = ExitCode.Failure;
|
|
error(message);
|
|
}
|
|
exports.setFailed = setFailed;
|
|
//-----------------------------------------------------------------------
|
|
// Logging Commands
|
|
//-----------------------------------------------------------------------
|
|
/**
|
|
* Gets whether Actions Step Debug is on or not
|
|
*/
|
|
function isDebug() {
|
|
return process.env['RUNNER_DEBUG'] === '1';
|
|
}
|
|
exports.isDebug = isDebug;
|
|
/**
|
|
* Writes debug message to user log
|
|
* @param message debug message
|
|
*/
|
|
function debug(message) {
|
|
command_1.issueCommand('debug', {}, message);
|
|
}
|
|
exports.debug = debug;
|
|
/**
|
|
* Adds an error issue
|
|
* @param message error issue message. Errors will be converted to string via toString()
|
|
* @param properties optional properties to add to the annotation.
|
|
*/
|
|
function error(message, properties = {}) {
|
|
command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
|
|
}
|
|
exports.error = error;
|
|
/**
|
|
* Adds a warning issue
|
|
* @param message warning issue message. Errors will be converted to string via toString()
|
|
* @param properties optional properties to add to the annotation.
|
|
*/
|
|
function warning(message, properties = {}) {
|
|
command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
|
|
}
|
|
exports.warning = warning;
|
|
/**
|
|
* Adds a notice issue
|
|
* @param message notice issue message. Errors will be converted to string via toString()
|
|
* @param properties optional properties to add to the annotation.
|
|
*/
|
|
function notice(message, properties = {}) {
|
|
command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
|
|
}
|
|
exports.notice = notice;
|
|
/**
|
|
* Writes info to log with console.log.
|
|
* @param message info message
|
|
*/
|
|
function info(message) {
|
|
process.stdout.write(message + os.EOL);
|
|
}
|
|
exports.info = info;
|
|
/**
|
|
* Begin an output group.
|
|
*
|
|
* Output until the next `groupEnd` will be foldable in this group
|
|
*
|
|
* @param name The name of the output group
|
|
*/
|
|
function startGroup(name) {
|
|
command_1.issue('group', name);
|
|
}
|
|
exports.startGroup = startGroup;
|
|
/**
|
|
* End an output group.
|
|
*/
|
|
function endGroup() {
|
|
command_1.issue('endgroup');
|
|
}
|
|
exports.endGroup = endGroup;
|
|
/**
|
|
* Wrap an asynchronous function call in a group.
|
|
*
|
|
* Returns the same type as the function itself.
|
|
*
|
|
* @param name The name of the group
|
|
* @param fn The function to wrap in the group
|
|
*/
|
|
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;
|
|
//-----------------------------------------------------------------------
|
|
// Wrapper action state
|
|
//-----------------------------------------------------------------------
|
|
/**
|
|
* Saves state for current action, the state can only be retrieved by this action's post job execution.
|
|
*
|
|
* @param name name of the state to store
|
|
* @param value value to store. Non-string values will be converted to a string via JSON.stringify
|
|
*/
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
function saveState(name, value) {
|
|
command_1.issueCommand('save-state', { name }, value);
|
|
}
|
|
exports.saveState = saveState;
|
|
/**
|
|
* Gets the value of an state set by this action's main execution.
|
|
*
|
|
* @param name name of the state to get
|
|
* @returns string
|
|
*/
|
|
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;
|
|
//# sourceMappingURL=core.js.map
|
|
|
|
/***/ }),
|
|
|
|
/***/ 717:
|
|
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
|
|
|
|
"use strict";
|
|
|
|
// For internal use, subject to change.
|
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
|
}) : (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
}));
|
|
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
}) : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = (this && this.__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.issueCommand = void 0;
|
|
// We use any as a valid input type
|
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
const fs = __importStar(__nccwpck_require__(747));
|
|
const os = __importStar(__nccwpck_require__(87));
|
|
const utils_1 = __nccwpck_require__(278);
|
|
function issueCommand(command, message) {
|
|
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.issueCommand = issueCommand;
|
|
//# sourceMappingURL=file-command.js.map
|
|
|
|
/***/ }),
|
|
|
|
/***/ 41:
|
|
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
|
|
|
|
"use strict";
|
|
|
|
var __awaiter = (this && this.__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;
|
|
const http_client_1 = __nccwpck_require__(925);
|
|
const auth_1 = __nccwpck_require__(702);
|
|
const core_1 = __nccwpck_require__(186);
|
|
class OidcClient {
|
|
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. \n
|
|
Error Code : ${error.statusCode}\n
|
|
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 {
|
|
// New ID Token is requested from action service
|
|
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;
|
|
//# sourceMappingURL=oidc-utils.js.map
|
|
|
|
/***/ }),
|
|
|
|
/***/ 278:
|
|
/***/ ((__unused_webpack_module, exports) => {
|
|
|
|
"use strict";
|
|
|
|
// We use any as a valid input type
|
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
exports.toCommandProperties = exports.toCommandValue = void 0;
|
|
/**
|
|
* Sanitizes an input into a string so it can be passed into issueCommand safely
|
|
* @param input input to sanitize into a string
|
|
*/
|
|
function toCommandValue(input) {
|
|
if (input === null || input === undefined) {
|
|
return '';
|
|
}
|
|
else if (typeof input === 'string' || input instanceof String) {
|
|
return input;
|
|
}
|
|
return JSON.stringify(input);
|
|
}
|
|
exports.toCommandValue = toCommandValue;
|
|
/**
|
|
*
|
|
* @param annotationProperties
|
|
* @returns The command properties to send with the actual annotation command
|
|
* See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646
|
|
*/
|
|
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;
|
|
//# sourceMappingURL=utils.js.map
|
|
|
|
/***/ }),
|
|
|
|
/***/ 702:
|
|
/***/ ((__unused_webpack_module, exports) => {
|
|
|
|
"use strict";
|
|
|
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
class BasicCredentialHandler {
|
|
constructor(username, password) {
|
|
this.username = username;
|
|
this.password = password;
|
|
}
|
|
prepareRequest(options) {
|
|
options.headers['Authorization'] =
|
|
'Basic ' +
|
|
Buffer.from(this.username + ':' + this.password).toString('base64');
|
|
}
|
|
// This handler cannot handle 401
|
|
canHandleAuthentication(response) {
|
|
return false;
|
|
}
|
|
handleAuthentication(httpClient, requestInfo, objs) {
|
|
return null;
|
|
}
|
|
}
|
|
exports.BasicCredentialHandler = BasicCredentialHandler;
|
|
class BearerCredentialHandler {
|
|
constructor(token) {
|
|
this.token = token;
|
|
}
|
|
// currently implements pre-authorization
|
|
// TODO: support preAuth = false where it hooks on 401
|
|
prepareRequest(options) {
|
|
options.headers['Authorization'] = 'Bearer ' + this.token;
|
|
}
|
|
// This handler cannot handle 401
|
|
canHandleAuthentication(response) {
|
|
return false;
|
|
}
|
|
handleAuthentication(httpClient, requestInfo, objs) {
|
|
return null;
|
|
}
|
|
}
|
|
exports.BearerCredentialHandler = BearerCredentialHandler;
|
|
class PersonalAccessTokenCredentialHandler {
|
|
constructor(token) {
|
|
this.token = token;
|
|
}
|
|
// currently implements pre-authorization
|
|
// TODO: support preAuth = false where it hooks on 401
|
|
prepareRequest(options) {
|
|
options.headers['Authorization'] =
|
|
'Basic ' + Buffer.from('PAT:' + this.token).toString('base64');
|
|
}
|
|
// This handler cannot handle 401
|
|
canHandleAuthentication(response) {
|
|
return false;
|
|
}
|
|
handleAuthentication(httpClient, requestInfo, objs) {
|
|
return null;
|
|
}
|
|
}
|
|
exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;
|
|
|
|
|
|
/***/ }),
|
|
|
|
/***/ 925:
|
|
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
|
|
|
|
"use strict";
|
|
|
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
const http = __nccwpck_require__(605);
|
|
const https = __nccwpck_require__(211);
|
|
const pm = __nccwpck_require__(443);
|
|
let tunnel;
|
|
var HttpCodes;
|
|
(function (HttpCodes) {
|
|
HttpCodes[HttpCodes["OK"] = 200] = "OK";
|
|
HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices";
|
|
HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently";
|
|
HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved";
|
|
HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther";
|
|
HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified";
|
|
HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy";
|
|
HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy";
|
|
HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect";
|
|
HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect";
|
|
HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest";
|
|
HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized";
|
|
HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired";
|
|
HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden";
|
|
HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound";
|
|
HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed";
|
|
HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable";
|
|
HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
|
|
HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout";
|
|
HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict";
|
|
HttpCodes[HttpCodes["Gone"] = 410] = "Gone";
|
|
HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests";
|
|
HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError";
|
|
HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented";
|
|
HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";
|
|
HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable";
|
|
HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout";
|
|
})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {}));
|
|
var Headers;
|
|
(function (Headers) {
|
|
Headers["Accept"] = "accept";
|
|
Headers["ContentType"] = "content-type";
|
|
})(Headers = exports.Headers || (exports.Headers = {}));
|
|
var MediaTypes;
|
|
(function (MediaTypes) {
|
|
MediaTypes["ApplicationJson"] = "application/json";
|
|
})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {}));
|
|
/**
|
|
* Returns the proxy URL, depending upon the supplied url and proxy environment variables.
|
|
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
|
|
*/
|
|
function getProxyUrl(serverUrl) {
|
|
let proxyUrl = pm.getProxyUrl(new URL(serverUrl));
|
|
return proxyUrl ? proxyUrl.href : '';
|
|
}
|
|
exports.getProxyUrl = getProxyUrl;
|
|
const HttpRedirectCodes = [
|
|
HttpCodes.MovedPermanently,
|
|
HttpCodes.ResourceMoved,
|
|
HttpCodes.SeeOther,
|
|
HttpCodes.TemporaryRedirect,
|
|
HttpCodes.PermanentRedirect
|
|
];
|
|
const HttpResponseRetryCodes = [
|
|
HttpCodes.BadGateway,
|
|
HttpCodes.ServiceUnavailable,
|
|
HttpCodes.GatewayTimeout
|
|
];
|
|
const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];
|
|
const ExponentialBackoffCeiling = 10;
|
|
const ExponentialBackoffTimeSlice = 5;
|
|
class HttpClientError extends Error {
|
|
constructor(message, statusCode) {
|
|
super(message);
|
|
this.name = 'HttpClientError';
|
|
this.statusCode = statusCode;
|
|
Object.setPrototypeOf(this, HttpClientError.prototype);
|
|
}
|
|
}
|
|
exports.HttpClientError = HttpClientError;
|
|
class HttpClientResponse {
|
|
constructor(message) {
|
|
this.message = message;
|
|
}
|
|
readBody() {
|
|
return new Promise(async (resolve, reject) => {
|
|
let output = Buffer.alloc(0);
|
|
this.message.on('data', (chunk) => {
|
|
output = Buffer.concat([output, chunk]);
|
|
});
|
|
this.message.on('end', () => {
|
|
resolve(output.toString());
|
|
});
|
|
});
|
|
}
|
|
}
|
|
exports.HttpClientResponse = HttpClientResponse;
|
|
function isHttps(requestUrl) {
|
|
let parsedUrl = new URL(requestUrl);
|
|
return parsedUrl.protocol === 'https:';
|
|
}
|
|
exports.isHttps = isHttps;
|
|
class HttpClient {
|
|
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 this.request('OPTIONS', requestUrl, null, additionalHeaders || {});
|
|
}
|
|
get(requestUrl, additionalHeaders) {
|
|
return this.request('GET', requestUrl, null, additionalHeaders || {});
|
|
}
|
|
del(requestUrl, additionalHeaders) {
|
|
return this.request('DELETE', requestUrl, null, additionalHeaders || {});
|
|
}
|
|
post(requestUrl, data, additionalHeaders) {
|
|
return this.request('POST', requestUrl, data, additionalHeaders || {});
|
|
}
|
|
patch(requestUrl, data, additionalHeaders) {
|
|
return this.request('PATCH', requestUrl, data, additionalHeaders || {});
|
|
}
|
|
put(requestUrl, data, additionalHeaders) {
|
|
return this.request('PUT', requestUrl, data, additionalHeaders || {});
|
|
}
|
|
head(requestUrl, additionalHeaders) {
|
|
return this.request('HEAD', requestUrl, null, additionalHeaders || {});
|
|
}
|
|
sendStream(verb, requestUrl, stream, additionalHeaders) {
|
|
return this.request(verb, requestUrl, stream, additionalHeaders);
|
|
}
|
|
/**
|
|
* Gets a typed object from an endpoint
|
|
* Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise
|
|
*/
|
|
async getJson(requestUrl, additionalHeaders = {}) {
|
|
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
|
|
let res = await this.get(requestUrl, additionalHeaders);
|
|
return this._processResponse(res, this.requestOptions);
|
|
}
|
|
async postJson(requestUrl, obj, additionalHeaders = {}) {
|
|
let 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);
|
|
let res = await this.post(requestUrl, data, additionalHeaders);
|
|
return this._processResponse(res, this.requestOptions);
|
|
}
|
|
async putJson(requestUrl, obj, additionalHeaders = {}) {
|
|
let 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);
|
|
let res = await this.put(requestUrl, data, additionalHeaders);
|
|
return this._processResponse(res, this.requestOptions);
|
|
}
|
|
async patchJson(requestUrl, obj, additionalHeaders = {}) {
|
|
let 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);
|
|
let res = await this.patch(requestUrl, data, additionalHeaders);
|
|
return this._processResponse(res, this.requestOptions);
|
|
}
|
|
/**
|
|
* Makes a raw http request.
|
|
* All other methods such as get, post, patch, and request ultimately call this.
|
|
* Prefer get, del, post and patch
|
|
*/
|
|
async request(verb, requestUrl, data, headers) {
|
|
if (this._disposed) {
|
|
throw new Error('Client has already been disposed.');
|
|
}
|
|
let parsedUrl = new URL(requestUrl);
|
|
let info = this._prepareRequest(verb, parsedUrl, headers);
|
|
// Only perform retries on reads since writes may not be idempotent.
|
|
let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1
|
|
? this._maxRetries + 1
|
|
: 1;
|
|
let numTries = 0;
|
|
let response;
|
|
while (numTries < maxTries) {
|
|
response = await this.requestRaw(info, data);
|
|
// Check if it's an authentication challenge
|
|
if (response &&
|
|
response.message &&
|
|
response.message.statusCode === HttpCodes.Unauthorized) {
|
|
let authenticationHandler;
|
|
for (let i = 0; i < this.handlers.length; i++) {
|
|
if (this.handlers[i].canHandleAuthentication(response)) {
|
|
authenticationHandler = this.handlers[i];
|
|
break;
|
|
}
|
|
}
|
|
if (authenticationHandler) {
|
|
return authenticationHandler.handleAuthentication(this, info, data);
|
|
}
|
|
else {
|
|
// We have received an unauthorized response but have no handlers to handle it.
|
|
// Let the response return to the caller.
|
|
return response;
|
|
}
|
|
}
|
|
let redirectsRemaining = this._maxRedirects;
|
|
while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 &&
|
|
this._allowRedirects &&
|
|
redirectsRemaining > 0) {
|
|
const redirectUrl = response.message.headers['location'];
|
|
if (!redirectUrl) {
|
|
// if there's no location to redirect to, we won't
|
|
break;
|
|
}
|
|
let 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.');
|
|
}
|
|
// we need to finish reading the response before reassigning response
|
|
// which will leak the open socket.
|
|
await response.readBody();
|
|
// strip authorization header if redirected to a different hostname
|
|
if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
|
|
for (let header in headers) {
|
|
// header names are case insensitive
|
|
if (header.toLowerCase() === 'authorization') {
|
|
delete headers[header];
|
|
}
|
|
}
|
|
}
|
|
// let's make the request with the new redirectUrl
|
|
info = this._prepareRequest(verb, parsedRedirectUrl, headers);
|
|
response = await this.requestRaw(info, data);
|
|
redirectsRemaining--;
|
|
}
|
|
if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) {
|
|
// If not a retry code, return immediately instead of retrying
|
|
return response;
|
|
}
|
|
numTries += 1;
|
|
if (numTries < maxTries) {
|
|
await response.readBody();
|
|
await this._performExponentialBackoff(numTries);
|
|
}
|
|
}
|
|
return response;
|
|
}
|
|
/**
|
|
* Needs to be called if keepAlive is set to true in request options.
|
|
*/
|
|
dispose() {
|
|
if (this._agent) {
|
|
this._agent.destroy();
|
|
}
|
|
this._disposed = true;
|
|
}
|
|
/**
|
|
* Raw request.
|
|
* @param info
|
|
* @param data
|
|
*/
|
|
requestRaw(info, data) {
|
|
return new Promise((resolve, reject) => {
|
|
let callbackForResult = function (err, res) {
|
|
if (err) {
|
|
reject(err);
|
|
}
|
|
resolve(res);
|
|
};
|
|
this.requestRawWithCallback(info, data, callbackForResult);
|
|
});
|
|
}
|
|
/**
|
|
* Raw request with callback.
|
|
* @param info
|
|
* @param data
|
|
* @param onResult
|
|
*/
|
|
requestRawWithCallback(info, data, onResult) {
|
|
let socket;
|
|
if (typeof data === 'string') {
|
|
info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
|
|
}
|
|
let callbackCalled = false;
|
|
let handleResult = (err, res) => {
|
|
if (!callbackCalled) {
|
|
callbackCalled = true;
|
|
onResult(err, res);
|
|
}
|
|
};
|
|
let req = info.httpModule.request(info.options, (msg) => {
|
|
let res = new HttpClientResponse(msg);
|
|
handleResult(null, res);
|
|
});
|
|
req.on('socket', sock => {
|
|
socket = sock;
|
|
});
|
|
// If we ever get disconnected, we want the socket to timeout eventually
|
|
req.setTimeout(this._socketTimeout || 3 * 60000, () => {
|
|
if (socket) {
|
|
socket.end();
|
|
}
|
|
handleResult(new Error('Request timeout: ' + info.options.path), null);
|
|
});
|
|
req.on('error', function (err) {
|
|
// err has statusCode property
|
|
// res should have headers
|
|
handleResult(err, null);
|
|
});
|
|
if (data && typeof data === 'string') {
|
|
req.write(data, 'utf8');
|
|
}
|
|
if (data && typeof data !== 'string') {
|
|
data.on('close', function () {
|
|
req.end();
|
|
});
|
|
data.pipe(req);
|
|
}
|
|
else {
|
|
req.end();
|
|
}
|
|
}
|
|
/**
|
|
* Gets an http agent. This function is useful when you need an http agent that handles
|
|
* routing through a proxy server - depending upon the url and proxy environment variables.
|
|
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
|
|
*/
|
|
getAgent(serverUrl) {
|
|
let parsedUrl = new URL(serverUrl);
|
|
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);
|
|
// gives handlers an opportunity to participate
|
|
if (this.handlers) {
|
|
this.handlers.forEach(handler => {
|
|
handler.prepareRequest(info.options);
|
|
});
|
|
}
|
|
return info;
|
|
}
|
|
_mergeHeaders(headers) {
|
|
const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
|
|
if (this.requestOptions && this.requestOptions.headers) {
|
|
return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers));
|
|
}
|
|
return lowercaseKeys(headers || {});
|
|
}
|
|
_getExistingOrDefaultHeader(additionalHeaders, header, _default) {
|
|
const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
|
|
let clientHeader;
|
|
if (this.requestOptions && this.requestOptions.headers) {
|
|
clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
|
|
}
|
|
return additionalHeaders[header] || clientHeader || _default;
|
|
}
|
|
_getAgent(parsedUrl) {
|
|
let agent;
|
|
let proxyUrl = pm.getProxyUrl(parsedUrl);
|
|
let useProxy = proxyUrl && proxyUrl.hostname;
|
|
if (this._keepAlive && useProxy) {
|
|
agent = this._proxyAgent;
|
|
}
|
|
if (this._keepAlive && !useProxy) {
|
|
agent = this._agent;
|
|
}
|
|
// if agent is already assigned use that agent.
|
|
if (!!agent) {
|
|
return agent;
|
|
}
|
|
const usingSsl = parsedUrl.protocol === 'https:';
|
|
let maxSockets = 100;
|
|
if (!!this.requestOptions) {
|
|
maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
|
|
}
|
|
if (useProxy) {
|
|
// If using proxy, need tunnel
|
|
if (!tunnel) {
|
|
tunnel = __nccwpck_require__(294);
|
|
}
|
|
const agentOptions = {
|
|
maxSockets: maxSockets,
|
|
keepAlive: this._keepAlive,
|
|
proxy: {
|
|
...((proxyUrl.username || proxyUrl.password) && {
|
|
proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`
|
|
}),
|
|
host: proxyUrl.hostname,
|
|
port: proxyUrl.port
|
|
}
|
|
};
|
|
let tunnelAgent;
|
|
const overHttps = proxyUrl.protocol === 'https:';
|
|
if (usingSsl) {
|
|
tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
|
|
}
|
|
else {
|
|
tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
|
|
}
|
|
agent = tunnelAgent(agentOptions);
|
|
this._proxyAgent = agent;
|
|
}
|
|
// if reusing agent across request and tunneling agent isn't assigned create a new agent
|
|
if (this._keepAlive && !agent) {
|
|
const options = { keepAlive: this._keepAlive, maxSockets: maxSockets };
|
|
agent = usingSsl ? new https.Agent(options) : new http.Agent(options);
|
|
this._agent = agent;
|
|
}
|
|
// if not using private agent and tunnel agent isn't setup then use global agent
|
|
if (!agent) {
|
|
agent = usingSsl ? https.globalAgent : http.globalAgent;
|
|
}
|
|
if (usingSsl && this._ignoreSslError) {
|
|
// we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
|
|
// http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
|
|
// we have to cast it to any and change it directly
|
|
agent.options = Object.assign(agent.options || {}, {
|
|
rejectUnauthorized: false
|
|
});
|
|
}
|
|
return agent;
|
|
}
|
|
_performExponentialBackoff(retryNumber) {
|
|
retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
|
|
const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
|
|
return new Promise(resolve => setTimeout(() => resolve(), ms));
|
|
}
|
|
static dateTimeDeserializer(key, value) {
|
|
if (typeof value === 'string') {
|
|
let a = new Date(value);
|
|
if (!isNaN(a.valueOf())) {
|
|
return a;
|
|
}
|
|
}
|
|
return value;
|
|
}
|
|
async _processResponse(res, options) {
|
|
return new Promise(async (resolve, reject) => {
|
|
const statusCode = res.message.statusCode;
|
|
const response = {
|
|
statusCode: statusCode,
|
|
result: null,
|
|
headers: {}
|
|
};
|
|
// not found leads to null obj returned
|
|
if (statusCode == HttpCodes.NotFound) {
|
|
resolve(response);
|
|
}
|
|
let obj;
|
|
let contents;
|
|
// get the result from the body
|
|
try {
|
|
contents = await res.readBody();
|
|
if (contents && contents.length > 0) {
|
|
if (options && options.deserializeDates) {
|
|
obj = JSON.parse(contents, HttpClient.dateTimeDeserializer);
|
|
}
|
|
else {
|
|
obj = JSON.parse(contents);
|
|
}
|
|
response.result = obj;
|
|
}
|
|
response.headers = res.message.headers;
|
|
}
|
|
catch (err) {
|
|
// Invalid resource (contents not json); leaving result obj null
|
|
}
|
|
// note that 3xx redirects are handled by the http layer.
|
|
if (statusCode > 299) {
|
|
let msg;
|
|
// if exception/error in body, attempt to get better error
|
|
if (obj && obj.message) {
|
|
msg = obj.message;
|
|
}
|
|
else if (contents && contents.length > 0) {
|
|
// it may be the case that the exception is in the body message as string
|
|
msg = contents;
|
|
}
|
|
else {
|
|
msg = 'Failed request: (' + statusCode + ')';
|
|
}
|
|
let err = new HttpClientError(msg, statusCode);
|
|
err.result = response.result;
|
|
reject(err);
|
|
}
|
|
else {
|
|
resolve(response);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
exports.HttpClient = HttpClient;
|
|
|
|
|
|
/***/ }),
|
|
|
|
/***/ 443:
|
|
/***/ ((__unused_webpack_module, exports) => {
|
|
|
|
"use strict";
|
|
|
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
function getProxyUrl(reqUrl) {
|
|
let usingSsl = reqUrl.protocol === 'https:';
|
|
let proxyUrl;
|
|
if (checkBypass(reqUrl)) {
|
|
return proxyUrl;
|
|
}
|
|
let proxyVar;
|
|
if (usingSsl) {
|
|
proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY'];
|
|
}
|
|
else {
|
|
proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY'];
|
|
}
|
|
if (proxyVar) {
|
|
proxyUrl = new URL(proxyVar);
|
|
}
|
|
return proxyUrl;
|
|
}
|
|
exports.getProxyUrl = getProxyUrl;
|
|
function checkBypass(reqUrl) {
|
|
if (!reqUrl.hostname) {
|
|
return false;
|
|
}
|
|
let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';
|
|
if (!noProxy) {
|
|
return false;
|
|
}
|
|
// Determine the request port
|
|
let reqPort;
|
|
if (reqUrl.port) {
|
|
reqPort = Number(reqUrl.port);
|
|
}
|
|
else if (reqUrl.protocol === 'http:') {
|
|
reqPort = 80;
|
|
}
|
|
else if (reqUrl.protocol === 'https:') {
|
|
reqPort = 443;
|
|
}
|
|
// Format the request hostname and hostname with port
|
|
let upperReqHosts = [reqUrl.hostname.toUpperCase()];
|
|
if (typeof reqPort === 'number') {
|
|
upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
|
|
}
|
|
// Compare request host against noproxy
|
|
for (let upperNoProxyItem of noProxy
|
|
.split(',')
|
|
.map(x => x.trim().toUpperCase())
|
|
.filter(x => x)) {
|
|
if (upperReqHosts.some(x => x === upperNoProxyItem)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
exports.checkBypass = checkBypass;
|
|
|
|
|
|
/***/ }),
|
|
|
|
/***/ 467:
|
|
/***/ ((module, exports, __nccwpck_require__) => {
|
|
|
|
"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(__nccwpck_require__(413));
|
|
var http = _interopDefault(__nccwpck_require__(605));
|
|
var Url = _interopDefault(__nccwpck_require__(835));
|
|
var https = _interopDefault(__nccwpck_require__(211));
|
|
var zlib = _interopDefault(__nccwpck_require__(761));
|
|
|
|
// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
|
|
|
|
// fix for "Readable" isn't a named export issue
|
|
const Readable = Stream.Readable;
|
|
|
|
const BUFFER = Symbol('buffer');
|
|
const TYPE = Symbol('type');
|
|
|
|
class Blob {
|
|
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 !== undefined && 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 === undefined) {
|
|
relativeStart = 0;
|
|
} else if (start < 0) {
|
|
relativeStart = Math.max(size + start, 0);
|
|
} else {
|
|
relativeStart = Math.min(start, size);
|
|
}
|
|
if (end === undefined) {
|
|
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
|
|
});
|
|
|
|
/**
|
|
* fetch-error.js
|
|
*
|
|
* FetchError interface for operational errors
|
|
*/
|
|
|
|
/**
|
|
* Create FetchError instance
|
|
*
|
|
* @param String message Error message for human
|
|
* @param String type Error type for machine
|
|
* @param String systemError For Node.js system error
|
|
* @return FetchError
|
|
*/
|
|
function FetchError(message, type, systemError) {
|
|
Error.call(this, message);
|
|
|
|
this.message = message;
|
|
this.type = type;
|
|
|
|
// when err.type is `system`, err.code contains system error code
|
|
if (systemError) {
|
|
this.code = this.errno = systemError.code;
|
|
}
|
|
|
|
// hide custom error implementation details from end-users
|
|
Error.captureStackTrace(this, this.constructor);
|
|
}
|
|
|
|
FetchError.prototype = Object.create(Error.prototype);
|
|
FetchError.prototype.constructor = FetchError;
|
|
FetchError.prototype.name = 'FetchError';
|
|
|
|
let convert;
|
|
try {
|
|
convert = __nccwpck_require__(877).convert;
|
|
} catch (e) {}
|
|
|
|
const INTERNALS = Symbol('Body internals');
|
|
|
|
// fix an issue where "PassThrough" isn't a named export for node <10
|
|
const PassThrough = Stream.PassThrough;
|
|
|
|
/**
|
|
* Body mixin
|
|
*
|
|
* Ref: https://fetch.spec.whatwg.org/#body
|
|
*
|
|
* @param Stream body Readable stream
|
|
* @param Object opts Response options
|
|
* @return Void
|
|
*/
|
|
function Body(body) {
|
|
var _this = this;
|
|
|
|
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
|
|
_ref$size = _ref.size;
|
|
|
|
let size = _ref$size === undefined ? 0 : _ref$size;
|
|
var _ref$timeout = _ref.timeout;
|
|
let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
|
|
|
|
if (body == null) {
|
|
// body is undefined or null
|
|
body = null;
|
|
} else if (isURLSearchParams(body)) {
|
|
// body is a URLSearchParams
|
|
body = Buffer.from(body.toString());
|
|
} else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
|
|
// body is ArrayBuffer
|
|
body = Buffer.from(body);
|
|
} else if (ArrayBuffer.isView(body)) {
|
|
// body is ArrayBufferView
|
|
body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
|
|
} else if (body instanceof Stream) ; else {
|
|
// none of the above
|
|
// coerce to string then buffer
|
|
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;
|
|
},
|
|
|
|
/**
|
|
* Decode response as ArrayBuffer
|
|
*
|
|
* @return Promise
|
|
*/
|
|
arrayBuffer() {
|
|
return consumeBody.call(this).then(function (buf) {
|
|
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
|
});
|
|
},
|
|
|
|
/**
|
|
* Return raw response as Blob
|
|
*
|
|
* @return Promise
|
|
*/
|
|
blob() {
|
|
let ct = this.headers && this.headers.get('content-type') || '';
|
|
return consumeBody.call(this).then(function (buf) {
|
|
return Object.assign(
|
|
// Prevent copying
|
|
new Blob([], {
|
|
type: ct.toLowerCase()
|
|
}), {
|
|
[BUFFER]: buf
|
|
});
|
|
});
|
|
},
|
|
|
|
/**
|
|
* Decode response as json
|
|
*
|
|
* @return Promise
|
|
*/
|
|
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'));
|
|
}
|
|
});
|
|
},
|
|
|
|
/**
|
|
* Decode response as text
|
|
*
|
|
* @return Promise
|
|
*/
|
|
text() {
|
|
return consumeBody.call(this).then(function (buffer) {
|
|
return buffer.toString();
|
|
});
|
|
},
|
|
|
|
/**
|
|
* Decode response as buffer (non-spec api)
|
|
*
|
|
* @return Promise
|
|
*/
|
|
buffer() {
|
|
return consumeBody.call(this);
|
|
},
|
|
|
|
/**
|
|
* Decode response as text, while automatically detecting the encoding and
|
|
* trying to decode to UTF-8 (non-spec api)
|
|
*
|
|
* @return Promise
|
|
*/
|
|
textConverted() {
|
|
var _this3 = this;
|
|
|
|
return consumeBody.call(this).then(function (buffer) {
|
|
return convertBody(buffer, _this3.headers);
|
|
});
|
|
}
|
|
};
|
|
|
|
// In browsers, all properties are enumerable.
|
|
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)) {
|
|
// istanbul ignore else: future proof
|
|
if (!(name in proto)) {
|
|
const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
|
|
Object.defineProperty(proto, name, desc);
|
|
}
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Consume and convert an entire Body to a Buffer.
|
|
*
|
|
* Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
|
|
*
|
|
* @return Promise
|
|
*/
|
|
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;
|
|
|
|
// body is null
|
|
if (body === null) {
|
|
return Body.Promise.resolve(Buffer.alloc(0));
|
|
}
|
|
|
|
// body is blob
|
|
if (isBlob(body)) {
|
|
body = body.stream();
|
|
}
|
|
|
|
// body is buffer
|
|
if (Buffer.isBuffer(body)) {
|
|
return Body.Promise.resolve(body);
|
|
}
|
|
|
|
// istanbul ignore if: should never happen
|
|
if (!(body instanceof Stream)) {
|
|
return Body.Promise.resolve(Buffer.alloc(0));
|
|
}
|
|
|
|
// body is stream
|
|
// get ready to actually consume the body
|
|
let accum = [];
|
|
let accumBytes = 0;
|
|
let abort = false;
|
|
|
|
return new Body.Promise(function (resolve, reject) {
|
|
let resTimeout;
|
|
|
|
// allow timeout on slow response body
|
|
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);
|
|
}
|
|
|
|
// handle stream errors
|
|
body.on('error', function (err) {
|
|
if (err.name === 'AbortError') {
|
|
// if the request was aborted, reject with this Error
|
|
abort = true;
|
|
reject(err);
|
|
} else {
|
|
// other errors, such as incorrect content-encoding
|
|
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) {
|
|
// handle streams that have accumulated too much data (issue #414)
|
|
reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Detect buffer encoding and convert to target encoding
|
|
* ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
|
|
*
|
|
* @param Buffer buffer Incoming buffer
|
|
* @param String encoding Target encoding
|
|
* @return String
|
|
*/
|
|
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;
|
|
|
|
// header
|
|
if (ct) {
|
|
res = /charset=([^;]*)/i.exec(ct);
|
|
}
|
|
|
|
// no charset in content type, peek at response body for at most 1024 bytes
|
|
str = buffer.slice(0, 1024).toString();
|
|
|
|
// html5
|
|
if (!res && str) {
|
|
res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);
|
|
}
|
|
|
|
// html4
|
|
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(); // drop last quote
|
|
}
|
|
}
|
|
|
|
if (res) {
|
|
res = /charset=(.*)/i.exec(res.pop());
|
|
}
|
|
}
|
|
|
|
// xml
|
|
if (!res && str) {
|
|
res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);
|
|
}
|
|
|
|
// found charset
|
|
if (res) {
|
|
charset = res.pop();
|
|
|
|
// prevent decode issues when sites use incorrect encoding
|
|
// ref: https://hsivonen.fi/encoding-menu/
|
|
if (charset === 'gb2312' || charset === 'gbk') {
|
|
charset = 'gb18030';
|
|
}
|
|
}
|
|
|
|
// turn raw buffers into a single utf-8 buffer
|
|
return convert(buffer, 'UTF-8', charset).toString();
|
|
}
|
|
|
|
/**
|
|
* Detect a URLSearchParams object
|
|
* ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143
|
|
*
|
|
* @param Object obj Object to detect by type or brand
|
|
* @return String
|
|
*/
|
|
function isURLSearchParams(obj) {
|
|
// Duck-typing as a necessary condition.
|
|
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;
|
|
}
|
|
|
|
// Brand-checking and more duck-typing as optional condition.
|
|
return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';
|
|
}
|
|
|
|
/**
|
|
* Check if `obj` is a W3C `Blob` object (which `File` inherits from)
|
|
* @param {*} obj
|
|
* @return {boolean}
|
|
*/
|
|
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]);
|
|
}
|
|
|
|
/**
|
|
* Clone body given Res/Req instance
|
|
*
|
|
* @param Mixed instance Response or Request instance
|
|
* @return Mixed
|
|
*/
|
|
function clone(instance) {
|
|
let p1, p2;
|
|
let body = instance.body;
|
|
|
|
// don't allow cloning a used body
|
|
if (instance.bodyUsed) {
|
|
throw new Error('cannot clone body after it is used');
|
|
}
|
|
|
|
// check that body is a stream and not form-data object
|
|
// note: we can't clone the form-data object without having it as a dependency
|
|
if (body instanceof Stream && typeof body.getBoundary !== 'function') {
|
|
// tee instance body
|
|
p1 = new PassThrough();
|
|
p2 = new PassThrough();
|
|
body.pipe(p1);
|
|
body.pipe(p2);
|
|
// set instance body to teed body and return the other teed body
|
|
instance[INTERNALS].body = p1;
|
|
body = p2;
|
|
}
|
|
|
|
return body;
|
|
}
|
|
|
|
/**
|
|
* Performs the operation "extract a `Content-Type` value from |object|" as
|
|
* specified in the specification:
|
|
* https://fetch.spec.whatwg.org/#concept-bodyinit-extract
|
|
*
|
|
* This function assumes that instance.body is present.
|
|
*
|
|
* @param Mixed instance Any options.body input
|
|
*/
|
|
function extractContentType(body) {
|
|
if (body === null) {
|
|
// body is null
|
|
return null;
|
|
} else if (typeof body === 'string') {
|
|
// body is string
|
|
return 'text/plain;charset=UTF-8';
|
|
} else if (isURLSearchParams(body)) {
|
|
// body is a URLSearchParams
|
|
return 'application/x-www-form-urlencoded;charset=UTF-8';
|
|
} else if (isBlob(body)) {
|
|
// body is blob
|
|
return body.type || null;
|
|
} else if (Buffer.isBuffer(body)) {
|
|
// body is buffer
|
|
return null;
|
|
} else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
|
|
// body is ArrayBuffer
|
|
return null;
|
|
} else if (ArrayBuffer.isView(body)) {
|
|
// body is ArrayBufferView
|
|
return null;
|
|
} else if (typeof body.getBoundary === 'function') {
|
|
// detect form data input from form-data module
|
|
return `multipart/form-data;boundary=${body.getBoundary()}`;
|
|
} else if (body instanceof Stream) {
|
|
// body is stream
|
|
// can't really do much about this
|
|
return null;
|
|
} else {
|
|
// Body constructor defaults other things to string
|
|
return 'text/plain;charset=UTF-8';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The Fetch Standard treats this as if "total bytes" is a property on the body.
|
|
* For us, we have to explicitly get it with a function.
|
|
*
|
|
* ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes
|
|
*
|
|
* @param Body instance Instance of Body
|
|
* @return Number? Number of bytes, or null if not possible
|
|
*/
|
|
function getTotalBytes(instance) {
|
|
const body = instance.body;
|
|
|
|
|
|
if (body === null) {
|
|
// body is null
|
|
return 0;
|
|
} else if (isBlob(body)) {
|
|
return body.size;
|
|
} else if (Buffer.isBuffer(body)) {
|
|
// body is buffer
|
|
return body.length;
|
|
} else if (body && typeof body.getLengthSync === 'function') {
|
|
// detect form data input from form-data module
|
|
if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
|
|
body.hasKnownLength && body.hasKnownLength()) {
|
|
// 2.x
|
|
return body.getLengthSync();
|
|
}
|
|
return null;
|
|
} else {
|
|
// body is stream
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Write a Body to a Node.js WritableStream (e.g. http.Request) object.
|
|
*
|
|
* @param Body instance Instance of Body
|
|
* @return Void
|
|
*/
|
|
function writeToStream(dest, instance) {
|
|
const body = instance.body;
|
|
|
|
|
|
if (body === null) {
|
|
// body is null
|
|
dest.end();
|
|
} else if (isBlob(body)) {
|
|
body.stream().pipe(dest);
|
|
} else if (Buffer.isBuffer(body)) {
|
|
// body is buffer
|
|
dest.write(body);
|
|
dest.end();
|
|
} else {
|
|
// body is stream
|
|
body.pipe(dest);
|
|
}
|
|
}
|
|
|
|
// expose Promise
|
|
Body.Promise = global.Promise;
|
|
|
|
/**
|
|
* headers.js
|
|
*
|
|
* Headers class offers convenient helpers
|
|
*/
|
|
|
|
const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
|
|
const 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`);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Find the key in the map object given a header name.
|
|
*
|
|
* Returns undefined if not found.
|
|
*
|
|
* @param String name Header name
|
|
* @return String|Undefined
|
|
*/
|
|
function find(map, name) {
|
|
name = name.toLowerCase();
|
|
for (const key in map) {
|
|
if (key.toLowerCase() === name) {
|
|
return key;
|
|
}
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
const MAP = Symbol('map');
|
|
class Headers {
|
|
/**
|
|
* Headers class
|
|
*
|
|
* @param Object headers Response headers
|
|
* @return Void
|
|
*/
|
|
constructor() {
|
|
let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
|
|
|
|
this[MAP] = 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;
|
|
}
|
|
|
|
// We don't worry about converting prop to ByteString here as append()
|
|
// will handle it.
|
|
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');
|
|
}
|
|
|
|
// sequence<sequence<ByteString>>
|
|
// Note: per spec we have to first exhaust the lists then process them
|
|
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 {
|
|
// record<ByteString, ByteString>
|
|
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');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Return combined header value given name
|
|
*
|
|
* @param String name Header name
|
|
* @return Mixed
|
|
*/
|
|
get(name) {
|
|
name = `${name}`;
|
|
validateName(name);
|
|
const key = find(this[MAP], name);
|
|
if (key === undefined) {
|
|
return null;
|
|
}
|
|
|
|
return this[MAP][key].join(', ');
|
|
}
|
|
|
|
/**
|
|
* Iterate over all headers
|
|
*
|
|
* @param Function callback Executed for each item with parameters (value, name, thisArg)
|
|
* @param Boolean thisArg `this` context for callback function
|
|
* @return Void
|
|
*/
|
|
forEach(callback) {
|
|
let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
|
|
|
|
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++;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Overwrite header values given name
|
|
*
|
|
* @param String name Header name
|
|
* @param String value Header value
|
|
* @return Void
|
|
*/
|
|
set(name, value) {
|
|
name = `${name}`;
|
|
value = `${value}`;
|
|
validateName(name);
|
|
validateValue(value);
|
|
const key = find(this[MAP], name);
|
|
this[MAP][key !== undefined ? key : name] = [value];
|
|
}
|
|
|
|
/**
|
|
* Append a value onto existing header
|
|
*
|
|
* @param String name Header name
|
|
* @param String value Header value
|
|
* @return Void
|
|
*/
|
|
append(name, value) {
|
|
name = `${name}`;
|
|
value = `${value}`;
|
|
validateName(name);
|
|
validateValue(value);
|
|
const key = find(this[MAP], name);
|
|
if (key !== undefined) {
|
|
this[MAP][key].push(value);
|
|
} else {
|
|
this[MAP][name] = [value];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check for header name existence
|
|
*
|
|
* @param String name Header name
|
|
* @return Boolean
|
|
*/
|
|
has(name) {
|
|
name = `${name}`;
|
|
validateName(name);
|
|
return find(this[MAP], name) !== undefined;
|
|
}
|
|
|
|
/**
|
|
* Delete all header values given name
|
|
*
|
|
* @param String name Header name
|
|
* @return Void
|
|
*/
|
|
delete(name) {
|
|
name = `${name}`;
|
|
validateName(name);
|
|
const key = find(this[MAP], name);
|
|
if (key !== undefined) {
|
|
delete this[MAP][key];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Return raw headers (non-spec api)
|
|
*
|
|
* @return Object
|
|
*/
|
|
raw() {
|
|
return this[MAP];
|
|
}
|
|
|
|
/**
|
|
* Get an iterator on keys.
|
|
*
|
|
* @return Iterator
|
|
*/
|
|
keys() {
|
|
return createHeadersIterator(this, 'key');
|
|
}
|
|
|
|
/**
|
|
* Get an iterator on values.
|
|
*
|
|
* @return Iterator
|
|
*/
|
|
values() {
|
|
return createHeadersIterator(this, 'value');
|
|
}
|
|
|
|
/**
|
|
* Get an iterator on entries.
|
|
*
|
|
* This is the default iterator of the Headers object.
|
|
*
|
|
* @return Iterator
|
|
*/
|
|
[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] !== undefined ? 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(', ')];
|
|
});
|
|
}
|
|
|
|
const INTERNAL = Symbol('internal');
|
|
|
|
function createHeadersIterator(target, kind) {
|
|
const iterator = Object.create(HeadersIteratorPrototype);
|
|
iterator[INTERNAL] = {
|
|
target,
|
|
kind,
|
|
index: 0
|
|
};
|
|
return iterator;
|
|
}
|
|
|
|
const HeadersIteratorPrototype = Object.setPrototypeOf({
|
|
next() {
|
|
// istanbul ignore if
|
|
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: undefined,
|
|
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
|
|
});
|
|
|
|
/**
|
|
* Export the Headers object in a form that Node.js can consume.
|
|
*
|
|
* @param Headers headers
|
|
* @return Object
|
|
*/
|
|
function exportNodeCompatibleHeaders(headers) {
|
|
const obj = Object.assign({ __proto__: null }, headers[MAP]);
|
|
|
|
// http.request() only supports string as Host header. This hack makes
|
|
// specifying custom Host header possible.
|
|
const hostHeaderKey = find(headers[MAP], 'Host');
|
|
if (hostHeaderKey !== undefined) {
|
|
obj[hostHeaderKey] = obj[hostHeaderKey][0];
|
|
}
|
|
|
|
return obj;
|
|
}
|
|
|
|
/**
|
|
* Create a Headers object from an object of headers, ignoring those that do
|
|
* not conform to HTTP grammar productions.
|
|
*
|
|
* @param Object obj Object of headers
|
|
* @return Headers
|
|
*/
|
|
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] === undefined) {
|
|
headers[MAP][name] = [val];
|
|
} else {
|
|
headers[MAP][name].push(val);
|
|
}
|
|
}
|
|
} else if (!invalidHeaderCharRegex.test(obj[name])) {
|
|
headers[MAP][name] = [obj[name]];
|
|
}
|
|
}
|
|
return headers;
|
|
}
|
|
|
|
const INTERNALS$1 = Symbol('Response internals');
|
|
|
|
// fix an issue where "STATUS_CODES" aren't a named export for node <10
|
|
const STATUS_CODES = http.STATUS_CODES;
|
|
|
|
/**
|
|
* Response class
|
|
*
|
|
* @param Stream body Readable stream
|
|
* @param Object opts Response options
|
|
* @return Void
|
|
*/
|
|
class Response {
|
|
constructor() {
|
|
let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
|
|
let opts = arguments.length > 1 && arguments[1] !== undefined ? 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;
|
|
}
|
|
|
|
/**
|
|
* Convenience property representing if the request ended normally
|
|
*/
|
|
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 this response
|
|
*
|
|
* @return Response
|
|
*/
|
|
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
|
|
});
|
|
|
|
const INTERNALS$2 = Symbol('Request internals');
|
|
|
|
// fix an issue where "format", "parse" aren't a named export for node <10
|
|
const parse_url = Url.parse;
|
|
const format_url = Url.format;
|
|
|
|
const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
|
|
|
|
/**
|
|
* Check if a value is an instance of Request.
|
|
*
|
|
* @param Mixed input
|
|
* @return Boolean
|
|
*/
|
|
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');
|
|
}
|
|
|
|
/**
|
|
* Request class
|
|
*
|
|
* @param Mixed input Url or Request instance
|
|
* @param Object init Custom options
|
|
* @return Void
|
|
*/
|
|
class Request {
|
|
constructor(input) {
|
|
let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
|
|
let parsedURL;
|
|
|
|
// normalize input
|
|
if (!isRequest(input)) {
|
|
if (input && input.href) {
|
|
// in order to support Node.js' Url objects; though WHATWG's URL objects
|
|
// will fall into this branch also (since their `toString()` will return
|
|
// `href` property anyway)
|
|
parsedURL = parse_url(input.href);
|
|
} else {
|
|
// coerce input to a string before attempting to parse
|
|
parsedURL = parse_url(`${input}`);
|
|
}
|
|
input = {};
|
|
} else {
|
|
parsedURL = parse_url(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
|
|
};
|
|
|
|
// node-fetch-only options
|
|
this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
|
|
this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? 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 this request
|
|
*
|
|
* @return Request
|
|
*/
|
|
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 }
|
|
});
|
|
|
|
/**
|
|
* Convert a Request to Node.js http request options.
|
|
*
|
|
* @param Request A Request instance
|
|
* @return Object The options object to be passed to http.request
|
|
*/
|
|
function getNodeRequestOptions(request) {
|
|
const parsedURL = request[INTERNALS$2].parsedURL;
|
|
const headers = new Headers(request[INTERNALS$2].headers);
|
|
|
|
// fetch step 1.3
|
|
if (!headers.has('Accept')) {
|
|
headers.set('Accept', '*/*');
|
|
}
|
|
|
|
// Basic fetch
|
|
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');
|
|
}
|
|
|
|
// HTTP-network-or-cache fetch steps 2.4-2.7
|
|
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);
|
|
}
|
|
|
|
// HTTP-network-or-cache fetch step 2.11
|
|
if (!headers.has('User-Agent')) {
|
|
headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
|
|
}
|
|
|
|
// HTTP-network-or-cache fetch step 2.15
|
|
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');
|
|
}
|
|
|
|
// HTTP-network fetch step 4.2
|
|
// chunked encoding is handled by Node.js
|
|
|
|
return Object.assign({}, parsedURL, {
|
|
method: request.method,
|
|
headers: exportNodeCompatibleHeaders(headers),
|
|
agent
|
|
});
|
|
}
|
|
|
|
/**
|
|
* abort-error.js
|
|
*
|
|
* AbortError interface for cancelled requests
|
|
*/
|
|
|
|
/**
|
|
* Create AbortError instance
|
|
*
|
|
* @param String message Error message for human
|
|
* @return AbortError
|
|
*/
|
|
function AbortError(message) {
|
|
Error.call(this, message);
|
|
|
|
this.type = 'aborted';
|
|
this.message = message;
|
|
|
|
// hide custom error implementation details from end-users
|
|
Error.captureStackTrace(this, this.constructor);
|
|
}
|
|
|
|
AbortError.prototype = Object.create(Error.prototype);
|
|
AbortError.prototype.constructor = AbortError;
|
|
AbortError.prototype.name = 'AbortError';
|
|
|
|
// fix an issue where "PassThrough", "resolve" aren't a named export for node <10
|
|
const PassThrough$1 = Stream.PassThrough;
|
|
const resolve_url = Url.resolve;
|
|
|
|
/**
|
|
* Fetch function
|
|
*
|
|
* @param Mixed url Absolute url or Request instance
|
|
* @param Object opts Fetch options
|
|
* @return Promise
|
|
*/
|
|
function fetch(url, opts) {
|
|
|
|
// allow custom promise
|
|
if (!fetch.Promise) {
|
|
throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
|
|
}
|
|
|
|
Body.Promise = fetch.Promise;
|
|
|
|
// wrap http.request into fetch
|
|
return new fetch.Promise(function (resolve, reject) {
|
|
// build request object
|
|
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 abort() {
|
|
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 abortAndFinalize() {
|
|
abort();
|
|
finalize();
|
|
};
|
|
|
|
// send request
|
|
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);
|
|
|
|
// HTTP fetch step 5
|
|
if (fetch.isRedirect(res.statusCode)) {
|
|
// HTTP fetch step 5.2
|
|
const location = headers.get('Location');
|
|
|
|
// HTTP fetch step 5.3
|
|
const locationURL = location === null ? null : resolve_url(request.url, location);
|
|
|
|
// HTTP fetch step 5.5
|
|
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':
|
|
// node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
|
|
if (locationURL !== null) {
|
|
// handle corrupted header
|
|
try {
|
|
headers.set('Location', locationURL);
|
|
} catch (err) {
|
|
// istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
|
|
reject(err);
|
|
}
|
|
}
|
|
break;
|
|
case 'follow':
|
|
// HTTP-redirect fetch step 2
|
|
if (locationURL === null) {
|
|
break;
|
|
}
|
|
|
|
// HTTP-redirect fetch step 5
|
|
if (request.counter >= request.follow) {
|
|
reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
|
|
finalize();
|
|
return;
|
|
}
|
|
|
|
// HTTP-redirect fetch step 6 (counter increment)
|
|
// Create a new Request object.
|
|
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
|
|
};
|
|
|
|
// HTTP-redirect fetch step 9
|
|
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;
|
|
}
|
|
|
|
// HTTP-redirect fetch step 11
|
|
if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
|
|
requestOpts.method = 'GET';
|
|
requestOpts.body = undefined;
|
|
requestOpts.headers.delete('content-length');
|
|
}
|
|
|
|
// HTTP-redirect fetch step 15
|
|
resolve(fetch(new Request(locationURL, requestOpts)));
|
|
finalize();
|
|
return;
|
|
}
|
|
}
|
|
|
|
// prepare response
|
|
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: headers,
|
|
size: request.size,
|
|
timeout: request.timeout,
|
|
counter: request.counter
|
|
};
|
|
|
|
// HTTP-network fetch step 12.1.1.3
|
|
const codings = headers.get('Content-Encoding');
|
|
|
|
// HTTP-network fetch step 12.1.1.4: handle content codings
|
|
|
|
// in following scenarios we ignore compression support
|
|
// 1. compression support is disabled
|
|
// 2. HEAD request
|
|
// 3. no Content-Encoding header
|
|
// 4. no content response (204)
|
|
// 5. content not modified response (304)
|
|
if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
|
|
response = new Response(body, response_options);
|
|
resolve(response);
|
|
return;
|
|
}
|
|
|
|
// For Node v6+
|
|
// Be less strict when decoding compressed responses, since sometimes
|
|
// servers send slightly invalid responses that are still accepted
|
|
// by common browsers.
|
|
// Always using Z_SYNC_FLUSH is what cURL does.
|
|
const zlibOptions = {
|
|
flush: zlib.Z_SYNC_FLUSH,
|
|
finishFlush: zlib.Z_SYNC_FLUSH
|
|
};
|
|
|
|
// for gzip
|
|
if (codings == 'gzip' || codings == 'x-gzip') {
|
|
body = body.pipe(zlib.createGunzip(zlibOptions));
|
|
response = new Response(body, response_options);
|
|
resolve(response);
|
|
return;
|
|
}
|
|
|
|
// for deflate
|
|
if (codings == 'deflate' || codings == 'x-deflate') {
|
|
// handle the infamous raw deflate response from old servers
|
|
// a hack for old IIS and Apache servers
|
|
const raw = res.pipe(new PassThrough$1());
|
|
raw.once('data', function (chunk) {
|
|
// see http://stackoverflow.com/questions/37519828
|
|
if ((chunk[0] & 0x0F) === 0x08) {
|
|
body = body.pipe(zlib.createInflate());
|
|
} else {
|
|
body = body.pipe(zlib.createInflateRaw());
|
|
}
|
|
response = new Response(body, response_options);
|
|
resolve(response);
|
|
});
|
|
return;
|
|
}
|
|
|
|
// for br
|
|
if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
|
|
body = body.pipe(zlib.createBrotliDecompress());
|
|
response = new Response(body, response_options);
|
|
resolve(response);
|
|
return;
|
|
}
|
|
|
|
// otherwise, use response as-is
|
|
response = new Response(body, response_options);
|
|
resolve(response);
|
|
});
|
|
|
|
writeToStream(req, request);
|
|
});
|
|
}
|
|
/**
|
|
* Redirect code matching
|
|
*
|
|
* @param Number code Status code
|
|
* @return Boolean
|
|
*/
|
|
fetch.isRedirect = function (code) {
|
|
return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
|
|
};
|
|
|
|
// expose Promise
|
|
fetch.Promise = global.Promise;
|
|
|
|
module.exports = exports = fetch;
|
|
Object.defineProperty(exports, "__esModule", ({ value: true }));
|
|
exports.default = exports;
|
|
exports.Headers = Headers;
|
|
exports.Request = Request;
|
|
exports.Response = Response;
|
|
exports.FetchError = FetchError;
|
|
|
|
|
|
/***/ }),
|
|
|
|
/***/ 294:
|
|
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
|
|
|
|
module.exports = __nccwpck_require__(219);
|
|
|
|
|
|
/***/ }),
|
|
|
|
/***/ 219:
|
|
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
|
|
|
|
"use strict";
|
|
|
|
|
|
var net = __nccwpck_require__(631);
|
|
var tls = __nccwpck_require__(16);
|
|
var http = __nccwpck_require__(605);
|
|
var https = __nccwpck_require__(211);
|
|
var events = __nccwpck_require__(614);
|
|
var assert = __nccwpck_require__(357);
|
|
var util = __nccwpck_require__(669);
|
|
|
|
|
|
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 options = toOptions(host, port, localAddress);
|
|
for (var i = 0, len = self.requests.length; i < len; ++i) {
|
|
var pending = self.requests[i];
|
|
if (pending.host === options.host && pending.port === options.port) {
|
|
// Detect the request to connect same origin server,
|
|
// reuse the connection.
|
|
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) {
|
|
// We are over limit so we'll add it to the queue.
|
|
self.requests.push(options);
|
|
return;
|
|
}
|
|
|
|
// If we are under maxSockets create a new one.
|
|
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; // for v0.6
|
|
connectReq.once('response', onResponse); // for v0.6
|
|
connectReq.once('upgrade', onUpgrade); // for v0.6
|
|
connectReq.once('connect', onConnect); // for v0.7 or later
|
|
connectReq.once('error', onError);
|
|
connectReq.end();
|
|
|
|
function onResponse(res) {
|
|
// Very hacky. This is necessary to avoid http-parser leaks.
|
|
res.upgrade = true;
|
|
}
|
|
|
|
function onUpgrade(res, socket, head) {
|
|
// Hacky.
|
|
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);
|
|
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);
|
|
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) {
|
|
// If we have pending requests and a socket gets closed a new one
|
|
// needs to be created to take over in the pool for the one that closed.
|
|
this.createSocket(pending, function(socket) {
|
|
pending.request.onSocket(socket);
|
|
});
|
|
}
|
|
};
|
|
|
|
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: socket,
|
|
servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host
|
|
});
|
|
|
|
// 0 is dummy port for v0.6
|
|
var secureSocket = tls.connect(0, tlsOptions);
|
|
self.sockets[self.sockets.indexOf(socket)] = secureSocket;
|
|
cb(secureSocket);
|
|
});
|
|
}
|
|
|
|
|
|
function toOptions(host, port, localAddress) {
|
|
if (typeof host === 'string') { // since v0.10
|
|
return {
|
|
host: host,
|
|
port: port,
|
|
localAddress: localAddress
|
|
};
|
|
}
|
|
return host; // for v0.11 or later
|
|
}
|
|
|
|
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] !== undefined) {
|
|
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; // for test
|
|
|
|
|
|
/***/ }),
|
|
|
|
/***/ 877:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = eval("require")("encoding");
|
|
|
|
|
|
/***/ }),
|
|
|
|
/***/ 357:
|
|
/***/ ((module) => {
|
|
|
|
"use strict";
|
|
module.exports = require("assert");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 614:
|
|
/***/ ((module) => {
|
|
|
|
"use strict";
|
|
module.exports = require("events");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 747:
|
|
/***/ ((module) => {
|
|
|
|
"use strict";
|
|
module.exports = require("fs");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 605:
|
|
/***/ ((module) => {
|
|
|
|
"use strict";
|
|
module.exports = require("http");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 211:
|
|
/***/ ((module) => {
|
|
|
|
"use strict";
|
|
module.exports = require("https");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 631:
|
|
/***/ ((module) => {
|
|
|
|
"use strict";
|
|
module.exports = require("net");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 87:
|
|
/***/ ((module) => {
|
|
|
|
"use strict";
|
|
module.exports = require("os");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 622:
|
|
/***/ ((module) => {
|
|
|
|
"use strict";
|
|
module.exports = require("path");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 413:
|
|
/***/ ((module) => {
|
|
|
|
"use strict";
|
|
module.exports = require("stream");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 16:
|
|
/***/ ((module) => {
|
|
|
|
"use strict";
|
|
module.exports = require("tls");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 835:
|
|
/***/ ((module) => {
|
|
|
|
"use strict";
|
|
module.exports = require("url");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 669:
|
|
/***/ ((module) => {
|
|
|
|
"use strict";
|
|
module.exports = require("util");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 761:
|
|
/***/ ((module) => {
|
|
|
|
"use strict";
|
|
module.exports = require("zlib");
|
|
|
|
/***/ })
|
|
|
|
/******/ });
|
|
/************************************************************************/
|
|
/******/ // The module cache
|
|
/******/ var __webpack_module_cache__ = {};
|
|
/******/
|
|
/******/ // The require function
|
|
/******/ function __nccwpck_require__(moduleId) {
|
|
/******/ // Check if module is in cache
|
|
/******/ var cachedModule = __webpack_module_cache__[moduleId];
|
|
/******/ if (cachedModule !== undefined) {
|
|
/******/ return cachedModule.exports;
|
|
/******/ }
|
|
/******/ // Create a new module (and put it into the cache)
|
|
/******/ var module = __webpack_module_cache__[moduleId] = {
|
|
/******/ // no module.id needed
|
|
/******/ // no module.loaded needed
|
|
/******/ exports: {}
|
|
/******/ };
|
|
/******/
|
|
/******/ // Execute the module function
|
|
/******/ var threw = true;
|
|
/******/ try {
|
|
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__);
|
|
/******/ threw = false;
|
|
/******/ } finally {
|
|
/******/ if(threw) delete __webpack_module_cache__[moduleId];
|
|
/******/ }
|
|
/******/
|
|
/******/ // Return the exports of the module
|
|
/******/ return module.exports;
|
|
/******/ }
|
|
/******/
|
|
/************************************************************************/
|
|
/******/ /* webpack/runtime/compat */
|
|
/******/
|
|
/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/";
|
|
/******/
|
|
/************************************************************************/
|
|
/******/
|
|
/******/ // startup
|
|
/******/ // Load entry module and return exports
|
|
/******/ // This entry module is referenced by other modules so it can't be inlined
|
|
/******/ var __webpack_exports__ = __nccwpck_require__(109);
|
|
/******/ module.exports = __webpack_exports__;
|
|
/******/
|
|
/******/ })()
|
|
; |