3344 lines
282 KiB
JavaScript
3344 lines
282 KiB
JavaScript
|
/*
|
||
|
THIS IS A GENERATED/BUNDLED FILE BY ROLLUP
|
||
|
if you want to view the source visit the plugins github repository
|
||
|
*/
|
||
|
|
||
|
'use strict';
|
||
|
|
||
|
var obsidian = require('obsidian');
|
||
|
var child_process = require('child_process');
|
||
|
var require$$0$1 = require('fs');
|
||
|
var url = require('url');
|
||
|
var http = require('http');
|
||
|
var https = require('https');
|
||
|
var require$$0 = require('util');
|
||
|
var path = require('path');
|
||
|
var zlib = require('zlib');
|
||
|
require('net');
|
||
|
var tls = require('tls');
|
||
|
var events = require('events');
|
||
|
require('assert');
|
||
|
var os = require('os');
|
||
|
|
||
|
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
||
|
|
||
|
var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
|
||
|
var url__default = /*#__PURE__*/_interopDefaultLegacy(url);
|
||
|
var http__default = /*#__PURE__*/_interopDefaultLegacy(http);
|
||
|
var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
|
||
|
var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
|
||
|
var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
|
||
|
var zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib);
|
||
|
var tls__default = /*#__PURE__*/_interopDefaultLegacy(tls);
|
||
|
var events__default = /*#__PURE__*/_interopDefaultLegacy(events);
|
||
|
|
||
|
/*! *****************************************************************************
|
||
|
Copyright (c) Microsoft Corporation.
|
||
|
|
||
|
Permission to use, copy, modify, and/or distribute this software for any
|
||
|
purpose with or without fee is hereby granted.
|
||
|
|
||
|
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||
|
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||
|
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||
|
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||
|
PERFORMANCE OF THIS SOFTWARE.
|
||
|
***************************************************************************** */
|
||
|
|
||
|
function __awaiter$1(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());
|
||
|
});
|
||
|
}
|
||
|
|
||
|
// Unique ID creation requires a high quality random # generator. In the browser we therefore
|
||
|
// require the crypto API and do not support built-in fallback to lower quality random number
|
||
|
// generators (like Math.random()).
|
||
|
var getRandomValues;
|
||
|
var rnds8 = new Uint8Array(16);
|
||
|
function rng() {
|
||
|
// lazy load so that environments that need to polyfill have a chance to do so
|
||
|
if (!getRandomValues) {
|
||
|
// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
|
||
|
// find the complete implementation of crypto (msCrypto) on IE11.
|
||
|
getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
|
||
|
|
||
|
if (!getRandomValues) {
|
||
|
throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return getRandomValues(rnds8);
|
||
|
}
|
||
|
|
||
|
var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
|
||
|
|
||
|
function validate(uuid) {
|
||
|
return typeof uuid === 'string' && REGEX.test(uuid);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Convert array of 16 byte values to UUID string format of the form:
|
||
|
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
|
||
|
*/
|
||
|
|
||
|
var byteToHex = [];
|
||
|
|
||
|
for (var i = 0; i < 256; ++i) {
|
||
|
byteToHex.push((i + 0x100).toString(16).substr(1));
|
||
|
}
|
||
|
|
||
|
function stringify$1(arr) {
|
||
|
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
|
||
|
// Note: Be careful editing this code! It's been tuned for performance
|
||
|
// and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
|
||
|
var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
|
||
|
// of the following:
|
||
|
// - One or more input array values don't map to a hex octet (leading to
|
||
|
// "undefined" in the uuid)
|
||
|
// - Invalid input values for the RFC `version` or `variant` fields
|
||
|
|
||
|
if (!validate(uuid)) {
|
||
|
throw TypeError('Stringified UUID is invalid');
|
||
|
}
|
||
|
|
||
|
return uuid;
|
||
|
}
|
||
|
|
||
|
function v4(options, buf, offset) {
|
||
|
options = options || {};
|
||
|
var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
|
||
|
|
||
|
rnds[6] = rnds[6] & 0x0f | 0x40;
|
||
|
rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
|
||
|
|
||
|
if (buf) {
|
||
|
offset = offset || 0;
|
||
|
|
||
|
for (var i = 0; i < 16; ++i) {
|
||
|
buf[offset + i] = rnds[i];
|
||
|
}
|
||
|
|
||
|
return buf;
|
||
|
}
|
||
|
|
||
|
return stringify$1(rnds);
|
||
|
}
|
||
|
|
||
|
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
|
||
|
|
||
|
function createCommonjsModule(fn) {
|
||
|
var module = { exports: {} };
|
||
|
return fn(module, module.exports), module.exports;
|
||
|
}
|
||
|
|
||
|
/* eslint complexity: [2, 18], max-statements: [2, 33] */
|
||
|
var shams = function hasSymbols() {
|
||
|
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
|
||
|
if (typeof Symbol.iterator === 'symbol') { return true; }
|
||
|
|
||
|
var obj = {};
|
||
|
var sym = Symbol('test');
|
||
|
var symObj = Object(sym);
|
||
|
if (typeof sym === 'string') { return false; }
|
||
|
|
||
|
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
|
||
|
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
|
||
|
|
||
|
// temp disabled per https://github.com/ljharb/object.assign/issues/17
|
||
|
// if (sym instanceof Symbol) { return false; }
|
||
|
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
|
||
|
// if (!(symObj instanceof Symbol)) { return false; }
|
||
|
|
||
|
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
|
||
|
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
|
||
|
|
||
|
var symVal = 42;
|
||
|
obj[sym] = symVal;
|
||
|
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
|
||
|
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
|
||
|
|
||
|
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
|
||
|
|
||
|
var syms = Object.getOwnPropertySymbols(obj);
|
||
|
if (syms.length !== 1 || syms[0] !== sym) { return false; }
|
||
|
|
||
|
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
|
||
|
|
||
|
if (typeof Object.getOwnPropertyDescriptor === 'function') {
|
||
|
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
|
||
|
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
|
||
|
}
|
||
|
|
||
|
return true;
|
||
|
};
|
||
|
|
||
|
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
|
||
|
|
||
|
|
||
|
var hasSymbols$1 = function hasNativeSymbols() {
|
||
|
if (typeof origSymbol !== 'function') { return false; }
|
||
|
if (typeof Symbol !== 'function') { return false; }
|
||
|
if (typeof origSymbol('foo') !== 'symbol') { return false; }
|
||
|
if (typeof Symbol('bar') !== 'symbol') { return false; }
|
||
|
|
||
|
return shams();
|
||
|
};
|
||
|
|
||
|
/* eslint no-invalid-this: 1 */
|
||
|
|
||
|
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
|
||
|
var slice = Array.prototype.slice;
|
||
|
var toStr$1 = Object.prototype.toString;
|
||
|
var funcType = '[object Function]';
|
||
|
|
||
|
var implementation = function bind(that) {
|
||
|
var target = this;
|
||
|
if (typeof target !== 'function' || toStr$1.call(target) !== funcType) {
|
||
|
throw new TypeError(ERROR_MESSAGE + target);
|
||
|
}
|
||
|
var args = slice.call(arguments, 1);
|
||
|
|
||
|
var bound;
|
||
|
var binder = function () {
|
||
|
if (this instanceof bound) {
|
||
|
var result = target.apply(
|
||
|
this,
|
||
|
args.concat(slice.call(arguments))
|
||
|
);
|
||
|
if (Object(result) === result) {
|
||
|
return result;
|
||
|
}
|
||
|
return this;
|
||
|
} else {
|
||
|
return target.apply(
|
||
|
that,
|
||
|
args.concat(slice.call(arguments))
|
||
|
);
|
||
|
}
|
||
|
};
|
||
|
|
||
|
var boundLength = Math.max(0, target.length - args.length);
|
||
|
var boundArgs = [];
|
||
|
for (var i = 0; i < boundLength; i++) {
|
||
|
boundArgs.push('$' + i);
|
||
|
}
|
||
|
|
||
|
bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
|
||
|
|
||
|
if (target.prototype) {
|
||
|
var Empty = function Empty() {};
|
||
|
Empty.prototype = target.prototype;
|
||
|
bound.prototype = new Empty();
|
||
|
Empty.prototype = null;
|
||
|
}
|
||
|
|
||
|
return bound;
|
||
|
};
|
||
|
|
||
|
var functionBind = Function.prototype.bind || implementation;
|
||
|
|
||
|
var src = functionBind.call(Function.call, Object.prototype.hasOwnProperty);
|
||
|
|
||
|
var undefined$1;
|
||
|
|
||
|
var $SyntaxError = SyntaxError;
|
||
|
var $Function = Function;
|
||
|
var $TypeError$1 = TypeError;
|
||
|
|
||
|
// eslint-disable-next-line consistent-return
|
||
|
var getEvalledConstructor = function (expressionSyntax) {
|
||
|
try {
|
||
|
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
|
||
|
} catch (e) {}
|
||
|
};
|
||
|
|
||
|
var $gOPD = Object.getOwnPropertyDescriptor;
|
||
|
if ($gOPD) {
|
||
|
try {
|
||
|
$gOPD({}, '');
|
||
|
} catch (e) {
|
||
|
$gOPD = null; // this is IE 8, which has a broken gOPD
|
||
|
}
|
||
|
}
|
||
|
|
||
|
var throwTypeError = function () {
|
||
|
throw new $TypeError$1();
|
||
|
};
|
||
|
var ThrowTypeError = $gOPD
|
||
|
? (function () {
|
||
|
try {
|
||
|
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
|
||
|
arguments.callee; // IE 8 does not throw here
|
||
|
return throwTypeError;
|
||
|
} catch (calleeThrows) {
|
||
|
try {
|
||
|
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
|
||
|
return $gOPD(arguments, 'callee').get;
|
||
|
} catch (gOPDthrows) {
|
||
|
return throwTypeError;
|
||
|
}
|
||
|
}
|
||
|
}())
|
||
|
: throwTypeError;
|
||
|
|
||
|
var hasSymbols = hasSymbols$1();
|
||
|
|
||
|
var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
|
||
|
|
||
|
var needsEval = {};
|
||
|
|
||
|
var TypedArray = typeof Uint8Array === 'undefined' ? undefined$1 : getProto(Uint8Array);
|
||
|
|
||
|
var INTRINSICS = {
|
||
|
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined$1 : AggregateError,
|
||
|
'%Array%': Array,
|
||
|
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer,
|
||
|
'%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined$1,
|
||
|
'%AsyncFromSyncIteratorPrototype%': undefined$1,
|
||
|
'%AsyncFunction%': needsEval,
|
||
|
'%AsyncGenerator%': needsEval,
|
||
|
'%AsyncGeneratorFunction%': needsEval,
|
||
|
'%AsyncIteratorPrototype%': needsEval,
|
||
|
'%Atomics%': typeof Atomics === 'undefined' ? undefined$1 : Atomics,
|
||
|
'%BigInt%': typeof BigInt === 'undefined' ? undefined$1 : BigInt,
|
||
|
'%Boolean%': Boolean,
|
||
|
'%DataView%': typeof DataView === 'undefined' ? undefined$1 : DataView,
|
||
|
'%Date%': Date,
|
||
|
'%decodeURI%': decodeURI,
|
||
|
'%decodeURIComponent%': decodeURIComponent,
|
||
|
'%encodeURI%': encodeURI,
|
||
|
'%encodeURIComponent%': encodeURIComponent,
|
||
|
'%Error%': Error,
|
||
|
'%eval%': eval, // eslint-disable-line no-eval
|
||
|
'%EvalError%': EvalError,
|
||
|
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array,
|
||
|
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array,
|
||
|
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined$1 : FinalizationRegistry,
|
||
|
'%Function%': $Function,
|
||
|
'%GeneratorFunction%': needsEval,
|
||
|
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array,
|
||
|
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined$1 : Int16Array,
|
||
|
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array,
|
||
|
'%isFinite%': isFinite,
|
||
|
'%isNaN%': isNaN,
|
||
|
'%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined$1,
|
||
|
'%JSON%': typeof JSON === 'object' ? JSON : undefined$1,
|
||
|
'%Map%': typeof Map === 'undefined' ? undefined$1 : Map,
|
||
|
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined$1 : getProto(new Map()[Symbol.iterator]()),
|
||
|
'%Math%': Math,
|
||
|
'%Number%': Number,
|
||
|
'%Object%': Object,
|
||
|
'%parseFloat%': parseFloat,
|
||
|
'%parseInt%': parseInt,
|
||
|
'%Promise%': typeof Promise === 'undefined' ? undefined$1 : Promise,
|
||
|
'%Proxy%': typeof Proxy === 'undefined' ? undefined$1 : Proxy,
|
||
|
'%RangeError%': RangeError,
|
||
|
'%ReferenceError%': ReferenceError,
|
||
|
'%Reflect%': typeof Reflect === 'undefined' ? undefined$1 : Reflect,
|
||
|
'%RegExp%': RegExp,
|
||
|
'%Set%': typeof Set === 'undefined' ? undefined$1 : Set,
|
||
|
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined$1 : getProto(new Set()[Symbol.iterator]()),
|
||
|
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer,
|
||
|
'%String%': String,
|
||
|
'%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined$1,
|
||
|
'%Symbol%': hasSymbols ? Symbol : undefined$1,
|
||
|
'%SyntaxError%': $SyntaxError,
|
||
|
'%ThrowTypeError%': ThrowTypeError,
|
||
|
'%TypedArray%': TypedArray,
|
||
|
'%TypeError%': $TypeError$1,
|
||
|
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array,
|
||
|
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray,
|
||
|
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array,
|
||
|
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array,
|
||
|
'%URIError%': URIError,
|
||
|
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap,
|
||
|
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined$1 : WeakRef,
|
||
|
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet
|
||
|
};
|
||
|
|
||
|
var doEval = function doEval(name) {
|
||
|
var value;
|
||
|
if (name === '%AsyncFunction%') {
|
||
|
value = getEvalledConstructor('async function () {}');
|
||
|
} else if (name === '%GeneratorFunction%') {
|
||
|
value = getEvalledConstructor('function* () {}');
|
||
|
} else if (name === '%AsyncGeneratorFunction%') {
|
||
|
value = getEvalledConstructor('async function* () {}');
|
||
|
} else if (name === '%AsyncGenerator%') {
|
||
|
var fn = doEval('%AsyncGeneratorFunction%');
|
||
|
if (fn) {
|
||
|
value = fn.prototype;
|
||
|
}
|
||
|
} else if (name === '%AsyncIteratorPrototype%') {
|
||
|
var gen = doEval('%AsyncGenerator%');
|
||
|
if (gen) {
|
||
|
value = getProto(gen.prototype);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
INTRINSICS[name] = value;
|
||
|
|
||
|
return value;
|
||
|
};
|
||
|
|
||
|
var LEGACY_ALIASES = {
|
||
|
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
|
||
|
'%ArrayPrototype%': ['Array', 'prototype'],
|
||
|
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
|
||
|
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
|
||
|
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
|
||
|
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
|
||
|
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
|
||
|
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
|
||
|
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
|
||
|
'%BooleanPrototype%': ['Boolean', 'prototype'],
|
||
|
'%DataViewPrototype%': ['DataView', 'prototype'],
|
||
|
'%DatePrototype%': ['Date', 'prototype'],
|
||
|
'%ErrorPrototype%': ['Error', 'prototype'],
|
||
|
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
|
||
|
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
|
||
|
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
|
||
|
'%FunctionPrototype%': ['Function', 'prototype'],
|
||
|
'%Generator%': ['GeneratorFunction', 'prototype'],
|
||
|
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
|
||
|
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
|
||
|
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
|
||
|
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
|
||
|
'%JSONParse%': ['JSON', 'parse'],
|
||
|
'%JSONStringify%': ['JSON', 'stringify'],
|
||
|
'%MapPrototype%': ['Map', 'prototype'],
|
||
|
'%NumberPrototype%': ['Number', 'prototype'],
|
||
|
'%ObjectPrototype%': ['Object', 'prototype'],
|
||
|
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
|
||
|
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
|
||
|
'%PromisePrototype%': ['Promise', 'prototype'],
|
||
|
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
|
||
|
'%Promise_all%': ['Promise', 'all'],
|
||
|
'%Promise_reject%': ['Promise', 'reject'],
|
||
|
'%Promise_resolve%': ['Promise', 'resolve'],
|
||
|
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
|
||
|
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
|
||
|
'%RegExpPrototype%': ['RegExp', 'prototype'],
|
||
|
'%SetPrototype%': ['Set', 'prototype'],
|
||
|
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
|
||
|
'%StringPrototype%': ['String', 'prototype'],
|
||
|
'%SymbolPrototype%': ['Symbol', 'prototype'],
|
||
|
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
|
||
|
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
|
||
|
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
|
||
|
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
|
||
|
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
|
||
|
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
|
||
|
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
|
||
|
'%URIErrorPrototype%': ['URIError', 'prototype'],
|
||
|
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
|
||
|
'%WeakSetPrototype%': ['WeakSet', 'prototype']
|
||
|
};
|
||
|
|
||
|
|
||
|
|
||
|
var $concat$1 = functionBind.call(Function.call, Array.prototype.concat);
|
||
|
var $spliceApply = functionBind.call(Function.apply, Array.prototype.splice);
|
||
|
var $replace$1 = functionBind.call(Function.call, String.prototype.replace);
|
||
|
var $strSlice = functionBind.call(Function.call, String.prototype.slice);
|
||
|
|
||
|
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
|
||
|
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
|
||
|
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
|
||
|
var stringToPath = function stringToPath(string) {
|
||
|
var first = $strSlice(string, 0, 1);
|
||
|
var last = $strSlice(string, -1);
|
||
|
if (first === '%' && last !== '%') {
|
||
|
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
|
||
|
} else if (last === '%' && first !== '%') {
|
||
|
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
|
||
|
}
|
||
|
var result = [];
|
||
|
$replace$1(string, rePropName, function (match, number, quote, subString) {
|
||
|
result[result.length] = quote ? $replace$1(subString, reEscapeChar, '$1') : number || match;
|
||
|
});
|
||
|
return result;
|
||
|
};
|
||
|
/* end adaptation */
|
||
|
|
||
|
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
|
||
|
var intrinsicName = name;
|
||
|
var alias;
|
||
|
if (src(LEGACY_ALIASES, intrinsicName)) {
|
||
|
alias = LEGACY_ALIASES[intrinsicName];
|
||
|
intrinsicName = '%' + alias[0] + '%';
|
||
|
}
|
||
|
|
||
|
if (src(INTRINSICS, intrinsicName)) {
|
||
|
var value = INTRINSICS[intrinsicName];
|
||
|
if (value === needsEval) {
|
||
|
value = doEval(intrinsicName);
|
||
|
}
|
||
|
if (typeof value === 'undefined' && !allowMissing) {
|
||
|
throw new $TypeError$1('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
|
||
|
}
|
||
|
|
||
|
return {
|
||
|
alias: alias,
|
||
|
name: intrinsicName,
|
||
|
value: value
|
||
|
};
|
||
|
}
|
||
|
|
||
|
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
|
||
|
};
|
||
|
|
||
|
var getIntrinsic = function GetIntrinsic(name, allowMissing) {
|
||
|
if (typeof name !== 'string' || name.length === 0) {
|
||
|
throw new $TypeError$1('intrinsic name must be a non-empty string');
|
||
|
}
|
||
|
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
|
||
|
throw new $TypeError$1('"allowMissing" argument must be a boolean');
|
||
|
}
|
||
|
|
||
|
var parts = stringToPath(name);
|
||
|
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
|
||
|
|
||
|
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
|
||
|
var intrinsicRealName = intrinsic.name;
|
||
|
var value = intrinsic.value;
|
||
|
var skipFurtherCaching = false;
|
||
|
|
||
|
var alias = intrinsic.alias;
|
||
|
if (alias) {
|
||
|
intrinsicBaseName = alias[0];
|
||
|
$spliceApply(parts, $concat$1([0, 1], alias));
|
||
|
}
|
||
|
|
||
|
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
|
||
|
var part = parts[i];
|
||
|
var first = $strSlice(part, 0, 1);
|
||
|
var last = $strSlice(part, -1);
|
||
|
if (
|
||
|
(
|
||
|
(first === '"' || first === "'" || first === '`')
|
||
|
|| (last === '"' || last === "'" || last === '`')
|
||
|
)
|
||
|
&& first !== last
|
||
|
) {
|
||
|
throw new $SyntaxError('property names with quotes must have matching quotes');
|
||
|
}
|
||
|
if (part === 'constructor' || !isOwn) {
|
||
|
skipFurtherCaching = true;
|
||
|
}
|
||
|
|
||
|
intrinsicBaseName += '.' + part;
|
||
|
intrinsicRealName = '%' + intrinsicBaseName + '%';
|
||
|
|
||
|
if (src(INTRINSICS, intrinsicRealName)) {
|
||
|
value = INTRINSICS[intrinsicRealName];
|
||
|
} else if (value != null) {
|
||
|
if (!(part in value)) {
|
||
|
if (!allowMissing) {
|
||
|
throw new $TypeError$1('base intrinsic for ' + name + ' exists, but the property is not available.');
|
||
|
}
|
||
|
return void undefined$1;
|
||
|
}
|
||
|
if ($gOPD && (i + 1) >= parts.length) {
|
||
|
var desc = $gOPD(value, part);
|
||
|
isOwn = !!desc;
|
||
|
|
||
|
// By convention, when a data property is converted to an accessor
|
||
|
// property to emulate a data property that does not suffer from
|
||
|
// the override mistake, that accessor's getter is marked with
|
||
|
// an `originalValue` property. Here, when we detect this, we
|
||
|
// uphold the illusion by pretending to see that original data
|
||
|
// property, i.e., returning the value rather than the getter
|
||
|
// itself.
|
||
|
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
|
||
|
value = desc.get;
|
||
|
} else {
|
||
|
value = value[part];
|
||
|
}
|
||
|
} else {
|
||
|
isOwn = src(value, part);
|
||
|
value = value[part];
|
||
|
}
|
||
|
|
||
|
if (isOwn && !skipFurtherCaching) {
|
||
|
INTRINSICS[intrinsicRealName] = value;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
return value;
|
||
|
};
|
||
|
|
||
|
var callBind = createCommonjsModule(function (module) {
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
var $apply = getIntrinsic('%Function.prototype.apply%');
|
||
|
var $call = getIntrinsic('%Function.prototype.call%');
|
||
|
var $reflectApply = getIntrinsic('%Reflect.apply%', true) || functionBind.call($call, $apply);
|
||
|
|
||
|
var $gOPD = getIntrinsic('%Object.getOwnPropertyDescriptor%', true);
|
||
|
var $defineProperty = getIntrinsic('%Object.defineProperty%', true);
|
||
|
var $max = getIntrinsic('%Math.max%');
|
||
|
|
||
|
if ($defineProperty) {
|
||
|
try {
|
||
|
$defineProperty({}, 'a', { value: 1 });
|
||
|
} catch (e) {
|
||
|
// IE 8 has a broken defineProperty
|
||
|
$defineProperty = null;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
module.exports = function callBind(originalFunction) {
|
||
|
var func = $reflectApply(functionBind, $call, arguments);
|
||
|
if ($gOPD && $defineProperty) {
|
||
|
var desc = $gOPD(func, 'length');
|
||
|
if (desc.configurable) {
|
||
|
// original length, plus the receiver, minus any additional arguments (after the receiver)
|
||
|
$defineProperty(
|
||
|
func,
|
||
|
'length',
|
||
|
{ value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }
|
||
|
);
|
||
|
}
|
||
|
}
|
||
|
return func;
|
||
|
};
|
||
|
|
||
|
var applyBind = function applyBind() {
|
||
|
return $reflectApply(functionBind, $apply, arguments);
|
||
|
};
|
||
|
|
||
|
if ($defineProperty) {
|
||
|
$defineProperty(module.exports, 'apply', { value: applyBind });
|
||
|
} else {
|
||
|
module.exports.apply = applyBind;
|
||
|
}
|
||
|
});
|
||
|
|
||
|
var $indexOf = callBind(getIntrinsic('String.prototype.indexOf'));
|
||
|
|
||
|
var callBound = function callBoundIntrinsic(name, allowMissing) {
|
||
|
var intrinsic = getIntrinsic(name, !!allowMissing);
|
||
|
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
|
||
|
return callBind(intrinsic);
|
||
|
}
|
||
|
return intrinsic;
|
||
|
};
|
||
|
|
||
|
var util_inspect = require$$0__default["default"].inspect;
|
||
|
|
||
|
var hasMap = typeof Map === 'function' && Map.prototype;
|
||
|
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
|
||
|
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
|
||
|
var mapForEach = hasMap && Map.prototype.forEach;
|
||
|
var hasSet = typeof Set === 'function' && Set.prototype;
|
||
|
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
|
||
|
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
|
||
|
var setForEach = hasSet && Set.prototype.forEach;
|
||
|
var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;
|
||
|
var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
|
||
|
var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;
|
||
|
var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
|
||
|
var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype;
|
||
|
var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
|
||
|
var booleanValueOf = Boolean.prototype.valueOf;
|
||
|
var objectToString = Object.prototype.toString;
|
||
|
var functionToString = Function.prototype.toString;
|
||
|
var $match = String.prototype.match;
|
||
|
var $slice = String.prototype.slice;
|
||
|
var $replace = String.prototype.replace;
|
||
|
var $toUpperCase = String.prototype.toUpperCase;
|
||
|
var $toLowerCase = String.prototype.toLowerCase;
|
||
|
var $test = RegExp.prototype.test;
|
||
|
var $concat = Array.prototype.concat;
|
||
|
var $join = Array.prototype.join;
|
||
|
var $arrSlice = Array.prototype.slice;
|
||
|
var $floor = Math.floor;
|
||
|
var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;
|
||
|
var gOPS = Object.getOwnPropertySymbols;
|
||
|
var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null;
|
||
|
var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object';
|
||
|
// ie, `has-tostringtag/shams
|
||
|
var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol')
|
||
|
? Symbol.toStringTag
|
||
|
: null;
|
||
|
var isEnumerable = Object.prototype.propertyIsEnumerable;
|
||
|
|
||
|
var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || (
|
||
|
[].__proto__ === Array.prototype // eslint-disable-line no-proto
|
||
|
? function (O) {
|
||
|
return O.__proto__; // eslint-disable-line no-proto
|
||
|
}
|
||
|
: null
|
||
|
);
|
||
|
|
||
|
function addNumericSeparator(num, str) {
|
||
|
if (
|
||
|
num === Infinity
|
||
|
|| num === -Infinity
|
||
|
|| num !== num
|
||
|
|| (num && num > -1000 && num < 1000)
|
||
|
|| $test.call(/e/, str)
|
||
|
) {
|
||
|
return str;
|
||
|
}
|
||
|
var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;
|
||
|
if (typeof num === 'number') {
|
||
|
var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num)
|
||
|
if (int !== num) {
|
||
|
var intStr = String(int);
|
||
|
var dec = $slice.call(str, intStr.length + 1);
|
||
|
return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, '');
|
||
|
}
|
||
|
}
|
||
|
return $replace.call(str, sepRegex, '$&_');
|
||
|
}
|
||
|
|
||
|
var inspectCustom = util_inspect.custom;
|
||
|
var inspectSymbol = inspectCustom && isSymbol(inspectCustom) ? inspectCustom : null;
|
||
|
|
||
|
var objectInspect = function inspect_(obj, options, depth, seen) {
|
||
|
var opts = options || {};
|
||
|
|
||
|
if (has$3(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) {
|
||
|
throw new TypeError('option "quoteStyle" must be "single" or "double"');
|
||
|
}
|
||
|
if (
|
||
|
has$3(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number'
|
||
|
? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity
|
||
|
: opts.maxStringLength !== null
|
||
|
)
|
||
|
) {
|
||
|
throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
|
||
|
}
|
||
|
var customInspect = has$3(opts, 'customInspect') ? opts.customInspect : true;
|
||
|
if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') {
|
||
|
throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`');
|
||
|
}
|
||
|
|
||
|
if (
|
||
|
has$3(opts, 'indent')
|
||
|
&& opts.indent !== null
|
||
|
&& opts.indent !== '\t'
|
||
|
&& !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)
|
||
|
) {
|
||
|
throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');
|
||
|
}
|
||
|
if (has$3(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') {
|
||
|
throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');
|
||
|
}
|
||
|
var numericSeparator = opts.numericSeparator;
|
||
|
|
||
|
if (typeof obj === 'undefined') {
|
||
|
return 'undefined';
|
||
|
}
|
||
|
if (obj === null) {
|
||
|
return 'null';
|
||
|
}
|
||
|
if (typeof obj === 'boolean') {
|
||
|
return obj ? 'true' : 'false';
|
||
|
}
|
||
|
|
||
|
if (typeof obj === 'string') {
|
||
|
return inspectString(obj, opts);
|
||
|
}
|
||
|
if (typeof obj === 'number') {
|
||
|
if (obj === 0) {
|
||
|
return Infinity / obj > 0 ? '0' : '-0';
|
||
|
}
|
||
|
var str = String(obj);
|
||
|
return numericSeparator ? addNumericSeparator(obj, str) : str;
|
||
|
}
|
||
|
if (typeof obj === 'bigint') {
|
||
|
var bigIntStr = String(obj) + 'n';
|
||
|
return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;
|
||
|
}
|
||
|
|
||
|
var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
|
||
|
if (typeof depth === 'undefined') { depth = 0; }
|
||
|
if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
|
||
|
return isArray$3(obj) ? '[Array]' : '[Object]';
|
||
|
}
|
||
|
|
||
|
var indent = getIndent(opts, depth);
|
||
|
|
||
|
if (typeof seen === 'undefined') {
|
||
|
seen = [];
|
||
|
} else if (indexOf(seen, obj) >= 0) {
|
||
|
return '[Circular]';
|
||
|
}
|
||
|
|
||
|
function inspect(value, from, noIndent) {
|
||
|
if (from) {
|
||
|
seen = $arrSlice.call(seen);
|
||
|
seen.push(from);
|
||
|
}
|
||
|
if (noIndent) {
|
||
|
var newOpts = {
|
||
|
depth: opts.depth
|
||
|
};
|
||
|
if (has$3(opts, 'quoteStyle')) {
|
||
|
newOpts.quoteStyle = opts.quoteStyle;
|
||
|
}
|
||
|
return inspect_(value, newOpts, depth + 1, seen);
|
||
|
}
|
||
|
return inspect_(value, opts, depth + 1, seen);
|
||
|
}
|
||
|
|
||
|
if (typeof obj === 'function') {
|
||
|
var name = nameOf(obj);
|
||
|
var keys = arrObjKeys(obj, inspect);
|
||
|
return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : '');
|
||
|
}
|
||
|
if (isSymbol(obj)) {
|
||
|
var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj);
|
||
|
return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString;
|
||
|
}
|
||
|
if (isElement(obj)) {
|
||
|
var s = '<' + $toLowerCase.call(String(obj.nodeName));
|
||
|
var attrs = obj.attributes || [];
|
||
|
for (var i = 0; i < attrs.length; i++) {
|
||
|
s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);
|
||
|
}
|
||
|
s += '>';
|
||
|
if (obj.childNodes && obj.childNodes.length) { s += '...'; }
|
||
|
s += '</' + $toLowerCase.call(String(obj.nodeName)) + '>';
|
||
|
return s;
|
||
|
}
|
||
|
if (isArray$3(obj)) {
|
||
|
if (obj.length === 0) { return '[]'; }
|
||
|
var xs = arrObjKeys(obj, inspect);
|
||
|
if (indent && !singleLineValues(xs)) {
|
||
|
return '[' + indentedJoin(xs, indent) + ']';
|
||
|
}
|
||
|
return '[ ' + $join.call(xs, ', ') + ' ]';
|
||
|
}
|
||
|
if (isError(obj)) {
|
||
|
var parts = arrObjKeys(obj, inspect);
|
||
|
if ('cause' in obj && !isEnumerable.call(obj, 'cause')) {
|
||
|
return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }';
|
||
|
}
|
||
|
if (parts.length === 0) { return '[' + String(obj) + ']'; }
|
||
|
return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }';
|
||
|
}
|
||
|
if (typeof obj === 'object' && customInspect) {
|
||
|
if (inspectSymbol && typeof obj[inspectSymbol] === 'function') {
|
||
|
return obj[inspectSymbol]();
|
||
|
} else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') {
|
||
|
return obj.inspect();
|
||
|
}
|
||
|
}
|
||
|
if (isMap(obj)) {
|
||
|
var mapParts = [];
|
||
|
mapForEach.call(obj, function (value, key) {
|
||
|
mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj));
|
||
|
});
|
||
|
return collectionOf('Map', mapSize.call(obj), mapParts, indent);
|
||
|
}
|
||
|
if (isSet(obj)) {
|
||
|
var setParts = [];
|
||
|
setForEach.call(obj, function (value) {
|
||
|
setParts.push(inspect(value, obj));
|
||
|
});
|
||
|
return collectionOf('Set', setSize.call(obj), setParts, indent);
|
||
|
}
|
||
|
if (isWeakMap(obj)) {
|
||
|
return weakCollectionOf('WeakMap');
|
||
|
}
|
||
|
if (isWeakSet(obj)) {
|
||
|
return weakCollectionOf('WeakSet');
|
||
|
}
|
||
|
if (isWeakRef(obj)) {
|
||
|
return weakCollectionOf('WeakRef');
|
||
|
}
|
||
|
if (isNumber(obj)) {
|
||
|
return markBoxed(inspect(Number(obj)));
|
||
|
}
|
||
|
if (isBigInt(obj)) {
|
||
|
return markBoxed(inspect(bigIntValueOf.call(obj)));
|
||
|
}
|
||
|
if (isBoolean(obj)) {
|
||
|
return markBoxed(booleanValueOf.call(obj));
|
||
|
}
|
||
|
if (isString(obj)) {
|
||
|
return markBoxed(inspect(String(obj)));
|
||
|
}
|
||
|
if (!isDate(obj) && !isRegExp$1(obj)) {
|
||
|
var ys = arrObjKeys(obj, inspect);
|
||
|
var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
|
||
|
var protoTag = obj instanceof Object ? '' : 'null prototype';
|
||
|
var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : '';
|
||
|
var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : '';
|
||
|
var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : '');
|
||
|
if (ys.length === 0) { return tag + '{}'; }
|
||
|
if (indent) {
|
||
|
return tag + '{' + indentedJoin(ys, indent) + '}';
|
||
|
}
|
||
|
return tag + '{ ' + $join.call(ys, ', ') + ' }';
|
||
|
}
|
||
|
return String(obj);
|
||
|
};
|
||
|
|
||
|
function wrapQuotes(s, defaultStyle, opts) {
|
||
|
var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'";
|
||
|
return quoteChar + s + quoteChar;
|
||
|
}
|
||
|
|
||
|
function quote(s) {
|
||
|
return $replace.call(String(s), /"/g, '"');
|
||
|
}
|
||
|
|
||
|
function isArray$3(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
|
||
|
function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
|
||
|
function isRegExp$1(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
|
||
|
function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
|
||
|
function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
|
||
|
function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
|
||
|
function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
|
||
|
|
||
|
// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives
|
||
|
function isSymbol(obj) {
|
||
|
if (hasShammedSymbols) {
|
||
|
return obj && typeof obj === 'object' && obj instanceof Symbol;
|
||
|
}
|
||
|
if (typeof obj === 'symbol') {
|
||
|
return true;
|
||
|
}
|
||
|
if (!obj || typeof obj !== 'object' || !symToString) {
|
||
|
return false;
|
||
|
}
|
||
|
try {
|
||
|
symToString.call(obj);
|
||
|
return true;
|
||
|
} catch (e) {}
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
function isBigInt(obj) {
|
||
|
if (!obj || typeof obj !== 'object' || !bigIntValueOf) {
|
||
|
return false;
|
||
|
}
|
||
|
try {
|
||
|
bigIntValueOf.call(obj);
|
||
|
return true;
|
||
|
} catch (e) {}
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };
|
||
|
function has$3(obj, key) {
|
||
|
return hasOwn.call(obj, key);
|
||
|
}
|
||
|
|
||
|
function toStr(obj) {
|
||
|
return objectToString.call(obj);
|
||
|
}
|
||
|
|
||
|
function nameOf(f) {
|
||
|
if (f.name) { return f.name; }
|
||
|
var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/);
|
||
|
if (m) { return m[1]; }
|
||
|
return null;
|
||
|
}
|
||
|
|
||
|
function indexOf(xs, x) {
|
||
|
if (xs.indexOf) { return xs.indexOf(x); }
|
||
|
for (var i = 0, l = xs.length; i < l; i++) {
|
||
|
if (xs[i] === x) { return i; }
|
||
|
}
|
||
|
return -1;
|
||
|
}
|
||
|
|
||
|
function isMap(x) {
|
||
|
if (!mapSize || !x || typeof x !== 'object') {
|
||
|
return false;
|
||
|
}
|
||
|
try {
|
||
|
mapSize.call(x);
|
||
|
try {
|
||
|
setSize.call(x);
|
||
|
} catch (s) {
|
||
|
return true;
|
||
|
}
|
||
|
return x instanceof Map; // core-js workaround, pre-v2.5.0
|
||
|
} catch (e) {}
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
function isWeakMap(x) {
|
||
|
if (!weakMapHas || !x || typeof x !== 'object') {
|
||
|
return false;
|
||
|
}
|
||
|
try {
|
||
|
weakMapHas.call(x, weakMapHas);
|
||
|
try {
|
||
|
weakSetHas.call(x, weakSetHas);
|
||
|
} catch (s) {
|
||
|
return true;
|
||
|
}
|
||
|
return x instanceof WeakMap; // core-js workaround, pre-v2.5.0
|
||
|
} catch (e) {}
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
function isWeakRef(x) {
|
||
|
if (!weakRefDeref || !x || typeof x !== 'object') {
|
||
|
return false;
|
||
|
}
|
||
|
try {
|
||
|
weakRefDeref.call(x);
|
||
|
return true;
|
||
|
} catch (e) {}
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
function isSet(x) {
|
||
|
if (!setSize || !x || typeof x !== 'object') {
|
||
|
return false;
|
||
|
}
|
||
|
try {
|
||
|
setSize.call(x);
|
||
|
try {
|
||
|
mapSize.call(x);
|
||
|
} catch (m) {
|
||
|
return true;
|
||
|
}
|
||
|
return x instanceof Set; // core-js workaround, pre-v2.5.0
|
||
|
} catch (e) {}
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
function isWeakSet(x) {
|
||
|
if (!weakSetHas || !x || typeof x !== 'object') {
|
||
|
return false;
|
||
|
}
|
||
|
try {
|
||
|
weakSetHas.call(x, weakSetHas);
|
||
|
try {
|
||
|
weakMapHas.call(x, weakMapHas);
|
||
|
} catch (s) {
|
||
|
return true;
|
||
|
}
|
||
|
return x instanceof WeakSet; // core-js workaround, pre-v2.5.0
|
||
|
} catch (e) {}
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
function isElement(x) {
|
||
|
if (!x || typeof x !== 'object') { return false; }
|
||
|
if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
|
||
|
return true;
|
||
|
}
|
||
|
return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function';
|
||
|
}
|
||
|
|
||
|
function inspectString(str, opts) {
|
||
|
if (str.length > opts.maxStringLength) {
|
||
|
var remaining = str.length - opts.maxStringLength;
|
||
|
var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : '');
|
||
|
return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer;
|
||
|
}
|
||
|
// eslint-disable-next-line no-control-regex
|
||
|
var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte);
|
||
|
return wrapQuotes(s, 'single', opts);
|
||
|
}
|
||
|
|
||
|
function lowbyte(c) {
|
||
|
var n = c.charCodeAt(0);
|
||
|
var x = {
|
||
|
8: 'b',
|
||
|
9: 't',
|
||
|
10: 'n',
|
||
|
12: 'f',
|
||
|
13: 'r'
|
||
|
}[n];
|
||
|
if (x) { return '\\' + x; }
|
||
|
return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16));
|
||
|
}
|
||
|
|
||
|
function markBoxed(str) {
|
||
|
return 'Object(' + str + ')';
|
||
|
}
|
||
|
|
||
|
function weakCollectionOf(type) {
|
||
|
return type + ' { ? }';
|
||
|
}
|
||
|
|
||
|
function collectionOf(type, size, entries, indent) {
|
||
|
var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', ');
|
||
|
return type + ' (' + size + ') {' + joinedEntries + '}';
|
||
|
}
|
||
|
|
||
|
function singleLineValues(xs) {
|
||
|
for (var i = 0; i < xs.length; i++) {
|
||
|
if (indexOf(xs[i], '\n') >= 0) {
|
||
|
return false;
|
||
|
}
|
||
|
}
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
function getIndent(opts, depth) {
|
||
|
var baseIndent;
|
||
|
if (opts.indent === '\t') {
|
||
|
baseIndent = '\t';
|
||
|
} else if (typeof opts.indent === 'number' && opts.indent > 0) {
|
||
|
baseIndent = $join.call(Array(opts.indent + 1), ' ');
|
||
|
} else {
|
||
|
return null;
|
||
|
}
|
||
|
return {
|
||
|
base: baseIndent,
|
||
|
prev: $join.call(Array(depth + 1), baseIndent)
|
||
|
};
|
||
|
}
|
||
|
|
||
|
function indentedJoin(xs, indent) {
|
||
|
if (xs.length === 0) { return ''; }
|
||
|
var lineJoiner = '\n' + indent.prev + indent.base;
|
||
|
return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev;
|
||
|
}
|
||
|
|
||
|
function arrObjKeys(obj, inspect) {
|
||
|
var isArr = isArray$3(obj);
|
||
|
var xs = [];
|
||
|
if (isArr) {
|
||
|
xs.length = obj.length;
|
||
|
for (var i = 0; i < obj.length; i++) {
|
||
|
xs[i] = has$3(obj, i) ? inspect(obj[i], obj) : '';
|
||
|
}
|
||
|
}
|
||
|
var syms = typeof gOPS === 'function' ? gOPS(obj) : [];
|
||
|
var symMap;
|
||
|
if (hasShammedSymbols) {
|
||
|
symMap = {};
|
||
|
for (var k = 0; k < syms.length; k++) {
|
||
|
symMap['$' + syms[k]] = syms[k];
|
||
|
}
|
||
|
}
|
||
|
|
||
|
for (var key in obj) { // eslint-disable-line no-restricted-syntax
|
||
|
if (!has$3(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
|
||
|
if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
|
||
|
if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) {
|
||
|
// this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section
|
||
|
continue; // eslint-disable-line no-restricted-syntax, no-continue
|
||
|
} else if ($test.call(/[^\w$]/, key)) {
|
||
|
xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
|
||
|
} else {
|
||
|
xs.push(key + ': ' + inspect(obj[key], obj));
|
||
|
}
|
||
|
}
|
||
|
if (typeof gOPS === 'function') {
|
||
|
for (var j = 0; j < syms.length; j++) {
|
||
|
if (isEnumerable.call(obj, syms[j])) {
|
||
|
xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj));
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
return xs;
|
||
|
}
|
||
|
|
||
|
var $TypeError = getIntrinsic('%TypeError%');
|
||
|
var $WeakMap = getIntrinsic('%WeakMap%', true);
|
||
|
var $Map = getIntrinsic('%Map%', true);
|
||
|
|
||
|
var $weakMapGet = callBound('WeakMap.prototype.get', true);
|
||
|
var $weakMapSet = callBound('WeakMap.prototype.set', true);
|
||
|
var $weakMapHas = callBound('WeakMap.prototype.has', true);
|
||
|
var $mapGet = callBound('Map.prototype.get', true);
|
||
|
var $mapSet = callBound('Map.prototype.set', true);
|
||
|
var $mapHas = callBound('Map.prototype.has', true);
|
||
|
|
||
|
/*
|
||
|
* This function traverses the list returning the node corresponding to the
|
||
|
* given key.
|
||
|
*
|
||
|
* That node is also moved to the head of the list, so that if it's accessed
|
||
|
* again we don't need to traverse the whole list. By doing so, all the recently
|
||
|
* used nodes can be accessed relatively quickly.
|
||
|
*/
|
||
|
var listGetNode = function (list, key) { // eslint-disable-line consistent-return
|
||
|
for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) {
|
||
|
if (curr.key === key) {
|
||
|
prev.next = curr.next;
|
||
|
curr.next = list.next;
|
||
|
list.next = curr; // eslint-disable-line no-param-reassign
|
||
|
return curr;
|
||
|
}
|
||
|
}
|
||
|
};
|
||
|
|
||
|
var listGet = function (objects, key) {
|
||
|
var node = listGetNode(objects, key);
|
||
|
return node && node.value;
|
||
|
};
|
||
|
var listSet = function (objects, key, value) {
|
||
|
var node = listGetNode(objects, key);
|
||
|
if (node) {
|
||
|
node.value = value;
|
||
|
} else {
|
||
|
// Prepend the new node to the beginning of the list
|
||
|
objects.next = { // eslint-disable-line no-param-reassign
|
||
|
key: key,
|
||
|
next: objects.next,
|
||
|
value: value
|
||
|
};
|
||
|
}
|
||
|
};
|
||
|
var listHas = function (objects, key) {
|
||
|
return !!listGetNode(objects, key);
|
||
|
};
|
||
|
|
||
|
var sideChannel = function getSideChannel() {
|
||
|
var $wm;
|
||
|
var $m;
|
||
|
var $o;
|
||
|
var channel = {
|
||
|
assert: function (key) {
|
||
|
if (!channel.has(key)) {
|
||
|
throw new $TypeError('Side channel does not contain ' + objectInspect(key));
|
||
|
}
|
||
|
},
|
||
|
get: function (key) { // eslint-disable-line consistent-return
|
||
|
if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
|
||
|
if ($wm) {
|
||
|
return $weakMapGet($wm, key);
|
||
|
}
|
||
|
} else if ($Map) {
|
||
|
if ($m) {
|
||
|
return $mapGet($m, key);
|
||
|
}
|
||
|
} else {
|
||
|
if ($o) { // eslint-disable-line no-lonely-if
|
||
|
return listGet($o, key);
|
||
|
}
|
||
|
}
|
||
|
},
|
||
|
has: function (key) {
|
||
|
if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
|
||
|
if ($wm) {
|
||
|
return $weakMapHas($wm, key);
|
||
|
}
|
||
|
} else if ($Map) {
|
||
|
if ($m) {
|
||
|
return $mapHas($m, key);
|
||
|
}
|
||
|
} else {
|
||
|
if ($o) { // eslint-disable-line no-lonely-if
|
||
|
return listHas($o, key);
|
||
|
}
|
||
|
}
|
||
|
return false;
|
||
|
},
|
||
|
set: function (key, value) {
|
||
|
if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
|
||
|
if (!$wm) {
|
||
|
$wm = new $WeakMap();
|
||
|
}
|
||
|
$weakMapSet($wm, key, value);
|
||
|
} else if ($Map) {
|
||
|
if (!$m) {
|
||
|
$m = new $Map();
|
||
|
}
|
||
|
$mapSet($m, key, value);
|
||
|
} else {
|
||
|
if (!$o) {
|
||
|
/*
|
||
|
* Initialize the linked list as an empty node, so that we don't have
|
||
|
* to special-case handling of the first node: we can always refer to
|
||
|
* it as (previous node).next, instead of something like (list).head
|
||
|
*/
|
||
|
$o = { key: {}, next: null };
|
||
|
}
|
||
|
listSet($o, key, value);
|
||
|
}
|
||
|
}
|
||
|
};
|
||
|
return channel;
|
||
|
};
|
||
|
|
||
|
var replace = String.prototype.replace;
|
||
|
var percentTwenties = /%20/g;
|
||
|
|
||
|
var Format = {
|
||
|
RFC1738: 'RFC1738',
|
||
|
RFC3986: 'RFC3986'
|
||
|
};
|
||
|
|
||
|
var formats = {
|
||
|
'default': Format.RFC3986,
|
||
|
formatters: {
|
||
|
RFC1738: function (value) {
|
||
|
return replace.call(value, percentTwenties, '+');
|
||
|
},
|
||
|
RFC3986: function (value) {
|
||
|
return String(value);
|
||
|
}
|
||
|
},
|
||
|
RFC1738: Format.RFC1738,
|
||
|
RFC3986: Format.RFC3986
|
||
|
};
|
||
|
|
||
|
var has$2 = Object.prototype.hasOwnProperty;
|
||
|
var isArray$2 = Array.isArray;
|
||
|
|
||
|
var hexTable = (function () {
|
||
|
var array = [];
|
||
|
for (var i = 0; i < 256; ++i) {
|
||
|
array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
|
||
|
}
|
||
|
|
||
|
return array;
|
||
|
}());
|
||
|
|
||
|
var compactQueue = function compactQueue(queue) {
|
||
|
while (queue.length > 1) {
|
||
|
var item = queue.pop();
|
||
|
var obj = item.obj[item.prop];
|
||
|
|
||
|
if (isArray$2(obj)) {
|
||
|
var compacted = [];
|
||
|
|
||
|
for (var j = 0; j < obj.length; ++j) {
|
||
|
if (typeof obj[j] !== 'undefined') {
|
||
|
compacted.push(obj[j]);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
item.obj[item.prop] = compacted;
|
||
|
}
|
||
|
}
|
||
|
};
|
||
|
|
||
|
var arrayToObject = function arrayToObject(source, options) {
|
||
|
var obj = options && options.plainObjects ? Object.create(null) : {};
|
||
|
for (var i = 0; i < source.length; ++i) {
|
||
|
if (typeof source[i] !== 'undefined') {
|
||
|
obj[i] = source[i];
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return obj;
|
||
|
};
|
||
|
|
||
|
var merge = function merge(target, source, options) {
|
||
|
/* eslint no-param-reassign: 0 */
|
||
|
if (!source) {
|
||
|
return target;
|
||
|
}
|
||
|
|
||
|
if (typeof source !== 'object') {
|
||
|
if (isArray$2(target)) {
|
||
|
target.push(source);
|
||
|
} else if (target && typeof target === 'object') {
|
||
|
if ((options && (options.plainObjects || options.allowPrototypes)) || !has$2.call(Object.prototype, source)) {
|
||
|
target[source] = true;
|
||
|
}
|
||
|
} else {
|
||
|
return [target, source];
|
||
|
}
|
||
|
|
||
|
return target;
|
||
|
}
|
||
|
|
||
|
if (!target || typeof target !== 'object') {
|
||
|
return [target].concat(source);
|
||
|
}
|
||
|
|
||
|
var mergeTarget = target;
|
||
|
if (isArray$2(target) && !isArray$2(source)) {
|
||
|
mergeTarget = arrayToObject(target, options);
|
||
|
}
|
||
|
|
||
|
if (isArray$2(target) && isArray$2(source)) {
|
||
|
source.forEach(function (item, i) {
|
||
|
if (has$2.call(target, i)) {
|
||
|
var targetItem = target[i];
|
||
|
if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {
|
||
|
target[i] = merge(targetItem, item, options);
|
||
|
} else {
|
||
|
target.push(item);
|
||
|
}
|
||
|
} else {
|
||
|
target[i] = item;
|
||
|
}
|
||
|
});
|
||
|
return target;
|
||
|
}
|
||
|
|
||
|
return Object.keys(source).reduce(function (acc, key) {
|
||
|
var value = source[key];
|
||
|
|
||
|
if (has$2.call(acc, key)) {
|
||
|
acc[key] = merge(acc[key], value, options);
|
||
|
} else {
|
||
|
acc[key] = value;
|
||
|
}
|
||
|
return acc;
|
||
|
}, mergeTarget);
|
||
|
};
|
||
|
|
||
|
var assign = function assignSingleSource(target, source) {
|
||
|
return Object.keys(source).reduce(function (acc, key) {
|
||
|
acc[key] = source[key];
|
||
|
return acc;
|
||
|
}, target);
|
||
|
};
|
||
|
|
||
|
var decode = function (str, decoder, charset) {
|
||
|
var strWithoutPlus = str.replace(/\+/g, ' ');
|
||
|
if (charset === 'iso-8859-1') {
|
||
|
// unescape never throws, no try...catch needed:
|
||
|
return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
|
||
|
}
|
||
|
// utf-8
|
||
|
try {
|
||
|
return decodeURIComponent(strWithoutPlus);
|
||
|
} catch (e) {
|
||
|
return strWithoutPlus;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
var encode = function encode(str, defaultEncoder, charset, kind, format) {
|
||
|
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
|
||
|
// It has been adapted here for stricter adherence to RFC 3986
|
||
|
if (str.length === 0) {
|
||
|
return str;
|
||
|
}
|
||
|
|
||
|
var string = str;
|
||
|
if (typeof str === 'symbol') {
|
||
|
string = Symbol.prototype.toString.call(str);
|
||
|
} else if (typeof str !== 'string') {
|
||
|
string = String(str);
|
||
|
}
|
||
|
|
||
|
if (charset === 'iso-8859-1') {
|
||
|
return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {
|
||
|
return '%26%23' + parseInt($0.slice(2), 16) + '%3B';
|
||
|
});
|
||
|
}
|
||
|
|
||
|
var out = '';
|
||
|
for (var i = 0; i < string.length; ++i) {
|
||
|
var c = string.charCodeAt(i);
|
||
|
|
||
|
if (
|
||
|
c === 0x2D // -
|
||
|
|| c === 0x2E // .
|
||
|
|| c === 0x5F // _
|
||
|
|| c === 0x7E // ~
|
||
|
|| (c >= 0x30 && c <= 0x39) // 0-9
|
||
|
|| (c >= 0x41 && c <= 0x5A) // a-z
|
||
|
|| (c >= 0x61 && c <= 0x7A) // A-Z
|
||
|
|| (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( )
|
||
|
) {
|
||
|
out += string.charAt(i);
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
if (c < 0x80) {
|
||
|
out = out + hexTable[c];
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
if (c < 0x800) {
|
||
|
out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
if (c < 0xD800 || c >= 0xE000) {
|
||
|
out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
i += 1;
|
||
|
c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
|
||
|
/* eslint operator-linebreak: [2, "before"] */
|
||
|
out += hexTable[0xF0 | (c >> 18)]
|
||
|
+ hexTable[0x80 | ((c >> 12) & 0x3F)]
|
||
|
+ hexTable[0x80 | ((c >> 6) & 0x3F)]
|
||
|
+ hexTable[0x80 | (c & 0x3F)];
|
||
|
}
|
||
|
|
||
|
return out;
|
||
|
};
|
||
|
|
||
|
var compact = function compact(value) {
|
||
|
var queue = [{ obj: { o: value }, prop: 'o' }];
|
||
|
var refs = [];
|
||
|
|
||
|
for (var i = 0; i < queue.length; ++i) {
|
||
|
var item = queue[i];
|
||
|
var obj = item.obj[item.prop];
|
||
|
|
||
|
var keys = Object.keys(obj);
|
||
|
for (var j = 0; j < keys.length; ++j) {
|
||
|
var key = keys[j];
|
||
|
var val = obj[key];
|
||
|
if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
|
||
|
queue.push({ obj: obj, prop: key });
|
||
|
refs.push(val);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
compactQueue(queue);
|
||
|
|
||
|
return value;
|
||
|
};
|
||
|
|
||
|
var isRegExp = function isRegExp(obj) {
|
||
|
return Object.prototype.toString.call(obj) === '[object RegExp]';
|
||
|
};
|
||
|
|
||
|
var isBuffer = function isBuffer(obj) {
|
||
|
if (!obj || typeof obj !== 'object') {
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
|
||
|
};
|
||
|
|
||
|
var combine = function combine(a, b) {
|
||
|
return [].concat(a, b);
|
||
|
};
|
||
|
|
||
|
var maybeMap = function maybeMap(val, fn) {
|
||
|
if (isArray$2(val)) {
|
||
|
var mapped = [];
|
||
|
for (var i = 0; i < val.length; i += 1) {
|
||
|
mapped.push(fn(val[i]));
|
||
|
}
|
||
|
return mapped;
|
||
|
}
|
||
|
return fn(val);
|
||
|
};
|
||
|
|
||
|
var utils = {
|
||
|
arrayToObject: arrayToObject,
|
||
|
assign: assign,
|
||
|
combine: combine,
|
||
|
compact: compact,
|
||
|
decode: decode,
|
||
|
encode: encode,
|
||
|
isBuffer: isBuffer,
|
||
|
isRegExp: isRegExp,
|
||
|
maybeMap: maybeMap,
|
||
|
merge: merge
|
||
|
};
|
||
|
|
||
|
var has$1 = Object.prototype.hasOwnProperty;
|
||
|
|
||
|
var arrayPrefixGenerators = {
|
||
|
brackets: function brackets(prefix) {
|
||
|
return prefix + '[]';
|
||
|
},
|
||
|
comma: 'comma',
|
||
|
indices: function indices(prefix, key) {
|
||
|
return prefix + '[' + key + ']';
|
||
|
},
|
||
|
repeat: function repeat(prefix) {
|
||
|
return prefix;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
var isArray$1 = Array.isArray;
|
||
|
var split = String.prototype.split;
|
||
|
var push = Array.prototype.push;
|
||
|
var pushToArray = function (arr, valueOrArray) {
|
||
|
push.apply(arr, isArray$1(valueOrArray) ? valueOrArray : [valueOrArray]);
|
||
|
};
|
||
|
|
||
|
var toISO = Date.prototype.toISOString;
|
||
|
|
||
|
var defaultFormat = formats['default'];
|
||
|
var defaults$1 = {
|
||
|
addQueryPrefix: false,
|
||
|
allowDots: false,
|
||
|
charset: 'utf-8',
|
||
|
charsetSentinel: false,
|
||
|
delimiter: '&',
|
||
|
encode: true,
|
||
|
encoder: utils.encode,
|
||
|
encodeValuesOnly: false,
|
||
|
format: defaultFormat,
|
||
|
formatter: formats.formatters[defaultFormat],
|
||
|
// deprecated
|
||
|
indices: false,
|
||
|
serializeDate: function serializeDate(date) {
|
||
|
return toISO.call(date);
|
||
|
},
|
||
|
skipNulls: false,
|
||
|
strictNullHandling: false
|
||
|
};
|
||
|
|
||
|
var isNonNullishPrimitive = function isNonNullishPrimitive(v) {
|
||
|
return typeof v === 'string'
|
||
|
|| typeof v === 'number'
|
||
|
|| typeof v === 'boolean'
|
||
|
|| typeof v === 'symbol'
|
||
|
|| typeof v === 'bigint';
|
||
|
};
|
||
|
|
||
|
var sentinel = {};
|
||
|
|
||
|
var stringify = function stringify(
|
||
|
object,
|
||
|
prefix,
|
||
|
generateArrayPrefix,
|
||
|
strictNullHandling,
|
||
|
skipNulls,
|
||
|
encoder,
|
||
|
filter,
|
||
|
sort,
|
||
|
allowDots,
|
||
|
serializeDate,
|
||
|
format,
|
||
|
formatter,
|
||
|
encodeValuesOnly,
|
||
|
charset,
|
||
|
sideChannel$1
|
||
|
) {
|
||
|
var obj = object;
|
||
|
|
||
|
var tmpSc = sideChannel$1;
|
||
|
var step = 0;
|
||
|
var findFlag = false;
|
||
|
while ((tmpSc = tmpSc.get(sentinel)) !== undefined && !findFlag) {
|
||
|
// Where object last appeared in the ref tree
|
||
|
var pos = tmpSc.get(object);
|
||
|
step += 1;
|
||
|
if (typeof pos !== 'undefined') {
|
||
|
if (pos === step) {
|
||
|
throw new RangeError('Cyclic object value');
|
||
|
} else {
|
||
|
findFlag = true; // Break while
|
||
|
}
|
||
|
}
|
||
|
if (typeof tmpSc.get(sentinel) === 'undefined') {
|
||
|
step = 0;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (typeof filter === 'function') {
|
||
|
obj = filter(prefix, obj);
|
||
|
} else if (obj instanceof Date) {
|
||
|
obj = serializeDate(obj);
|
||
|
} else if (generateArrayPrefix === 'comma' && isArray$1(obj)) {
|
||
|
obj = utils.maybeMap(obj, function (value) {
|
||
|
if (value instanceof Date) {
|
||
|
return serializeDate(value);
|
||
|
}
|
||
|
return value;
|
||
|
});
|
||
|
}
|
||
|
|
||
|
if (obj === null) {
|
||
|
if (strictNullHandling) {
|
||
|
return encoder && !encodeValuesOnly ? encoder(prefix, defaults$1.encoder, charset, 'key', format) : prefix;
|
||
|
}
|
||
|
|
||
|
obj = '';
|
||
|
}
|
||
|
|
||
|
if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) {
|
||
|
if (encoder) {
|
||
|
var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults$1.encoder, charset, 'key', format);
|
||
|
if (generateArrayPrefix === 'comma' && encodeValuesOnly) {
|
||
|
var valuesArray = split.call(String(obj), ',');
|
||
|
var valuesJoined = '';
|
||
|
for (var i = 0; i < valuesArray.length; ++i) {
|
||
|
valuesJoined += (i === 0 ? '' : ',') + formatter(encoder(valuesArray[i], defaults$1.encoder, charset, 'value', format));
|
||
|
}
|
||
|
return [formatter(keyValue) + '=' + valuesJoined];
|
||
|
}
|
||
|
return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults$1.encoder, charset, 'value', format))];
|
||
|
}
|
||
|
return [formatter(prefix) + '=' + formatter(String(obj))];
|
||
|
}
|
||
|
|
||
|
var values = [];
|
||
|
|
||
|
if (typeof obj === 'undefined') {
|
||
|
return values;
|
||
|
}
|
||
|
|
||
|
var objKeys;
|
||
|
if (generateArrayPrefix === 'comma' && isArray$1(obj)) {
|
||
|
// we need to join elements in
|
||
|
objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : undefined }];
|
||
|
} else if (isArray$1(filter)) {
|
||
|
objKeys = filter;
|
||
|
} else {
|
||
|
var keys = Object.keys(obj);
|
||
|
objKeys = sort ? keys.sort(sort) : keys;
|
||
|
}
|
||
|
|
||
|
for (var j = 0; j < objKeys.length; ++j) {
|
||
|
var key = objKeys[j];
|
||
|
var value = typeof key === 'object' && key.value !== undefined ? key.value : obj[key];
|
||
|
|
||
|
if (skipNulls && value === null) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
var keyPrefix = isArray$1(obj)
|
||
|
? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix
|
||
|
: prefix + (allowDots ? '.' + key : '[' + key + ']');
|
||
|
|
||
|
sideChannel$1.set(object, step);
|
||
|
var valueSideChannel = sideChannel();
|
||
|
valueSideChannel.set(sentinel, sideChannel$1);
|
||
|
pushToArray(values, stringify(
|
||
|
value,
|
||
|
keyPrefix,
|
||
|
generateArrayPrefix,
|
||
|
strictNullHandling,
|
||
|
skipNulls,
|
||
|
encoder,
|
||
|
filter,
|
||
|
sort,
|
||
|
allowDots,
|
||
|
serializeDate,
|
||
|
format,
|
||
|
formatter,
|
||
|
encodeValuesOnly,
|
||
|
charset,
|
||
|
valueSideChannel
|
||
|
));
|
||
|
}
|
||
|
|
||
|
return values;
|
||
|
};
|
||
|
|
||
|
var normalizeStringifyOptions = function normalizeStringifyOptions(opts) {
|
||
|
if (!opts) {
|
||
|
return defaults$1;
|
||
|
}
|
||
|
|
||
|
if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') {
|
||
|
throw new TypeError('Encoder has to be a function.');
|
||
|
}
|
||
|
|
||
|
var charset = opts.charset || defaults$1.charset;
|
||
|
if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
|
||
|
throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
|
||
|
}
|
||
|
|
||
|
var format = formats['default'];
|
||
|
if (typeof opts.format !== 'undefined') {
|
||
|
if (!has$1.call(formats.formatters, opts.format)) {
|
||
|
throw new TypeError('Unknown format option provided.');
|
||
|
}
|
||
|
format = opts.format;
|
||
|
}
|
||
|
var formatter = formats.formatters[format];
|
||
|
|
||
|
var filter = defaults$1.filter;
|
||
|
if (typeof opts.filter === 'function' || isArray$1(opts.filter)) {
|
||
|
filter = opts.filter;
|
||
|
}
|
||
|
|
||
|
return {
|
||
|
addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults$1.addQueryPrefix,
|
||
|
allowDots: typeof opts.allowDots === 'undefined' ? defaults$1.allowDots : !!opts.allowDots,
|
||
|
charset: charset,
|
||
|
charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults$1.charsetSentinel,
|
||
|
delimiter: typeof opts.delimiter === 'undefined' ? defaults$1.delimiter : opts.delimiter,
|
||
|
encode: typeof opts.encode === 'boolean' ? opts.encode : defaults$1.encode,
|
||
|
encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults$1.encoder,
|
||
|
encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults$1.encodeValuesOnly,
|
||
|
filter: filter,
|
||
|
format: format,
|
||
|
formatter: formatter,
|
||
|
serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults$1.serializeDate,
|
||
|
skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults$1.skipNulls,
|
||
|
sort: typeof opts.sort === 'function' ? opts.sort : null,
|
||
|
strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults$1.strictNullHandling
|
||
|
};
|
||
|
};
|
||
|
|
||
|
var stringify_1 = function (object, opts) {
|
||
|
var obj = object;
|
||
|
var options = normalizeStringifyOptions(opts);
|
||
|
|
||
|
var objKeys;
|
||
|
var filter;
|
||
|
|
||
|
if (typeof options.filter === 'function') {
|
||
|
filter = options.filter;
|
||
|
obj = filter('', obj);
|
||
|
} else if (isArray$1(options.filter)) {
|
||
|
filter = options.filter;
|
||
|
objKeys = filter;
|
||
|
}
|
||
|
|
||
|
var keys = [];
|
||
|
|
||
|
if (typeof obj !== 'object' || obj === null) {
|
||
|
return '';
|
||
|
}
|
||
|
|
||
|
var arrayFormat;
|
||
|
if (opts && opts.arrayFormat in arrayPrefixGenerators) {
|
||
|
arrayFormat = opts.arrayFormat;
|
||
|
} else if (opts && 'indices' in opts) {
|
||
|
arrayFormat = opts.indices ? 'indices' : 'repeat';
|
||
|
} else {
|
||
|
arrayFormat = 'indices';
|
||
|
}
|
||
|
|
||
|
var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
|
||
|
|
||
|
if (!objKeys) {
|
||
|
objKeys = Object.keys(obj);
|
||
|
}
|
||
|
|
||
|
if (options.sort) {
|
||
|
objKeys.sort(options.sort);
|
||
|
}
|
||
|
|
||
|
var sideChannel$1 = sideChannel();
|
||
|
for (var i = 0; i < objKeys.length; ++i) {
|
||
|
var key = objKeys[i];
|
||
|
|
||
|
if (options.skipNulls && obj[key] === null) {
|
||
|
continue;
|
||
|
}
|
||
|
pushToArray(keys, stringify(
|
||
|
obj[key],
|
||
|
key,
|
||
|
generateArrayPrefix,
|
||
|
options.strictNullHandling,
|
||
|
options.skipNulls,
|
||
|
options.encode ? options.encoder : null,
|
||
|
options.filter,
|
||
|
options.sort,
|
||
|
options.allowDots,
|
||
|
options.serializeDate,
|
||
|
options.format,
|
||
|
options.formatter,
|
||
|
options.encodeValuesOnly,
|
||
|
options.charset,
|
||
|
sideChannel$1
|
||
|
));
|
||
|
}
|
||
|
|
||
|
var joined = keys.join(options.delimiter);
|
||
|
var prefix = options.addQueryPrefix === true ? '?' : '';
|
||
|
|
||
|
if (options.charsetSentinel) {
|
||
|
if (options.charset === 'iso-8859-1') {
|
||
|
// encodeURIComponent('✓'), the "numeric entity" representation of a checkmark
|
||
|
prefix += 'utf8=%26%2310003%3B&';
|
||
|
} else {
|
||
|
// encodeURIComponent('✓')
|
||
|
prefix += 'utf8=%E2%9C%93&';
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return joined.length > 0 ? prefix + joined : '';
|
||
|
};
|
||
|
|
||
|
var has = Object.prototype.hasOwnProperty;
|
||
|
var isArray = Array.isArray;
|
||
|
|
||
|
var defaults = {
|
||
|
allowDots: false,
|
||
|
allowPrototypes: false,
|
||
|
allowSparse: false,
|
||
|
arrayLimit: 20,
|
||
|
charset: 'utf-8',
|
||
|
charsetSentinel: false,
|
||
|
comma: false,
|
||
|
decoder: utils.decode,
|
||
|
delimiter: '&',
|
||
|
depth: 5,
|
||
|
ignoreQueryPrefix: false,
|
||
|
interpretNumericEntities: false,
|
||
|
parameterLimit: 1000,
|
||
|
parseArrays: true,
|
||
|
plainObjects: false,
|
||
|
strictNullHandling: false
|
||
|
};
|
||
|
|
||
|
var interpretNumericEntities = function (str) {
|
||
|
return str.replace(/&#(\d+);/g, function ($0, numberStr) {
|
||
|
return String.fromCharCode(parseInt(numberStr, 10));
|
||
|
});
|
||
|
};
|
||
|
|
||
|
var parseArrayValue = function (val, options) {
|
||
|
if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) {
|
||
|
return val.split(',');
|
||
|
}
|
||
|
|
||
|
return val;
|
||
|
};
|
||
|
|
||
|
// This is what browsers will submit when the ✓ character occurs in an
|
||
|
// application/x-www-form-urlencoded body and the encoding of the page containing
|
||
|
// the form is iso-8859-1, or when the submitted form has an accept-charset
|
||
|
// attribute of iso-8859-1. Presumably also with other charsets that do not contain
|
||
|
// the ✓ character, such as us-ascii.
|
||
|
var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓')
|
||
|
|
||
|
// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.
|
||
|
var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')
|
||
|
|
||
|
var parseValues = function parseQueryStringValues(str, options) {
|
||
|
var obj = {};
|
||
|
var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
|
||
|
var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
|
||
|
var parts = cleanStr.split(options.delimiter, limit);
|
||
|
var skipIndex = -1; // Keep track of where the utf8 sentinel was found
|
||
|
var i;
|
||
|
|
||
|
var charset = options.charset;
|
||
|
if (options.charsetSentinel) {
|
||
|
for (i = 0; i < parts.length; ++i) {
|
||
|
if (parts[i].indexOf('utf8=') === 0) {
|
||
|
if (parts[i] === charsetSentinel) {
|
||
|
charset = 'utf-8';
|
||
|
} else if (parts[i] === isoSentinel) {
|
||
|
charset = 'iso-8859-1';
|
||
|
}
|
||
|
skipIndex = i;
|
||
|
i = parts.length; // The eslint settings do not allow break;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
for (i = 0; i < parts.length; ++i) {
|
||
|
if (i === skipIndex) {
|
||
|
continue;
|
||
|
}
|
||
|
var part = parts[i];
|
||
|
|
||
|
var bracketEqualsPos = part.indexOf(']=');
|
||
|
var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
|
||
|
|
||
|
var key, val;
|
||
|
if (pos === -1) {
|
||
|
key = options.decoder(part, defaults.decoder, charset, 'key');
|
||
|
val = options.strictNullHandling ? null : '';
|
||
|
} else {
|
||
|
key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key');
|
||
|
val = utils.maybeMap(
|
||
|
parseArrayValue(part.slice(pos + 1), options),
|
||
|
function (encodedVal) {
|
||
|
return options.decoder(encodedVal, defaults.decoder, charset, 'value');
|
||
|
}
|
||
|
);
|
||
|
}
|
||
|
|
||
|
if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {
|
||
|
val = interpretNumericEntities(val);
|
||
|
}
|
||
|
|
||
|
if (part.indexOf('[]=') > -1) {
|
||
|
val = isArray(val) ? [val] : val;
|
||
|
}
|
||
|
|
||
|
if (has.call(obj, key)) {
|
||
|
obj[key] = utils.combine(obj[key], val);
|
||
|
} else {
|
||
|
obj[key] = val;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return obj;
|
||
|
};
|
||
|
|
||
|
var parseObject = function (chain, val, options, valuesParsed) {
|
||
|
var leaf = valuesParsed ? val : parseArrayValue(val, options);
|
||
|
|
||
|
for (var i = chain.length - 1; i >= 0; --i) {
|
||
|
var obj;
|
||
|
var root = chain[i];
|
||
|
|
||
|
if (root === '[]' && options.parseArrays) {
|
||
|
obj = [].concat(leaf);
|
||
|
} else {
|
||
|
obj = options.plainObjects ? Object.create(null) : {};
|
||
|
var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
|
||
|
var index = parseInt(cleanRoot, 10);
|
||
|
if (!options.parseArrays && cleanRoot === '') {
|
||
|
obj = { 0: leaf };
|
||
|
} else if (
|
||
|
!isNaN(index)
|
||
|
&& root !== cleanRoot
|
||
|
&& String(index) === cleanRoot
|
||
|
&& index >= 0
|
||
|
&& (options.parseArrays && index <= options.arrayLimit)
|
||
|
) {
|
||
|
obj = [];
|
||
|
obj[index] = leaf;
|
||
|
} else {
|
||
|
obj[cleanRoot] = leaf;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
leaf = obj;
|
||
|
}
|
||
|
|
||
|
return leaf;
|
||
|
};
|
||
|
|
||
|
var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
|
||
|
if (!givenKey) {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
// Transform dot notation to bracket notation
|
||
|
var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
|
||
|
|
||
|
// The regex chunks
|
||
|
|
||
|
var brackets = /(\[[^[\]]*])/;
|
||
|
var child = /(\[[^[\]]*])/g;
|
||
|
|
||
|
// Get the parent
|
||
|
|
||
|
var segment = options.depth > 0 && brackets.exec(key);
|
||
|
var parent = segment ? key.slice(0, segment.index) : key;
|
||
|
|
||
|
// Stash the parent if it exists
|
||
|
|
||
|
var keys = [];
|
||
|
if (parent) {
|
||
|
// If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties
|
||
|
if (!options.plainObjects && has.call(Object.prototype, parent)) {
|
||
|
if (!options.allowPrototypes) {
|
||
|
return;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
keys.push(parent);
|
||
|
}
|
||
|
|
||
|
// Loop through children appending to the array until we hit depth
|
||
|
|
||
|
var i = 0;
|
||
|
while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) {
|
||
|
i += 1;
|
||
|
if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
|
||
|
if (!options.allowPrototypes) {
|
||
|
return;
|
||
|
}
|
||
|
}
|
||
|
keys.push(segment[1]);
|
||
|
}
|
||
|
|
||
|
// If there's a remainder, just add whatever is left
|
||
|
|
||
|
if (segment) {
|
||
|
keys.push('[' + key.slice(segment.index) + ']');
|
||
|
}
|
||
|
|
||
|
return parseObject(keys, val, options, valuesParsed);
|
||
|
};
|
||
|
|
||
|
var normalizeParseOptions = function normalizeParseOptions(opts) {
|
||
|
if (!opts) {
|
||
|
return defaults;
|
||
|
}
|
||
|
|
||
|
if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') {
|
||
|
throw new TypeError('Decoder has to be a function.');
|
||
|
}
|
||
|
|
||
|
if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
|
||
|
throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
|
||
|
}
|
||
|
var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;
|
||
|
|
||
|
return {
|
||
|
allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
|
||
|
allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,
|
||
|
allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse,
|
||
|
arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,
|
||
|
charset: charset,
|
||
|
charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
|
||
|
comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,
|
||
|
decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,
|
||
|
delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,
|
||
|
// eslint-disable-next-line no-implicit-coercion, no-extra-parens
|
||
|
depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth,
|
||
|
ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
|
||
|
interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,
|
||
|
parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,
|
||
|
parseArrays: opts.parseArrays !== false,
|
||
|
plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,
|
||
|
strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
|
||
|
};
|
||
|
};
|
||
|
|
||
|
var parse = function (str, opts) {
|
||
|
var options = normalizeParseOptions(opts);
|
||
|
|
||
|
if (str === '' || str === null || typeof str === 'undefined') {
|
||
|
return options.plainObjects ? Object.create(null) : {};
|
||
|
}
|
||
|
|
||
|
var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
|
||
|
var obj = options.plainObjects ? Object.create(null) : {};
|
||
|
|
||
|
// Iterate over the keys and setup the new object
|
||
|
|
||
|
var keys = Object.keys(tempObj);
|
||
|
for (var i = 0; i < keys.length; ++i) {
|
||
|
var key = keys[i];
|
||
|
var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string');
|
||
|
obj = utils.merge(obj, newObj, options);
|
||
|
}
|
||
|
|
||
|
if (options.allowSparse === true) {
|
||
|
return obj;
|
||
|
}
|
||
|
|
||
|
return utils.compact(obj);
|
||
|
};
|
||
|
|
||
|
var lib = {
|
||
|
formats: formats,
|
||
|
parse: parse,
|
||
|
stringify: stringify_1
|
||
|
};
|
||
|
|
||
|
// Copyright (c) Microsoft. All rights reserved.
|
||
|
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||
|
var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||
|
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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
|
||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||
|
});
|
||
|
};
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
/**
|
||
|
* creates an url from a request url and optional base url (http://server:8080)
|
||
|
* @param {string} resource - a fully qualified url or relative path
|
||
|
* @param {string} baseUrl - an optional baseUrl (http://server:8080)
|
||
|
* @param {IRequestOptions} options - an optional options object, could include QueryParameters e.g.
|
||
|
* @return {string} - resultant url
|
||
|
*/
|
||
|
function getUrl(resource, baseUrl, queryParams) {
|
||
|
const pathApi = path__default["default"].posix || path__default["default"];
|
||
|
let requestUrl = '';
|
||
|
if (!baseUrl) {
|
||
|
requestUrl = resource;
|
||
|
}
|
||
|
else if (!resource) {
|
||
|
requestUrl = baseUrl;
|
||
|
}
|
||
|
else {
|
||
|
const base = url__default["default"].parse(baseUrl);
|
||
|
const resultantUrl = url__default["default"].parse(resource);
|
||
|
// resource (specific per request) elements take priority
|
||
|
resultantUrl.protocol = resultantUrl.protocol || base.protocol;
|
||
|
resultantUrl.auth = resultantUrl.auth || base.auth;
|
||
|
resultantUrl.host = resultantUrl.host || base.host;
|
||
|
resultantUrl.pathname = pathApi.resolve(base.pathname, resultantUrl.pathname);
|
||
|
if (!resultantUrl.pathname.endsWith('/') && resource.endsWith('/')) {
|
||
|
resultantUrl.pathname += '/';
|
||
|
}
|
||
|
requestUrl = url__default["default"].format(resultantUrl);
|
||
|
}
|
||
|
return queryParams ?
|
||
|
getUrlWithParsedQueryParams(requestUrl, queryParams) :
|
||
|
requestUrl;
|
||
|
}
|
||
|
var getUrl_1 = getUrl;
|
||
|
/**
|
||
|
*
|
||
|
* @param {string} requestUrl
|
||
|
* @param {IRequestQueryParams} queryParams
|
||
|
* @return {string} - Request's URL with Query Parameters appended/parsed.
|
||
|
*/
|
||
|
function getUrlWithParsedQueryParams(requestUrl, queryParams) {
|
||
|
const url = requestUrl.replace(/\?$/g, ''); // Clean any extra end-of-string "?" character
|
||
|
const parsedQueryParams = lib.stringify(queryParams.params, buildParamsStringifyOptions(queryParams));
|
||
|
return `${url}${parsedQueryParams}`;
|
||
|
}
|
||
|
/**
|
||
|
* Build options for QueryParams Stringifying.
|
||
|
*
|
||
|
* @param {IRequestQueryParams} queryParams
|
||
|
* @return {object}
|
||
|
*/
|
||
|
function buildParamsStringifyOptions(queryParams) {
|
||
|
let options = {
|
||
|
addQueryPrefix: true,
|
||
|
delimiter: (queryParams.options || {}).separator || '&',
|
||
|
allowDots: (queryParams.options || {}).shouldAllowDots || false,
|
||
|
arrayFormat: (queryParams.options || {}).arrayFormat || 'repeat',
|
||
|
encodeValuesOnly: (queryParams.options || {}).shouldOnlyEncodeValues || true
|
||
|
};
|
||
|
return options;
|
||
|
}
|
||
|
/**
|
||
|
* Decompress/Decode gzip encoded JSON
|
||
|
* Using Node.js built-in zlib module
|
||
|
*
|
||
|
* @param {Buffer} buffer
|
||
|
* @param {string} charset? - optional; defaults to 'utf-8'
|
||
|
* @return {Promise<string>}
|
||
|
*/
|
||
|
function decompressGzippedContent(buffer, charset) {
|
||
|
return __awaiter(this, void 0, void 0, function* () {
|
||
|
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
|
||
|
zlib__default["default"].gunzip(buffer, function (error, buffer) {
|
||
|
if (error) {
|
||
|
reject(error);
|
||
|
}
|
||
|
resolve(buffer.toString(charset || 'utf-8'));
|
||
|
});
|
||
|
}));
|
||
|
});
|
||
|
}
|
||
|
var decompressGzippedContent_1 = decompressGzippedContent;
|
||
|
/**
|
||
|
* Builds a RegExp to test urls against for deciding
|
||
|
* wether to bypass proxy from an entry of the
|
||
|
* environment variable setting NO_PROXY
|
||
|
*
|
||
|
* @param {string} bypass
|
||
|
* @return {RegExp}
|
||
|
*/
|
||
|
function buildProxyBypassRegexFromEnv(bypass) {
|
||
|
try {
|
||
|
// We need to keep this around for back-compat purposes
|
||
|
return new RegExp(bypass, 'i');
|
||
|
}
|
||
|
catch (err) {
|
||
|
if (err instanceof SyntaxError && (bypass || "").startsWith("*")) {
|
||
|
let wildcardEscaped = bypass.replace('*', '(.*)');
|
||
|
return new RegExp(wildcardEscaped, 'i');
|
||
|
}
|
||
|
throw err;
|
||
|
}
|
||
|
}
|
||
|
var buildProxyBypassRegexFromEnv_1 = buildProxyBypassRegexFromEnv;
|
||
|
/**
|
||
|
* Obtain Response's Content Charset.
|
||
|
* Through inspecting `content-type` response header.
|
||
|
* It Returns 'utf-8' if NO charset specified/matched.
|
||
|
*
|
||
|
* @param {IHttpClientResponse} response
|
||
|
* @return {string} - Content Encoding Charset; Default=utf-8
|
||
|
*/
|
||
|
function obtainContentCharset(response) {
|
||
|
// Find the charset, if specified.
|
||
|
// Search for the `charset=CHARSET` string, not including `;,\r\n`
|
||
|
// Example: content-type: 'application/json;charset=utf-8'
|
||
|
// |__ matches would be ['charset=utf-8', 'utf-8', index: 18, input: 'application/json; charset=utf-8']
|
||
|
// |_____ matches[1] would have the charset :tada: , in our example it's utf-8
|
||
|
// However, if the matches Array was empty or no charset found, 'utf-8' would be returned by default.
|
||
|
const nodeSupportedEncodings = ['ascii', 'utf8', 'utf16le', 'ucs2', 'base64', 'binary', 'hex'];
|
||
|
const contentType = response.message.headers['content-type'] || '';
|
||
|
const matches = contentType.match(/charset=([^;,\r\n]+)/i);
|
||
|
return (matches && matches[1] && nodeSupportedEncodings.indexOf(matches[1]) != -1) ? matches[1] : 'utf-8';
|
||
|
}
|
||
|
var obtainContentCharset_1 = obtainContentCharset;
|
||
|
|
||
|
var Util = /*#__PURE__*/Object.defineProperty({
|
||
|
getUrl: getUrl_1,
|
||
|
decompressGzippedContent: decompressGzippedContent_1,
|
||
|
buildProxyBypassRegexFromEnv: buildProxyBypassRegexFromEnv_1,
|
||
|
obtainContentCharset: obtainContentCharset_1
|
||
|
}, '__esModule', {value: true});
|
||
|
|
||
|
var httpOverHttp_1 = httpOverHttp;
|
||
|
var httpsOverHttp_1 = httpsOverHttp;
|
||
|
var httpOverHttps_1 = httpOverHttps;
|
||
|
var httpsOverHttps_1 = httpsOverHttps;
|
||
|
|
||
|
|
||
|
function httpOverHttp(options) {
|
||
|
var agent = new TunnelingAgent(options);
|
||
|
agent.request = http__default["default"].request;
|
||
|
return agent;
|
||
|
}
|
||
|
|
||
|
function httpsOverHttp(options) {
|
||
|
var agent = new TunnelingAgent(options);
|
||
|
agent.request = http__default["default"].request;
|
||
|
agent.createSocket = createSecureSocket;
|
||
|
agent.defaultPort = 443;
|
||
|
return agent;
|
||
|
}
|
||
|
|
||
|
function httpOverHttps(options) {
|
||
|
var agent = new TunnelingAgent(options);
|
||
|
agent.request = https__default["default"].request;
|
||
|
return agent;
|
||
|
}
|
||
|
|
||
|
function httpsOverHttps(options) {
|
||
|
var agent = new TunnelingAgent(options);
|
||
|
agent.request = https__default["default"].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__default["default"].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);
|
||
|
});
|
||
|
}
|
||
|
require$$0__default["default"].inherits(TunnelingAgent, events__default["default"].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__default["default"].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() {};
|
||
|
}
|
||
|
var debug_1 = debug; // for test
|
||
|
|
||
|
var tunnel$1 = {
|
||
|
httpOverHttp: httpOverHttp_1,
|
||
|
httpsOverHttp: httpsOverHttp_1,
|
||
|
httpOverHttps: httpOverHttps_1,
|
||
|
httpsOverHttps: httpsOverHttps_1,
|
||
|
debug: debug_1
|
||
|
};
|
||
|
|
||
|
var tunnel = tunnel$1;
|
||
|
|
||
|
var HttpClient_1 = createCommonjsModule(function (module, exports) {
|
||
|
// Copyright (c) Microsoft. All rights reserved.
|
||
|
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||
|
var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||
|
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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
|
||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||
|
});
|
||
|
};
|
||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
let fs;
|
||
|
let tunnel$1;
|
||
|
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 = {}));
|
||
|
const HttpRedirectCodes = [HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect];
|
||
|
const HttpResponseRetryCodes = [HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout];
|
||
|
const NetworkRetryErrors = ['ECONNRESET', 'ENOTFOUND', 'ESOCKETTIMEDOUT', 'ETIMEDOUT', 'ECONNREFUSED'];
|
||
|
const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];
|
||
|
const ExponentialBackoffCeiling = 10;
|
||
|
const ExponentialBackoffTimeSlice = 5;
|
||
|
class HttpClientResponse {
|
||
|
constructor(message) {
|
||
|
this.message = message;
|
||
|
}
|
||
|
readBody() {
|
||
|
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
|
||
|
let buffer = Buffer.alloc(0);
|
||
|
const encodingCharset = Util.obtainContentCharset(this);
|
||
|
// Extract Encoding from header: 'content-encoding'
|
||
|
// Match `gzip`, `gzip, deflate` variations of GZIP encoding
|
||
|
const contentEncoding = this.message.headers['content-encoding'] || '';
|
||
|
const isGzippedEncoded = new RegExp('(gzip$)|(gzip, *deflate)').test(contentEncoding);
|
||
|
this.message.on('data', function (data) {
|
||
|
const chunk = (typeof data === 'string') ? Buffer.from(data, encodingCharset) : data;
|
||
|
buffer = Buffer.concat([buffer, chunk]);
|
||
|
}).on('end', function () {
|
||
|
return __awaiter(this, void 0, void 0, function* () {
|
||
|
if (isGzippedEncoded) { // Process GZipped Response Body HERE
|
||
|
const gunzippedBody = yield Util.decompressGzippedContent(buffer, encodingCharset);
|
||
|
resolve(gunzippedBody);
|
||
|
}
|
||
|
else {
|
||
|
resolve(buffer.toString(encodingCharset));
|
||
|
}
|
||
|
});
|
||
|
}).on('error', function (err) {
|
||
|
reject(err);
|
||
|
});
|
||
|
}));
|
||
|
}
|
||
|
}
|
||
|
exports.HttpClientResponse = HttpClientResponse;
|
||
|
function isHttps(requestUrl) {
|
||
|
let parsedUrl = url__default["default"].parse(requestUrl);
|
||
|
return parsedUrl.protocol === 'https:';
|
||
|
}
|
||
|
exports.isHttps = isHttps;
|
||
|
var EnvironmentVariables;
|
||
|
(function (EnvironmentVariables) {
|
||
|
EnvironmentVariables["HTTP_PROXY"] = "HTTP_PROXY";
|
||
|
EnvironmentVariables["HTTPS_PROXY"] = "HTTPS_PROXY";
|
||
|
EnvironmentVariables["NO_PROXY"] = "NO_PROXY";
|
||
|
})(EnvironmentVariables || (EnvironmentVariables = {}));
|
||
|
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 || [];
|
||
|
let no_proxy = process.env[EnvironmentVariables.NO_PROXY];
|
||
|
if (no_proxy) {
|
||
|
this._httpProxyBypassHosts = [];
|
||
|
no_proxy.split(',').forEach(bypass => {
|
||
|
this._httpProxyBypassHosts.push(Util.buildProxyBypassRegexFromEnv(bypass));
|
||
|
});
|
||
|
}
|
||
|
this.requestOptions = requestOptions;
|
||
|
if (requestOptions) {
|
||
|
if (requestOptions.ignoreSslError != null) {
|
||
|
this._ignoreSslError = requestOptions.ignoreSslError;
|
||
|
}
|
||
|
this._socketTimeout = requestOptions.socketTimeout;
|
||
|
this._httpProxy = requestOptions.proxy;
|
||
|
if (requestOptions.proxy && requestOptions.proxy.proxyBypassHosts) {
|
||
|
this._httpProxyBypassHosts = [];
|
||
|
requestOptions.proxy.proxyBypassHosts.forEach(bypass => {
|
||
|
this._httpProxyBypassHosts.push(new RegExp(bypass, 'i'));
|
||
|
});
|
||
|
}
|
||
|
this._certConfig = requestOptions.cert;
|
||
|
if (this._certConfig) {
|
||
|
// If using cert, need fs
|
||
|
fs = require$$0__default$1["default"];
|
||
|
// cache the cert content into memory, so we don't have to read it from disk every time
|
||
|
if (this._certConfig.caFile && fs.existsSync(this._certConfig.caFile)) {
|
||
|
this._ca = fs.readFileSync(this._certConfig.caFile, 'utf8');
|
||
|
}
|
||
|
if (this._certConfig.certFile && fs.existsSync(this._certConfig.certFile)) {
|
||
|
this._cert = fs.readFileSync(this._certConfig.certFile, 'utf8');
|
||
|
}
|
||
|
if (this._certConfig.keyFile && fs.existsSync(this._certConfig.keyFile)) {
|
||
|
this._key = fs.readFileSync(this._certConfig.keyFile, 'utf8');
|
||
|
}
|
||
|
}
|
||
|
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);
|
||
|
}
|
||
|
/**
|
||
|
* Makes a raw http request.
|
||
|
* All other methods such as get, post, patch, and request ultimately call this.
|
||
|
* Prefer get, del, post and patch
|
||
|
*/
|
||
|
request(verb, requestUrl, data, headers) {
|
||
|
return __awaiter(this, void 0, void 0, function* () {
|
||
|
if (this._disposed) {
|
||
|
throw new Error("Client has already been disposed.");
|
||
|
}
|
||
|
let parsedUrl = url__default["default"].parse(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) {
|
||
|
try {
|
||
|
response = yield this.requestRaw(info, data);
|
||
|
}
|
||
|
catch (err) {
|
||
|
numTries++;
|
||
|
if (err && err.code && NetworkRetryErrors.indexOf(err.code) > -1 && numTries < maxTries) {
|
||
|
yield this._performExponentialBackoff(numTries);
|
||
|
continue;
|
||
|
}
|
||
|
throw err;
|
||
|
}
|
||
|
// 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 = url__default["default"].parse(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.
|
||
|
yield response.readBody();
|
||
|
// let's make the request with the new redirectUrl
|
||
|
info = this._prepareRequest(verb, parsedRedirectUrl, headers);
|
||
|
response = yield 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) {
|
||
|
yield response.readBody();
|
||
|
yield 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.destroy();
|
||
|
}
|
||
|
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();
|
||
|
}
|
||
|
}
|
||
|
_prepareRequest(method, requestUrl, headers) {
|
||
|
const info = {};
|
||
|
info.parsedUrl = requestUrl;
|
||
|
const usingSsl = info.parsedUrl.protocol === 'https:';
|
||
|
info.httpModule = usingSsl ? https__default["default"] : http__default["default"];
|
||
|
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.timeout = (this.requestOptions && this.requestOptions.socketTimeout) || this._socketTimeout;
|
||
|
this._socketTimeout = info.options.timeout;
|
||
|
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._isPresigned(url__default["default"].format(requestUrl))) {
|
||
|
this.handlers.forEach((handler) => {
|
||
|
handler.prepareRequest(info.options);
|
||
|
});
|
||
|
}
|
||
|
return info;
|
||
|
}
|
||
|
_isPresigned(requestUrl) {
|
||
|
if (this.requestOptions && this.requestOptions.presignedUrlPatterns) {
|
||
|
const patterns = this.requestOptions.presignedUrlPatterns;
|
||
|
for (let i = 0; i < patterns.length; i++) {
|
||
|
if (requestUrl.match(patterns[i])) {
|
||
|
return true;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
return false;
|
||
|
}
|
||
|
_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 || {});
|
||
|
}
|
||
|
_getAgent(parsedUrl) {
|
||
|
let agent;
|
||
|
let proxy = this._getProxy(parsedUrl);
|
||
|
let useProxy = proxy.proxyUrl && proxy.proxyUrl.hostname && !this._isMatchInBypassProxyList(parsedUrl);
|
||
|
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__default["default"].globalAgent.maxSockets;
|
||
|
}
|
||
|
if (useProxy) {
|
||
|
// If using proxy, need tunnel
|
||
|
if (!tunnel$1) {
|
||
|
tunnel$1 = tunnel;
|
||
|
}
|
||
|
const agentOptions = {
|
||
|
maxSockets: maxSockets,
|
||
|
keepAlive: this._keepAlive,
|
||
|
proxy: {
|
||
|
proxyAuth: proxy.proxyAuth,
|
||
|
host: proxy.proxyUrl.hostname,
|
||
|
port: proxy.proxyUrl.port
|
||
|
},
|
||
|
};
|
||
|
let tunnelAgent;
|
||
|
const overHttps = proxy.proxyUrl.protocol === 'https:';
|
||
|
if (usingSsl) {
|
||
|
tunnelAgent = overHttps ? tunnel$1.httpsOverHttps : tunnel$1.httpsOverHttp;
|
||
|
}
|
||
|
else {
|
||
|
tunnelAgent = overHttps ? tunnel$1.httpOverHttps : tunnel$1.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__default["default"].Agent(options) : new http__default["default"].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__default["default"].globalAgent : http__default["default"].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 });
|
||
|
}
|
||
|
if (usingSsl && this._certConfig) {
|
||
|
agent.options = Object.assign(agent.options || {}, { ca: this._ca, cert: this._cert, key: this._key, passphrase: this._certConfig.passphrase });
|
||
|
}
|
||
|
return agent;
|
||
|
}
|
||
|
_getProxy(parsedUrl) {
|
||
|
let usingSsl = parsedUrl.protocol === 'https:';
|
||
|
let proxyConfig = this._httpProxy;
|
||
|
// fallback to http_proxy and https_proxy env
|
||
|
let https_proxy = process.env[EnvironmentVariables.HTTPS_PROXY];
|
||
|
let http_proxy = process.env[EnvironmentVariables.HTTP_PROXY];
|
||
|
if (!proxyConfig) {
|
||
|
if (https_proxy && usingSsl) {
|
||
|
proxyConfig = {
|
||
|
proxyUrl: https_proxy
|
||
|
};
|
||
|
}
|
||
|
else if (http_proxy) {
|
||
|
proxyConfig = {
|
||
|
proxyUrl: http_proxy
|
||
|
};
|
||
|
}
|
||
|
}
|
||
|
let proxyUrl;
|
||
|
let proxyAuth;
|
||
|
if (proxyConfig) {
|
||
|
if (proxyConfig.proxyUrl.length > 0) {
|
||
|
proxyUrl = url__default["default"].parse(proxyConfig.proxyUrl);
|
||
|
}
|
||
|
if (proxyConfig.proxyUsername || proxyConfig.proxyPassword) {
|
||
|
proxyAuth = proxyConfig.proxyUsername + ":" + proxyConfig.proxyPassword;
|
||
|
}
|
||
|
}
|
||
|
return { proxyUrl: proxyUrl, proxyAuth: proxyAuth };
|
||
|
}
|
||
|
_isMatchInBypassProxyList(parsedUrl) {
|
||
|
if (!this._httpProxyBypassHosts) {
|
||
|
return false;
|
||
|
}
|
||
|
let bypass = false;
|
||
|
this._httpProxyBypassHosts.forEach(bypassHost => {
|
||
|
if (bypassHost.test(parsedUrl.href)) {
|
||
|
bypass = true;
|
||
|
}
|
||
|
});
|
||
|
return bypass;
|
||
|
}
|
||
|
_performExponentialBackoff(retryNumber) {
|
||
|
retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
|
||
|
const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
|
||
|
return new Promise(resolve => setTimeout(() => resolve(), ms));
|
||
|
}
|
||
|
}
|
||
|
exports.HttpClient = HttpClient;
|
||
|
});
|
||
|
|
||
|
// https://stackoverflow.com/a/47614491/1150961.
|
||
|
function setInnerHTML(elm, html) {
|
||
|
elm.innerHTML = html;
|
||
|
Array.from(elm.querySelectorAll("script")).forEach(oldScript => {
|
||
|
const newScript = document.createElement("script");
|
||
|
Array.from(oldScript.attributes)
|
||
|
.forEach(attr => newScript.setAttribute(attr.name, attr.value));
|
||
|
newScript.appendChild(document.createTextNode(oldScript.innerHTML));
|
||
|
oldScript.parentNode.replaceChild(newScript, oldScript);
|
||
|
});
|
||
|
}
|
||
|
const DEFAULT_SETTINGS = {
|
||
|
pythonInterpreter: 'python',
|
||
|
setupScript: '',
|
||
|
};
|
||
|
class JupterPreview extends obsidian.FileView {
|
||
|
constructor(leaf, interpreter) {
|
||
|
super(leaf);
|
||
|
// Show a placeholder before we've converted the notebook.
|
||
|
this.contentEl.innerHTML = 'Converting notebook...';
|
||
|
this.interpreter = interpreter;
|
||
|
}
|
||
|
onLoadFile(file) {
|
||
|
// Get the base path of the vault.
|
||
|
let adapter = file.vault.adapter;
|
||
|
if (!(adapter instanceof obsidian.FileSystemAdapter)) {
|
||
|
this.contentEl.innerHTML = 'Could not determine notebook path.';
|
||
|
return null;
|
||
|
}
|
||
|
// Convert the file by writing it to a temporary location. Piping unfortunately leads to
|
||
|
// problems for long lines due to buffer overflows.
|
||
|
let basePath = adapter.getBasePath();
|
||
|
let filename = `${basePath}/${file.path}`;
|
||
|
let htmlPath = `${os.tmpdir()}/${v4()}.html`;
|
||
|
let args = ['-m', 'nbconvert', `--output=${htmlPath}`, '--to=html', filename];
|
||
|
let child = child_process.spawn(this.interpreter, args);
|
||
|
// Process the output and delete the temporary file.
|
||
|
child.on('close', (code) => {
|
||
|
if (code) {
|
||
|
this.contentEl.innerHTML = 'Failed to convert notebook to HTML.';
|
||
|
}
|
||
|
else {
|
||
|
setInnerHTML(this.contentEl, require$$0$1.readFileSync(htmlPath).toString());
|
||
|
}
|
||
|
require$$0$1.rm(htmlPath, () => null);
|
||
|
});
|
||
|
return null;
|
||
|
}
|
||
|
getViewType() {
|
||
|
return 'ipynb';
|
||
|
}
|
||
|
canAcceptExtension(extension) {
|
||
|
return extension === 'ipynb';
|
||
|
}
|
||
|
}
|
||
|
class JupyterClient {
|
||
|
constructor(interpreter, args, options) {
|
||
|
this.interpreter = interpreter;
|
||
|
this.process = child_process.spawn(interpreter, args, options);
|
||
|
this.process.stdout.on('data', this.processStdOut.bind(this));
|
||
|
this.process.stderr.on('data', this.processStdErr.bind(this));
|
||
|
this.process.on('error', console.log);
|
||
|
this.promises = new Map();
|
||
|
this.stdoutParts = [];
|
||
|
}
|
||
|
processStdOut(data) {
|
||
|
this.stdoutParts.push(data.toString());
|
||
|
if (this.stdoutParts.last().endsWith('\n')) {
|
||
|
let response = JSON.parse(this.stdoutParts.join(''));
|
||
|
console.log('received response', response);
|
||
|
this.stdoutParts = [];
|
||
|
let promise = this.promises.get(response.id);
|
||
|
if (promise === undefined) {
|
||
|
console.error(`received response for unrecognised promise: ${response.id}`);
|
||
|
return;
|
||
|
}
|
||
|
promise(response.body);
|
||
|
}
|
||
|
}
|
||
|
processStdErr(data) {
|
||
|
console.log(data.toString());
|
||
|
}
|
||
|
request(body) {
|
||
|
return __awaiter$1(this, void 0, void 0, function* () {
|
||
|
// Generate a random identifier.
|
||
|
let id = v4();
|
||
|
// Send the request (\n terminated to make sure it gets picked up by the python process).
|
||
|
let data = JSON.stringify({ id: id, body: body });
|
||
|
this.process.stdin.write(data + '\n');
|
||
|
// Create a resolvable promise and store it against the id.
|
||
|
let resolve;
|
||
|
let promise = new Promise((resolve_, reject_) => {
|
||
|
resolve = resolve_;
|
||
|
});
|
||
|
this.promises.set(id, resolve);
|
||
|
return promise;
|
||
|
});
|
||
|
}
|
||
|
stop() {
|
||
|
this.process.stdin.end();
|
||
|
}
|
||
|
}
|
||
|
class JupyterPlugin extends obsidian.Plugin {
|
||
|
postprocessor(src, el, ctx) {
|
||
|
return __awaiter$1(this, void 0, void 0, function* () {
|
||
|
// Render the code using the default renderer for python.
|
||
|
yield obsidian.MarkdownRenderer.renderMarkdown('```python\n' + src + '```', el, '', this.app.workspace.activeLeaf.view);
|
||
|
// Needed for positioning of the button and hiding Jupyter prompts.
|
||
|
el.classList.add('obsidian-jupyter');
|
||
|
// Add a button to run the code.
|
||
|
let button = el.querySelector('pre').createEl('button', {
|
||
|
type: 'button',
|
||
|
text: 'Run',
|
||
|
cls: 'copy-code-button',
|
||
|
});
|
||
|
button.setAttribute('style', `right: 32pt`);
|
||
|
button.addEventListener('click', () => {
|
||
|
button.innerText = 'Running...';
|
||
|
this.getJupyterClient(ctx).request({
|
||
|
command: 'execute',
|
||
|
source: `${this.settings.setupScript}\n${src}`,
|
||
|
}).then(response => {
|
||
|
// Find the div to paste the output into or create it if necessary.
|
||
|
let output = el.querySelector('div.obsidian-jupyter-output');
|
||
|
if (output == null) {
|
||
|
output = el.createEl('div');
|
||
|
output.classList.add('obsidian-jupyter-output');
|
||
|
}
|
||
|
// Paste the output and reset the button.
|
||
|
setInnerHTML(output, response);
|
||
|
button.innerText = 'Run';
|
||
|
});
|
||
|
});
|
||
|
});
|
||
|
}
|
||
|
getJupyterClient(ctx) {
|
||
|
let client = this.clients.get(ctx.docId);
|
||
|
// Construct the interpeter path.
|
||
|
let cache = this.app.metadataCache.getCache(ctx.sourcePath);
|
||
|
let frontmatter = (cache ? cache.frontmatter : {}) || {};
|
||
|
let interpreter = (frontmatter['obsidian-jupyter'] || {})['interpreter'] || this.settings.pythonInterpreter;
|
||
|
// If we have a client, check that the interpreter path is right and stop it if not.
|
||
|
if (client && client.interpreter != interpreter) {
|
||
|
console.log(`interpreter path (${client.interpreter}) for the client for doc ` +
|
||
|
`${ctx.docId} does not match the desired path (${interpreter})`);
|
||
|
client.stop();
|
||
|
client = undefined;
|
||
|
}
|
||
|
// Create a new interpreter if required.
|
||
|
if (client === undefined) {
|
||
|
let options = { cwd: this.getBasePath() };
|
||
|
let path = this.getRelativeScriptPath();
|
||
|
client = new JupyterClient(interpreter, [path, ctx.docId], options);
|
||
|
this.clients.set(ctx.docId, client);
|
||
|
console.log(`created new client for doc ${ctx.docId} using interpreter ${interpreter}`);
|
||
|
}
|
||
|
return client;
|
||
|
}
|
||
|
createJupyterPreview(leaf) {
|
||
|
return new JupterPreview(leaf, this.settings.pythonInterpreter);
|
||
|
}
|
||
|
onload() {
|
||
|
return __awaiter$1(this, void 0, void 0, function* () {
|
||
|
console.log('loading jupyter plugin');
|
||
|
this.clients = new Map();
|
||
|
yield this.loadSettings();
|
||
|
yield this.downloadPythonScript();
|
||
|
this.addSettingTab(new JupyterSettingTab(this.app, this));
|
||
|
this.registerMarkdownCodeBlockProcessor('jupyter', this.postprocessor.bind(this));
|
||
|
this.registerView("ipynb", this.createJupyterPreview.bind(this));
|
||
|
this.registerExtensions(["ipynb"], "ipynb");
|
||
|
});
|
||
|
}
|
||
|
downloadPythonScript() {
|
||
|
return __awaiter$1(this, void 0, void 0, function* () {
|
||
|
let path = this.getAbsoluteScriptPath();
|
||
|
try {
|
||
|
let stats = require$$0$1.statSync(path);
|
||
|
if (!stats.isFile()) {
|
||
|
throw new Error('python script is missing');
|
||
|
}
|
||
|
console.log(`python script exists at ${path}`);
|
||
|
}
|
||
|
catch (_a) {
|
||
|
console.log('downloading missing python script...');
|
||
|
let client = new HttpClient_1.HttpClient('obsidian-jupyter');
|
||
|
let url = `https://github.com/tillahoffmann/obsidian-jupyter/releases/download/${this.manifest.version}/obsidian-jupyter.py`;
|
||
|
let response = yield client.get(url);
|
||
|
if (response.message.statusCode != 200) {
|
||
|
throw new Error(`could not download missing python script: ${response.message.statusMessage}`);
|
||
|
}
|
||
|
let content = yield response.readBody();
|
||
|
require$$0$1.writeFileSync(path, content);
|
||
|
console.log('obtained missing python script');
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
getRelativeScriptPath() {
|
||
|
return `${this.app.vault.configDir}/plugins/obsidian-jupyter/obsidian-jupyter.py`;
|
||
|
}
|
||
|
getAbsoluteScriptPath() {
|
||
|
return `${this.getBasePath()}/${this.getRelativeScriptPath()}`;
|
||
|
}
|
||
|
getBasePath() {
|
||
|
if (this.app.vault.adapter instanceof obsidian.FileSystemAdapter) {
|
||
|
return this.app.vault.adapter.getBasePath();
|
||
|
}
|
||
|
throw new Error('cannot determine base path');
|
||
|
}
|
||
|
onunload() {
|
||
|
console.log('unloading jupyter plugin');
|
||
|
this.clients.forEach((client, docId) => {
|
||
|
console.log(`stopping client for doc ${docId}...`);
|
||
|
client.stop();
|
||
|
});
|
||
|
}
|
||
|
loadSettings() {
|
||
|
return __awaiter$1(this, void 0, void 0, function* () {
|
||
|
this.settings = Object.assign({}, DEFAULT_SETTINGS, yield this.loadData());
|
||
|
});
|
||
|
}
|
||
|
saveSettings() {
|
||
|
return __awaiter$1(this, void 0, void 0, function* () {
|
||
|
yield this.saveData(this.settings);
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
class JupyterSettingTab extends obsidian.PluginSettingTab {
|
||
|
constructor(app, plugin) {
|
||
|
super(app, plugin);
|
||
|
this.plugin = plugin;
|
||
|
}
|
||
|
display() {
|
||
|
let { containerEl } = this;
|
||
|
containerEl.empty();
|
||
|
new obsidian.Setting(containerEl)
|
||
|
.setName('Python interpreter')
|
||
|
.setDesc('Path to your python interpreter, e.g. `/usr/bin/python`.')
|
||
|
.setClass('wideSettingsElement')
|
||
|
.addText(text => text
|
||
|
.setValue(this.plugin.settings.pythonInterpreter)
|
||
|
.onChange((value) => __awaiter$1(this, void 0, void 0, function* () {
|
||
|
this.plugin.settings.pythonInterpreter = value;
|
||
|
yield this.plugin.saveSettings();
|
||
|
})));
|
||
|
new obsidian.Setting(containerEl)
|
||
|
.setName('Python setup script')
|
||
|
.setDesc('Script that is run prior to every execution of a python code block.')
|
||
|
.setClass('setupScriptTextArea')
|
||
|
.setClass('wideSettingsElement')
|
||
|
.addTextArea(text => text
|
||
|
.setValue(this.plugin.settings.setupScript)
|
||
|
.onChange((value) => __awaiter$1(this, void 0, void 0, function* () {
|
||
|
this.plugin.settings.setupScript = value;
|
||
|
yield this.plugin.saveSettings();
|
||
|
})));
|
||
|
new obsidian.Setting(containerEl)
|
||
|
.setName('Test python environment')
|
||
|
.setDesc('Run a script to test the setup of your python environment (view developer console for details).')
|
||
|
.addButton(button => {
|
||
|
button.setButtonText('Run test');
|
||
|
button.onClick(evt => {
|
||
|
let client = this.plugin.getJupyterClient({
|
||
|
docId: 'test-document',
|
||
|
sourcePath: null,
|
||
|
frontmatter: null,
|
||
|
addChild: null,
|
||
|
getSectionInfo: null,
|
||
|
});
|
||
|
client.request({
|
||
|
command: 'execute',
|
||
|
source: '1 + 1',
|
||
|
}).then(response => {
|
||
|
console.log('Received response', response);
|
||
|
new obsidian.Notice('Test successful, view developer console for details.');
|
||
|
}).catch(error => {
|
||
|
console.error(error);
|
||
|
new obsidian.Notice('Test failed, view developer console for details.');
|
||
|
}).finally(() => {
|
||
|
client.stop();
|
||
|
this.plugin.clients.delete('test-document');
|
||
|
});
|
||
|
});
|
||
|
});
|
||
|
new obsidian.Setting(containerEl)
|
||
|
.setName('Install python dependencies')
|
||
|
.setDesc('This will modify your environment-use at your own risk.')
|
||
|
.addButton(button => {
|
||
|
button.setButtonText('Install dependencies');
|
||
|
button.onClick(evt => {
|
||
|
let interpreter = this.plugin.settings.pythonInterpreter;
|
||
|
let command = `${interpreter} -u -m pip install --upgrade --upgrade-strategy eager jupyter`;
|
||
|
new obsidian.Notice('Installing dependencies; this may take some time...');
|
||
|
child_process.exec(command, (error, stdout, stderr) => {
|
||
|
if (error) {
|
||
|
console.error(`failed to install dependencies: {error}`);
|
||
|
new obsidian.Notice('Failed to install dependencies, view developer console for details.');
|
||
|
}
|
||
|
console.log(`install stdout: ${stdout}`);
|
||
|
console.log(`install stderr: ${stdout}`);
|
||
|
new obsidian.Notice('Installed dependencies, view developer console for details.');
|
||
|
});
|
||
|
});
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
|
||
|
module.exports = JupyterPlugin;
|
||
|
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWFpbi5qcyIsInNvdXJjZXMiOlsibm9kZV9tb2R1bGVzL3RzbGliL3RzbGliLmVzNi5qcyIsIm5vZGVfbW9kdWxlcy91dWlkL2Rpc3QvZXNtLWJyb3dzZXIvcm5nLmpzIiwibm9kZV9tb2R1bGVzL3V1aWQvZGlzdC9lc20tYnJvd3Nlci9yZWdleC5qcyIsIm5vZGVfbW9kdWxlcy91dWlkL2Rpc3QvZXNtLWJyb3dzZXIvdmFsaWRhdGUuanMiLCJub2RlX21vZHVsZXMvdXVpZC9kaXN0L2VzbS1icm93c2VyL3N0cmluZ2lmeS5qcyIsIm5vZGVfbW9kdWxlcy91dWlkL2Rpc3QvZXNtLWJyb3dzZXIvdjQuanMiLCJub2RlX21vZHVsZXMvaGFzLXN5bWJvbHMvc2hhbXMuanMiLCJub2RlX21vZHVsZXMvaGFzLXN5bWJvbHMvaW5kZXguanMiLCJub2RlX21vZHVsZXMvZnVuY3Rpb24tYmluZC9pbXBsZW1lbnRhdGlvbi5qcyIsIm5vZGVfbW9kdWxlcy9mdW5jdGlvbi1iaW5kL2luZGV4LmpzIiwibm9kZV9tb2R1bGVzL2hhcy9zcmMvaW5kZXguanMiLCJub2RlX21vZHVsZXMvZ2V0LWludHJpbnNpYy9pbmRleC5qcyIsIm5vZGVfbW9kdWxlcy9jYWxsLWJpbmQvaW5kZXguanMiLCJub2RlX21vZHVsZXMvY2FsbC1iaW5kL2NhbGxCb3VuZC5qcyIsIm5vZGVfbW9kdWxlcy9vYmplY3QtaW5zcGVjdC91dGlsLmluc3BlY3QuanMiLCJub2RlX21vZHVsZXMvb2JqZWN0LWluc3BlY3QvaW5kZXguanMiLCJub2RlX21vZHVsZXMvc2lkZS1jaGFubmVsL2luZGV4LmpzIiwibm9kZV9tb2R1bGVzL3FzL2xpYi9mb3JtYXRzLmpzIiwibm9kZV9tb2R1bGVzL3FzL2xpYi91dGlscy5qcyIsIm5vZGVfbW9kdWxlcy9xcy9saWIvc3RyaW5naWZ5LmpzIiwibm9kZV9tb2R1bGVzL3FzL2xpYi9wYXJzZS5qcyIsIm5vZGVfbW9kdWxlcy9xcy9saWIvaW5kZXguanMiLCJub2RlX21vZHVsZXMvdHlwZWQtcmVzdC1jbGllbnQvVXRpbC5qcyIsIm5vZGVfbW9kdWxlcy90dW5uZWwvbGliL3R1bm5lbC5qcyIsIm5vZGVfbW9kdWxlcy90dW5uZWwvaW5kZXguanMiLCJub2RlX21vZHVsZXMvdHlwZWQtcmVzdC1jbGllbnQvSHR0cENsaWVudC5qcyIsIm1haW4udHMiXSwic291cmNlc0NvbnRlbnQiOm51bGwsIm5hbWVzIjpbIl9fYXdhaXRlciIsInN0cmluZ2lmeSIsImhhc1N5bWJvbFNoYW0iLCJ0b1N0ciIsImJpbmQiLCJ1bmRlZmluZWQiLCIkVHlwZUVycm9yIiwicmVxdWlyZSQkMCIsIiRjb25jYXQiLCIkcmVwbGFjZSIsImhhc093biIsIkdldEludHJpbnNpYyIsImhhcyIsImlzQXJyYXkiLCJpc1JlZ0V4cCIsImluc3BlY3QiLCJkZWZhdWx0cyIsInNpZGVDaGFubmVsIiwiZ2V0U2lkZUNoYW5uZWwiLCJ0aGlzIiwicGF0aCIsInVybCIsInFzIiwiemxpYiIsImh0dHAiLCJodHRwcyIsInV0aWwiLCJldmVudHMiLCJ0bHMiLCJ0dW5uZWwiLCJyZXF1aXJlJCQxIiwiRmlsZVZpZXciLCJGaWxlU3lzdGVtQWRhcHRlciIsInRtcGRpciIsInV1aWQiLCJzcGF3biIsInJlYWRGaWxlU3luYyIsInJtIiwiUGx1Z2luIiwiTWFya2Rvd25SZW5kZXJlciIsInN0YXRTeW5jIiwiSHR0cENsaWVudCIsIndyaXRlRmlsZVN5bmMiLCJQbHVnaW5TZXR0aW5nVGFiIiwiU2V0dGluZyIsIk5vdGljZSIsImV4ZWMiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBdURBO0FBQ08sU0FBU0EsV0FBUyxDQUFDLE9BQU8sRUFBRSxVQUFVLEVBQUUsQ0FBQyxFQUFFLFNBQVMsRUFBRTtBQUM3RCxJQUFJLFNBQVMsS0FBSyxDQUFDLEtBQUssRUFBRSxFQUFFLE9BQU8sS0FBSyxZQUFZLENBQUMsR0FBRyxLQUFLLEdBQUcsSUFBSSxDQUFDLENBQUMsVUFBVSxPQUFPLEVBQUUsRUFBRSxPQUFPLENBQUMsS0FBSyxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRTtBQUNoSCxJQUFJLE9BQU8sS0FBSyxDQUFDLEtBQUssQ0FBQyxHQUFHLE9BQU8sQ0FBQyxFQUFFLFVBQVUsT0FBTyxFQUFFLE1BQU0sRUFBRTtBQUMvRCxRQUFRLFNBQVMsU0FBUyxDQUFDLEtBQUssRUFBRSxFQUFFLElBQUksRUFBRSxJQUFJLENBQUMsU0FBUyxDQUFDLElBQUksQ0FBQyxLQUFLLENBQUMsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxPQUFPLENBQUMsRUFBRSxFQUFFLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxFQUFFLEVBQUU7QUFDbkcsUUFBUSxTQUFTLFFBQVEsQ0FBQyxLQUFLLEVBQUUsRUFBRSxJQUFJLEVBQUUsSUFBSSxDQUFDLFNBQVMsQ0FBQyxPQUFPLENBQUMsQ0FBQyxLQUFLLENBQUMsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxPQUFPLENBQUMsRUFBRSxFQUFFLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxFQUFFLEVBQUU7QUFDdEcsUUFBUSxTQUFTLElBQUksQ0FBQyxNQUFNLEVBQUUsRUFBRSxNQUFNLENBQUMsSUFBSSxHQUFHLE9BQU8sQ0FBQyxNQUFNLENBQUMsS0FBSyxDQUFDLEdBQUcsS0FBSyxDQUFDLE1BQU0sQ0FBQyxLQUFLLENBQUMsQ0FBQyxJQUFJLENBQUMsU0FBUyxFQUFFLFFBQVEsQ0FBQyxDQUFDLEVBQUU7QUFDdEgsUUFBUSxJQUFJLENBQUMsQ0FBQyxTQUFTLEdBQUcsU0FBUyxDQUFDLEtBQUssQ0FBQyxPQUFPLEVBQUUsVUFBVSxJQUFJLEVBQUUsQ0FBQyxFQUFFLElBQUksRUFBRSxDQUFDLENBQUM7QUFDOUUsS0FBSyxDQUFDLENBQUM7QUFDUDs7QUM3RUE7QUFDQTtBQUNBO0FBQ0EsSUFBSSxlQUFlLENBQUM7QUFDcEIsSUFBSSxLQUFLLEdBQUcsSUFBSSxVQUFVLENBQUMsRUFBRSxDQUFDLENBQUM7QUFDaEIsU0FBUyxHQUFHLEdBQUc7QUFDOUI7QUFDQSxFQUFFLElBQUksQ0FBQyxlQUFlLEVBQUU7QUFDeEI7QUFDQTtBQUNBLElBQUksZUFBZSxHQUFHLE9BQU8sTUFBTSxLQUFLLFdBQVcsSUFBSSxNQUFNLENBQUMsZUFBZSxJQUFJLE1BQU0sQ0FBQyxlQUFlLENBQUMsSUFBSSxDQUFDLE1BQU0sQ0FBQyxJQUFJLE9BQU8sUUFBUSxLQUFLLFdBQVcsSUFBSSxPQUFPLFFBQVEsQ0FBQyxlQUFlLEtBQUssVUFBVSxJQUFJLFFBQVEsQ0FBQyxlQUFlLENBQUMsSUFBSSxDQUFDLFFBQVEsQ0FBQyxDQUFDO0FBQ3J
|