From 7036f868b6f0e1a0b24d74dad6b70829e5761061 Mon Sep 17 00:00:00 2001 From: Matthew Ondash Date: Tue, 29 Sep 2020 16:09:15 -0500 Subject: [PATCH 1/3] Now uses official @actions/cache package --- build/index.js | 151728 +++++++++++++++++++++++++++-------------- package.json | 2 +- src/cache.ts | 6 +- tests/cache.test.ts | 12 +- yarn.lock | 297 +- 5 files changed, 99505 insertions(+), 52540 deletions(-) diff --git a/build/index.js b/build/index.js index 415476b4..ec76563c 100644 --- a/build/index.js +++ b/build/index.js @@ -347,8 +347,142 @@ function copyFile(srcFile, destFile, force) { //# sourceMappingURL=io.js.map /***/ }), -/* 2 */, -/* 3 */, +/* 2 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultGetter = void 0; +/** + * Default getter which just does a simple property access. Returns + * undefined if the key is not set. + * + * @param carrier + * @param key + */ +function defaultGetter(carrier, key) { + return carrier[key]; +} +exports.defaultGetter = defaultGetter; +//# sourceMappingURL=getter.js.map + +/***/ }), +/* 3 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +var once = __webpack_require__(49); + +var noop = function() {}; + +var isRequest = function(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +}; + +var isChildProcess = function(stream) { + return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 +}; + +var eos = function(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + + callback = once(callback || noop); + + var ws = stream._writableState; + var rs = stream._readableState; + var readable = opts.readable || (opts.readable !== false && stream.readable); + var writable = opts.writable || (opts.writable !== false && stream.writable); + var cancelled = false; + + var onlegacyfinish = function() { + if (!stream.writable) onfinish(); + }; + + var onfinish = function() { + writable = false; + if (!readable) callback.call(stream); + }; + + var onend = function() { + readable = false; + if (!writable) callback.call(stream); + }; + + var onexit = function(exitCode) { + callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); + }; + + var onerror = function(err) { + callback.call(stream, err); + }; + + var onclose = function() { + process.nextTick(onclosenexttick); + }; + + var onclosenexttick = function() { + if (cancelled) return; + if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); + if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); + }; + + var onrequest = function() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest(); + else stream.on('request', onrequest); + } else if (writable && !ws) { // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + if (isChildProcess(stream)) stream.on('exit', onexit); + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + + return function() { + cancelled = true; + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('exit', onexit); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +}; + +module.exports = eos; + + +/***/ }), /* 4 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -1445,68 +1579,11 @@ function wrappy (fn, cb) { /***/ }), -/* 12 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -Object.defineProperty(exports, "__esModule", { value: true }); -class BasicCredentialHandler { - constructor(username, password) { - this.username = username; - this.password = password; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; - options.headers['X-TFS-FedAuthRedirect'] = 'Suppress'; - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } -} -exports.BasicCredentialHandler = BasicCredentialHandler; - - -/***/ }), +/* 12 */, /* 13 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -var replace = String.prototype.replace; -var percentTwenties = /%20/g; - -var util = __webpack_require__(581); - -var Format = { - RFC1738: 'RFC1738', - RFC3986: 'RFC3986' -}; - -module.exports = util.assign( - { - 'default': Format.RFC3986, - formatters: { - RFC1738: function (value) { - return replace.call(value, percentTwenties, '+'); - }, - RFC3986: function (value) { - return String(value); - } - } - }, - Format -); +/***/ (function(module) { +module.exports = require("worker_threads"); /***/ }), /* 14 */ @@ -1523,24 +1600,177 @@ module.exports.stream = index.lsStream /***/ }), /* 15 */ -/***/ (function(module) { +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - - -const noop = Function.prototype -module.exports = { - error: noop, - warn: noop, - notice: noop, - info: noop, - verbose: noop, - silly: noop, - http: noop, - pause: noop, - resume: noop -} - + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(470)); +const exec = __importStar(__webpack_require__(986)); +const glob = __importStar(__webpack_require__(281)); +const io = __importStar(__webpack_require__(1)); +const fs = __importStar(__webpack_require__(747)); +const path = __importStar(__webpack_require__(622)); +const semver = __importStar(__webpack_require__(882)); +const util = __importStar(__webpack_require__(669)); +const uuid_1 = __webpack_require__(898); +const constants_1 = __webpack_require__(931); +// From https://github.com/actions/toolkit/blob/main/packages/tool-cache/src/tool-cache.ts#L23 +function createTempDirectory() { + return __awaiter(this, void 0, void 0, function* () { + const IS_WINDOWS = process.platform === 'win32'; + let tempDirectory = process.env['RUNNER_TEMP'] || ''; + if (!tempDirectory) { + let baseLocation; + if (IS_WINDOWS) { + // On Windows use the USERPROFILE env variable + baseLocation = process.env['USERPROFILE'] || 'C:\\'; + } + else { + if (process.platform === 'darwin') { + baseLocation = '/Users'; + } + else { + baseLocation = '/home'; + } + } + tempDirectory = path.join(baseLocation, 'actions', 'temp'); + } + const dest = path.join(tempDirectory, uuid_1.v4()); + yield io.mkdirP(dest); + return dest; + }); +} +exports.createTempDirectory = createTempDirectory; +function getArchiveFileSizeIsBytes(filePath) { + return fs.statSync(filePath).size; +} +exports.getArchiveFileSizeIsBytes = getArchiveFileSizeIsBytes; +function resolvePaths(patterns) { + var e_1, _a; + var _b; + return __awaiter(this, void 0, void 0, function* () { + const paths = []; + const workspace = (_b = process.env['GITHUB_WORKSPACE']) !== null && _b !== void 0 ? _b : process.cwd(); + const globber = yield glob.create(patterns.join('\n'), { + implicitDescendants: false + }); + try { + for (var _c = __asyncValues(globber.globGenerator()), _d; _d = yield _c.next(), !_d.done;) { + const file = _d.value; + const relativeFile = path.relative(workspace, file); + core.debug(`Matched: ${relativeFile}`); + // Paths are made relative so the tar entries are all relative to the root of the workspace. + paths.push(`${relativeFile}`); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_d && !_d.done && (_a = _c.return)) yield _a.call(_c); + } + finally { if (e_1) throw e_1.error; } + } + return paths; + }); +} +exports.resolvePaths = resolvePaths; +function unlinkFile(filePath) { + return __awaiter(this, void 0, void 0, function* () { + return util.promisify(fs.unlink)(filePath); + }); +} +exports.unlinkFile = unlinkFile; +function getVersion(app) { + return __awaiter(this, void 0, void 0, function* () { + core.debug(`Checking ${app} --version`); + let versionOutput = ''; + try { + yield exec.exec(`${app} --version`, [], { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => (versionOutput += data.toString()), + stderr: (data) => (versionOutput += data.toString()) + } + }); + } + catch (err) { + core.debug(err.message); + } + versionOutput = versionOutput.trim(); + core.debug(versionOutput); + return versionOutput; + }); +} +// Use zstandard if possible to maximize cache performance +function getCompressionMethod() { + return __awaiter(this, void 0, void 0, function* () { + if (process.platform === 'win32' && !(yield isGnuTarInstalled())) { + // Disable zstd due to bug https://github.com/actions/cache/issues/301 + return constants_1.CompressionMethod.Gzip; + } + const versionOutput = yield getVersion('zstd'); + const version = semver.clean(versionOutput); + if (!versionOutput.toLowerCase().includes('zstd command line interface')) { + // zstd is not installed + return constants_1.CompressionMethod.Gzip; + } + else if (!version || semver.lt(version, 'v1.3.2')) { + // zstd is installed but using a version earlier than v1.3.2 + // v1.3.2 is required to use the `--long` options in zstd + return constants_1.CompressionMethod.ZstdWithoutLong; + } + else { + return constants_1.CompressionMethod.Zstd; + } + }); +} +exports.getCompressionMethod = getCompressionMethod; +function getCacheFileName(compressionMethod) { + return compressionMethod === constants_1.CompressionMethod.Gzip + ? constants_1.CacheFilename.Gzip + : constants_1.CacheFilename.Zstd; +} +exports.getCacheFileName = getCacheFileName; +function isGnuTarInstalled() { + return __awaiter(this, void 0, void 0, function* () { + const versionOutput = yield getVersion('tar'); + return versionOutput.toLowerCase().includes('gnu tar'); + }); +} +exports.isGnuTarInstalled = isGnuTarInstalled; +function assertDefined(name, value) { + if (value === undefined) { + throw Error(`Expected ${name} but value was undefiend`); + } + return value; +} +exports.assertDefined = assertDefined; +//# sourceMappingURL=cacheUtils.js.map /***/ }), /* 16 */ @@ -1576,387 +1806,234 @@ var hasUnicode = module.exports = function () { /* 19 */ /***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDTDNotation, XMLNode, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + XMLNode = __webpack_require__(257); -module.exports = { - config: __webpack_require__(374), - parseArg: __webpack_require__(508), - readJSON: __webpack_require__(708), - logicalTree: __webpack_require__(4), - getPrefix: __webpack_require__(367), - verifyLock: __webpack_require__(873), - stringifyPackage: __webpack_require__(424), - manifest: __webpack_require__(638), - tarball: __webpack_require__(890), - extract: __webpack_require__(113), - packument: __webpack_require__(863), - hook: __webpack_require__(771), - access: __webpack_require__(704), - search: __webpack_require__(263), - team: __webpack_require__(449), - org: __webpack_require__(714), - fetch: __webpack_require__(270), - login: __webpack_require__(838), - adduser: __webpack_require__(495), - profile: __webpack_require__(244), - publish: __webpack_require__(24), - unpublish: __webpack_require__(423), - runScript: __webpack_require__(85), - log: __webpack_require__(898), - linkBin: __webpack_require__(927) -} + NodeType = __webpack_require__(683); + + module.exports = XMLDTDNotation = (function(superClass) { + extend(XMLDTDNotation, superClass); + + function XMLDTDNotation(parent, name, value) { + XMLDTDNotation.__super__.constructor.call(this, parent); + if (name == null) { + throw new Error("Missing DTD notation name. " + this.debugInfo(name)); + } + if (!value.pubID && !value.sysID) { + throw new Error("Public or system identifiers are required for an external entity. " + this.debugInfo(name)); + } + this.name = this.stringify.name(name); + this.type = NodeType.NotationDeclaration; + if (value.pubID != null) { + this.pubID = this.stringify.dtdPubID(value.pubID); + } + if (value.sysID != null) { + this.sysID = this.stringify.dtdSysID(value.sysID); + } + } + + Object.defineProperty(XMLDTDNotation.prototype, 'publicId', { + get: function() { + return this.pubID; + } + }); + + Object.defineProperty(XMLDTDNotation.prototype, 'systemId', { + get: function() { + return this.sysID; + } + }); + + XMLDTDNotation.prototype.toString = function(options) { + return this.options.writer.dtdNotation(this, this.options.writer.filterOptions(options)); + }; + + return XMLDTDNotation; + + })(XMLNode); + +}).call(this); /***/ }), /* 20 */, /* 21 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +/** + * Https Agent base on custom http agent + */ -const path = __webpack_require__(622) -const fs = __webpack_require__(598) -const chain = __webpack_require__(404).chain -const mkdir = __webpack_require__(521) -const rm = __webpack_require__(570) -const inferOwner = __webpack_require__(686) -const chown = __webpack_require__(358) - -exports = module.exports = { - link: link, - linkIfExists: linkIfExists -} -function linkIfExists (from, to, opts, cb) { - opts.currentIsLink = false - opts.currentExists = false - fs.stat(from, function (er) { - if (er) return cb() - fs.readlink(to, function (er, fromOnDisk) { - if (!er || er.code !== 'ENOENT') { - opts.currentExists = true - } - // if the link already exists and matches what we would do, - // we don't need to do anything - if (!er) { - opts.currentIsLink = true - var toDir = path.dirname(to) - var absoluteFrom = path.resolve(toDir, from) - var absoluteFromOnDisk = path.resolve(toDir, fromOnDisk) - opts.currentTarget = absoluteFromOnDisk - if (absoluteFrom === absoluteFromOnDisk) return cb() - } - link(from, to, opts, cb) - }) - }) -} +const https = __webpack_require__(211); +const HttpAgent = __webpack_require__(146); +const OriginalHttpsAgent = https.Agent; -function resolveIfSymlink (maybeSymlinkPath, cb) { - fs.lstat(maybeSymlinkPath, function (err, stat) { - if (err) return cb.apply(this, arguments) - if (!stat.isSymbolicLink()) return cb(null, maybeSymlinkPath) - fs.readlink(maybeSymlinkPath, cb) - }) -} +class HttpsAgent extends HttpAgent { + constructor(options) { + super(options); -function ensureFromIsNotSource (from, to, cb) { - resolveIfSymlink(from, function (err, fromDestination) { - if (err) return cb.apply(this, arguments) - if (path.resolve(path.dirname(from), fromDestination) === path.resolve(to)) { - return cb(new Error('Link target resolves to the same directory as link source: ' + to)) + this.defaultPort = 443; + this.protocol = 'https:'; + this.maxCachedSessions = this.options.maxCachedSessions; + if (this.maxCachedSessions === undefined) { + this.maxCachedSessions = 100; } - cb.apply(this, arguments) - }) -} - -function link (from, to, opts, cb) { - to = path.resolve(to) - opts.base = path.dirname(to) - var absTarget = path.resolve(opts.base, from) - var relativeTarget = path.relative(opts.base, absTarget) - var target = opts.absolute ? absTarget : relativeTarget - - const tasks = [ - [ensureFromIsNotSource, absTarget, to], - [fs, 'stat', absTarget], - [clobberLinkGently, from, to, opts], - [mkdir, path.dirname(to)], - [fs, 'symlink', target, to, 'junction'] - ] - if (chown.selfOwner.uid !== 0) { - chain(tasks, cb) - } else { - inferOwner(to).then(owner => { - tasks.push([chown, to, owner.uid, owner.gid]) - chain(tasks, cb) - }) + this._sessionCache = { + map: {}, + list: [], + }; } } -exports._clobberLinkGently = clobberLinkGently -function clobberLinkGently (from, to, opts, cb) { - if (opts.currentExists === false) { - // nothing to clobber! - opts.log.silly('gently link', 'link does not already exist', { - link: to, - target: from - }) - return cb() - } - - if (!opts.clobberLinkGently || - opts.force === true || - !opts.gently || - typeof opts.gently !== 'string') { - opts.log.silly('gently link', 'deleting existing link forcefully', { - link: to, - target: from, - force: opts.force, - gently: opts.gently, - clobberLinkGently: opts.clobberLinkGently - }) - return rm(to, opts, cb) - } - - if (!opts.currentIsLink) { - opts.log.verbose('gently link', 'cannot remove, not a link', to) - // don't delete. it'll fail with EEXIST when it tries to symlink. - return cb() +[ + 'createConnection', + 'getName', + '_getSession', + '_cacheSession', + // https://github.com/nodejs/node/pull/4982 + '_evictSession', +].forEach(function(method) { + if (typeof OriginalHttpsAgent.prototype[method] === 'function') { + HttpsAgent.prototype[method] = OriginalHttpsAgent.prototype[method]; } +}); - if (opts.currentTarget.indexOf(opts.gently) === 0) { - opts.log.silly('gently link', 'delete existing link', to) - return rm(to, opts, cb) - } else { - opts.log.verbose('gently link', 'refusing to delete existing link', { - link: to, - currentTarget: opts.currentTarget, - newTarget: from, - gently: opts.gently - }) - return cb() - } -} +module.exports = HttpsAgent; /***/ }), -/* 22 */, -/* 23 */ -/***/ (function(module) { +/* 22 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PropagationAPI = void 0; +var getter_1 = __webpack_require__(2); +var NoopHttpTextPropagator_1 = __webpack_require__(744); +var setter_1 = __webpack_require__(753); +var context_1 = __webpack_require__(77); +var global_utils_1 = __webpack_require__(976); +var contextApi = context_1.ContextAPI.getInstance(); +/** + * Singleton object which represents the entry point to the OpenTelemetry Propagation API + */ +var PropagationAPI = /** @class */ (function () { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + function PropagationAPI() { + } + /** Get the singleton instance of the Propagator API */ + PropagationAPI.getInstance = function () { + if (!this._instance) { + this._instance = new PropagationAPI(); + } + return this._instance; + }; + /** + * Set the current propagator. Returns the initialized propagator + */ + PropagationAPI.prototype.setGlobalPropagator = function (propagator) { + if (global_utils_1._global[global_utils_1.GLOBAL_PROPAGATION_API_KEY]) { + // global propagator has already been set + return this._getGlobalPropagator(); + } + global_utils_1._global[global_utils_1.GLOBAL_PROPAGATION_API_KEY] = global_utils_1.makeGetter(global_utils_1.API_BACKWARDS_COMPATIBILITY_VERSION, propagator, NoopHttpTextPropagator_1.NOOP_HTTP_TEXT_PROPAGATOR); + return propagator; + }; + /** + * Inject context into a carrier to be propagated inter-process + * + * @param carrier carrier to inject context into + * @param setter Function used to set values on the carrier + * @param context Context carrying tracing data to inject. Defaults to the currently active context. + */ + PropagationAPI.prototype.inject = function (carrier, setter, context) { + if (setter === void 0) { setter = setter_1.defaultSetter; } + if (context === void 0) { context = contextApi.active(); } + return this._getGlobalPropagator().inject(context, carrier, setter); + }; + /** + * Extract context from a carrier + * + * @param carrier Carrier to extract context from + * @param getter Function used to extract keys from a carrier + * @param context Context which the newly created context will inherit from. Defaults to the currently active context. + */ + PropagationAPI.prototype.extract = function (carrier, getter, context) { + if (getter === void 0) { getter = getter_1.defaultGetter; } + if (context === void 0) { context = contextApi.active(); } + return this._getGlobalPropagator().extract(context, carrier, getter); + }; + /** Remove the global propagator */ + PropagationAPI.prototype.disable = function () { + delete global_utils_1._global[global_utils_1.GLOBAL_PROPAGATION_API_KEY]; + }; + PropagationAPI.prototype._getGlobalPropagator = function () { + var _a, _b; + return ((_b = (_a = global_utils_1._global[global_utils_1.GLOBAL_PROPAGATION_API_KEY]) === null || _a === void 0 ? void 0 : _a.call(global_utils_1._global, global_utils_1.API_BACKWARDS_COMPATIBILITY_VERSION)) !== null && _b !== void 0 ? _b : NoopHttpTextPropagator_1.NOOP_HTTP_TEXT_PROPAGATOR); + }; + return PropagationAPI; +}()); +exports.PropagationAPI = PropagationAPI; +//# sourceMappingURL=propagation.js.map -// Manually added data to be used by sbcs codec in addition to generated one. - -module.exports = { - // Not supported by iconv, not sure why. - "10029": "maccenteuro", - "maccenteuro": { - "type": "_sbcs", - "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" - }, +/***/ }), +/* 23 */, +/* 24 */ +/***/ (function(__unusedmodule, exports) { - "808": "cp808", - "ibm808": "cp808", - "cp808": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " - }, +"use strict"; - "mik": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "cp720": { - "type": "_sbcs", - "chars": "\x80\x81éâ\x84à\x86çêëèïî\x8d\x8e\x8f\x90\u0651\u0652ô¤ـûùءآأؤ£إئابةتثجحخدذرزسشص«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ضطظعغفµقكلمنهوىي≡\u064b\u064c\u064d\u064e\u064f\u0650≈°∙·√ⁿ²■\u00a0" - }, +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports.default = _default; - // Aliases of generated encodings. - "ascii8bit": "ascii", - "usascii": "ascii", - "ansix34": "ascii", - "ansix341968": "ascii", - "ansix341986": "ascii", - "csascii": "ascii", - "cp367": "ascii", - "ibm367": "ascii", - "isoir6": "ascii", - "iso646us": "ascii", - "iso646irv": "ascii", - "us": "ascii", +/***/ }), +/* 25 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - "latin1": "iso88591", - "latin2": "iso88592", - "latin3": "iso88593", - "latin4": "iso88594", - "latin5": "iso88599", - "latin6": "iso885910", - "latin7": "iso885913", - "latin8": "iso885914", - "latin9": "iso885915", - "latin10": "iso885916", +"use strict"; - "csisolatin1": "iso88591", - "csisolatin2": "iso88592", - "csisolatin3": "iso88593", - "csisolatin4": "iso88594", - "csisolatincyrillic": "iso88595", - "csisolatinarabic": "iso88596", - "csisolatingreek" : "iso88597", - "csisolatinhebrew": "iso88598", - "csisolatin5": "iso88599", - "csisolatin6": "iso885910", - - "l1": "iso88591", - "l2": "iso88592", - "l3": "iso88593", - "l4": "iso88594", - "l5": "iso88599", - "l6": "iso885910", - "l7": "iso885913", - "l8": "iso885914", - "l9": "iso885915", - "l10": "iso885916", - - "isoir14": "iso646jp", - "isoir57": "iso646cn", - "isoir100": "iso88591", - "isoir101": "iso88592", - "isoir109": "iso88593", - "isoir110": "iso88594", - "isoir144": "iso88595", - "isoir127": "iso88596", - "isoir126": "iso88597", - "isoir138": "iso88598", - "isoir148": "iso88599", - "isoir157": "iso885910", - "isoir166": "tis620", - "isoir179": "iso885913", - "isoir199": "iso885914", - "isoir203": "iso885915", - "isoir226": "iso885916", - - "cp819": "iso88591", - "ibm819": "iso88591", - - "cyrillic": "iso88595", - - "arabic": "iso88596", - "arabic8": "iso88596", - "ecma114": "iso88596", - "asmo708": "iso88596", - - "greek" : "iso88597", - "greek8" : "iso88597", - "ecma118" : "iso88597", - "elot928" : "iso88597", - - "hebrew": "iso88598", - "hebrew8": "iso88598", - - "turkish": "iso88599", - "turkish8": "iso88599", - - "thai": "iso885911", - "thai8": "iso885911", - - "celtic": "iso885914", - "celtic8": "iso885914", - "isoceltic": "iso885914", - - "tis6200": "tis620", - "tis62025291": "tis620", - "tis62025330": "tis620", - - "10000": "macroman", - "10006": "macgreek", - "10007": "maccyrillic", - "10079": "maciceland", - "10081": "macturkish", - - "cspc8codepage437": "cp437", - "cspc775baltic": "cp775", - "cspc850multilingual": "cp850", - "cspcp852": "cp852", - "cspc862latinhebrew": "cp862", - "cpgr": "cp869", - - "msee": "cp1250", - "mscyrl": "cp1251", - "msansi": "cp1252", - "msgreek": "cp1253", - "msturk": "cp1254", - "mshebr": "cp1255", - "msarab": "cp1256", - "winbaltrim": "cp1257", - - "cp20866": "koi8r", - "20866": "koi8r", - "ibm878": "koi8r", - "cskoi8r": "koi8r", - - "cp21866": "koi8u", - "21866": "koi8u", - "ibm1168": "koi8u", - - "strk10482002": "rk1048", - - "tcvn5712": "tcvn", - "tcvn57121": "tcvn", - - "gb198880": "iso646cn", - "cn": "iso646cn", - - "csiso14jisc6220ro": "iso646jp", - "jisc62201969ro": "iso646jp", - "jp": "iso646jp", - - "cshproman8": "hproman8", - "r8": "hproman8", - "roman8": "hproman8", - "xroman8": "hproman8", - "ibm1051": "hproman8", - - "mac": "macintosh", - "csmacintosh": "macintosh", -}; - - - -/***/ }), -/* 24 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -module.exports = __webpack_require__(355).publish - - -/***/ }), -/* 25 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -module.exports = function(Promise, - apiRejection, - INTERNAL, - tryConvertToPromise, - Proxyable, - debug) { -var errors = __webpack_require__(607); -var TypeError = errors.TypeError; -var util = __webpack_require__(248); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -var yieldHandlers = []; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise, + Proxyable, + debug) { +var errors = __webpack_require__(351); +var TypeError = errors.TypeError; +var util = __webpack_require__(248); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +var yieldHandlers = []; function promiseFromYieldHandler(value, yieldHandlers, traceParent) { for (var i = 0; i < yieldHandlers.length; ++i) { @@ -2172,590 +2249,718 @@ Promise.spawn = function (generatorFunction) { /***/ }), /* 26 */, /* 27 */ -/***/ (function(module) { +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -// rfc7231 6.1 +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -var statusCodeCacheableByDefault = [200, 203, 204, 206, 300, 301, 404, 405, 410, 414, 501]; -// This implementation does not understand partial responses (206) -var understoodStatuses = [200, 203, 204, 300, 301, 302, 303, 307, 308, 404, 405, 410, 414, 501]; +/**/ -var hopByHopHeaders = { 'connection': true, 'keep-alive': true, 'proxy-authenticate': true, 'proxy-authorization': true, 'te': true, 'trailer': true, 'transfer-encoding': true, 'upgrade': true }; -var excludedFromRevalidationUpdate = { - // Since the old body is reused, it doesn't make sense to change properties of the body - 'content-length': true, 'content-encoding': true, 'transfer-encoding': true, - 'content-range': true -}; +var pna = __webpack_require__(822); +/**/ -function parseCacheControl(header) { - var cc = {}; - if (!header) return cc; +module.exports = Writable; - // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives), - // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale - var parts = header.trim().split(/\s*,\s*/); // TODO: lame parsing - for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { - var _ref; +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; - var part = _ref; + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ - var _part$split = part.split(/\s*=\s*/, 2), - k = _part$split[0], - v = _part$split[1]; +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ - cc[k] = v === undefined ? true : v.replace(/^"|"$/g, ''); // TODO: lame unquoting - } +/**/ +var Duplex; +/**/ - return cc; -} +Writable.WritableState = WritableState; -function formatCacheControl(cc) { - var parts = []; - for (var k in cc) { - var v = cc[k]; - parts.push(v === true ? k : k + '=' + v); - } - if (!parts.length) { - return undefined; - } - return parts.join(', '); +/**/ +var util = Object.create(__webpack_require__(286)); +util.inherits = __webpack_require__(689); +/**/ + +/**/ +var internalUtil = { + deprecate: __webpack_require__(917) +}; +/**/ + +/**/ +var Stream = __webpack_require__(427); +/**/ + +/**/ + +var Buffer = __webpack_require__(254).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } -module.exports = function () { - function CachePolicy(req, res) { - var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, - shared = _ref2.shared, - cacheHeuristic = _ref2.cacheHeuristic, - immutableMinTimeToLive = _ref2.immutableMinTimeToLive, - ignoreCargoCult = _ref2.ignoreCargoCult, - _fromObject = _ref2._fromObject; +/**/ - _classCallCheck(this, CachePolicy); +var destroyImpl = __webpack_require__(232); - if (_fromObject) { - this._fromObject(_fromObject); - return; - } +util.inherits(Writable, Stream); - if (!res || !res.headers) { - throw Error("Response headers missing"); - } - this._assertRequestHasHeaders(req); +function nop() {} - this._responseTime = this.now(); - this._isShared = shared !== false; - this._cacheHeuristic = undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE - this._immutableMinTtl = undefined !== immutableMinTimeToLive ? immutableMinTimeToLive : 24 * 3600 * 1000; +function WritableState(options, stream) { + Duplex = Duplex || __webpack_require__(907); - this._status = 'status' in res ? res.status : 200; - this._resHeaders = res.headers; - this._rescc = parseCacheControl(res.headers['cache-control']); - this._method = 'method' in req ? req.method : 'GET'; - this._url = req.url; - this._host = req.headers.host; - this._noAuthorization = !req.headers.authorization; - this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used - this._reqcc = parseCacheControl(req.headers['cache-control']); + options = options || {}; - // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching, - // so there's no point stricly adhering to the blindly copy&pasted directives. - if (ignoreCargoCult && "pre-check" in this._rescc && "post-check" in this._rescc) { - delete this._rescc['pre-check']; - delete this._rescc['post-check']; - delete this._rescc['no-cache']; - delete this._rescc['no-store']; - delete this._rescc['must-revalidate']; - this._resHeaders = Object.assign({}, this._resHeaders, { 'cache-control': formatCacheControl(this._rescc) }); - delete this._resHeaders.expires; - delete this._resHeaders.pragma; - } + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; - // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive - // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1). - if (!res.headers['cache-control'] && /no-cache/.test(res.headers.pragma)) { - this._rescc['no-cache'] = true; - } - } + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - CachePolicy.prototype.now = function now() { - return Date.now(); - }; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - CachePolicy.prototype.storable = function storable() { - // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it. - return !!(!this._reqcc['no-store'] && ( - // A cache MUST NOT store a response to any request, unless: - // The request method is understood by the cache and defined as being cacheable, and - 'GET' === this._method || 'HEAD' === this._method || 'POST' === this._method && this._hasExplicitExpiration()) && - // the response status code is understood by the cache, and - understoodStatuses.indexOf(this._status) !== -1 && - // the "no-store" cache directive does not appear in request or response header fields, and - !this._rescc['no-store'] && ( - // the "private" response directive does not appear in the response, if the cache is shared, and - !this._isShared || !this._rescc.private) && ( - // the Authorization header field does not appear in the request, if the cache is shared, - !this._isShared || this._noAuthorization || this._allowsStoringAuthenticated()) && ( - // the response either: + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; - // contains an Expires header field, or - this._resHeaders.expires || - // contains a max-age response directive, or - // contains a s-maxage response directive and the cache is shared, or - // contains a public response directive. - this._rescc.public || this._rescc['max-age'] || this._rescc['s-maxage'] || - // has a status code that is defined as cacheable by default - statusCodeCacheableByDefault.indexOf(this._status) !== -1)); - }; + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; - CachePolicy.prototype._hasExplicitExpiration = function _hasExplicitExpiration() { - // 4.2.1 Calculating Freshness Lifetime - return this._isShared && this._rescc['s-maxage'] || this._rescc['max-age'] || this._resHeaders.expires; - }; + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); - CachePolicy.prototype._assertRequestHasHeaders = function _assertRequestHasHeaders(req) { - if (!req || !req.headers) { - throw Error("Request headers missing"); - } - }; + // if _final has been called + this.finalCalled = false; - CachePolicy.prototype.satisfiesWithoutRevalidation = function satisfiesWithoutRevalidation(req) { - this._assertRequestHasHeaders(req); + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - // When presented with a request, a cache MUST NOT reuse a stored response, unless: - // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive, - // unless the stored response is successfully validated (Section 4.3), and - var requestCC = parseCacheControl(req.headers['cache-control']); - if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) { - return false; - } + // has it been destroyed + this.destroyed = false; - if (requestCC['max-age'] && this.age() > requestCC['max-age']) { - return false; - } + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - if (requestCC['min-fresh'] && this.timeToLive() < 1000 * requestCC['min-fresh']) { - return false; - } + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - // the stored response is either: - // fresh, or allowed to be served stale - if (this.stale()) { - var allowsStale = requestCC['max-stale'] && !this._rescc['must-revalidate'] && (true === requestCC['max-stale'] || requestCC['max-stale'] > this.age() - this.maxAge()); - if (!allowsStale) { - return false; - } - } + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; - return this._requestMatches(req, false); - }; + // a flag to see when we're in the middle of a write. + this.writing = false; - CachePolicy.prototype._requestMatches = function _requestMatches(req, allowHeadMethod) { - // The presented effective request URI and that of the stored response match, and - return (!this._url || this._url === req.url) && this._host === req.headers.host && ( - // the request method associated with the stored response allows it to be used for the presented request, and - !req.method || this._method === req.method || allowHeadMethod && 'HEAD' === req.method) && - // selecting header fields nominated by the stored response (if any) match those presented, and - this._varyMatches(req); - }; + // when true all writes will be buffered until .uncork() call + this.corked = 0; - CachePolicy.prototype._allowsStoringAuthenticated = function _allowsStoringAuthenticated() { - // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage. - return this._rescc['must-revalidate'] || this._rescc.public || this._rescc['s-maxage']; - }; + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - CachePolicy.prototype._varyMatches = function _varyMatches(req) { - if (!this._resHeaders.vary) { - return true; - } + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - // A Vary header field-value of "*" always fails to match - if (this._resHeaders.vary === '*') { - return false; - } + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; - var fields = this._resHeaders.vary.trim().toLowerCase().split(/\s*,\s*/); - for (var _iterator2 = fields, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { - var _ref3; + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref3 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref3 = _i2.value; - } + // the amount that is being written when _write is called. + this.writelen = 0; - var name = _ref3; + this.bufferedRequest = null; + this.lastBufferedRequest = null; - if (req.headers[name] !== this._reqHeaders[name]) return false; - } - return true; - }; + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; - CachePolicy.prototype._copyWithoutHopByHopHeaders = function _copyWithoutHopByHopHeaders(inHeaders) { - var headers = {}; - for (var name in inHeaders) { - if (hopByHopHeaders[name]) continue; - headers[name] = inHeaders[name]; - } - // 9.1. Connection - if (inHeaders.connection) { - var tokens = inHeaders.connection.trim().split(/\s*,\s*/); - for (var _iterator3 = tokens, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { - var _ref4; + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref4 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref4 = _i3.value; - } + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; - var _name = _ref4; + // count buffered requests + this.bufferedRequestCount = 0; - delete headers[_name]; - } - } - if (headers.warning) { - var warnings = headers.warning.split(/,/).filter(function (warning) { - return !/^\s*1[0-9][0-9]/.test(warning); - }); - if (!warnings.length) { - delete headers.warning; - } else { - headers.warning = warnings.join(',').trim(); - } - } - return headers; - }; + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} - CachePolicy.prototype.responseHeaders = function responseHeaders() { - var headers = this._copyWithoutHopByHopHeaders(this._resHeaders); - var age = this.age(); +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; - // A cache SHOULD generate 113 warning if it heuristically chose a freshness - // lifetime greater than 24 hours and the response's age is greater than 24 hours. - if (age > 3600 * 24 && !this._hasExplicitExpiration() && this.maxAge() > 3600 * 24) { - headers.warning = (headers.warning ? `${headers.warning}, ` : '') + '113 - "rfc7234 5.5.4"'; - } - headers.age = `${Math.round(age)}`; - return headers; - }; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); - /** - * Value of the Date response header or current time if Date was demed invalid - * @return timestamp - */ +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} - CachePolicy.prototype.date = function date() { - var dateValue = Date.parse(this._resHeaders.date); - var maxClockDrift = 8 * 3600 * 1000; - if (Number.isNaN(dateValue) || dateValue < this._responseTime - maxClockDrift || dateValue > this._responseTime + maxClockDrift) { - return this._responseTime; - } - return dateValue; - }; +function Writable(options) { + Duplex = Duplex || __webpack_require__(907); - /** - * Value of the Age header, in seconds, updated for the current time. - * May be fractional. - * - * @return Number - */ + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } - CachePolicy.prototype.age = function age() { - var age = Math.max(0, (this._responseTime - this.date()) / 1000); - if (this._resHeaders.age) { - var ageValue = this._ageValue(); - if (ageValue > age) age = ageValue; - } + this._writableState = new WritableState(options, this); - var residentTime = (this.now() - this._responseTime) / 1000; - return age + residentTime; - }; + // legacy. + this.writable = true; - CachePolicy.prototype._ageValue = function _ageValue() { - var ageValue = parseInt(this._resHeaders.age); - return isFinite(ageValue) ? ageValue : 0; - }; + if (options) { + if (typeof options.write === 'function') this._write = options.write; - /** - * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`. - * - * For an up-to-date value, see `timeToLive()`. - * - * @return Number - */ + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; - CachePolicy.prototype.maxAge = function maxAge() { - if (!this.storable() || this._rescc['no-cache']) { - return 0; - } + if (typeof options.final === 'function') this._final = options.final; + } - // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default - // so this implementation requires explicit opt-in via public header - if (this._isShared && this._resHeaders['set-cookie'] && !this._rescc.public && !this._rescc.immutable) { - return 0; - } + Stream.call(this); +} - if (this._resHeaders.vary === '*') { - return 0; - } +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; - if (this._isShared) { - if (this._rescc['proxy-revalidate']) { - return 0; - } - // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field. - if (this._rescc['s-maxage']) { - return parseInt(this._rescc['s-maxage'], 10); - } - } +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); +} - // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field. - if (this._rescc['max-age']) { - return parseInt(this._rescc['max-age'], 10); - } +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; - var defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0; + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; + } + return valid; +} - var dateValue = this.date(); - if (this._resHeaders.expires) { - var expires = Date.parse(this._resHeaders.expires); - // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired"). - if (Number.isNaN(expires) || expires < dateValue) { - return 0; - } - return Math.max(defaultMinTtl, (expires - dateValue) / 1000); - } +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); - if (this._resHeaders['last-modified']) { - var lastModified = Date.parse(this._resHeaders['last-modified']); - if (isFinite(lastModified) && dateValue > lastModified) { - return Math.max(defaultMinTtl, (dateValue - lastModified) / 1000 * this._cacheHeuristic); - } - } + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } - return defaultMinTtl; - }; + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - CachePolicy.prototype.timeToLive = function timeToLive() { - return Math.max(0, this.maxAge() - this.age()) * 1000; - }; + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - CachePolicy.prototype.stale = function stale() { - return this.maxAge() <= this.age(); - }; + if (typeof cb !== 'function') cb = nop; - CachePolicy.fromObject = function fromObject(obj) { - return new this(undefined, undefined, { _fromObject: obj }); - }; + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } - CachePolicy.prototype._fromObject = function _fromObject(obj) { - if (this._responseTime) throw Error("Reinitialized"); - if (!obj || obj.v !== 1) throw Error("Invalid serialization"); + return ret; +}; - this._responseTime = obj.t; - this._isShared = obj.sh; - this._cacheHeuristic = obj.ch; - this._immutableMinTtl = obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000; - this._status = obj.st; - this._resHeaders = obj.resh; - this._rescc = obj.rescc; - this._method = obj.m; - this._url = obj.u; - this._host = obj.h; - this._noAuthorization = obj.a; - this._reqHeaders = obj.reqh; - this._reqcc = obj.reqcc; - }; +Writable.prototype.cork = function () { + var state = this._writableState; - CachePolicy.prototype.toObject = function toObject() { - return { - v: 1, - t: this._responseTime, - sh: this._isShared, - ch: this._cacheHeuristic, - imm: this._immutableMinTtl, - st: this._status, - resh: this._resHeaders, - rescc: this._rescc, - m: this._method, - u: this._url, - h: this._host, - a: this._noAuthorization, - reqh: this._reqHeaders, - reqcc: this._reqcc - }; - }; + state.corked++; +}; - /** - * Headers for sending to the origin server to revalidate stale response. - * Allows server to return 304 to allow reuse of the previous response. - * - * Hop by hop headers are always stripped. - * Revalidation headers may be added or removed, depending on request. - */ +Writable.prototype.uncork = function () { + var state = this._writableState; + if (state.corked) { + state.corked--; - CachePolicy.prototype.revalidationHeaders = function revalidationHeaders(incomingReq) { - this._assertRequestHasHeaders(incomingReq); - var headers = this._copyWithoutHopByHopHeaders(incomingReq.headers); + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; - // This implementation does not understand range requests - delete headers['if-range']; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; - if (!this._requestMatches(incomingReq, true) || !this.storable()) { - // revalidation allowed via HEAD - // not for the same resource, or wasn't allowed to be cached anyway - delete headers['if-none-match']; - delete headers['if-modified-since']; - return headers; - } +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} - /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */ - if (this._resHeaders.etag) { - headers['if-none-match'] = headers['if-none-match'] ? `${headers['if-none-match']}, ${this._resHeaders.etag}` : this._resHeaders.etag; - } +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); - // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request. - var forbidsWeakValidators = headers['accept-ranges'] || headers['if-match'] || headers['if-unmodified-since'] || this._method && this._method != 'GET'; +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; - /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server. - Note: This implementation does not understand partial responses (206) */ - if (forbidsWeakValidators) { - delete headers['if-modified-since']; + state.length += len; - if (headers['if-none-match']) { - var etags = headers['if-none-match'].split(/,/).filter(function (etag) { - return !/^\s*W\//.test(etag); - }); - if (!etags.length) { - delete headers['if-none-match']; - } else { - headers['if-none-match'] = etags.join(',').trim(); - } - } - } else if (this._resHeaders['last-modified'] && !headers['if-modified-since']) { - headers['if-modified-since'] = this._resHeaders['last-modified']; - } + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; - return headers; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } - /** - * Creates new CachePolicy with information combined from the previews response, - * and the new revalidation response. - * - * Returns {policy, modified} where modified is a boolean indicating - * whether the response body has been modified, and old cached body can't be used. - * - * @return {Object} {policy: CachePolicy, modified: Boolean} - */ + return ret; +} +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} - CachePolicy.prototype.revalidatedPolicy = function revalidatedPolicy(request, response) { - this._assertRequestHasHeaders(request); - if (!response || !response.headers) { - throw Error("Response headers missing"); - } +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; - // These aren't going to be supported exactly, since one CachePolicy object - // doesn't know about all the other cached objects. - var matches = false; - if (response.status !== undefined && response.status != 304) { - matches = false; - } else if (response.headers.etag && !/^\s*W\//.test(response.headers.etag)) { - // "All of the stored responses with the same strong validator are selected. - // If none of the stored responses contain the same strong validator, - // then the cache MUST NOT use the new response to update any stored responses." - matches = this._resHeaders.etag && this._resHeaders.etag.replace(/^\s*W\//, '') === response.headers.etag; - } else if (this._resHeaders.etag && response.headers.etag) { - // "If the new response contains a weak validator and that validator corresponds - // to one of the cache's stored responses, - // then the most recent of those matching stored responses is selected for update." - matches = this._resHeaders.etag.replace(/^\s*W\//, '') === response.headers.etag.replace(/^\s*W\//, ''); - } else if (this._resHeaders['last-modified']) { - matches = this._resHeaders['last-modified'] === response.headers['last-modified']; - } else { - // If the new response does not include any form of validator (such as in the case where - // a client generates an If-Modified-Since request from a source other than the Last-Modified - // response header field), and there is only one stored response, and that stored response also - // lacks a validator, then that stored response is selected for update. - if (!this._resHeaders.etag && !this._resHeaders['last-modified'] && !response.headers.etag && !response.headers['last-modified']) { - matches = true; - } - } + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} - if (!matches) { - return { - policy: new this.constructor(request, response), - modified: true - }; - } +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} - // use other header fields provided in the 304 (Not Modified) response to replace all instances - // of the corresponding header fields in the stored response. - var headers = {}; - for (var k in this._resHeaders) { - headers[k] = k in response.headers && !excludedFromRevalidationUpdate[k] ? response.headers[k] : this._resHeaders[k]; - } +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; - var newResponse = Object.assign({}, response, { - status: this._status, - method: this._method, - headers - }); - return { - policy: new this.constructor(request, newResponse), - modified: false - }; - }; + onwriteStateUpdate(state); - return CachePolicy; -}(); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); -/***/ }), -/* 28 */ -/***/ (function(module) { + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } -"use strict"; + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} -// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. -module.exports = { - "437": "cp437", - "737": "cp737", - "775": "cp775", - "850": "cp850", - "852": "cp852", - "855": "cp855", - "856": "cp856", - "857": "cp857", - "858": "cp858", - "860": "cp860", - "861": "cp861", - "862": "cp862", +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); + +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; + +/***/ }), +/* 28 */ +/***/ (function(module) { + +"use strict"; + + +// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. +module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", "863": "cp863", "864": "cp864", "865": "cp865", @@ -3193,148 +3398,13 @@ module.exports = { } /***/ }), -/* 29 */ -/***/ (function(module) { - -"use strict"; - - -// turn tar(1) style args like `C` into the more verbose things like `cwd` - -const argmap = new Map([ - ['C', 'cwd'], - ['f', 'file'], - ['z', 'gzip'], - ['P', 'preservePaths'], - ['U', 'unlink'], - ['strip-components', 'strip'], - ['stripComponents', 'strip'], - ['keep-newer', 'newer'], - ['keepNewer', 'newer'], - ['keep-newer-files', 'newer'], - ['keepNewerFiles', 'newer'], - ['k', 'keep'], - ['keep-existing', 'keep'], - ['keepExisting', 'keep'], - ['m', 'noMtime'], - ['no-mtime', 'noMtime'], - ['p', 'preserveOwner'], - ['L', 'follow'], - ['h', 'follow'] -]) - -const parse = module.exports = opt => opt ? Object.keys(opt).map(k => [ - argmap.has(k) ? argmap.get(k) : k, opt[k] -]).reduce((set, kv) => (set[kv[0]] = kv[1], set), Object.create(null)) : {} - - -/***/ }), +/* 29 */, /* 30 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ (function(module) { "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); -const exec_1 = __webpack_require__(986); -const io = __importStar(__webpack_require__(1)); -const path = __importStar(__webpack_require__(622)); -const cacheHttpClient = __importStar(__webpack_require__(730)); -const constants_1 = __webpack_require__(132); -const utils = __importStar(__webpack_require__(532)); -/** - * Restore previously saved cache. Resolves with true if cache was hit. - */ -function restoreCache(inputPath, primaryKey, restoreKeys) { - return __awaiter(this, void 0, void 0, function* () { - console.log("restoring cache %s", inputPath); - console.log("primary key %s", primaryKey); - try { - // Validate inputs, this can cause task failure - let cachePath = utils.resolvePath(inputPath); - core.debug(`Cache Path: ${cachePath}`); - core.saveState(constants_1.State.CacheKey, primaryKey); - const restoredKeys = restoreKeys.split("\n").filter(x => x !== ""); - const keys = [primaryKey, ...restoredKeys]; - core.debug("Resolved Keys:"); - core.debug(JSON.stringify(keys)); - if (keys.length > 10) { - core.setFailed(`Key Validation Error: Keys are limited to a maximum of 10.`); - return false; - } - for (const key of keys) { - if (key.length > 512) { - core.setFailed(`Key Validation Error: ${key} cannot be larger than 512 characters.`); - return false; - } - const regex = /^[^,]*$/; - if (!regex.test(key)) { - core.setFailed(`Key Validation Error: ${key} cannot contain commas.`); - return false; - } - } - try { - const cacheEntry = yield cacheHttpClient.getCacheEntry(keys); - if (!cacheEntry) { - core.info(`Cache not found for input keys: ${keys.join(", ")}.`); - return false; - } - let archivePath = path.join(yield utils.createTempDirectory(), "cache.tgz"); - core.debug(`Archive Path: ${archivePath}`); - // Store the cache result - utils.setCacheState(cacheEntry); - // Download the cache from the cache entry - yield cacheHttpClient.downloadCache(cacheEntry, archivePath); - const archiveFileSize = utils.getArchiveFileSize(archivePath); - core.debug(`File Size: ${archiveFileSize}`); - io.mkdirP(cachePath); - // http://man7.org/linux/man-pages/man1/tar.1.html - // tar [-options] [files or directories which to add into archive] - const args = ["-xz"]; - const IS_WINDOWS = process.platform === "win32"; - if (IS_WINDOWS) { - args.push("--force-local"); - archivePath = archivePath.replace(/\\/g, "/"); - cachePath = cachePath.replace(/\\/g, "/"); - } - args.push(...["-f", archivePath, "-C", cachePath]); - const tarPath = yield io.which("tar", true); - core.debug(`Tar Path: ${tarPath}`); - yield exec_1.exec(`"${tarPath}"`, args); - const isExactKeyMatch = utils.isExactKeyMatch(primaryKey, cacheEntry); - utils.setCacheHitOutput(isExactKeyMatch); - core.info(`Cache restored from key: ${cacheEntry && cacheEntry.cacheKey}`); - return isExactKeyMatch; - } - catch (error) { - core.warning(error.message); - utils.setCacheHitOutput(false); - return false; - } - } - catch (error) { - core.setFailed(error.message); - return false; - } - }); -} -exports.restoreCache = restoreCache; +module.exports = process.platform === 'win32' /***/ }), @@ -3451,344 +3521,306 @@ exports._readLinuxVersionFile = _readLinuxVersionFile; /***/ }), /* 32 */, -/* 33 */, -/* 34 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 33 */ +/***/ (function(__unusedmodule, exports) { "use strict"; - -const BB = __webpack_require__(440) - -module.exports = function (child, hasExitCode = false) { - return BB.fromNode(function (cb) { - child.on('error', cb) - child.on(hasExitCode ? 'close' : 'end', function (exitCode) { - if (exitCode === undefined || exitCode === 0) { - cb() - } else { - let err = new Error('exited with error code: ' + exitCode) - cb(err) - } - }) - }) -} - +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=HttpTextPropagator.js.map /***/ }), -/* 35 */, -/* 36 */, -/* 37 */, -/* 38 */, -/* 39 */, -/* 40 */ +/* 34 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +// wrapper around mkdirp for tar's needs. -const BB = __webpack_require__(440) +// TODO: This should probably be a class, not functionally +// passing around state in a gazillion args. -const cp = __webpack_require__(129) -const execFileAsync = BB.promisify(cp.execFile, { - multiArgs: true -}) -const finished = __webpack_require__(34) -const LRU = __webpack_require__(702) -const optCheck = __webpack_require__(420) -const osenv = __webpack_require__(580) +const mkdirp = __webpack_require__(626) +const fs = __webpack_require__(747) const path = __webpack_require__(622) -const pinflight = __webpack_require__(593) -const promiseRetry = __webpack_require__(312) -const uniqueFilename = __webpack_require__(106) -const which = BB.promisify(__webpack_require__(142)) -const semver = __webpack_require__(280) -const inferOwner = __webpack_require__(686) - -const GOOD_ENV_VARS = new Set([ - 'GIT_ASKPASS', - 'GIT_EXEC_PATH', - 'GIT_PROXY_COMMAND', - 'GIT_SSH', - 'GIT_SSH_COMMAND', - 'GIT_SSL_CAINFO', - 'GIT_SSL_NO_VERIFY' -]) - -const GIT_TRANSIENT_ERRORS = [ - 'remote error: Internal Server Error', - 'The remote end hung up unexpectedly', - 'Connection timed out', - 'Operation timed out', - 'Failed to connect to .* Timed out', - 'Connection reset by peer', - 'SSL_ERROR_SYSCALL', - 'The requested URL returned error: 503' -].join('|') - -const GIT_TRANSIENT_ERROR_RE = new RegExp(GIT_TRANSIENT_ERRORS) - -const GIT_TRANSIENT_ERROR_MAX_RETRY_NUMBER = 3 +const chownr = __webpack_require__(941) -function shouldRetry (error, number) { - return GIT_TRANSIENT_ERROR_RE.test(error) && (number < GIT_TRANSIENT_ERROR_MAX_RETRY_NUMBER) -} - -const GIT_ = 'GIT_' -let GITENV -function gitEnv () { - if (GITENV) { return GITENV } - const tmpDir = path.join(osenv.tmpdir(), 'pacote-git-template-tmp') - const tmpName = uniqueFilename(tmpDir, 'git-clone') - GITENV = { - GIT_ASKPASS: 'echo', - GIT_TEMPLATE_DIR: tmpName +class SymlinkError extends Error { + constructor (symlink, path) { + super('Cannot extract through symbolic link') + this.path = path + this.symlink = symlink } - Object.keys(process.env).forEach(k => { - if (GOOD_ENV_VARS.has(k) || !k.startsWith(GIT_)) { - GITENV[k] = process.env[k] - } - }) - return GITENV -} - -let GITPATH -try { - GITPATH = which.sync('git') -} catch (e) {} -module.exports.clone = fullClone -function fullClone (repo, committish, target, opts) { - opts = optCheck(opts) - const gitArgs = ['clone', '--mirror', '-q', repo, path.join(target, '.git')] - if (process.platform === 'win32') { - gitArgs.push('--config', 'core.longpaths=true') + get name () { + return 'SylinkError' } - return execGit(gitArgs, { cwd: target }, opts).then(() => { - return execGit(['init'], { cwd: target }, opts) - }).then(() => { - return execGit(['checkout', committish || 'HEAD'], { cwd: target }, opts) - }).then(() => { - return updateSubmodules(target, opts) - }).then(() => headSha(target, opts)) } -module.exports.shallow = shallowClone -function shallowClone (repo, branch, target, opts) { - opts = optCheck(opts) - const gitArgs = ['clone', '--depth=1', '-q'] - if (branch) { - gitArgs.push('-b', branch) +class CwdError extends Error { + constructor (path, code) { + super(code + ': Cannot cd into \'' + path + '\'') + this.path = path + this.code = code } - gitArgs.push(repo, target) - if (process.platform === 'win32') { - gitArgs.push('--config', 'core.longpaths=true') + + get name () { + return 'CwdError' } - return execGit(gitArgs, { - cwd: target - }, opts).then(() => { - return updateSubmodules(target, opts) - }).then(() => headSha(target, opts)) } -function updateSubmodules (localRepo, opts) { - const gitArgs = ['submodule', 'update', '-q', '--init', '--recursive'] - return execGit(gitArgs, { - cwd: localRepo - }, opts) -} +const mkdir = module.exports = (dir, opt, cb) => { + // if there's any overlap between mask and mode, + // then we'll need an explicit chmod + const umask = opt.umask + const mode = opt.mode | 0o0700 + const needChmod = (mode & umask) !== 0 -function headSha (repo, opts) { - opts = optCheck(opts) - return execGit(['rev-parse', '--revs-only', 'HEAD'], { cwd: repo }, opts).spread(stdout => { - return stdout.trim() - }) -} + const uid = opt.uid + const gid = opt.gid + const doChown = typeof uid === 'number' && + typeof gid === 'number' && + ( uid !== opt.processUid || gid !== opt.processGid ) -const CARET_BRACES = '^{}' -const REVS = new LRU({ - max: 100, - maxAge: 5 * 60 * 1000 -}) -module.exports.revs = revs -function revs (repo, opts) { - opts = optCheck(opts) - const cached = REVS.get(repo) - if (cached) { - return BB.resolve(cached) - } - return pinflight(`ls-remote:${repo}`, () => { - return spawnGit(['ls-remote', '-h', '-t', repo], { - env: gitEnv() - }, opts).then((stdout) => { - return stdout.split('\n').reduce((revs, line) => { - const split = line.split(/\s+/, 2) - if (split.length < 2) { return revs } - const sha = split[0].trim() - const ref = split[1].trim().match(/(?:refs\/[^/]+\/)?(.*)/)[1] - if (!ref) { return revs } // ??? - if (ref.endsWith(CARET_BRACES)) { return revs } // refs/tags/x^{} crap - const type = refType(line) - const doc = { sha, ref, type } + const preserve = opt.preserve + const unlink = opt.unlink + const cache = opt.cache + const cwd = opt.cwd - revs.refs[ref] = doc - // We can check out shallow clones on specific SHAs if we have a ref - if (revs.shas[sha]) { - revs.shas[sha].push(ref) - } else { - revs.shas[sha] = [ref] - } + const done = (er, created) => { + if (er) + cb(er) + else { + cache.set(dir, true) + if (created && doChown) + chownr(created, uid, gid, er => done(er)) + else if (needChmod) + fs.chmod(dir, mode, cb) + else + cb() + } + } - if (type === 'tag') { - const match = ref.match(/v?(\d+\.\d+\.\d+(?:[-+].+)?)$/) - if (match && semver.valid(match[1], true)) { - revs.versions[semver.clean(match[1], true)] = doc - } - } + if (cache && cache.get(dir) === true) + return done() - return revs - }, { versions: {}, 'dist-tags': {}, refs: {}, shas: {} }) - }, err => { - err.message = `Error while executing:\n${GITPATH} ls-remote -h -t ${repo}\n\n${err.stderr}\n${err.message}` - throw err - }).then(revs => { - if (revs.refs.HEAD) { - const HEAD = revs.refs.HEAD - Object.keys(revs.versions).forEach(v => { - if (v.sha === HEAD.sha) { - revs['dist-tags'].HEAD = v - if (!revs.refs.latest) { - revs['dist-tags'].latest = revs.refs.HEAD - } - } - }) - } - REVS.set(repo, revs) - return revs + if (dir === cwd) + return fs.stat(dir, (er, st) => { + if (er || !st.isDirectory()) + er = new CwdError(dir, er && er.code || 'ENOTDIR') + done(er) }) - }) -} -// infer the owner from the cwd git is operating in, if not the -// process cwd, but only if we're root. -// See: https://github.com/npm/cli/issues/624 -module.exports._cwdOwner = cwdOwner -function cwdOwner (gitOpts, opts) { - const isRoot = process.getuid && process.getuid() === 0 - if (!isRoot || !gitOpts.cwd) { return Promise.resolve() } + if (preserve) + return mkdirp(dir, mode, done) - return BB.resolve(inferOwner(gitOpts.cwd).then(owner => { - gitOpts.uid = owner.uid - gitOpts.gid = owner.gid - })) + const sub = path.relative(cwd, dir) + const parts = sub.split(/\/|\\/) + mkdir_(cwd, parts, mode, cache, unlink, cwd, null, done) } -module.exports._exec = execGit -function execGit (gitArgs, gitOpts, opts) { - opts = optCheck(opts) - return BB.resolve(cwdOwner(gitOpts, opts).then(() => checkGit(opts).then(gitPath => { - return promiseRetry((retry, number) => { - if (number !== 1) { - opts.log.silly('pacote', 'Retrying git command: ' + gitArgs.join(' ') + ' attempt # ' + number) - } - return execFileAsync(gitPath, gitArgs, mkOpts(gitOpts, opts)).catch((err) => { - if (shouldRetry(err, number)) { - retry(err) - } else { - throw err - } - }) - }, opts.retry != null ? opts.retry : { - retries: opts['fetch-retries'], - factor: opts['fetch-retry-factor'], - maxTimeout: opts['fetch-retry-maxtimeout'], - minTimeout: opts['fetch-retry-mintimeout'] +const mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => { + if (!parts.length) + return cb(null, created) + const p = parts.shift() + const part = base + '/' + p + if (cache.get(part)) + return mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) + fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) +} + +const onmkdir = (part, parts, mode, cache, unlink, cwd, created, cb) => er => { + if (er) { + if (er.path && path.dirname(er.path) === cwd && + (er.code === 'ENOTDIR' || er.code === 'ENOENT')) + return cb(new CwdError(cwd, er.code)) + + fs.lstat(part, (statEr, st) => { + if (statEr) + cb(statEr) + else if (st.isDirectory()) + mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) + else if (unlink) + fs.unlink(part, er => { + if (er) + return cb(er) + fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) + }) + else if (st.isSymbolicLink()) + return cb(new SymlinkError(part, part + '/' + parts.join('/'))) + else + cb(er) }) - }))) + } else { + created = created || part + mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) + } } -module.exports._spawn = spawnGit -function spawnGit (gitArgs, gitOpts, opts) { - opts = optCheck(opts) - return BB.resolve(cwdOwner(gitOpts, opts).then(() => checkGit(opts).then(gitPath => { - return promiseRetry((retry, number) => { - if (number !== 1) { - opts.log.silly('pacote', 'Retrying git command: ' + gitArgs.join(' ') + ' attempt # ' + number) - } - const child = cp.spawn(gitPath, gitArgs, mkOpts(gitOpts, opts)) +const mkdirSync = module.exports.sync = (dir, opt) => { + // if there's any overlap between mask and mode, + // then we'll need an explicit chmod + const umask = opt.umask + const mode = opt.mode | 0o0700 + const needChmod = (mode & umask) !== 0 - let stdout = '' - let stderr = '' - child.stdout.on('data', d => { stdout += d }) - child.stderr.on('data', d => { stderr += d }) + const uid = opt.uid + const gid = opt.gid + const doChown = typeof uid === 'number' && + typeof gid === 'number' && + ( uid !== opt.processUid || gid !== opt.processGid ) - return finished(child, true).catch(err => { - if (shouldRetry(stderr, number)) { - retry(err) - } else { - err.stderr = stderr - throw err - } - }).then(() => { - return stdout - }) - }, opts.retry) - }))) -} + const preserve = opt.preserve + const unlink = opt.unlink + const cache = opt.cache + const cwd = opt.cwd -module.exports._mkOpts = mkOpts -function mkOpts (_gitOpts, opts) { - const gitOpts = { - env: gitEnv() - } - const isRoot = process.getuid && process.getuid() === 0 - // don't change child process uid/gid if not root - if (+opts.uid && !isNaN(opts.uid) && isRoot) { - gitOpts.uid = +opts.uid + const done = (created) => { + cache.set(dir, true) + if (created && doChown) + chownr.sync(created, uid, gid) + if (needChmod) + fs.chmodSync(dir, mode) } - if (+opts.gid && !isNaN(opts.gid) && isRoot) { - gitOpts.gid = +opts.gid + + if (cache && cache.get(dir) === true) + return done() + + if (dir === cwd) { + let ok = false + let code = 'ENOTDIR' + try { + ok = fs.statSync(dir).isDirectory() + } catch (er) { + code = er.code + } finally { + if (!ok) + throw new CwdError(dir, code) + } + done() + return } - Object.assign(gitOpts, _gitOpts) - return gitOpts -} -function checkGit (opts) { - if (opts.git) { - return BB.resolve(opts.git) - } else if (!GITPATH) { - const err = new Error('No git binary found in $PATH') - err.code = 'ENOGIT' - return BB.reject(err) - } else { - return BB.resolve(GITPATH) + if (preserve) + return done(mkdirp.sync(dir, mode)) + + const sub = path.relative(cwd, dir) + const parts = sub.split(/\/|\\/) + let created = null + for (let p = parts.shift(), part = cwd; + p && (part += '/' + p); + p = parts.shift()) { + + if (cache.get(part)) + continue + + try { + fs.mkdirSync(part, mode) + created = created || part + cache.set(part, true) + } catch (er) { + if (er.path && path.dirname(er.path) === cwd && + (er.code === 'ENOTDIR' || er.code === 'ENOENT')) + return new CwdError(cwd, er.code) + + const st = fs.lstatSync(part) + if (st.isDirectory()) { + cache.set(part, true) + continue + } else if (unlink) { + fs.unlinkSync(part) + fs.mkdirSync(part, mode) + created = created || part + cache.set(part, true) + continue + } else if (st.isSymbolicLink()) + return new SymlinkError(part, part + '/' + parts.join('/')) + } } -} -const REFS_TAGS = 'refs/tags/' -const REFS_HEADS = 'refs/heads/' -const HEAD = 'HEAD' -function refType (ref) { - return ref.indexOf(REFS_TAGS) !== -1 - ? 'tag' - : ref.indexOf(REFS_HEADS) !== -1 - ? 'branch' - : ref.endsWith(HEAD) - ? 'head' - : 'other' + return done(created) } /***/ }), -/* 41 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 35 */, +/* 36 */, +/* 37 */, +/* 38 */, +/* 39 */, +/* 40 */ +/***/ (function(__unusedmodule, exports) { -module.exports = __webpack_require__(794); +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EntryTtl = void 0; +/** + * EntryTtl is an integer that represents number of hops an entry can propagate. + * + * For now, ONLY special values (0 and -1) are supported. + */ +var EntryTtl; +(function (EntryTtl) { + /** + * NO_PROPAGATION is considered to have local context and is used within the + * process it created. + */ + EntryTtl[EntryTtl["NO_PROPAGATION"] = 0] = "NO_PROPAGATION"; + /** UNLIMITED_PROPAGATION can propagate unlimited hops. */ + EntryTtl[EntryTtl["UNLIMITED_PROPAGATION"] = -1] = "UNLIMITED_PROPAGATION"; +})(EntryTtl = exports.EntryTtl || (exports.EntryTtl = {})); +//# sourceMappingURL=EntryValue.js.map /***/ }), +/* 41 */, /* 42 */, -/* 43 */, +/* 43 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueType = void 0; +/** The Type of value. It describes how the data is reported. */ +var ValueType; +(function (ValueType) { + ValueType[ValueType["INT"] = 0] = "INT"; + ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; +})(ValueType = exports.ValueType || (exports.ValueType = {})); +//# sourceMappingURL=Metric.js.map + +/***/ }), /* 44 */, /* 45 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -3929,29 +3961,110 @@ function onceStrict (fn) { /***/ }), -/* 50 */, -/* 51 */, -/* 52 */ +/* 50 */ /***/ (function(module) { -module.exports = ["389-exception","Autoconf-exception-2.0","Autoconf-exception-3.0","Bison-exception-2.2","Bootloader-exception","Classpath-exception-2.0","CLISP-exception-2.0","DigiRule-FOSS-exception","eCos-exception-2.0","Fawkes-Runtime-exception","FLTK-exception","Font-exception-2.0","freertos-exception-2.0","GCC-exception-2.0","GCC-exception-3.1","gnu-javamail-exception","GPL-3.0-linking-exception","GPL-3.0-linking-source-exception","GPL-CC-1.0","i2p-gpl-java-exception","Libtool-exception","Linux-syscall-note","LLVM-exception","LZMA-exception","mif-exception","Nokia-Qt-exception-1.1","OCaml-LGPL-linking-exception","OCCT-exception-1.0","OpenJDK-assembly-exception-1.0","openvpn-openssl-exception","PS-or-PDF-font-exception-20170817","Qt-GPL-exception-1.0","Qt-LGPL-exception-1.1","Qwt-exception-1.0","Swift-exception","u-boot-exception-2.0","Universal-FOSS-exception-1.0","WxWindows-exception-3.1"]; +module.exports = ["ac","com.ac","edu.ac","gov.ac","net.ac","mil.ac","org.ac","ad","nom.ad","ae","co.ae","net.ae","org.ae","sch.ae","ac.ae","gov.ae","mil.ae","aero","accident-investigation.aero","accident-prevention.aero","aerobatic.aero","aeroclub.aero","aerodrome.aero","agents.aero","aircraft.aero","airline.aero","airport.aero","air-surveillance.aero","airtraffic.aero","air-traffic-control.aero","ambulance.aero","amusement.aero","association.aero","author.aero","ballooning.aero","broker.aero","caa.aero","cargo.aero","catering.aero","certification.aero","championship.aero","charter.aero","civilaviation.aero","club.aero","conference.aero","consultant.aero","consulting.aero","control.aero","council.aero","crew.aero","design.aero","dgca.aero","educator.aero","emergency.aero","engine.aero","engineer.aero","entertainment.aero","equipment.aero","exchange.aero","express.aero","federation.aero","flight.aero","freight.aero","fuel.aero","gliding.aero","government.aero","groundhandling.aero","group.aero","hanggliding.aero","homebuilt.aero","insurance.aero","journal.aero","journalist.aero","leasing.aero","logistics.aero","magazine.aero","maintenance.aero","media.aero","microlight.aero","modelling.aero","navigation.aero","parachuting.aero","paragliding.aero","passenger-association.aero","pilot.aero","press.aero","production.aero","recreation.aero","repbody.aero","res.aero","research.aero","rotorcraft.aero","safety.aero","scientist.aero","services.aero","show.aero","skydiving.aero","software.aero","student.aero","trader.aero","trading.aero","trainer.aero","union.aero","workinggroup.aero","works.aero","af","gov.af","com.af","org.af","net.af","edu.af","ag","com.ag","org.ag","net.ag","co.ag","nom.ag","ai","off.ai","com.ai","net.ai","org.ai","al","com.al","edu.al","gov.al","mil.al","net.al","org.al","am","co.am","com.am","commune.am","net.am","org.am","ao","ed.ao","gv.ao","og.ao","co.ao","pb.ao","it.ao","aq","ar","com.ar","edu.ar","gob.ar","gov.ar","int.ar","mil.ar","musica.ar","net.ar","org.ar","tur.ar","arpa","e164.arpa","in-addr.arpa","ip6.arpa","iris.arpa","uri.arpa","urn.arpa","as","gov.as","asia","at","ac.at","co.at","gv.at","or.at","au","com.au","net.au","org.au","edu.au","gov.au","asn.au","id.au","info.au","conf.au","oz.au","act.au","nsw.au","nt.au","qld.au","sa.au","tas.au","vic.au","wa.au","act.edu.au","catholic.edu.au","nsw.edu.au","nt.edu.au","qld.edu.au","sa.edu.au","tas.edu.au","vic.edu.au","wa.edu.au","qld.gov.au","sa.gov.au","tas.gov.au","vic.gov.au","wa.gov.au","education.tas.edu.au","schools.nsw.edu.au","aw","com.aw","ax","az","com.az","net.az","int.az","gov.az","org.az","edu.az","info.az","pp.az","mil.az","name.az","pro.az","biz.az","ba","com.ba","edu.ba","gov.ba","mil.ba","net.ba","org.ba","bb","biz.bb","co.bb","com.bb","edu.bb","gov.bb","info.bb","net.bb","org.bb","store.bb","tv.bb","*.bd","be","ac.be","bf","gov.bf","bg","a.bg","b.bg","c.bg","d.bg","e.bg","f.bg","g.bg","h.bg","i.bg","j.bg","k.bg","l.bg","m.bg","n.bg","o.bg","p.bg","q.bg","r.bg","s.bg","t.bg","u.bg","v.bg","w.bg","x.bg","y.bg","z.bg","0.bg","1.bg","2.bg","3.bg","4.bg","5.bg","6.bg","7.bg","8.bg","9.bg","bh","com.bh","edu.bh","net.bh","org.bh","gov.bh","bi","co.bi","com.bi","edu.bi","or.bi","org.bi","biz","bj","asso.bj","barreau.bj","gouv.bj","bm","com.bm","edu.bm","gov.bm","net.bm","org.bm","bn","com.bn","edu.bn","gov.bn","net.bn","org.bn","bo","com.bo","edu.bo","gob.bo","int.bo","org.bo","net.bo","mil.bo","tv.bo","web.bo","academia.bo","agro.bo","arte.bo","blog.bo","bolivia.bo","ciencia.bo","cooperativa.bo","democracia.bo","deporte.bo","ecologia.bo","economia.bo","empresa.bo","indigena.bo","industria.bo","info.bo","medicina.bo","movimiento.bo","musica.bo","natural.bo","nombre.bo","noticias.bo","patria.bo","politica.bo","profesional.bo","plurinacional.bo","pueblo.bo","revista.bo","salud.bo","tecnologia.bo","tksat.bo","transporte.bo","wiki.bo","br","9guacu.br","abc.br","adm.br","adv.br","agr.br","aju.br","am.br","anani.br","aparecida.br","arq.br","art.br","ato.br","b.br","barueri.br","belem.br","bhz.br","bio.br","blog.br","bmd.br","boavista.br","bsb.br","campinagrande.br","campinas.br","caxias.br","cim.br","cng.br","cnt.br","com.br","contagem.br","coop.br","cri.br","cuiaba.br","curitiba.br","def.br","ecn.br","eco.br","edu.br","emp.br","eng.br","esp.br","etc.br","eti.br","far.br","feira.br","flog.br","floripa.br","fm.br","fnd.br","fortal.br","fot.br","foz.br","fst.br","g12.br","ggf.br","goiania.br","gov.br","ac.gov.br","al.gov.br","am.gov.br","ap.gov.br","ba.gov.br","ce.gov.br","df.gov.br","es.gov.br","go.gov.br","ma.gov.br","mg.gov.br","ms.gov.br","mt.gov.br","pa.gov.br","pb.gov.br","pe.gov.br","pi.gov.br","pr.gov.br","rj.gov.br","rn.gov.br","ro.gov.br","rr.gov.br","rs.gov.br","sc.gov.br","se.gov.br","sp.gov.br","to.gov.br","gru.br","imb.br","ind.br","inf.br","jab.br","jampa.br","jdf.br","joinville.br","jor.br","jus.br","leg.br","lel.br","londrina.br","macapa.br","maceio.br","manaus.br","maringa.br","mat.br","med.br","mil.br","morena.br","mp.br","mus.br","natal.br","net.br","niteroi.br","*.nom.br","not.br","ntr.br","odo.br","ong.br","org.br","osasco.br","palmas.br","poa.br","ppg.br","pro.br","psc.br","psi.br","pvh.br","qsl.br","radio.br","rec.br","recife.br","ribeirao.br","rio.br","riobranco.br","riopreto.br","salvador.br","sampa.br","santamaria.br","santoandre.br","saobernardo.br","saogonca.br","sjc.br","slg.br","slz.br","sorocaba.br","srv.br","taxi.br","tc.br","teo.br","the.br","tmp.br","trd.br","tur.br","tv.br","udi.br","vet.br","vix.br","vlog.br","wiki.br","zlg.br","bs","com.bs","net.bs","org.bs","edu.bs","gov.bs","bt","com.bt","edu.bt","gov.bt","net.bt","org.bt","bv","bw","co.bw","org.bw","by","gov.by","mil.by","com.by","of.by","bz","com.bz","net.bz","org.bz","edu.bz","gov.bz","ca","ab.ca","bc.ca","mb.ca","nb.ca","nf.ca","nl.ca","ns.ca","nt.ca","nu.ca","on.ca","pe.ca","qc.ca","sk.ca","yk.ca","gc.ca","cat","cc","cd","gov.cd","cf","cg","ch","ci","org.ci","or.ci","com.ci","co.ci","edu.ci","ed.ci","ac.ci","net.ci","go.ci","asso.ci","aéroport.ci","int.ci","presse.ci","md.ci","gouv.ci","*.ck","!www.ck","cl","aprendemas.cl","co.cl","gob.cl","gov.cl","mil.cl","cm","co.cm","com.cm","gov.cm","net.cm","cn","ac.cn","com.cn","edu.cn","gov.cn","net.cn","org.cn","mil.cn","公司.cn","网络.cn","網絡.cn","ah.cn","bj.cn","cq.cn","fj.cn","gd.cn","gs.cn","gz.cn","gx.cn","ha.cn","hb.cn","he.cn","hi.cn","hl.cn","hn.cn","jl.cn","js.cn","jx.cn","ln.cn","nm.cn","nx.cn","qh.cn","sc.cn","sd.cn","sh.cn","sn.cn","sx.cn","tj.cn","xj.cn","xz.cn","yn.cn","zj.cn","hk.cn","mo.cn","tw.cn","co","arts.co","com.co","edu.co","firm.co","gov.co","info.co","int.co","mil.co","net.co","nom.co","org.co","rec.co","web.co","com","coop","cr","ac.cr","co.cr","ed.cr","fi.cr","go.cr","or.cr","sa.cr","cu","com.cu","edu.cu","org.cu","net.cu","gov.cu","inf.cu","cv","cw","com.cw","edu.cw","net.cw","org.cw","cx","gov.cx","cy","ac.cy","biz.cy","com.cy","ekloges.cy","gov.cy","ltd.cy","name.cy","net.cy","org.cy","parliament.cy","press.cy","pro.cy","tm.cy","cz","de","dj","dk","dm","com.dm","net.dm","org.dm","edu.dm","gov.dm","do","art.do","com.do","edu.do","gob.do","gov.do","mil.do","net.do","org.do","sld.do","web.do","dz","com.dz","org.dz","net.dz","gov.dz","edu.dz","asso.dz","pol.dz","art.dz","ec","com.ec","info.ec","net.ec","fin.ec","k12.ec","med.ec","pro.ec","org.ec","edu.ec","gov.ec","gob.ec","mil.ec","edu","ee","edu.ee","gov.ee","riik.ee","lib.ee","med.ee","com.ee","pri.ee","aip.ee","org.ee","fie.ee","eg","com.eg","edu.eg","eun.eg","gov.eg","mil.eg","name.eg","net.eg","org.eg","sci.eg","*.er","es","com.es","nom.es","org.es","gob.es","edu.es","et","com.et","gov.et","org.et","edu.et","biz.et","name.et","info.et","net.et","eu","fi","aland.fi","fj","ac.fj","biz.fj","com.fj","gov.fj","info.fj","mil.fj","name.fj","net.fj","org.fj","pro.fj","*.fk","fm","fo","fr","asso.fr","com.fr","gouv.fr","nom.fr","prd.fr","tm.fr","aeroport.fr","avocat.fr","avoues.fr","cci.fr","chambagri.fr","chirurgiens-dentistes.fr","experts-comptables.fr","geometre-expert.fr","greta.fr","huissier-justice.fr","medecin.fr","notaires.fr","pharmacien.fr","port.fr","veterinaire.fr","ga","gb","gd","ge","com.ge","edu.ge","gov.ge","org.ge","mil.ge","net.ge","pvt.ge","gf","gg","co.gg","net.gg","org.gg","gh","com.gh","edu.gh","gov.gh","org.gh","mil.gh","gi","com.gi","ltd.gi","gov.gi","mod.gi","edu.gi","org.gi","gl","co.gl","com.gl","edu.gl","net.gl","org.gl","gm","gn","ac.gn","com.gn","edu.gn","gov.gn","org.gn","net.gn","gov","gp","com.gp","net.gp","mobi.gp","edu.gp","org.gp","asso.gp","gq","gr","com.gr","edu.gr","net.gr","org.gr","gov.gr","gs","gt","com.gt","edu.gt","gob.gt","ind.gt","mil.gt","net.gt","org.gt","gu","com.gu","edu.gu","gov.gu","guam.gu","info.gu","net.gu","org.gu","web.gu","gw","gy","co.gy","com.gy","edu.gy","gov.gy","net.gy","org.gy","hk","com.hk","edu.hk","gov.hk","idv.hk","net.hk","org.hk","公司.hk","教育.hk","敎育.hk","政府.hk","個人.hk","个人.hk","箇人.hk","網络.hk","网络.hk","组織.hk","網絡.hk","网絡.hk","组织.hk","組織.hk","組织.hk","hm","hn","com.hn","edu.hn","org.hn","net.hn","mil.hn","gob.hn","hr","iz.hr","from.hr","name.hr","com.hr","ht","com.ht","shop.ht","firm.ht","info.ht","adult.ht","net.ht","pro.ht","org.ht","med.ht","art.ht","coop.ht","pol.ht","asso.ht","edu.ht","rel.ht","gouv.ht","perso.ht","hu","co.hu","info.hu","org.hu","priv.hu","sport.hu","tm.hu","2000.hu","agrar.hu","bolt.hu","casino.hu","city.hu","erotica.hu","erotika.hu","film.hu","forum.hu","games.hu","hotel.hu","ingatlan.hu","jogasz.hu","konyvelo.hu","lakas.hu","media.hu","news.hu","reklam.hu","sex.hu","shop.hu","suli.hu","szex.hu","tozsde.hu","utazas.hu","video.hu","id","ac.id","biz.id","co.id","desa.id","go.id","mil.id","my.id","net.id","or.id","ponpes.id","sch.id","web.id","ie","gov.ie","il","ac.il","co.il","gov.il","idf.il","k12.il","muni.il","net.il","org.il","im","ac.im","co.im","com.im","ltd.co.im","net.im","org.im","plc.co.im","tt.im","tv.im","in","co.in","firm.in","net.in","org.in","gen.in","ind.in","nic.in","ac.in","edu.in","res.in","gov.in","mil.in","info","int","eu.int","io","com.io","iq","gov.iq","edu.iq","mil.iq","com.iq","org.iq","net.iq","ir","ac.ir","co.ir","gov.ir","id.ir","net.ir","org.ir","sch.ir","ایران.ir","ايران.ir","is","net.is","com.is","edu.is","gov.is","org.is","int.is","it","gov.it","edu.it","abr.it","abruzzo.it","aosta-valley.it","aostavalley.it","bas.it","basilicata.it","cal.it","calabria.it","cam.it","campania.it","emilia-romagna.it","emiliaromagna.it","emr.it","friuli-v-giulia.it","friuli-ve-giulia.it","friuli-vegiulia.it","friuli-venezia-giulia.it","friuli-veneziagiulia.it","friuli-vgiulia.it","friuliv-giulia.it","friulive-giulia.it","friulivegiulia.it","friulivenezia-giulia.it","friuliveneziagiulia.it","friulivgiulia.it","fvg.it","laz.it","lazio.it","lig.it","liguria.it","lom.it","lombardia.it","lombardy.it","lucania.it","mar.it","marche.it","mol.it","molise.it","piedmont.it","piemonte.it","pmn.it","pug.it","puglia.it","sar.it","sardegna.it","sardinia.it","sic.it","sicilia.it","sicily.it","taa.it","tos.it","toscana.it","trentin-sud-tirol.it","trentin-süd-tirol.it","trentin-sudtirol.it","trentin-südtirol.it","trentin-sued-tirol.it","trentin-suedtirol.it","trentino-a-adige.it","trentino-aadige.it","trentino-alto-adige.it","trentino-altoadige.it","trentino-s-tirol.it","trentino-stirol.it","trentino-sud-tirol.it","trentino-süd-tirol.it","trentino-sudtirol.it","trentino-südtirol.it","trentino-sued-tirol.it","trentino-suedtirol.it","trentino.it","trentinoa-adige.it","trentinoaadige.it","trentinoalto-adige.it","trentinoaltoadige.it","trentinos-tirol.it","trentinostirol.it","trentinosud-tirol.it","trentinosüd-tirol.it","trentinosudtirol.it","trentinosüdtirol.it","trentinosued-tirol.it","trentinosuedtirol.it","trentinsud-tirol.it","trentinsüd-tirol.it","trentinsudtirol.it","trentinsüdtirol.it","trentinsued-tirol.it","trentinsuedtirol.it","tuscany.it","umb.it","umbria.it","val-d-aosta.it","val-daosta.it","vald-aosta.it","valdaosta.it","valle-aosta.it","valle-d-aosta.it","valle-daosta.it","valleaosta.it","valled-aosta.it","valledaosta.it","vallee-aoste.it","vallée-aoste.it","vallee-d-aoste.it","vallée-d-aoste.it","valleeaoste.it","valléeaoste.it","valleedaoste.it","valléedaoste.it","vao.it","vda.it","ven.it","veneto.it","ag.it","agrigento.it","al.it","alessandria.it","alto-adige.it","altoadige.it","an.it","ancona.it","andria-barletta-trani.it","andria-trani-barletta.it","andriabarlettatrani.it","andriatranibarletta.it","ao.it","aosta.it","aoste.it","ap.it","aq.it","aquila.it","ar.it","arezzo.it","ascoli-piceno.it","ascolipiceno.it","asti.it","at.it","av.it","avellino.it","ba.it","balsan-sudtirol.it","balsan-südtirol.it","balsan-suedtirol.it","balsan.it","bari.it","barletta-trani-andria.it","barlettatraniandria.it","belluno.it","benevento.it","bergamo.it","bg.it","bi.it","biella.it","bl.it","bn.it","bo.it","bologna.it","bolzano-altoadige.it","bolzano.it","bozen-sudtirol.it","bozen-südtirol.it","bozen-suedtirol.it","bozen.it","br.it","brescia.it","brindisi.it","bs.it","bt.it","bulsan-sudtirol.it","bulsan-südtirol.it","bulsan-suedtirol.it","bulsan.it","bz.it","ca.it","cagliari.it","caltanissetta.it","campidano-medio.it","campidanomedio.it","campobasso.it","carbonia-iglesias.it","carboniaiglesias.it","carrara-massa.it","carraramassa.it","caserta.it","catania.it","catanzaro.it","cb.it","ce.it","cesena-forli.it","cesena-forlì.it","cesenaforli.it","cesenaforlì.it","ch.it","chieti.it","ci.it","cl.it","cn.it","co.it","como.it","cosenza.it","cr.it","cremona.it","crotone.it","cs.it","ct.it","cuneo.it","cz.it","dell-ogliastra.it","dellogliastra.it","en.it","enna.it","fc.it","fe.it","fermo.it","ferrara.it","fg.it","fi.it","firenze.it","florence.it","fm.it","foggia.it","forli-cesena.it","forlì-cesena.it","forlicesena.it","forlìcesena.it","fr.it","frosinone.it","ge.it","genoa.it","genova.it","go.it","gorizia.it","gr.it","grosseto.it","iglesias-carbonia.it","iglesiascarbonia.it","im.it","imperia.it","is.it","isernia.it","kr.it","la-spezia.it","laquila.it","laspezia.it","latina.it","lc.it","le.it","lecce.it","lecco.it","li.it","livorno.it","lo.it","lodi.it","lt.it","lu.it","lucca.it","macerata.it","mantova.it","massa-carrara.it","massacarrara.it","matera.it","mb.it","mc.it","me.it","medio-campidano.it","mediocampidano.it","messina.it","mi.it","milan.it","milano.it","mn.it","mo.it","modena.it","monza-brianza.it","monza-e-della-brianza.it","monza.it","monzabrianza.it","monzaebrianza.it","monzaedellabrianza.it","ms.it","mt.it","na.it","naples.it","napoli.it","no.it","novara.it","nu.it","nuoro.it","og.it","ogliastra.it","olbia-tempio.it","olbiatempio.it","or.it","oristano.it","ot.it","pa.it","padova.it","padua.it","palermo.it","parma.it","pavia.it","pc.it","pd.it","pe.it","perugia.it","pesaro-urbino.it","pesarourbino.it","pescara.it","pg.it","pi.it","piacenza.it","pisa.it","pistoia.it","pn.it","po.it","pordenone.it","potenza.it","pr.it","prato.it","pt.it","pu.it","pv.it","pz.it","ra.it","ragusa.it","ravenna.it","rc.it","re.it","reggio-calabria.it","reggio-emilia.it","reggiocalabria.it","reggioemilia.it","rg.it","ri.it","rieti.it","rimini.it","rm.it","rn.it","ro.it","roma.it","rome.it","rovigo.it","sa.it","salerno.it","sassari.it","savona.it","si.it","siena.it","siracusa.it","so.it","sondrio.it","sp.it","sr.it","ss.it","suedtirol.it","südtirol.it","sv.it","ta.it","taranto.it","te.it","tempio-olbia.it","tempioolbia.it","teramo.it","terni.it","tn.it","to.it","torino.it","tp.it","tr.it","trani-andria-barletta.it","trani-barletta-andria.it","traniandriabarletta.it","tranibarlettaandria.it","trapani.it","trento.it","treviso.it","trieste.it","ts.it","turin.it","tv.it","ud.it","udine.it","urbino-pesaro.it","urbinopesaro.it","va.it","varese.it","vb.it","vc.it","ve.it","venezia.it","venice.it","verbania.it","vercelli.it","verona.it","vi.it","vibo-valentia.it","vibovalentia.it","vicenza.it","viterbo.it","vr.it","vs.it","vt.it","vv.it","je","co.je","net.je","org.je","*.jm","jo","com.jo","org.jo","net.jo","edu.jo","sch.jo","gov.jo","mil.jo","name.jo","jobs","jp","ac.jp","ad.jp","co.jp","ed.jp","go.jp","gr.jp","lg.jp","ne.jp","or.jp","aichi.jp","akita.jp","aomori.jp","chiba.jp","ehime.jp","fukui.jp","fukuoka.jp","fukushima.jp","gifu.jp","gunma.jp","hiroshima.jp","hokkaido.jp","hyogo.jp","ibaraki.jp","ishikawa.jp","iwate.jp","kagawa.jp","kagoshima.jp","kanagawa.jp","kochi.jp","kumamoto.jp","kyoto.jp","mie.jp","miyagi.jp","miyazaki.jp","nagano.jp","nagasaki.jp","nara.jp","niigata.jp","oita.jp","okayama.jp","okinawa.jp","osaka.jp","saga.jp","saitama.jp","shiga.jp","shimane.jp","shizuoka.jp","tochigi.jp","tokushima.jp","tokyo.jp","tottori.jp","toyama.jp","wakayama.jp","yamagata.jp","yamaguchi.jp","yamanashi.jp","栃木.jp","愛知.jp","愛媛.jp","兵庫.jp","熊本.jp","茨城.jp","北海道.jp","千葉.jp","和歌山.jp","長崎.jp","長野.jp","新潟.jp","青森.jp","静岡.jp","東京.jp","石川.jp","埼玉.jp","三重.jp","京都.jp","佐賀.jp","大分.jp","大阪.jp","奈良.jp","宮城.jp","宮崎.jp","富山.jp","山口.jp","山形.jp","山梨.jp","岩手.jp","岐阜.jp","岡山.jp","島根.jp","広島.jp","徳島.jp","沖縄.jp","滋賀.jp","神奈川.jp","福井.jp","福岡.jp","福島.jp","秋田.jp","群馬.jp","香川.jp","高知.jp","鳥取.jp","鹿児島.jp","*.kawasaki.jp","*.kitakyushu.jp","*.kobe.jp","*.nagoya.jp","*.sapporo.jp","*.sendai.jp","*.yokohama.jp","!city.kawasaki.jp","!city.kitakyushu.jp","!city.kobe.jp","!city.nagoya.jp","!city.sapporo.jp","!city.sendai.jp","!city.yokohama.jp","aisai.aichi.jp","ama.aichi.jp","anjo.aichi.jp","asuke.aichi.jp","chiryu.aichi.jp","chita.aichi.jp","fuso.aichi.jp","gamagori.aichi.jp","handa.aichi.jp","hazu.aichi.jp","hekinan.aichi.jp","higashiura.aichi.jp","ichinomiya.aichi.jp","inazawa.aichi.jp","inuyama.aichi.jp","isshiki.aichi.jp","iwakura.aichi.jp","kanie.aichi.jp","kariya.aichi.jp","kasugai.aichi.jp","kira.aichi.jp","kiyosu.aichi.jp","komaki.aichi.jp","konan.aichi.jp","kota.aichi.jp","mihama.aichi.jp","miyoshi.aichi.jp","nishio.aichi.jp","nisshin.aichi.jp","obu.aichi.jp","oguchi.aichi.jp","oharu.aichi.jp","okazaki.aichi.jp","owariasahi.aichi.jp","seto.aichi.jp","shikatsu.aichi.jp","shinshiro.aichi.jp","shitara.aichi.jp","tahara.aichi.jp","takahama.aichi.jp","tobishima.aichi.jp","toei.aichi.jp","togo.aichi.jp","tokai.aichi.jp","tokoname.aichi.jp","toyoake.aichi.jp","toyohashi.aichi.jp","toyokawa.aichi.jp","toyone.aichi.jp","toyota.aichi.jp","tsushima.aichi.jp","yatomi.aichi.jp","akita.akita.jp","daisen.akita.jp","fujisato.akita.jp","gojome.akita.jp","hachirogata.akita.jp","happou.akita.jp","higashinaruse.akita.jp","honjo.akita.jp","honjyo.akita.jp","ikawa.akita.jp","kamikoani.akita.jp","kamioka.akita.jp","katagami.akita.jp","kazuno.akita.jp","kitaakita.akita.jp","kosaka.akita.jp","kyowa.akita.jp","misato.akita.jp","mitane.akita.jp","moriyoshi.akita.jp","nikaho.akita.jp","noshiro.akita.jp","odate.akita.jp","oga.akita.jp","ogata.akita.jp","semboku.akita.jp","yokote.akita.jp","yurihonjo.akita.jp","aomori.aomori.jp","gonohe.aomori.jp","hachinohe.aomori.jp","hashikami.aomori.jp","hiranai.aomori.jp","hirosaki.aomori.jp","itayanagi.aomori.jp","kuroishi.aomori.jp","misawa.aomori.jp","mutsu.aomori.jp","nakadomari.aomori.jp","noheji.aomori.jp","oirase.aomori.jp","owani.aomori.jp","rokunohe.aomori.jp","sannohe.aomori.jp","shichinohe.aomori.jp","shingo.aomori.jp","takko.aomori.jp","towada.aomori.jp","tsugaru.aomori.jp","tsuruta.aomori.jp","abiko.chiba.jp","asahi.chiba.jp","chonan.chiba.jp","chosei.chiba.jp","choshi.chiba.jp","chuo.chiba.jp","funabashi.chiba.jp","futtsu.chiba.jp","hanamigawa.chiba.jp","ichihara.chiba.jp","ichikawa.chiba.jp","ichinomiya.chiba.jp","inzai.chiba.jp","isumi.chiba.jp","kamagaya.chiba.jp","kamogawa.chiba.jp","kashiwa.chiba.jp","katori.chiba.jp","katsuura.chiba.jp","kimitsu.chiba.jp","kisarazu.chiba.jp","kozaki.chiba.jp","kujukuri.chiba.jp","kyonan.chiba.jp","matsudo.chiba.jp","midori.chiba.jp","mihama.chiba.jp","minamiboso.chiba.jp","mobara.chiba.jp","mutsuzawa.chiba.jp","nagara.chiba.jp","nagareyama.chiba.jp","narashino.chiba.jp","narita.chiba.jp","noda.chiba.jp","oamishirasato.chiba.jp","omigawa.chiba.jp","onjuku.chiba.jp","otaki.chiba.jp","sakae.chiba.jp","sakura.chiba.jp","shimofusa.chiba.jp","shirako.chiba.jp","shiroi.chiba.jp","shisui.chiba.jp","sodegaura.chiba.jp","sosa.chiba.jp","tako.chiba.jp","tateyama.chiba.jp","togane.chiba.jp","tohnosho.chiba.jp","tomisato.chiba.jp","urayasu.chiba.jp","yachimata.chiba.jp","yachiyo.chiba.jp","yokaichiba.chiba.jp","yokoshibahikari.chiba.jp","yotsukaido.chiba.jp","ainan.ehime.jp","honai.ehime.jp","ikata.ehime.jp","imabari.ehime.jp","iyo.ehime.jp","kamijima.ehime.jp","kihoku.ehime.jp","kumakogen.ehime.jp","masaki.ehime.jp","matsuno.ehime.jp","matsuyama.ehime.jp","namikata.ehime.jp","niihama.ehime.jp","ozu.ehime.jp","saijo.ehime.jp","seiyo.ehime.jp","shikokuchuo.ehime.jp","tobe.ehime.jp","toon.ehime.jp","uchiko.ehime.jp","uwajima.ehime.jp","yawatahama.ehime.jp","echizen.fukui.jp","eiheiji.fukui.jp","fukui.fukui.jp","ikeda.fukui.jp","katsuyama.fukui.jp","mihama.fukui.jp","minamiechizen.fukui.jp","obama.fukui.jp","ohi.fukui.jp","ono.fukui.jp","sabae.fukui.jp","sakai.fukui.jp","takahama.fukui.jp","tsuruga.fukui.jp","wakasa.fukui.jp","ashiya.fukuoka.jp","buzen.fukuoka.jp","chikugo.fukuoka.jp","chikuho.fukuoka.jp","chikujo.fukuoka.jp","chikushino.fukuoka.jp","chikuzen.fukuoka.jp","chuo.fukuoka.jp","dazaifu.fukuoka.jp","fukuchi.fukuoka.jp","hakata.fukuoka.jp","higashi.fukuoka.jp","hirokawa.fukuoka.jp","hisayama.fukuoka.jp","iizuka.fukuoka.jp","inatsuki.fukuoka.jp","kaho.fukuoka.jp","kasuga.fukuoka.jp","kasuya.fukuoka.jp","kawara.fukuoka.jp","keisen.fukuoka.jp","koga.fukuoka.jp","kurate.fukuoka.jp","kurogi.fukuoka.jp","kurume.fukuoka.jp","minami.fukuoka.jp","miyako.fukuoka.jp","miyama.fukuoka.jp","miyawaka.fukuoka.jp","mizumaki.fukuoka.jp","munakata.fukuoka.jp","nakagawa.fukuoka.jp","nakama.fukuoka.jp","nishi.fukuoka.jp","nogata.fukuoka.jp","ogori.fukuoka.jp","okagaki.fukuoka.jp","okawa.fukuoka.jp","oki.fukuoka.jp","omuta.fukuoka.jp","onga.fukuoka.jp","onojo.fukuoka.jp","oto.fukuoka.jp","saigawa.fukuoka.jp","sasaguri.fukuoka.jp","shingu.fukuoka.jp","shinyoshitomi.fukuoka.jp","shonai.fukuoka.jp","soeda.fukuoka.jp","sue.fukuoka.jp","tachiarai.fukuoka.jp","tagawa.fukuoka.jp","takata.fukuoka.jp","toho.fukuoka.jp","toyotsu.fukuoka.jp","tsuiki.fukuoka.jp","ukiha.fukuoka.jp","umi.fukuoka.jp","usui.fukuoka.jp","yamada.fukuoka.jp","yame.fukuoka.jp","yanagawa.fukuoka.jp","yukuhashi.fukuoka.jp","aizubange.fukushima.jp","aizumisato.fukushima.jp","aizuwakamatsu.fukushima.jp","asakawa.fukushima.jp","bandai.fukushima.jp","date.fukushima.jp","fukushima.fukushima.jp","furudono.fukushima.jp","futaba.fukushima.jp","hanawa.fukushima.jp","higashi.fukushima.jp","hirata.fukushima.jp","hirono.fukushima.jp","iitate.fukushima.jp","inawashiro.fukushima.jp","ishikawa.fukushima.jp","iwaki.fukushima.jp","izumizaki.fukushima.jp","kagamiishi.fukushima.jp","kaneyama.fukushima.jp","kawamata.fukushima.jp","kitakata.fukushima.jp","kitashiobara.fukushima.jp","koori.fukushima.jp","koriyama.fukushima.jp","kunimi.fukushima.jp","miharu.fukushima.jp","mishima.fukushima.jp","namie.fukushima.jp","nango.fukushima.jp","nishiaizu.fukushima.jp","nishigo.fukushima.jp","okuma.fukushima.jp","omotego.fukushima.jp","ono.fukushima.jp","otama.fukushima.jp","samegawa.fukushima.jp","shimogo.fukushima.jp","shirakawa.fukushima.jp","showa.fukushima.jp","soma.fukushima.jp","sukagawa.fukushima.jp","taishin.fukushima.jp","tamakawa.fukushima.jp","tanagura.fukushima.jp","tenei.fukushima.jp","yabuki.fukushima.jp","yamato.fukushima.jp","yamatsuri.fukushima.jp","yanaizu.fukushima.jp","yugawa.fukushima.jp","anpachi.gifu.jp","ena.gifu.jp","gifu.gifu.jp","ginan.gifu.jp","godo.gifu.jp","gujo.gifu.jp","hashima.gifu.jp","hichiso.gifu.jp","hida.gifu.jp","higashishirakawa.gifu.jp","ibigawa.gifu.jp","ikeda.gifu.jp","kakamigahara.gifu.jp","kani.gifu.jp","kasahara.gifu.jp","kasamatsu.gifu.jp","kawaue.gifu.jp","kitagata.gifu.jp","mino.gifu.jp","minokamo.gifu.jp","mitake.gifu.jp","mizunami.gifu.jp","motosu.gifu.jp","nakatsugawa.gifu.jp","ogaki.gifu.jp","sakahogi.gifu.jp","seki.gifu.jp","sekigahara.gifu.jp","shirakawa.gifu.jp","tajimi.gifu.jp","takayama.gifu.jp","tarui.gifu.jp","toki.gifu.jp","tomika.gifu.jp","wanouchi.gifu.jp","yamagata.gifu.jp","yaotsu.gifu.jp","yoro.gifu.jp","annaka.gunma.jp","chiyoda.gunma.jp","fujioka.gunma.jp","higashiagatsuma.gunma.jp","isesaki.gunma.jp","itakura.gunma.jp","kanna.gunma.jp","kanra.gunma.jp","katashina.gunma.jp","kawaba.gunma.jp","kiryu.gunma.jp","kusatsu.gunma.jp","maebashi.gunma.jp","meiwa.gunma.jp","midori.gunma.jp","minakami.gunma.jp","naganohara.gunma.jp","nakanojo.gunma.jp","nanmoku.gunma.jp","numata.gunma.jp","oizumi.gunma.jp","ora.gunma.jp","ota.gunma.jp","shibukawa.gunma.jp","shimonita.gunma.jp","shinto.gunma.jp","showa.gunma.jp","takasaki.gunma.jp","takayama.gunma.jp","tamamura.gunma.jp","tatebayashi.gunma.jp","tomioka.gunma.jp","tsukiyono.gunma.jp","tsumagoi.gunma.jp","ueno.gunma.jp","yoshioka.gunma.jp","asaminami.hiroshima.jp","daiwa.hiroshima.jp","etajima.hiroshima.jp","fuchu.hiroshima.jp","fukuyama.hiroshima.jp","hatsukaichi.hiroshima.jp","higashihiroshima.hiroshima.jp","hongo.hiroshima.jp","jinsekikogen.hiroshima.jp","kaita.hiroshima.jp","kui.hiroshima.jp","kumano.hiroshima.jp","kure.hiroshima.jp","mihara.hiroshima.jp","miyoshi.hiroshima.jp","naka.hiroshima.jp","onomichi.hiroshima.jp","osakikamijima.hiroshima.jp","otake.hiroshima.jp","saka.hiroshima.jp","sera.hiroshima.jp","seranishi.hiroshima.jp","shinichi.hiroshima.jp","shobara.hiroshima.jp","takehara.hiroshima.jp","abashiri.hokkaido.jp","abira.hokkaido.jp","aibetsu.hokkaido.jp","akabira.hokkaido.jp","akkeshi.hokkaido.jp","asahikawa.hokkaido.jp","ashibetsu.hokkaido.jp","ashoro.hokkaido.jp","assabu.hokkaido.jp","atsuma.hokkaido.jp","bibai.hokkaido.jp","biei.hokkaido.jp","bifuka.hokkaido.jp","bihoro.hokkaido.jp","biratori.hokkaido.jp","chippubetsu.hokkaido.jp","chitose.hokkaido.jp","date.hokkaido.jp","ebetsu.hokkaido.jp","embetsu.hokkaido.jp","eniwa.hokkaido.jp","erimo.hokkaido.jp","esan.hokkaido.jp","esashi.hokkaido.jp","fukagawa.hokkaido.jp","fukushima.hokkaido.jp","furano.hokkaido.jp","furubira.hokkaido.jp","haboro.hokkaido.jp","hakodate.hokkaido.jp","hamatonbetsu.hokkaido.jp","hidaka.hokkaido.jp","higashikagura.hokkaido.jp","higashikawa.hokkaido.jp","hiroo.hokkaido.jp","hokuryu.hokkaido.jp","hokuto.hokkaido.jp","honbetsu.hokkaido.jp","horokanai.hokkaido.jp","horonobe.hokkaido.jp","ikeda.hokkaido.jp","imakane.hokkaido.jp","ishikari.hokkaido.jp","iwamizawa.hokkaido.jp","iwanai.hokkaido.jp","kamifurano.hokkaido.jp","kamikawa.hokkaido.jp","kamishihoro.hokkaido.jp","kamisunagawa.hokkaido.jp","kamoenai.hokkaido.jp","kayabe.hokkaido.jp","kembuchi.hokkaido.jp","kikonai.hokkaido.jp","kimobetsu.hokkaido.jp","kitahiroshima.hokkaido.jp","kitami.hokkaido.jp","kiyosato.hokkaido.jp","koshimizu.hokkaido.jp","kunneppu.hokkaido.jp","kuriyama.hokkaido.jp","kuromatsunai.hokkaido.jp","kushiro.hokkaido.jp","kutchan.hokkaido.jp","kyowa.hokkaido.jp","mashike.hokkaido.jp","matsumae.hokkaido.jp","mikasa.hokkaido.jp","minamifurano.hokkaido.jp","mombetsu.hokkaido.jp","moseushi.hokkaido.jp","mukawa.hokkaido.jp","muroran.hokkaido.jp","naie.hokkaido.jp","nakagawa.hokkaido.jp","nakasatsunai.hokkaido.jp","nakatombetsu.hokkaido.jp","nanae.hokkaido.jp","nanporo.hokkaido.jp","nayoro.hokkaido.jp","nemuro.hokkaido.jp","niikappu.hokkaido.jp","niki.hokkaido.jp","nishiokoppe.hokkaido.jp","noboribetsu.hokkaido.jp","numata.hokkaido.jp","obihiro.hokkaido.jp","obira.hokkaido.jp","oketo.hokkaido.jp","okoppe.hokkaido.jp","otaru.hokkaido.jp","otobe.hokkaido.jp","otofuke.hokkaido.jp","otoineppu.hokkaido.jp","oumu.hokkaido.jp","ozora.hokkaido.jp","pippu.hokkaido.jp","rankoshi.hokkaido.jp","rebun.hokkaido.jp","rikubetsu.hokkaido.jp","rishiri.hokkaido.jp","rishirifuji.hokkaido.jp","saroma.hokkaido.jp","sarufutsu.hokkaido.jp","shakotan.hokkaido.jp","shari.hokkaido.jp","shibecha.hokkaido.jp","shibetsu.hokkaido.jp","shikabe.hokkaido.jp","shikaoi.hokkaido.jp","shimamaki.hokkaido.jp","shimizu.hokkaido.jp","shimokawa.hokkaido.jp","shinshinotsu.hokkaido.jp","shintoku.hokkaido.jp","shiranuka.hokkaido.jp","shiraoi.hokkaido.jp","shiriuchi.hokkaido.jp","sobetsu.hokkaido.jp","sunagawa.hokkaido.jp","taiki.hokkaido.jp","takasu.hokkaido.jp","takikawa.hokkaido.jp","takinoue.hokkaido.jp","teshikaga.hokkaido.jp","tobetsu.hokkaido.jp","tohma.hokkaido.jp","tomakomai.hokkaido.jp","tomari.hokkaido.jp","toya.hokkaido.jp","toyako.hokkaido.jp","toyotomi.hokkaido.jp","toyoura.hokkaido.jp","tsubetsu.hokkaido.jp","tsukigata.hokkaido.jp","urakawa.hokkaido.jp","urausu.hokkaido.jp","uryu.hokkaido.jp","utashinai.hokkaido.jp","wakkanai.hokkaido.jp","wassamu.hokkaido.jp","yakumo.hokkaido.jp","yoichi.hokkaido.jp","aioi.hyogo.jp","akashi.hyogo.jp","ako.hyogo.jp","amagasaki.hyogo.jp","aogaki.hyogo.jp","asago.hyogo.jp","ashiya.hyogo.jp","awaji.hyogo.jp","fukusaki.hyogo.jp","goshiki.hyogo.jp","harima.hyogo.jp","himeji.hyogo.jp","ichikawa.hyogo.jp","inagawa.hyogo.jp","itami.hyogo.jp","kakogawa.hyogo.jp","kamigori.hyogo.jp","kamikawa.hyogo.jp","kasai.hyogo.jp","kasuga.hyogo.jp","kawanishi.hyogo.jp","miki.hyogo.jp","minamiawaji.hyogo.jp","nishinomiya.hyogo.jp","nishiwaki.hyogo.jp","ono.hyogo.jp","sanda.hyogo.jp","sannan.hyogo.jp","sasayama.hyogo.jp","sayo.hyogo.jp","shingu.hyogo.jp","shinonsen.hyogo.jp","shiso.hyogo.jp","sumoto.hyogo.jp","taishi.hyogo.jp","taka.hyogo.jp","takarazuka.hyogo.jp","takasago.hyogo.jp","takino.hyogo.jp","tamba.hyogo.jp","tatsuno.hyogo.jp","toyooka.hyogo.jp","yabu.hyogo.jp","yashiro.hyogo.jp","yoka.hyogo.jp","yokawa.hyogo.jp","ami.ibaraki.jp","asahi.ibaraki.jp","bando.ibaraki.jp","chikusei.ibaraki.jp","daigo.ibaraki.jp","fujishiro.ibaraki.jp","hitachi.ibaraki.jp","hitachinaka.ibaraki.jp","hitachiomiya.ibaraki.jp","hitachiota.ibaraki.jp","ibaraki.ibaraki.jp","ina.ibaraki.jp","inashiki.ibaraki.jp","itako.ibaraki.jp","iwama.ibaraki.jp","joso.ibaraki.jp","kamisu.ibaraki.jp","kasama.ibaraki.jp","kashima.ibaraki.jp","kasumigaura.ibaraki.jp","koga.ibaraki.jp","miho.ibaraki.jp","mito.ibaraki.jp","moriya.ibaraki.jp","naka.ibaraki.jp","namegata.ibaraki.jp","oarai.ibaraki.jp","ogawa.ibaraki.jp","omitama.ibaraki.jp","ryugasaki.ibaraki.jp","sakai.ibaraki.jp","sakuragawa.ibaraki.jp","shimodate.ibaraki.jp","shimotsuma.ibaraki.jp","shirosato.ibaraki.jp","sowa.ibaraki.jp","suifu.ibaraki.jp","takahagi.ibaraki.jp","tamatsukuri.ibaraki.jp","tokai.ibaraki.jp","tomobe.ibaraki.jp","tone.ibaraki.jp","toride.ibaraki.jp","tsuchiura.ibaraki.jp","tsukuba.ibaraki.jp","uchihara.ibaraki.jp","ushiku.ibaraki.jp","yachiyo.ibaraki.jp","yamagata.ibaraki.jp","yawara.ibaraki.jp","yuki.ibaraki.jp","anamizu.ishikawa.jp","hakui.ishikawa.jp","hakusan.ishikawa.jp","kaga.ishikawa.jp","kahoku.ishikawa.jp","kanazawa.ishikawa.jp","kawakita.ishikawa.jp","komatsu.ishikawa.jp","nakanoto.ishikawa.jp","nanao.ishikawa.jp","nomi.ishikawa.jp","nonoichi.ishikawa.jp","noto.ishikawa.jp","shika.ishikawa.jp","suzu.ishikawa.jp","tsubata.ishikawa.jp","tsurugi.ishikawa.jp","uchinada.ishikawa.jp","wajima.ishikawa.jp","fudai.iwate.jp","fujisawa.iwate.jp","hanamaki.iwate.jp","hiraizumi.iwate.jp","hirono.iwate.jp","ichinohe.iwate.jp","ichinoseki.iwate.jp","iwaizumi.iwate.jp","iwate.iwate.jp","joboji.iwate.jp","kamaishi.iwate.jp","kanegasaki.iwate.jp","karumai.iwate.jp","kawai.iwate.jp","kitakami.iwate.jp","kuji.iwate.jp","kunohe.iwate.jp","kuzumaki.iwate.jp","miyako.iwate.jp","mizusawa.iwate.jp","morioka.iwate.jp","ninohe.iwate.jp","noda.iwate.jp","ofunato.iwate.jp","oshu.iwate.jp","otsuchi.iwate.jp","rikuzentakata.iwate.jp","shiwa.iwate.jp","shizukuishi.iwate.jp","sumita.iwate.jp","tanohata.iwate.jp","tono.iwate.jp","yahaba.iwate.jp","yamada.iwate.jp","ayagawa.kagawa.jp","higashikagawa.kagawa.jp","kanonji.kagawa.jp","kotohira.kagawa.jp","manno.kagawa.jp","marugame.kagawa.jp","mitoyo.kagawa.jp","naoshima.kagawa.jp","sanuki.kagawa.jp","tadotsu.kagawa.jp","takamatsu.kagawa.jp","tonosho.kagawa.jp","uchinomi.kagawa.jp","utazu.kagawa.jp","zentsuji.kagawa.jp","akune.kagoshima.jp","amami.kagoshima.jp","hioki.kagoshima.jp","isa.kagoshima.jp","isen.kagoshima.jp","izumi.kagoshima.jp","kagoshima.kagoshima.jp","kanoya.kagoshima.jp","kawanabe.kagoshima.jp","kinko.kagoshima.jp","kouyama.kagoshima.jp","makurazaki.kagoshima.jp","matsumoto.kagoshima.jp","minamitane.kagoshima.jp","nakatane.kagoshima.jp","nishinoomote.kagoshima.jp","satsumasendai.kagoshima.jp","soo.kagoshima.jp","tarumizu.kagoshima.jp","yusui.kagoshima.jp","aikawa.kanagawa.jp","atsugi.kanagawa.jp","ayase.kanagawa.jp","chigasaki.kanagawa.jp","ebina.kanagawa.jp","fujisawa.kanagawa.jp","hadano.kanagawa.jp","hakone.kanagawa.jp","hiratsuka.kanagawa.jp","isehara.kanagawa.jp","kaisei.kanagawa.jp","kamakura.kanagawa.jp","kiyokawa.kanagawa.jp","matsuda.kanagawa.jp","minamiashigara.kanagawa.jp","miura.kanagawa.jp","nakai.kanagawa.jp","ninomiya.kanagawa.jp","odawara.kanagawa.jp","oi.kanagawa.jp","oiso.kanagawa.jp","sagamihara.kanagawa.jp","samukawa.kanagawa.jp","tsukui.kanagawa.jp","yamakita.kanagawa.jp","yamato.kanagawa.jp","yokosuka.kanagawa.jp","yugawara.kanagawa.jp","zama.kanagawa.jp","zushi.kanagawa.jp","aki.kochi.jp","geisei.kochi.jp","hidaka.kochi.jp","higashitsuno.kochi.jp","ino.kochi.jp","kagami.kochi.jp","kami.kochi.jp","kitagawa.kochi.jp","kochi.kochi.jp","mihara.kochi.jp","motoyama.kochi.jp","muroto.kochi.jp","nahari.kochi.jp","nakamura.kochi.jp","nankoku.kochi.jp","nishitosa.kochi.jp","niyodogawa.kochi.jp","ochi.kochi.jp","okawa.kochi.jp","otoyo.kochi.jp","otsuki.kochi.jp","sakawa.kochi.jp","sukumo.kochi.jp","susaki.kochi.jp","tosa.kochi.jp","tosashimizu.kochi.jp","toyo.kochi.jp","tsuno.kochi.jp","umaji.kochi.jp","yasuda.kochi.jp","yusuhara.kochi.jp","amakusa.kumamoto.jp","arao.kumamoto.jp","aso.kumamoto.jp","choyo.kumamoto.jp","gyokuto.kumamoto.jp","kamiamakusa.kumamoto.jp","kikuchi.kumamoto.jp","kumamoto.kumamoto.jp","mashiki.kumamoto.jp","mifune.kumamoto.jp","minamata.kumamoto.jp","minamioguni.kumamoto.jp","nagasu.kumamoto.jp","nishihara.kumamoto.jp","oguni.kumamoto.jp","ozu.kumamoto.jp","sumoto.kumamoto.jp","takamori.kumamoto.jp","uki.kumamoto.jp","uto.kumamoto.jp","yamaga.kumamoto.jp","yamato.kumamoto.jp","yatsushiro.kumamoto.jp","ayabe.kyoto.jp","fukuchiyama.kyoto.jp","higashiyama.kyoto.jp","ide.kyoto.jp","ine.kyoto.jp","joyo.kyoto.jp","kameoka.kyoto.jp","kamo.kyoto.jp","kita.kyoto.jp","kizu.kyoto.jp","kumiyama.kyoto.jp","kyotamba.kyoto.jp","kyotanabe.kyoto.jp","kyotango.kyoto.jp","maizuru.kyoto.jp","minami.kyoto.jp","minamiyamashiro.kyoto.jp","miyazu.kyoto.jp","muko.kyoto.jp","nagaokakyo.kyoto.jp","nakagyo.kyoto.jp","nantan.kyoto.jp","oyamazaki.kyoto.jp","sakyo.kyoto.jp","seika.kyoto.jp","tanabe.kyoto.jp","uji.kyoto.jp","ujitawara.kyoto.jp","wazuka.kyoto.jp","yamashina.kyoto.jp","yawata.kyoto.jp","asahi.mie.jp","inabe.mie.jp","ise.mie.jp","kameyama.mie.jp","kawagoe.mie.jp","kiho.mie.jp","kisosaki.mie.jp","kiwa.mie.jp","komono.mie.jp","kumano.mie.jp","kuwana.mie.jp","matsusaka.mie.jp","meiwa.mie.jp","mihama.mie.jp","minamiise.mie.jp","misugi.mie.jp","miyama.mie.jp","nabari.mie.jp","shima.mie.jp","suzuka.mie.jp","tado.mie.jp","taiki.mie.jp","taki.mie.jp","tamaki.mie.jp","toba.mie.jp","tsu.mie.jp","udono.mie.jp","ureshino.mie.jp","watarai.mie.jp","yokkaichi.mie.jp","furukawa.miyagi.jp","higashimatsushima.miyagi.jp","ishinomaki.miyagi.jp","iwanuma.miyagi.jp","kakuda.miyagi.jp","kami.miyagi.jp","kawasaki.miyagi.jp","marumori.miyagi.jp","matsushima.miyagi.jp","minamisanriku.miyagi.jp","misato.miyagi.jp","murata.miyagi.jp","natori.miyagi.jp","ogawara.miyagi.jp","ohira.miyagi.jp","onagawa.miyagi.jp","osaki.miyagi.jp","rifu.miyagi.jp","semine.miyagi.jp","shibata.miyagi.jp","shichikashuku.miyagi.jp","shikama.miyagi.jp","shiogama.miyagi.jp","shiroishi.miyagi.jp","tagajo.miyagi.jp","taiwa.miyagi.jp","tome.miyagi.jp","tomiya.miyagi.jp","wakuya.miyagi.jp","watari.miyagi.jp","yamamoto.miyagi.jp","zao.miyagi.jp","aya.miyazaki.jp","ebino.miyazaki.jp","gokase.miyazaki.jp","hyuga.miyazaki.jp","kadogawa.miyazaki.jp","kawaminami.miyazaki.jp","kijo.miyazaki.jp","kitagawa.miyazaki.jp","kitakata.miyazaki.jp","kitaura.miyazaki.jp","kobayashi.miyazaki.jp","kunitomi.miyazaki.jp","kushima.miyazaki.jp","mimata.miyazaki.jp","miyakonojo.miyazaki.jp","miyazaki.miyazaki.jp","morotsuka.miyazaki.jp","nichinan.miyazaki.jp","nishimera.miyazaki.jp","nobeoka.miyazaki.jp","saito.miyazaki.jp","shiiba.miyazaki.jp","shintomi.miyazaki.jp","takaharu.miyazaki.jp","takanabe.miyazaki.jp","takazaki.miyazaki.jp","tsuno.miyazaki.jp","achi.nagano.jp","agematsu.nagano.jp","anan.nagano.jp","aoki.nagano.jp","asahi.nagano.jp","azumino.nagano.jp","chikuhoku.nagano.jp","chikuma.nagano.jp","chino.nagano.jp","fujimi.nagano.jp","hakuba.nagano.jp","hara.nagano.jp","hiraya.nagano.jp","iida.nagano.jp","iijima.nagano.jp","iiyama.nagano.jp","iizuna.nagano.jp","ikeda.nagano.jp","ikusaka.nagano.jp","ina.nagano.jp","karuizawa.nagano.jp","kawakami.nagano.jp","kiso.nagano.jp","kisofukushima.nagano.jp","kitaaiki.nagano.jp","komagane.nagano.jp","komoro.nagano.jp","matsukawa.nagano.jp","matsumoto.nagano.jp","miasa.nagano.jp","minamiaiki.nagano.jp","minamimaki.nagano.jp","minamiminowa.nagano.jp","minowa.nagano.jp","miyada.nagano.jp","miyota.nagano.jp","mochizuki.nagano.jp","nagano.nagano.jp","nagawa.nagano.jp","nagiso.nagano.jp","nakagawa.nagano.jp","nakano.nagano.jp","nozawaonsen.nagano.jp","obuse.nagano.jp","ogawa.nagano.jp","okaya.nagano.jp","omachi.nagano.jp","omi.nagano.jp","ookuwa.nagano.jp","ooshika.nagano.jp","otaki.nagano.jp","otari.nagano.jp","sakae.nagano.jp","sakaki.nagano.jp","saku.nagano.jp","sakuho.nagano.jp","shimosuwa.nagano.jp","shinanomachi.nagano.jp","shiojiri.nagano.jp","suwa.nagano.jp","suzaka.nagano.jp","takagi.nagano.jp","takamori.nagano.jp","takayama.nagano.jp","tateshina.nagano.jp","tatsuno.nagano.jp","togakushi.nagano.jp","togura.nagano.jp","tomi.nagano.jp","ueda.nagano.jp","wada.nagano.jp","yamagata.nagano.jp","yamanouchi.nagano.jp","yasaka.nagano.jp","yasuoka.nagano.jp","chijiwa.nagasaki.jp","futsu.nagasaki.jp","goto.nagasaki.jp","hasami.nagasaki.jp","hirado.nagasaki.jp","iki.nagasaki.jp","isahaya.nagasaki.jp","kawatana.nagasaki.jp","kuchinotsu.nagasaki.jp","matsuura.nagasaki.jp","nagasaki.nagasaki.jp","obama.nagasaki.jp","omura.nagasaki.jp","oseto.nagasaki.jp","saikai.nagasaki.jp","sasebo.nagasaki.jp","seihi.nagasaki.jp","shimabara.nagasaki.jp","shinkamigoto.nagasaki.jp","togitsu.nagasaki.jp","tsushima.nagasaki.jp","unzen.nagasaki.jp","ando.nara.jp","gose.nara.jp","heguri.nara.jp","higashiyoshino.nara.jp","ikaruga.nara.jp","ikoma.nara.jp","kamikitayama.nara.jp","kanmaki.nara.jp","kashiba.nara.jp","kashihara.nara.jp","katsuragi.nara.jp","kawai.nara.jp","kawakami.nara.jp","kawanishi.nara.jp","koryo.nara.jp","kurotaki.nara.jp","mitsue.nara.jp","miyake.nara.jp","nara.nara.jp","nosegawa.nara.jp","oji.nara.jp","ouda.nara.jp","oyodo.nara.jp","sakurai.nara.jp","sango.nara.jp","shimoichi.nara.jp","shimokitayama.nara.jp","shinjo.nara.jp","soni.nara.jp","takatori.nara.jp","tawaramoto.nara.jp","tenkawa.nara.jp","tenri.nara.jp","uda.nara.jp","yamatokoriyama.nara.jp","yamatotakada.nara.jp","yamazoe.nara.jp","yoshino.nara.jp","aga.niigata.jp","agano.niigata.jp","gosen.niigata.jp","itoigawa.niigata.jp","izumozaki.niigata.jp","joetsu.niigata.jp","kamo.niigata.jp","kariwa.niigata.jp","kashiwazaki.niigata.jp","minamiuonuma.niigata.jp","mitsuke.niigata.jp","muika.niigata.jp","murakami.niigata.jp","myoko.niigata.jp","nagaoka.niigata.jp","niigata.niigata.jp","ojiya.niigata.jp","omi.niigata.jp","sado.niigata.jp","sanjo.niigata.jp","seiro.niigata.jp","seirou.niigata.jp","sekikawa.niigata.jp","shibata.niigata.jp","tagami.niigata.jp","tainai.niigata.jp","tochio.niigata.jp","tokamachi.niigata.jp","tsubame.niigata.jp","tsunan.niigata.jp","uonuma.niigata.jp","yahiko.niigata.jp","yoita.niigata.jp","yuzawa.niigata.jp","beppu.oita.jp","bungoono.oita.jp","bungotakada.oita.jp","hasama.oita.jp","hiji.oita.jp","himeshima.oita.jp","hita.oita.jp","kamitsue.oita.jp","kokonoe.oita.jp","kuju.oita.jp","kunisaki.oita.jp","kusu.oita.jp","oita.oita.jp","saiki.oita.jp","taketa.oita.jp","tsukumi.oita.jp","usa.oita.jp","usuki.oita.jp","yufu.oita.jp","akaiwa.okayama.jp","asakuchi.okayama.jp","bizen.okayama.jp","hayashima.okayama.jp","ibara.okayama.jp","kagamino.okayama.jp","kasaoka.okayama.jp","kibichuo.okayama.jp","kumenan.okayama.jp","kurashiki.okayama.jp","maniwa.okayama.jp","misaki.okayama.jp","nagi.okayama.jp","niimi.okayama.jp","nishiawakura.okayama.jp","okayama.okayama.jp","satosho.okayama.jp","setouchi.okayama.jp","shinjo.okayama.jp","shoo.okayama.jp","soja.okayama.jp","takahashi.okayama.jp","tamano.okayama.jp","tsuyama.okayama.jp","wake.okayama.jp","yakage.okayama.jp","aguni.okinawa.jp","ginowan.okinawa.jp","ginoza.okinawa.jp","gushikami.okinawa.jp","haebaru.okinawa.jp","higashi.okinawa.jp","hirara.okinawa.jp","iheya.okinawa.jp","ishigaki.okinawa.jp","ishikawa.okinawa.jp","itoman.okinawa.jp","izena.okinawa.jp","kadena.okinawa.jp","kin.okinawa.jp","kitadaito.okinawa.jp","kitanakagusuku.okinawa.jp","kumejima.okinawa.jp","kunigami.okinawa.jp","minamidaito.okinawa.jp","motobu.okinawa.jp","nago.okinawa.jp","naha.okinawa.jp","nakagusuku.okinawa.jp","nakijin.okinawa.jp","nanjo.okinawa.jp","nishihara.okinawa.jp","ogimi.okinawa.jp","okinawa.okinawa.jp","onna.okinawa.jp","shimoji.okinawa.jp","taketomi.okinawa.jp","tarama.okinawa.jp","tokashiki.okinawa.jp","tomigusuku.okinawa.jp","tonaki.okinawa.jp","urasoe.okinawa.jp","uruma.okinawa.jp","yaese.okinawa.jp","yomitan.okinawa.jp","yonabaru.okinawa.jp","yonaguni.okinawa.jp","zamami.okinawa.jp","abeno.osaka.jp","chihayaakasaka.osaka.jp","chuo.osaka.jp","daito.osaka.jp","fujiidera.osaka.jp","habikino.osaka.jp","hannan.osaka.jp","higashiosaka.osaka.jp","higashisumiyoshi.osaka.jp","higashiyodogawa.osaka.jp","hirakata.osaka.jp","ibaraki.osaka.jp","ikeda.osaka.jp","izumi.osaka.jp","izumiotsu.osaka.jp","izumisano.osaka.jp","kadoma.osaka.jp","kaizuka.osaka.jp","kanan.osaka.jp","kashiwara.osaka.jp","katano.osaka.jp","kawachinagano.osaka.jp","kishiwada.osaka.jp","kita.osaka.jp","kumatori.osaka.jp","matsubara.osaka.jp","minato.osaka.jp","minoh.osaka.jp","misaki.osaka.jp","moriguchi.osaka.jp","neyagawa.osaka.jp","nishi.osaka.jp","nose.osaka.jp","osakasayama.osaka.jp","sakai.osaka.jp","sayama.osaka.jp","sennan.osaka.jp","settsu.osaka.jp","shijonawate.osaka.jp","shimamoto.osaka.jp","suita.osaka.jp","tadaoka.osaka.jp","taishi.osaka.jp","tajiri.osaka.jp","takaishi.osaka.jp","takatsuki.osaka.jp","tondabayashi.osaka.jp","toyonaka.osaka.jp","toyono.osaka.jp","yao.osaka.jp","ariake.saga.jp","arita.saga.jp","fukudomi.saga.jp","genkai.saga.jp","hamatama.saga.jp","hizen.saga.jp","imari.saga.jp","kamimine.saga.jp","kanzaki.saga.jp","karatsu.saga.jp","kashima.saga.jp","kitagata.saga.jp","kitahata.saga.jp","kiyama.saga.jp","kouhoku.saga.jp","kyuragi.saga.jp","nishiarita.saga.jp","ogi.saga.jp","omachi.saga.jp","ouchi.saga.jp","saga.saga.jp","shiroishi.saga.jp","taku.saga.jp","tara.saga.jp","tosu.saga.jp","yoshinogari.saga.jp","arakawa.saitama.jp","asaka.saitama.jp","chichibu.saitama.jp","fujimi.saitama.jp","fujimino.saitama.jp","fukaya.saitama.jp","hanno.saitama.jp","hanyu.saitama.jp","hasuda.saitama.jp","hatogaya.saitama.jp","hatoyama.saitama.jp","hidaka.saitama.jp","higashichichibu.saitama.jp","higashimatsuyama.saitama.jp","honjo.saitama.jp","ina.saitama.jp","iruma.saitama.jp","iwatsuki.saitama.jp","kamiizumi.saitama.jp","kamikawa.saitama.jp","kamisato.saitama.jp","kasukabe.saitama.jp","kawagoe.saitama.jp","kawaguchi.saitama.jp","kawajima.saitama.jp","kazo.saitama.jp","kitamoto.saitama.jp","koshigaya.saitama.jp","kounosu.saitama.jp","kuki.saitama.jp","kumagaya.saitama.jp","matsubushi.saitama.jp","minano.saitama.jp","misato.saitama.jp","miyashiro.saitama.jp","miyoshi.saitama.jp","moroyama.saitama.jp","nagatoro.saitama.jp","namegawa.saitama.jp","niiza.saitama.jp","ogano.saitama.jp","ogawa.saitama.jp","ogose.saitama.jp","okegawa.saitama.jp","omiya.saitama.jp","otaki.saitama.jp","ranzan.saitama.jp","ryokami.saitama.jp","saitama.saitama.jp","sakado.saitama.jp","satte.saitama.jp","sayama.saitama.jp","shiki.saitama.jp","shiraoka.saitama.jp","soka.saitama.jp","sugito.saitama.jp","toda.saitama.jp","tokigawa.saitama.jp","tokorozawa.saitama.jp","tsurugashima.saitama.jp","urawa.saitama.jp","warabi.saitama.jp","yashio.saitama.jp","yokoze.saitama.jp","yono.saitama.jp","yorii.saitama.jp","yoshida.saitama.jp","yoshikawa.saitama.jp","yoshimi.saitama.jp","aisho.shiga.jp","gamo.shiga.jp","higashiomi.shiga.jp","hikone.shiga.jp","koka.shiga.jp","konan.shiga.jp","kosei.shiga.jp","koto.shiga.jp","kusatsu.shiga.jp","maibara.shiga.jp","moriyama.shiga.jp","nagahama.shiga.jp","nishiazai.shiga.jp","notogawa.shiga.jp","omihachiman.shiga.jp","otsu.shiga.jp","ritto.shiga.jp","ryuoh.shiga.jp","takashima.shiga.jp","takatsuki.shiga.jp","torahime.shiga.jp","toyosato.shiga.jp","yasu.shiga.jp","akagi.shimane.jp","ama.shimane.jp","gotsu.shimane.jp","hamada.shimane.jp","higashiizumo.shimane.jp","hikawa.shimane.jp","hikimi.shimane.jp","izumo.shimane.jp","kakinoki.shimane.jp","masuda.shimane.jp","matsue.shimane.jp","misato.shimane.jp","nishinoshima.shimane.jp","ohda.shimane.jp","okinoshima.shimane.jp","okuizumo.shimane.jp","shimane.shimane.jp","tamayu.shimane.jp","tsuwano.shimane.jp","unnan.shimane.jp","yakumo.shimane.jp","yasugi.shimane.jp","yatsuka.shimane.jp","arai.shizuoka.jp","atami.shizuoka.jp","fuji.shizuoka.jp","fujieda.shizuoka.jp","fujikawa.shizuoka.jp","fujinomiya.shizuoka.jp","fukuroi.shizuoka.jp","gotemba.shizuoka.jp","haibara.shizuoka.jp","hamamatsu.shizuoka.jp","higashiizu.shizuoka.jp","ito.shizuoka.jp","iwata.shizuoka.jp","izu.shizuoka.jp","izunokuni.shizuoka.jp","kakegawa.shizuoka.jp","kannami.shizuoka.jp","kawanehon.shizuoka.jp","kawazu.shizuoka.jp","kikugawa.shizuoka.jp","kosai.shizuoka.jp","makinohara.shizuoka.jp","matsuzaki.shizuoka.jp","minamiizu.shizuoka.jp","mishima.shizuoka.jp","morimachi.shizuoka.jp","nishiizu.shizuoka.jp","numazu.shizuoka.jp","omaezaki.shizuoka.jp","shimada.shizuoka.jp","shimizu.shizuoka.jp","shimoda.shizuoka.jp","shizuoka.shizuoka.jp","susono.shizuoka.jp","yaizu.shizuoka.jp","yoshida.shizuoka.jp","ashikaga.tochigi.jp","bato.tochigi.jp","haga.tochigi.jp","ichikai.tochigi.jp","iwafune.tochigi.jp","kaminokawa.tochigi.jp","kanuma.tochigi.jp","karasuyama.tochigi.jp","kuroiso.tochigi.jp","mashiko.tochigi.jp","mibu.tochigi.jp","moka.tochigi.jp","motegi.tochigi.jp","nasu.tochigi.jp","nasushiobara.tochigi.jp","nikko.tochigi.jp","nishikata.tochigi.jp","nogi.tochigi.jp","ohira.tochigi.jp","ohtawara.tochigi.jp","oyama.tochigi.jp","sakura.tochigi.jp","sano.tochigi.jp","shimotsuke.tochigi.jp","shioya.tochigi.jp","takanezawa.tochigi.jp","tochigi.tochigi.jp","tsuga.tochigi.jp","ujiie.tochigi.jp","utsunomiya.tochigi.jp","yaita.tochigi.jp","aizumi.tokushima.jp","anan.tokushima.jp","ichiba.tokushima.jp","itano.tokushima.jp","kainan.tokushima.jp","komatsushima.tokushima.jp","matsushige.tokushima.jp","mima.tokushima.jp","minami.tokushima.jp","miyoshi.tokushima.jp","mugi.tokushima.jp","nakagawa.tokushima.jp","naruto.tokushima.jp","sanagochi.tokushima.jp","shishikui.tokushima.jp","tokushima.tokushima.jp","wajiki.tokushima.jp","adachi.tokyo.jp","akiruno.tokyo.jp","akishima.tokyo.jp","aogashima.tokyo.jp","arakawa.tokyo.jp","bunkyo.tokyo.jp","chiyoda.tokyo.jp","chofu.tokyo.jp","chuo.tokyo.jp","edogawa.tokyo.jp","fuchu.tokyo.jp","fussa.tokyo.jp","hachijo.tokyo.jp","hachioji.tokyo.jp","hamura.tokyo.jp","higashikurume.tokyo.jp","higashimurayama.tokyo.jp","higashiyamato.tokyo.jp","hino.tokyo.jp","hinode.tokyo.jp","hinohara.tokyo.jp","inagi.tokyo.jp","itabashi.tokyo.jp","katsushika.tokyo.jp","kita.tokyo.jp","kiyose.tokyo.jp","kodaira.tokyo.jp","koganei.tokyo.jp","kokubunji.tokyo.jp","komae.tokyo.jp","koto.tokyo.jp","kouzushima.tokyo.jp","kunitachi.tokyo.jp","machida.tokyo.jp","meguro.tokyo.jp","minato.tokyo.jp","mitaka.tokyo.jp","mizuho.tokyo.jp","musashimurayama.tokyo.jp","musashino.tokyo.jp","nakano.tokyo.jp","nerima.tokyo.jp","ogasawara.tokyo.jp","okutama.tokyo.jp","ome.tokyo.jp","oshima.tokyo.jp","ota.tokyo.jp","setagaya.tokyo.jp","shibuya.tokyo.jp","shinagawa.tokyo.jp","shinjuku.tokyo.jp","suginami.tokyo.jp","sumida.tokyo.jp","tachikawa.tokyo.jp","taito.tokyo.jp","tama.tokyo.jp","toshima.tokyo.jp","chizu.tottori.jp","hino.tottori.jp","kawahara.tottori.jp","koge.tottori.jp","kotoura.tottori.jp","misasa.tottori.jp","nanbu.tottori.jp","nichinan.tottori.jp","sakaiminato.tottori.jp","tottori.tottori.jp","wakasa.tottori.jp","yazu.tottori.jp","yonago.tottori.jp","asahi.toyama.jp","fuchu.toyama.jp","fukumitsu.toyama.jp","funahashi.toyama.jp","himi.toyama.jp","imizu.toyama.jp","inami.toyama.jp","johana.toyama.jp","kamiichi.toyama.jp","kurobe.toyama.jp","nakaniikawa.toyama.jp","namerikawa.toyama.jp","nanto.toyama.jp","nyuzen.toyama.jp","oyabe.toyama.jp","taira.toyama.jp","takaoka.toyama.jp","tateyama.toyama.jp","toga.toyama.jp","tonami.toyama.jp","toyama.toyama.jp","unazuki.toyama.jp","uozu.toyama.jp","yamada.toyama.jp","arida.wakayama.jp","aridagawa.wakayama.jp","gobo.wakayama.jp","hashimoto.wakayama.jp","hidaka.wakayama.jp","hirogawa.wakayama.jp","inami.wakayama.jp","iwade.wakayama.jp","kainan.wakayama.jp","kamitonda.wakayama.jp","katsuragi.wakayama.jp","kimino.wakayama.jp","kinokawa.wakayama.jp","kitayama.wakayama.jp","koya.wakayama.jp","koza.wakayama.jp","kozagawa.wakayama.jp","kudoyama.wakayama.jp","kushimoto.wakayama.jp","mihama.wakayama.jp","misato.wakayama.jp","nachikatsuura.wakayama.jp","shingu.wakayama.jp","shirahama.wakayama.jp","taiji.wakayama.jp","tanabe.wakayama.jp","wakayama.wakayama.jp","yuasa.wakayama.jp","yura.wakayama.jp","asahi.yamagata.jp","funagata.yamagata.jp","higashine.yamagata.jp","iide.yamagata.jp","kahoku.yamagata.jp","kaminoyama.yamagata.jp","kaneyama.yamagata.jp","kawanishi.yamagata.jp","mamurogawa.yamagata.jp","mikawa.yamagata.jp","murayama.yamagata.jp","nagai.yamagata.jp","nakayama.yamagata.jp","nanyo.yamagata.jp","nishikawa.yamagata.jp","obanazawa.yamagata.jp","oe.yamagata.jp","oguni.yamagata.jp","ohkura.yamagata.jp","oishida.yamagata.jp","sagae.yamagata.jp","sakata.yamagata.jp","sakegawa.yamagata.jp","shinjo.yamagata.jp","shirataka.yamagata.jp","shonai.yamagata.jp","takahata.yamagata.jp","tendo.yamagata.jp","tozawa.yamagata.jp","tsuruoka.yamagata.jp","yamagata.yamagata.jp","yamanobe.yamagata.jp","yonezawa.yamagata.jp","yuza.yamagata.jp","abu.yamaguchi.jp","hagi.yamaguchi.jp","hikari.yamaguchi.jp","hofu.yamaguchi.jp","iwakuni.yamaguchi.jp","kudamatsu.yamaguchi.jp","mitou.yamaguchi.jp","nagato.yamaguchi.jp","oshima.yamaguchi.jp","shimonoseki.yamaguchi.jp","shunan.yamaguchi.jp","tabuse.yamaguchi.jp","tokuyama.yamaguchi.jp","toyota.yamaguchi.jp","ube.yamaguchi.jp","yuu.yamaguchi.jp","chuo.yamanashi.jp","doshi.yamanashi.jp","fuefuki.yamanashi.jp","fujikawa.yamanashi.jp","fujikawaguchiko.yamanashi.jp","fujiyoshida.yamanashi.jp","hayakawa.yamanashi.jp","hokuto.yamanashi.jp","ichikawamisato.yamanashi.jp","kai.yamanashi.jp","kofu.yamanashi.jp","koshu.yamanashi.jp","kosuge.yamanashi.jp","minami-alps.yamanashi.jp","minobu.yamanashi.jp","nakamichi.yamanashi.jp","nanbu.yamanashi.jp","narusawa.yamanashi.jp","nirasaki.yamanashi.jp","nishikatsura.yamanashi.jp","oshino.yamanashi.jp","otsuki.yamanashi.jp","showa.yamanashi.jp","tabayama.yamanashi.jp","tsuru.yamanashi.jp","uenohara.yamanashi.jp","yamanakako.yamanashi.jp","yamanashi.yamanashi.jp","ke","ac.ke","co.ke","go.ke","info.ke","me.ke","mobi.ke","ne.ke","or.ke","sc.ke","kg","org.kg","net.kg","com.kg","edu.kg","gov.kg","mil.kg","*.kh","ki","edu.ki","biz.ki","net.ki","org.ki","gov.ki","info.ki","com.ki","km","org.km","nom.km","gov.km","prd.km","tm.km","edu.km","mil.km","ass.km","com.km","coop.km","asso.km","presse.km","medecin.km","notaires.km","pharmaciens.km","veterinaire.km","gouv.km","kn","net.kn","org.kn","edu.kn","gov.kn","kp","com.kp","edu.kp","gov.kp","org.kp","rep.kp","tra.kp","kr","ac.kr","co.kr","es.kr","go.kr","hs.kr","kg.kr","mil.kr","ms.kr","ne.kr","or.kr","pe.kr","re.kr","sc.kr","busan.kr","chungbuk.kr","chungnam.kr","daegu.kr","daejeon.kr","gangwon.kr","gwangju.kr","gyeongbuk.kr","gyeonggi.kr","gyeongnam.kr","incheon.kr","jeju.kr","jeonbuk.kr","jeonnam.kr","seoul.kr","ulsan.kr","kw","com.kw","edu.kw","emb.kw","gov.kw","ind.kw","net.kw","org.kw","ky","edu.ky","gov.ky","com.ky","org.ky","net.ky","kz","org.kz","edu.kz","net.kz","gov.kz","mil.kz","com.kz","la","int.la","net.la","info.la","edu.la","gov.la","per.la","com.la","org.la","lb","com.lb","edu.lb","gov.lb","net.lb","org.lb","lc","com.lc","net.lc","co.lc","org.lc","edu.lc","gov.lc","li","lk","gov.lk","sch.lk","net.lk","int.lk","com.lk","org.lk","edu.lk","ngo.lk","soc.lk","web.lk","ltd.lk","assn.lk","grp.lk","hotel.lk","ac.lk","lr","com.lr","edu.lr","gov.lr","org.lr","net.lr","ls","ac.ls","biz.ls","co.ls","edu.ls","gov.ls","info.ls","net.ls","org.ls","sc.ls","lt","gov.lt","lu","lv","com.lv","edu.lv","gov.lv","org.lv","mil.lv","id.lv","net.lv","asn.lv","conf.lv","ly","com.ly","net.ly","gov.ly","plc.ly","edu.ly","sch.ly","med.ly","org.ly","id.ly","ma","co.ma","net.ma","gov.ma","org.ma","ac.ma","press.ma","mc","tm.mc","asso.mc","md","me","co.me","net.me","org.me","edu.me","ac.me","gov.me","its.me","priv.me","mg","org.mg","nom.mg","gov.mg","prd.mg","tm.mg","edu.mg","mil.mg","com.mg","co.mg","mh","mil","mk","com.mk","org.mk","net.mk","edu.mk","gov.mk","inf.mk","name.mk","ml","com.ml","edu.ml","gouv.ml","gov.ml","net.ml","org.ml","presse.ml","*.mm","mn","gov.mn","edu.mn","org.mn","mo","com.mo","net.mo","org.mo","edu.mo","gov.mo","mobi","mp","mq","mr","gov.mr","ms","com.ms","edu.ms","gov.ms","net.ms","org.ms","mt","com.mt","edu.mt","net.mt","org.mt","mu","com.mu","net.mu","org.mu","gov.mu","ac.mu","co.mu","or.mu","museum","academy.museum","agriculture.museum","air.museum","airguard.museum","alabama.museum","alaska.museum","amber.museum","ambulance.museum","american.museum","americana.museum","americanantiques.museum","americanart.museum","amsterdam.museum","and.museum","annefrank.museum","anthro.museum","anthropology.museum","antiques.museum","aquarium.museum","arboretum.museum","archaeological.museum","archaeology.museum","architecture.museum","art.museum","artanddesign.museum","artcenter.museum","artdeco.museum","arteducation.museum","artgallery.museum","arts.museum","artsandcrafts.museum","asmatart.museum","assassination.museum","assisi.museum","association.museum","astronomy.museum","atlanta.museum","austin.museum","australia.museum","automotive.museum","aviation.museum","axis.museum","badajoz.museum","baghdad.museum","bahn.museum","bale.museum","baltimore.museum","barcelona.museum","baseball.museum","basel.museum","baths.museum","bauern.museum","beauxarts.museum","beeldengeluid.museum","bellevue.museum","bergbau.museum","berkeley.museum","berlin.museum","bern.museum","bible.museum","bilbao.museum","bill.museum","birdart.museum","birthplace.museum","bonn.museum","boston.museum","botanical.museum","botanicalgarden.museum","botanicgarden.museum","botany.museum","brandywinevalley.museum","brasil.museum","bristol.museum","british.museum","britishcolumbia.museum","broadcast.museum","brunel.museum","brussel.museum","brussels.museum","bruxelles.museum","building.museum","burghof.museum","bus.museum","bushey.museum","cadaques.museum","california.museum","cambridge.museum","can.museum","canada.museum","capebreton.museum","carrier.museum","cartoonart.museum","casadelamoneda.museum","castle.museum","castres.museum","celtic.museum","center.museum","chattanooga.museum","cheltenham.museum","chesapeakebay.museum","chicago.museum","children.museum","childrens.museum","childrensgarden.museum","chiropractic.museum","chocolate.museum","christiansburg.museum","cincinnati.museum","cinema.museum","circus.museum","civilisation.museum","civilization.museum","civilwar.museum","clinton.museum","clock.museum","coal.museum","coastaldefence.museum","cody.museum","coldwar.museum","collection.museum","colonialwilliamsburg.museum","coloradoplateau.museum","columbia.museum","columbus.museum","communication.museum","communications.museum","community.museum","computer.museum","computerhistory.museum","comunicações.museum","contemporary.museum","contemporaryart.museum","convent.museum","copenhagen.museum","corporation.museum","correios-e-telecomunicações.museum","corvette.museum","costume.museum","countryestate.museum","county.museum","crafts.museum","cranbrook.museum","creation.museum","cultural.museum","culturalcenter.museum","culture.museum","cyber.museum","cymru.museum","dali.museum","dallas.museum","database.museum","ddr.museum","decorativearts.museum","delaware.museum","delmenhorst.museum","denmark.museum","depot.museum","design.museum","detroit.museum","dinosaur.museum","discovery.museum","dolls.museum","donostia.museum","durham.museum","eastafrica.museum","eastcoast.museum","education.museum","educational.museum","egyptian.museum","eisenbahn.museum","elburg.museum","elvendrell.museum","embroidery.museum","encyclopedic.museum","england.museum","entomology.museum","environment.museum","environmentalconservation.museum","epilepsy.museum","essex.museum","estate.museum","ethnology.museum","exeter.museum","exhibition.museum","family.museum","farm.museum","farmequipment.museum","farmers.museum","farmstead.museum","field.museum","figueres.museum","filatelia.museum","film.museum","fineart.museum","finearts.museum","finland.museum","flanders.museum","florida.museum","force.museum","fortmissoula.museum","fortworth.museum","foundation.museum","francaise.museum","frankfurt.museum","franziskaner.museum","freemasonry.museum","freiburg.museum","fribourg.museum","frog.museum","fundacio.museum","furniture.museum","gallery.museum","garden.museum","gateway.museum","geelvinck.museum","gemological.museum","geology.museum","georgia.museum","giessen.museum","glas.museum","glass.museum","gorge.museum","grandrapids.museum","graz.museum","guernsey.museum","halloffame.museum","hamburg.museum","handson.museum","harvestcelebration.museum","hawaii.museum","health.museum","heimatunduhren.museum","hellas.museum","helsinki.museum","hembygdsforbund.museum","heritage.museum","histoire.museum","historical.museum","historicalsociety.museum","historichouses.museum","historisch.museum","historisches.museum","history.museum","historyofscience.museum","horology.museum","house.museum","humanities.museum","illustration.museum","imageandsound.museum","indian.museum","indiana.museum","indianapolis.museum","indianmarket.museum","intelligence.museum","interactive.museum","iraq.museum","iron.museum","isleofman.museum","jamison.museum","jefferson.museum","jerusalem.museum","jewelry.museum","jewish.museum","jewishart.museum","jfk.museum","journalism.museum","judaica.museum","judygarland.museum","juedisches.museum","juif.museum","karate.museum","karikatur.museum","kids.museum","koebenhavn.museum","koeln.museum","kunst.museum","kunstsammlung.museum","kunstunddesign.museum","labor.museum","labour.museum","lajolla.museum","lancashire.museum","landes.museum","lans.museum","läns.museum","larsson.museum","lewismiller.museum","lincoln.museum","linz.museum","living.museum","livinghistory.museum","localhistory.museum","london.museum","losangeles.museum","louvre.museum","loyalist.museum","lucerne.museum","luxembourg.museum","luzern.museum","mad.museum","madrid.museum","mallorca.museum","manchester.museum","mansion.museum","mansions.museum","manx.museum","marburg.museum","maritime.museum","maritimo.museum","maryland.museum","marylhurst.museum","media.museum","medical.museum","medizinhistorisches.museum","meeres.museum","memorial.museum","mesaverde.museum","michigan.museum","midatlantic.museum","military.museum","mill.museum","miners.museum","mining.museum","minnesota.museum","missile.museum","missoula.museum","modern.museum","moma.museum","money.museum","monmouth.museum","monticello.museum","montreal.museum","moscow.museum","motorcycle.museum","muenchen.museum","muenster.museum","mulhouse.museum","muncie.museum","museet.museum","museumcenter.museum","museumvereniging.museum","music.museum","national.museum","nationalfirearms.museum","nationalheritage.museum","nativeamerican.museum","naturalhistory.museum","naturalhistorymuseum.museum","naturalsciences.museum","nature.museum","naturhistorisches.museum","natuurwetenschappen.museum","naumburg.museum","naval.museum","nebraska.museum","neues.museum","newhampshire.museum","newjersey.museum","newmexico.museum","newport.museum","newspaper.museum","newyork.museum","niepce.museum","norfolk.museum","north.museum","nrw.museum","nyc.museum","nyny.museum","oceanographic.museum","oceanographique.museum","omaha.museum","online.museum","ontario.museum","openair.museum","oregon.museum","oregontrail.museum","otago.museum","oxford.museum","pacific.museum","paderborn.museum","palace.museum","paleo.museum","palmsprings.museum","panama.museum","paris.museum","pasadena.museum","pharmacy.museum","philadelphia.museum","philadelphiaarea.museum","philately.museum","phoenix.museum","photography.museum","pilots.museum","pittsburgh.museum","planetarium.museum","plantation.museum","plants.museum","plaza.museum","portal.museum","portland.museum","portlligat.museum","posts-and-telecommunications.museum","preservation.museum","presidio.museum","press.museum","project.museum","public.museum","pubol.museum","quebec.museum","railroad.museum","railway.museum","research.museum","resistance.museum","riodejaneiro.museum","rochester.museum","rockart.museum","roma.museum","russia.museum","saintlouis.museum","salem.museum","salvadordali.museum","salzburg.museum","sandiego.museum","sanfrancisco.museum","santabarbara.museum","santacruz.museum","santafe.museum","saskatchewan.museum","satx.museum","savannahga.museum","schlesisches.museum","schoenbrunn.museum","schokoladen.museum","school.museum","schweiz.museum","science.museum","scienceandhistory.museum","scienceandindustry.museum","sciencecenter.museum","sciencecenters.museum","science-fiction.museum","sciencehistory.museum","sciences.museum","sciencesnaturelles.museum","scotland.museum","seaport.museum","settlement.museum","settlers.museum","shell.museum","sherbrooke.museum","sibenik.museum","silk.museum","ski.museum","skole.museum","society.museum","sologne.museum","soundandvision.museum","southcarolina.museum","southwest.museum","space.museum","spy.museum","square.museum","stadt.museum","stalbans.museum","starnberg.museum","state.museum","stateofdelaware.museum","station.museum","steam.museum","steiermark.museum","stjohn.museum","stockholm.museum","stpetersburg.museum","stuttgart.museum","suisse.museum","surgeonshall.museum","surrey.museum","svizzera.museum","sweden.museum","sydney.museum","tank.museum","tcm.museum","technology.museum","telekommunikation.museum","television.museum","texas.museum","textile.museum","theater.museum","time.museum","timekeeping.museum","topology.museum","torino.museum","touch.museum","town.museum","transport.museum","tree.museum","trolley.museum","trust.museum","trustee.museum","uhren.museum","ulm.museum","undersea.museum","university.museum","usa.museum","usantiques.museum","usarts.museum","uscountryestate.museum","usculture.museum","usdecorativearts.museum","usgarden.museum","ushistory.museum","ushuaia.museum","uslivinghistory.museum","utah.museum","uvic.museum","valley.museum","vantaa.museum","versailles.museum","viking.museum","village.museum","virginia.museum","virtual.museum","virtuel.museum","vlaanderen.museum","volkenkunde.museum","wales.museum","wallonie.museum","war.museum","washingtondc.museum","watchandclock.museum","watch-and-clock.museum","western.museum","westfalen.museum","whaling.museum","wildlife.museum","williamsburg.museum","windmill.museum","workshop.museum","york.museum","yorkshire.museum","yosemite.museum","youth.museum","zoological.museum","zoology.museum","ירושלים.museum","иком.museum","mv","aero.mv","biz.mv","com.mv","coop.mv","edu.mv","gov.mv","info.mv","int.mv","mil.mv","museum.mv","name.mv","net.mv","org.mv","pro.mv","mw","ac.mw","biz.mw","co.mw","com.mw","coop.mw","edu.mw","gov.mw","int.mw","museum.mw","net.mw","org.mw","mx","com.mx","org.mx","gob.mx","edu.mx","net.mx","my","com.my","net.my","org.my","gov.my","edu.my","mil.my","name.my","mz","ac.mz","adv.mz","co.mz","edu.mz","gov.mz","mil.mz","net.mz","org.mz","na","info.na","pro.na","name.na","school.na","or.na","dr.na","us.na","mx.na","ca.na","in.na","cc.na","tv.na","ws.na","mobi.na","co.na","com.na","org.na","name","nc","asso.nc","nom.nc","ne","net","nf","com.nf","net.nf","per.nf","rec.nf","web.nf","arts.nf","firm.nf","info.nf","other.nf","store.nf","ng","com.ng","edu.ng","gov.ng","i.ng","mil.ng","mobi.ng","name.ng","net.ng","org.ng","sch.ng","ni","ac.ni","biz.ni","co.ni","com.ni","edu.ni","gob.ni","in.ni","info.ni","int.ni","mil.ni","net.ni","nom.ni","org.ni","web.ni","nl","no","fhs.no","vgs.no","fylkesbibl.no","folkebibl.no","museum.no","idrett.no","priv.no","mil.no","stat.no","dep.no","kommune.no","herad.no","aa.no","ah.no","bu.no","fm.no","hl.no","hm.no","jan-mayen.no","mr.no","nl.no","nt.no","of.no","ol.no","oslo.no","rl.no","sf.no","st.no","svalbard.no","tm.no","tr.no","va.no","vf.no","gs.aa.no","gs.ah.no","gs.bu.no","gs.fm.no","gs.hl.no","gs.hm.no","gs.jan-mayen.no","gs.mr.no","gs.nl.no","gs.nt.no","gs.of.no","gs.ol.no","gs.oslo.no","gs.rl.no","gs.sf.no","gs.st.no","gs.svalbard.no","gs.tm.no","gs.tr.no","gs.va.no","gs.vf.no","akrehamn.no","åkrehamn.no","algard.no","ålgård.no","arna.no","brumunddal.no","bryne.no","bronnoysund.no","brønnøysund.no","drobak.no","drøbak.no","egersund.no","fetsund.no","floro.no","florø.no","fredrikstad.no","hokksund.no","honefoss.no","hønefoss.no","jessheim.no","jorpeland.no","jørpeland.no","kirkenes.no","kopervik.no","krokstadelva.no","langevag.no","langevåg.no","leirvik.no","mjondalen.no","mjøndalen.no","mo-i-rana.no","mosjoen.no","mosjøen.no","nesoddtangen.no","orkanger.no","osoyro.no","osøyro.no","raholt.no","råholt.no","sandnessjoen.no","sandnessjøen.no","skedsmokorset.no","slattum.no","spjelkavik.no","stathelle.no","stavern.no","stjordalshalsen.no","stjørdalshalsen.no","tananger.no","tranby.no","vossevangen.no","afjord.no","åfjord.no","agdenes.no","al.no","ål.no","alesund.no","ålesund.no","alstahaug.no","alta.no","áltá.no","alaheadju.no","álaheadju.no","alvdal.no","amli.no","åmli.no","amot.no","åmot.no","andebu.no","andoy.no","andøy.no","andasuolo.no","ardal.no","årdal.no","aremark.no","arendal.no","ås.no","aseral.no","åseral.no","asker.no","askim.no","askvoll.no","askoy.no","askøy.no","asnes.no","åsnes.no","audnedaln.no","aukra.no","aure.no","aurland.no","aurskog-holand.no","aurskog-høland.no","austevoll.no","austrheim.no","averoy.no","averøy.no","balestrand.no","ballangen.no","balat.no","bálát.no","balsfjord.no","bahccavuotna.no","báhccavuotna.no","bamble.no","bardu.no","beardu.no","beiarn.no","bajddar.no","bájddar.no","baidar.no","báidár.no","berg.no","bergen.no","berlevag.no","berlevåg.no","bearalvahki.no","bearalváhki.no","bindal.no","birkenes.no","bjarkoy.no","bjarkøy.no","bjerkreim.no","bjugn.no","bodo.no","bodø.no","badaddja.no","bådåddjå.no","budejju.no","bokn.no","bremanger.no","bronnoy.no","brønnøy.no","bygland.no","bykle.no","barum.no","bærum.no","bo.telemark.no","bø.telemark.no","bo.nordland.no","bø.nordland.no","bievat.no","bievát.no","bomlo.no","bømlo.no","batsfjord.no","båtsfjord.no","bahcavuotna.no","báhcavuotna.no","dovre.no","drammen.no","drangedal.no","dyroy.no","dyrøy.no","donna.no","dønna.no","eid.no","eidfjord.no","eidsberg.no","eidskog.no","eidsvoll.no","eigersund.no","elverum.no","enebakk.no","engerdal.no","etne.no","etnedal.no","evenes.no","evenassi.no","evenášši.no","evje-og-hornnes.no","farsund.no","fauske.no","fuossko.no","fuoisku.no","fedje.no","fet.no","finnoy.no","finnøy.no","fitjar.no","fjaler.no","fjell.no","flakstad.no","flatanger.no","flekkefjord.no","flesberg.no","flora.no","fla.no","flå.no","folldal.no","forsand.no","fosnes.no","frei.no","frogn.no","froland.no","frosta.no","frana.no","fræna.no","froya.no","frøya.no","fusa.no","fyresdal.no","forde.no","førde.no","gamvik.no","gangaviika.no","gáŋgaviika.no","gaular.no","gausdal.no","gildeskal.no","gildeskål.no","giske.no","gjemnes.no","gjerdrum.no","gjerstad.no","gjesdal.no","gjovik.no","gjøvik.no","gloppen.no","gol.no","gran.no","grane.no","granvin.no","gratangen.no","grimstad.no","grong.no","kraanghke.no","kråanghke.no","grue.no","gulen.no","hadsel.no","halden.no","halsa.no","hamar.no","hamaroy.no","habmer.no","hábmer.no","hapmir.no","hápmir.no","hammerfest.no","hammarfeasta.no","hámmárfeasta.no","haram.no","hareid.no","harstad.no","hasvik.no","aknoluokta.no","ákŋoluokta.no","hattfjelldal.no","aarborte.no","haugesund.no","hemne.no","hemnes.no","hemsedal.no","heroy.more-og-romsdal.no","herøy.møre-og-romsdal.no","heroy.nordland.no","herøy.nordland.no","hitra.no","hjartdal.no","hjelmeland.no","hobol.no","hobøl.no","hof.no","hol.no","hole.no","holmestrand.no","holtalen.no","holtålen.no","hornindal.no","horten.no","hurdal.no","hurum.no","hvaler.no","hyllestad.no","hagebostad.no","hægebostad.no","hoyanger.no","høyanger.no","hoylandet.no","høylandet.no","ha.no","hå.no","ibestad.no","inderoy.no","inderøy.no","iveland.no","jevnaker.no","jondal.no","jolster.no","jølster.no","karasjok.no","karasjohka.no","kárášjohka.no","karlsoy.no","galsa.no","gálsá.no","karmoy.no","karmøy.no","kautokeino.no","guovdageaidnu.no","klepp.no","klabu.no","klæbu.no","kongsberg.no","kongsvinger.no","kragero.no","kragerø.no","kristiansand.no","kristiansund.no","krodsherad.no","krødsherad.no","kvalsund.no","rahkkeravju.no","ráhkkerávju.no","kvam.no","kvinesdal.no","kvinnherad.no","kviteseid.no","kvitsoy.no","kvitsøy.no","kvafjord.no","kvæfjord.no","giehtavuoatna.no","kvanangen.no","kvænangen.no","navuotna.no","návuotna.no","kafjord.no","kåfjord.no","gaivuotna.no","gáivuotna.no","larvik.no","lavangen.no","lavagis.no","loabat.no","loabát.no","lebesby.no","davvesiida.no","leikanger.no","leirfjord.no","leka.no","leksvik.no","lenvik.no","leangaviika.no","leaŋgaviika.no","lesja.no","levanger.no","lier.no","lierne.no","lillehammer.no","lillesand.no","lindesnes.no","lindas.no","lindås.no","lom.no","loppa.no","lahppi.no","láhppi.no","lund.no","lunner.no","luroy.no","lurøy.no","luster.no","lyngdal.no","lyngen.no","ivgu.no","lardal.no","lerdal.no","lærdal.no","lodingen.no","lødingen.no","lorenskog.no","lørenskog.no","loten.no","løten.no","malvik.no","masoy.no","måsøy.no","muosat.no","muosát.no","mandal.no","marker.no","marnardal.no","masfjorden.no","meland.no","meldal.no","melhus.no","meloy.no","meløy.no","meraker.no","meråker.no","moareke.no","moåreke.no","midsund.no","midtre-gauldal.no","modalen.no","modum.no","molde.no","moskenes.no","moss.no","mosvik.no","malselv.no","målselv.no","malatvuopmi.no","málatvuopmi.no","namdalseid.no","aejrie.no","namsos.no","namsskogan.no","naamesjevuemie.no","nååmesjevuemie.no","laakesvuemie.no","nannestad.no","narvik.no","narviika.no","naustdal.no","nedre-eiker.no","nes.akershus.no","nes.buskerud.no","nesna.no","nesodden.no","nesseby.no","unjarga.no","unjárga.no","nesset.no","nissedal.no","nittedal.no","nord-aurdal.no","nord-fron.no","nord-odal.no","norddal.no","nordkapp.no","davvenjarga.no","davvenjárga.no","nordre-land.no","nordreisa.no","raisa.no","ráisa.no","nore-og-uvdal.no","notodden.no","naroy.no","nærøy.no","notteroy.no","nøtterøy.no","odda.no","oksnes.no","øksnes.no","oppdal.no","oppegard.no","oppegård.no","orkdal.no","orland.no","ørland.no","orskog.no","ørskog.no","orsta.no","ørsta.no","os.hedmark.no","os.hordaland.no","osen.no","osteroy.no","osterøy.no","ostre-toten.no","østre-toten.no","overhalla.no","ovre-eiker.no","øvre-eiker.no","oyer.no","øyer.no","oygarden.no","øygarden.no","oystre-slidre.no","øystre-slidre.no","porsanger.no","porsangu.no","porsáŋgu.no","porsgrunn.no","radoy.no","radøy.no","rakkestad.no","rana.no","ruovat.no","randaberg.no","rauma.no","rendalen.no","rennebu.no","rennesoy.no","rennesøy.no","rindal.no","ringebu.no","ringerike.no","ringsaker.no","rissa.no","risor.no","risør.no","roan.no","rollag.no","rygge.no","ralingen.no","rælingen.no","rodoy.no","rødøy.no","romskog.no","rømskog.no","roros.no","røros.no","rost.no","røst.no","royken.no","røyken.no","royrvik.no","røyrvik.no","rade.no","råde.no","salangen.no","siellak.no","saltdal.no","salat.no","sálát.no","sálat.no","samnanger.no","sande.more-og-romsdal.no","sande.møre-og-romsdal.no","sande.vestfold.no","sandefjord.no","sandnes.no","sandoy.no","sandøy.no","sarpsborg.no","sauda.no","sauherad.no","sel.no","selbu.no","selje.no","seljord.no","sigdal.no","siljan.no","sirdal.no","skaun.no","skedsmo.no","ski.no","skien.no","skiptvet.no","skjervoy.no","skjervøy.no","skierva.no","skiervá.no","skjak.no","skjåk.no","skodje.no","skanland.no","skånland.no","skanit.no","skánit.no","smola.no","smøla.no","snillfjord.no","snasa.no","snåsa.no","snoasa.no","snaase.no","snåase.no","sogndal.no","sokndal.no","sola.no","solund.no","songdalen.no","sortland.no","spydeberg.no","stange.no","stavanger.no","steigen.no","steinkjer.no","stjordal.no","stjørdal.no","stokke.no","stor-elvdal.no","stord.no","stordal.no","storfjord.no","omasvuotna.no","strand.no","stranda.no","stryn.no","sula.no","suldal.no","sund.no","sunndal.no","surnadal.no","sveio.no","svelvik.no","sykkylven.no","sogne.no","søgne.no","somna.no","sømna.no","sondre-land.no","søndre-land.no","sor-aurdal.no","sør-aurdal.no","sor-fron.no","sør-fron.no","sor-odal.no","sør-odal.no","sor-varanger.no","sør-varanger.no","matta-varjjat.no","mátta-várjjat.no","sorfold.no","sørfold.no","sorreisa.no","sørreisa.no","sorum.no","sørum.no","tana.no","deatnu.no","time.no","tingvoll.no","tinn.no","tjeldsund.no","dielddanuorri.no","tjome.no","tjøme.no","tokke.no","tolga.no","torsken.no","tranoy.no","tranøy.no","tromso.no","tromsø.no","tromsa.no","romsa.no","trondheim.no","troandin.no","trysil.no","trana.no","træna.no","trogstad.no","trøgstad.no","tvedestrand.no","tydal.no","tynset.no","tysfjord.no","divtasvuodna.no","divttasvuotna.no","tysnes.no","tysvar.no","tysvær.no","tonsberg.no","tønsberg.no","ullensaker.no","ullensvang.no","ulvik.no","utsira.no","vadso.no","vadsø.no","cahcesuolo.no","čáhcesuolo.no","vaksdal.no","valle.no","vang.no","vanylven.no","vardo.no","vardø.no","varggat.no","várggát.no","vefsn.no","vaapste.no","vega.no","vegarshei.no","vegårshei.no","vennesla.no","verdal.no","verran.no","vestby.no","vestnes.no","vestre-slidre.no","vestre-toten.no","vestvagoy.no","vestvågøy.no","vevelstad.no","vik.no","vikna.no","vindafjord.no","volda.no","voss.no","varoy.no","værøy.no","vagan.no","vågan.no","voagat.no","vagsoy.no","vågsøy.no","vaga.no","vågå.no","valer.ostfold.no","våler.østfold.no","valer.hedmark.no","våler.hedmark.no","*.np","nr","biz.nr","info.nr","gov.nr","edu.nr","org.nr","net.nr","com.nr","nu","nz","ac.nz","co.nz","cri.nz","geek.nz","gen.nz","govt.nz","health.nz","iwi.nz","kiwi.nz","maori.nz","mil.nz","māori.nz","net.nz","org.nz","parliament.nz","school.nz","om","co.om","com.om","edu.om","gov.om","med.om","museum.om","net.om","org.om","pro.om","onion","org","pa","ac.pa","gob.pa","com.pa","org.pa","sld.pa","edu.pa","net.pa","ing.pa","abo.pa","med.pa","nom.pa","pe","edu.pe","gob.pe","nom.pe","mil.pe","org.pe","com.pe","net.pe","pf","com.pf","org.pf","edu.pf","*.pg","ph","com.ph","net.ph","org.ph","gov.ph","edu.ph","ngo.ph","mil.ph","i.ph","pk","com.pk","net.pk","edu.pk","org.pk","fam.pk","biz.pk","web.pk","gov.pk","gob.pk","gok.pk","gon.pk","gop.pk","gos.pk","info.pk","pl","com.pl","net.pl","org.pl","aid.pl","agro.pl","atm.pl","auto.pl","biz.pl","edu.pl","gmina.pl","gsm.pl","info.pl","mail.pl","miasta.pl","media.pl","mil.pl","nieruchomosci.pl","nom.pl","pc.pl","powiat.pl","priv.pl","realestate.pl","rel.pl","sex.pl","shop.pl","sklep.pl","sos.pl","szkola.pl","targi.pl","tm.pl","tourism.pl","travel.pl","turystyka.pl","gov.pl","ap.gov.pl","ic.gov.pl","is.gov.pl","us.gov.pl","kmpsp.gov.pl","kppsp.gov.pl","kwpsp.gov.pl","psp.gov.pl","wskr.gov.pl","kwp.gov.pl","mw.gov.pl","ug.gov.pl","um.gov.pl","umig.gov.pl","ugim.gov.pl","upow.gov.pl","uw.gov.pl","starostwo.gov.pl","pa.gov.pl","po.gov.pl","psse.gov.pl","pup.gov.pl","rzgw.gov.pl","sa.gov.pl","so.gov.pl","sr.gov.pl","wsa.gov.pl","sko.gov.pl","uzs.gov.pl","wiih.gov.pl","winb.gov.pl","pinb.gov.pl","wios.gov.pl","witd.gov.pl","wzmiuw.gov.pl","piw.gov.pl","wiw.gov.pl","griw.gov.pl","wif.gov.pl","oum.gov.pl","sdn.gov.pl","zp.gov.pl","uppo.gov.pl","mup.gov.pl","wuoz.gov.pl","konsulat.gov.pl","oirm.gov.pl","augustow.pl","babia-gora.pl","bedzin.pl","beskidy.pl","bialowieza.pl","bialystok.pl","bielawa.pl","bieszczady.pl","boleslawiec.pl","bydgoszcz.pl","bytom.pl","cieszyn.pl","czeladz.pl","czest.pl","dlugoleka.pl","elblag.pl","elk.pl","glogow.pl","gniezno.pl","gorlice.pl","grajewo.pl","ilawa.pl","jaworzno.pl","jelenia-gora.pl","jgora.pl","kalisz.pl","kazimierz-dolny.pl","karpacz.pl","kartuzy.pl","kaszuby.pl","katowice.pl","kepno.pl","ketrzyn.pl","klodzko.pl","kobierzyce.pl","kolobrzeg.pl","konin.pl","konskowola.pl","kutno.pl","lapy.pl","lebork.pl","legnica.pl","lezajsk.pl","limanowa.pl","lomza.pl","lowicz.pl","lubin.pl","lukow.pl","malbork.pl","malopolska.pl","mazowsze.pl","mazury.pl","mielec.pl","mielno.pl","mragowo.pl","naklo.pl","nowaruda.pl","nysa.pl","olawa.pl","olecko.pl","olkusz.pl","olsztyn.pl","opoczno.pl","opole.pl","ostroda.pl","ostroleka.pl","ostrowiec.pl","ostrowwlkp.pl","pila.pl","pisz.pl","podhale.pl","podlasie.pl","polkowice.pl","pomorze.pl","pomorskie.pl","prochowice.pl","pruszkow.pl","przeworsk.pl","pulawy.pl","radom.pl","rawa-maz.pl","rybnik.pl","rzeszow.pl","sanok.pl","sejny.pl","slask.pl","slupsk.pl","sosnowiec.pl","stalowa-wola.pl","skoczow.pl","starachowice.pl","stargard.pl","suwalki.pl","swidnica.pl","swiebodzin.pl","swinoujscie.pl","szczecin.pl","szczytno.pl","tarnobrzeg.pl","tgory.pl","turek.pl","tychy.pl","ustka.pl","walbrzych.pl","warmia.pl","warszawa.pl","waw.pl","wegrow.pl","wielun.pl","wlocl.pl","wloclawek.pl","wodzislaw.pl","wolomin.pl","wroclaw.pl","zachpomor.pl","zagan.pl","zarow.pl","zgora.pl","zgorzelec.pl","pm","pn","gov.pn","co.pn","org.pn","edu.pn","net.pn","post","pr","com.pr","net.pr","org.pr","gov.pr","edu.pr","isla.pr","pro.pr","biz.pr","info.pr","name.pr","est.pr","prof.pr","ac.pr","pro","aaa.pro","aca.pro","acct.pro","avocat.pro","bar.pro","cpa.pro","eng.pro","jur.pro","law.pro","med.pro","recht.pro","ps","edu.ps","gov.ps","sec.ps","plo.ps","com.ps","org.ps","net.ps","pt","net.pt","gov.pt","org.pt","edu.pt","int.pt","publ.pt","com.pt","nome.pt","pw","co.pw","ne.pw","or.pw","ed.pw","go.pw","belau.pw","py","com.py","coop.py","edu.py","gov.py","mil.py","net.py","org.py","qa","com.qa","edu.qa","gov.qa","mil.qa","name.qa","net.qa","org.qa","sch.qa","re","asso.re","com.re","nom.re","ro","arts.ro","com.ro","firm.ro","info.ro","nom.ro","nt.ro","org.ro","rec.ro","store.ro","tm.ro","www.ro","rs","ac.rs","co.rs","edu.rs","gov.rs","in.rs","org.rs","ru","rw","ac.rw","co.rw","coop.rw","gov.rw","mil.rw","net.rw","org.rw","sa","com.sa","net.sa","org.sa","gov.sa","med.sa","pub.sa","edu.sa","sch.sa","sb","com.sb","edu.sb","gov.sb","net.sb","org.sb","sc","com.sc","gov.sc","net.sc","org.sc","edu.sc","sd","com.sd","net.sd","org.sd","edu.sd","med.sd","tv.sd","gov.sd","info.sd","se","a.se","ac.se","b.se","bd.se","brand.se","c.se","d.se","e.se","f.se","fh.se","fhsk.se","fhv.se","g.se","h.se","i.se","k.se","komforb.se","kommunalforbund.se","komvux.se","l.se","lanbib.se","m.se","n.se","naturbruksgymn.se","o.se","org.se","p.se","parti.se","pp.se","press.se","r.se","s.se","t.se","tm.se","u.se","w.se","x.se","y.se","z.se","sg","com.sg","net.sg","org.sg","gov.sg","edu.sg","per.sg","sh","com.sh","net.sh","gov.sh","org.sh","mil.sh","si","sj","sk","sl","com.sl","net.sl","edu.sl","gov.sl","org.sl","sm","sn","art.sn","com.sn","edu.sn","gouv.sn","org.sn","perso.sn","univ.sn","so","com.so","edu.so","gov.so","me.so","net.so","org.so","sr","ss","biz.ss","com.ss","edu.ss","gov.ss","net.ss","org.ss","st","co.st","com.st","consulado.st","edu.st","embaixada.st","gov.st","mil.st","net.st","org.st","principe.st","saotome.st","store.st","su","sv","com.sv","edu.sv","gob.sv","org.sv","red.sv","sx","gov.sx","sy","edu.sy","gov.sy","net.sy","mil.sy","com.sy","org.sy","sz","co.sz","ac.sz","org.sz","tc","td","tel","tf","tg","th","ac.th","co.th","go.th","in.th","mi.th","net.th","or.th","tj","ac.tj","biz.tj","co.tj","com.tj","edu.tj","go.tj","gov.tj","int.tj","mil.tj","name.tj","net.tj","nic.tj","org.tj","test.tj","web.tj","tk","tl","gov.tl","tm","com.tm","co.tm","org.tm","net.tm","nom.tm","gov.tm","mil.tm","edu.tm","tn","com.tn","ens.tn","fin.tn","gov.tn","ind.tn","intl.tn","nat.tn","net.tn","org.tn","info.tn","perso.tn","tourism.tn","edunet.tn","rnrt.tn","rns.tn","rnu.tn","mincom.tn","agrinet.tn","defense.tn","turen.tn","to","com.to","gov.to","net.to","org.to","edu.to","mil.to","tr","av.tr","bbs.tr","bel.tr","biz.tr","com.tr","dr.tr","edu.tr","gen.tr","gov.tr","info.tr","mil.tr","k12.tr","kep.tr","name.tr","net.tr","org.tr","pol.tr","tel.tr","tsk.tr","tv.tr","web.tr","nc.tr","gov.nc.tr","tt","co.tt","com.tt","org.tt","net.tt","biz.tt","info.tt","pro.tt","int.tt","coop.tt","jobs.tt","mobi.tt","travel.tt","museum.tt","aero.tt","name.tt","gov.tt","edu.tt","tv","tw","edu.tw","gov.tw","mil.tw","com.tw","net.tw","org.tw","idv.tw","game.tw","ebiz.tw","club.tw","網路.tw","組織.tw","商業.tw","tz","ac.tz","co.tz","go.tz","hotel.tz","info.tz","me.tz","mil.tz","mobi.tz","ne.tz","or.tz","sc.tz","tv.tz","ua","com.ua","edu.ua","gov.ua","in.ua","net.ua","org.ua","cherkassy.ua","cherkasy.ua","chernigov.ua","chernihiv.ua","chernivtsi.ua","chernovtsy.ua","ck.ua","cn.ua","cr.ua","crimea.ua","cv.ua","dn.ua","dnepropetrovsk.ua","dnipropetrovsk.ua","dominic.ua","donetsk.ua","dp.ua","if.ua","ivano-frankivsk.ua","kh.ua","kharkiv.ua","kharkov.ua","kherson.ua","khmelnitskiy.ua","khmelnytskyi.ua","kiev.ua","kirovograd.ua","km.ua","kr.ua","krym.ua","ks.ua","kv.ua","kyiv.ua","lg.ua","lt.ua","lugansk.ua","lutsk.ua","lv.ua","lviv.ua","mk.ua","mykolaiv.ua","nikolaev.ua","od.ua","odesa.ua","odessa.ua","pl.ua","poltava.ua","rivne.ua","rovno.ua","rv.ua","sb.ua","sebastopol.ua","sevastopol.ua","sm.ua","sumy.ua","te.ua","ternopil.ua","uz.ua","uzhgorod.ua","vinnica.ua","vinnytsia.ua","vn.ua","volyn.ua","yalta.ua","zaporizhzhe.ua","zaporizhzhia.ua","zhitomir.ua","zhytomyr.ua","zp.ua","zt.ua","ug","co.ug","or.ug","ac.ug","sc.ug","go.ug","ne.ug","com.ug","org.ug","uk","ac.uk","co.uk","gov.uk","ltd.uk","me.uk","net.uk","nhs.uk","org.uk","plc.uk","police.uk","*.sch.uk","us","dni.us","fed.us","isa.us","kids.us","nsn.us","ak.us","al.us","ar.us","as.us","az.us","ca.us","co.us","ct.us","dc.us","de.us","fl.us","ga.us","gu.us","hi.us","ia.us","id.us","il.us","in.us","ks.us","ky.us","la.us","ma.us","md.us","me.us","mi.us","mn.us","mo.us","ms.us","mt.us","nc.us","nd.us","ne.us","nh.us","nj.us","nm.us","nv.us","ny.us","oh.us","ok.us","or.us","pa.us","pr.us","ri.us","sc.us","sd.us","tn.us","tx.us","ut.us","vi.us","vt.us","va.us","wa.us","wi.us","wv.us","wy.us","k12.ak.us","k12.al.us","k12.ar.us","k12.as.us","k12.az.us","k12.ca.us","k12.co.us","k12.ct.us","k12.dc.us","k12.de.us","k12.fl.us","k12.ga.us","k12.gu.us","k12.ia.us","k12.id.us","k12.il.us","k12.in.us","k12.ks.us","k12.ky.us","k12.la.us","k12.ma.us","k12.md.us","k12.me.us","k12.mi.us","k12.mn.us","k12.mo.us","k12.ms.us","k12.mt.us","k12.nc.us","k12.ne.us","k12.nh.us","k12.nj.us","k12.nm.us","k12.nv.us","k12.ny.us","k12.oh.us","k12.ok.us","k12.or.us","k12.pa.us","k12.pr.us","k12.ri.us","k12.sc.us","k12.tn.us","k12.tx.us","k12.ut.us","k12.vi.us","k12.vt.us","k12.va.us","k12.wa.us","k12.wi.us","k12.wy.us","cc.ak.us","cc.al.us","cc.ar.us","cc.as.us","cc.az.us","cc.ca.us","cc.co.us","cc.ct.us","cc.dc.us","cc.de.us","cc.fl.us","cc.ga.us","cc.gu.us","cc.hi.us","cc.ia.us","cc.id.us","cc.il.us","cc.in.us","cc.ks.us","cc.ky.us","cc.la.us","cc.ma.us","cc.md.us","cc.me.us","cc.mi.us","cc.mn.us","cc.mo.us","cc.ms.us","cc.mt.us","cc.nc.us","cc.nd.us","cc.ne.us","cc.nh.us","cc.nj.us","cc.nm.us","cc.nv.us","cc.ny.us","cc.oh.us","cc.ok.us","cc.or.us","cc.pa.us","cc.pr.us","cc.ri.us","cc.sc.us","cc.sd.us","cc.tn.us","cc.tx.us","cc.ut.us","cc.vi.us","cc.vt.us","cc.va.us","cc.wa.us","cc.wi.us","cc.wv.us","cc.wy.us","lib.ak.us","lib.al.us","lib.ar.us","lib.as.us","lib.az.us","lib.ca.us","lib.co.us","lib.ct.us","lib.dc.us","lib.fl.us","lib.ga.us","lib.gu.us","lib.hi.us","lib.ia.us","lib.id.us","lib.il.us","lib.in.us","lib.ks.us","lib.ky.us","lib.la.us","lib.ma.us","lib.md.us","lib.me.us","lib.mi.us","lib.mn.us","lib.mo.us","lib.ms.us","lib.mt.us","lib.nc.us","lib.nd.us","lib.ne.us","lib.nh.us","lib.nj.us","lib.nm.us","lib.nv.us","lib.ny.us","lib.oh.us","lib.ok.us","lib.or.us","lib.pa.us","lib.pr.us","lib.ri.us","lib.sc.us","lib.sd.us","lib.tn.us","lib.tx.us","lib.ut.us","lib.vi.us","lib.vt.us","lib.va.us","lib.wa.us","lib.wi.us","lib.wy.us","pvt.k12.ma.us","chtr.k12.ma.us","paroch.k12.ma.us","ann-arbor.mi.us","cog.mi.us","dst.mi.us","eaton.mi.us","gen.mi.us","mus.mi.us","tec.mi.us","washtenaw.mi.us","uy","com.uy","edu.uy","gub.uy","mil.uy","net.uy","org.uy","uz","co.uz","com.uz","net.uz","org.uz","va","vc","com.vc","net.vc","org.vc","gov.vc","mil.vc","edu.vc","ve","arts.ve","co.ve","com.ve","e12.ve","edu.ve","firm.ve","gob.ve","gov.ve","info.ve","int.ve","mil.ve","net.ve","org.ve","rec.ve","store.ve","tec.ve","web.ve","vg","vi","co.vi","com.vi","k12.vi","net.vi","org.vi","vn","com.vn","net.vn","org.vn","edu.vn","gov.vn","int.vn","ac.vn","biz.vn","info.vn","name.vn","pro.vn","health.vn","vu","com.vu","edu.vu","net.vu","org.vu","wf","ws","com.ws","net.ws","org.ws","gov.ws","edu.ws","yt","امارات","հայ","বাংলা","бг","бел","中国","中國","الجزائر","مصر","ею","ευ","موريتانيا","გე","ελ","香港","公司.香港","教育.香港","政府.香港","個人.香港","網絡.香港","組織.香港","ಭಾರತ","ଭାରତ","ভাৰত","भारतम्","भारोत","ڀارت","ഭാരതം","भारत","بارت","بھارت","భారత్","ભારત","ਭਾਰਤ","ভারত","இந்தியா","ایران","ايران","عراق","الاردن","한국","қаз","ලංකා","இலங்கை","المغرب","мкд","мон","澳門","澳门","مليسيا","عمان","پاکستان","پاكستان","فلسطين","срб","пр.срб","орг.срб","обр.срб","од.срб","упр.срб","ак.срб","рф","قطر","السعودية","السعودیة","السعودیۃ","السعوديه","سودان","新加坡","சிங்கப்பூர்","سورية","سوريا","ไทย","ศึกษา.ไทย","ธุรกิจ.ไทย","รัฐบาล.ไทย","ทหาร.ไทย","เน็ต.ไทย","องค์กร.ไทย","تونس","台灣","台湾","臺灣","укр","اليمن","xxx","*.ye","ac.za","agric.za","alt.za","co.za","edu.za","gov.za","grondar.za","law.za","mil.za","net.za","ngo.za","nic.za","nis.za","nom.za","org.za","school.za","tm.za","web.za","zm","ac.zm","biz.zm","co.zm","com.zm","edu.zm","gov.zm","info.zm","mil.zm","net.zm","org.zm","sch.zm","zw","ac.zw","co.zw","gov.zw","mil.zw","org.zw","aaa","aarp","abarth","abb","abbott","abbvie","abc","able","abogado","abudhabi","academy","accenture","accountant","accountants","aco","actor","adac","ads","adult","aeg","aetna","afamilycompany","afl","africa","agakhan","agency","aig","aigo","airbus","airforce","airtel","akdn","alfaromeo","alibaba","alipay","allfinanz","allstate","ally","alsace","alstom","amazon","americanexpress","americanfamily","amex","amfam","amica","amsterdam","analytics","android","anquan","anz","aol","apartments","app","apple","aquarelle","arab","aramco","archi","army","art","arte","asda","associates","athleta","attorney","auction","audi","audible","audio","auspost","author","auto","autos","avianca","aws","axa","azure","baby","baidu","banamex","bananarepublic","band","bank","bar","barcelona","barclaycard","barclays","barefoot","bargains","baseball","basketball","bauhaus","bayern","bbc","bbt","bbva","bcg","bcn","beats","beauty","beer","bentley","berlin","best","bestbuy","bet","bharti","bible","bid","bike","bing","bingo","bio","black","blackfriday","blockbuster","blog","bloomberg","blue","bms","bmw","bnpparibas","boats","boehringer","bofa","bom","bond","boo","book","booking","bosch","bostik","boston","bot","boutique","box","bradesco","bridgestone","broadway","broker","brother","brussels","budapest","bugatti","build","builders","business","buy","buzz","bzh","cab","cafe","cal","call","calvinklein","cam","camera","camp","cancerresearch","canon","capetown","capital","capitalone","car","caravan","cards","care","career","careers","cars","casa","case","caseih","cash","casino","catering","catholic","cba","cbn","cbre","cbs","ceb","center","ceo","cern","cfa","cfd","chanel","channel","charity","chase","chat","cheap","chintai","christmas","chrome","church","cipriani","circle","cisco","citadel","citi","citic","city","cityeats","claims","cleaning","click","clinic","clinique","clothing","cloud","club","clubmed","coach","codes","coffee","college","cologne","comcast","commbank","community","company","compare","computer","comsec","condos","construction","consulting","contact","contractors","cooking","cookingchannel","cool","corsica","country","coupon","coupons","courses","cpa","credit","creditcard","creditunion","cricket","crown","crs","cruise","cruises","csc","cuisinella","cymru","cyou","dabur","dad","dance","data","date","dating","datsun","day","dclk","dds","deal","dealer","deals","degree","delivery","dell","deloitte","delta","democrat","dental","dentist","desi","design","dev","dhl","diamonds","diet","digital","direct","directory","discount","discover","dish","diy","dnp","docs","doctor","dog","domains","dot","download","drive","dtv","dubai","duck","dunlop","dupont","durban","dvag","dvr","earth","eat","eco","edeka","education","email","emerck","energy","engineer","engineering","enterprises","epson","equipment","ericsson","erni","esq","estate","esurance","etisalat","eurovision","eus","events","exchange","expert","exposed","express","extraspace","fage","fail","fairwinds","faith","family","fan","fans","farm","farmers","fashion","fast","fedex","feedback","ferrari","ferrero","fiat","fidelity","fido","film","final","finance","financial","fire","firestone","firmdale","fish","fishing","fit","fitness","flickr","flights","flir","florist","flowers","fly","foo","food","foodnetwork","football","ford","forex","forsale","forum","foundation","fox","free","fresenius","frl","frogans","frontdoor","frontier","ftr","fujitsu","fujixerox","fun","fund","furniture","futbol","fyi","gal","gallery","gallo","gallup","game","games","gap","garden","gay","gbiz","gdn","gea","gent","genting","george","ggee","gift","gifts","gives","giving","glade","glass","gle","global","globo","gmail","gmbh","gmo","gmx","godaddy","gold","goldpoint","golf","goo","goodyear","goog","google","gop","got","grainger","graphics","gratis","green","gripe","grocery","group","guardian","gucci","guge","guide","guitars","guru","hair","hamburg","hangout","haus","hbo","hdfc","hdfcbank","health","healthcare","help","helsinki","here","hermes","hgtv","hiphop","hisamitsu","hitachi","hiv","hkt","hockey","holdings","holiday","homedepot","homegoods","homes","homesense","honda","horse","hospital","host","hosting","hot","hoteles","hotels","hotmail","house","how","hsbc","hughes","hyatt","hyundai","ibm","icbc","ice","icu","ieee","ifm","ikano","imamat","imdb","immo","immobilien","inc","industries","infiniti","ing","ink","institute","insurance","insure","intel","international","intuit","investments","ipiranga","irish","ismaili","ist","istanbul","itau","itv","iveco","jaguar","java","jcb","jcp","jeep","jetzt","jewelry","jio","jll","jmp","jnj","joburg","jot","joy","jpmorgan","jprs","juegos","juniper","kaufen","kddi","kerryhotels","kerrylogistics","kerryproperties","kfh","kia","kim","kinder","kindle","kitchen","kiwi","koeln","komatsu","kosher","kpmg","kpn","krd","kred","kuokgroup","kyoto","lacaixa","lamborghini","lamer","lancaster","lancia","land","landrover","lanxess","lasalle","lat","latino","latrobe","law","lawyer","lds","lease","leclerc","lefrak","legal","lego","lexus","lgbt","lidl","life","lifeinsurance","lifestyle","lighting","like","lilly","limited","limo","lincoln","linde","link","lipsy","live","living","lixil","llc","llp","loan","loans","locker","locus","loft","lol","london","lotte","lotto","love","lpl","lplfinancial","ltd","ltda","lundbeck","lupin","luxe","luxury","macys","madrid","maif","maison","makeup","man","management","mango","map","market","marketing","markets","marriott","marshalls","maserati","mattel","mba","mckinsey","med","media","meet","melbourne","meme","memorial","men","menu","merckmsd","metlife","miami","microsoft","mini","mint","mit","mitsubishi","mlb","mls","mma","mobile","moda","moe","moi","mom","monash","money","monster","mormon","mortgage","moscow","moto","motorcycles","mov","movie","msd","mtn","mtr","mutual","nab","nadex","nagoya","nationwide","natura","navy","nba","nec","netbank","netflix","network","neustar","new","newholland","news","next","nextdirect","nexus","nfl","ngo","nhk","nico","nike","nikon","ninja","nissan","nissay","nokia","northwesternmutual","norton","now","nowruz","nowtv","nra","nrw","ntt","nyc","obi","observer","off","office","okinawa","olayan","olayangroup","oldnavy","ollo","omega","one","ong","onl","online","onyourside","ooo","open","oracle","orange","organic","origins","osaka","otsuka","ott","ovh","page","panasonic","paris","pars","partners","parts","party","passagens","pay","pccw","pet","pfizer","pharmacy","phd","philips","phone","photo","photography","photos","physio","pics","pictet","pictures","pid","pin","ping","pink","pioneer","pizza","place","play","playstation","plumbing","plus","pnc","pohl","poker","politie","porn","pramerica","praxi","press","prime","prod","productions","prof","progressive","promo","properties","property","protection","pru","prudential","pub","pwc","qpon","quebec","quest","qvc","racing","radio","raid","read","realestate","realtor","realty","recipes","red","redstone","redumbrella","rehab","reise","reisen","reit","reliance","ren","rent","rentals","repair","report","republican","rest","restaurant","review","reviews","rexroth","rich","richardli","ricoh","rightathome","ril","rio","rip","rmit","rocher","rocks","rodeo","rogers","room","rsvp","rugby","ruhr","run","rwe","ryukyu","saarland","safe","safety","sakura","sale","salon","samsclub","samsung","sandvik","sandvikcoromant","sanofi","sap","sarl","sas","save","saxo","sbi","sbs","sca","scb","schaeffler","schmidt","scholarships","school","schule","schwarz","science","scjohnson","scor","scot","search","seat","secure","security","seek","select","sener","services","ses","seven","sew","sex","sexy","sfr","shangrila","sharp","shaw","shell","shia","shiksha","shoes","shop","shopping","shouji","show","showtime","shriram","silk","sina","singles","site","ski","skin","sky","skype","sling","smart","smile","sncf","soccer","social","softbank","software","sohu","solar","solutions","song","sony","soy","spa","space","sport","spot","spreadbetting","srl","stada","staples","star","statebank","statefarm","stc","stcgroup","stockholm","storage","store","stream","studio","study","style","sucks","supplies","supply","support","surf","surgery","suzuki","swatch","swiftcover","swiss","sydney","symantec","systems","tab","taipei","talk","taobao","target","tatamotors","tatar","tattoo","tax","taxi","tci","tdk","team","tech","technology","temasek","tennis","teva","thd","theater","theatre","tiaa","tickets","tienda","tiffany","tips","tires","tirol","tjmaxx","tjx","tkmaxx","tmall","today","tokyo","tools","top","toray","toshiba","total","tours","town","toyota","toys","trade","trading","training","travel","travelchannel","travelers","travelersinsurance","trust","trv","tube","tui","tunes","tushu","tvs","ubank","ubs","unicom","university","uno","uol","ups","vacations","vana","vanguard","vegas","ventures","verisign","versicherung","vet","viajes","video","vig","viking","villas","vin","vip","virgin","visa","vision","viva","vivo","vlaanderen","vodka","volkswagen","volvo","vote","voting","voto","voyage","vuelos","wales","walmart","walter","wang","wanggou","watch","watches","weather","weatherchannel","webcam","weber","website","wed","wedding","weibo","weir","whoswho","wien","wiki","williamhill","win","windows","wine","winners","wme","wolterskluwer","woodside","work","works","world","wow","wtc","wtf","xbox","xerox","xfinity","xihuan","xin","कॉम","セール","佛山","慈善","集团","在线","大众汽车","点看","คอม","八卦","موقع","公益","公司","香格里拉","网站","移动","我爱你","москва","католик","онлайн","сайт","联通","קום","时尚","微博","淡马锡","ファッション","орг","नेट","ストア","アマゾン","삼성","商标","商店","商城","дети","ポイント","新闻","工行","家電","كوم","中文网","中信","娱乐","谷歌","電訊盈科","购物","クラウド","通販","网店","संगठन","餐厅","网络","ком","亚马逊","诺基亚","食品","飞利浦","手表","手机","ارامكو","العليان","اتصالات","بازار","ابوظبي","كاثوليك","همراه","닷컴","政府","شبكة","بيتك","عرب","机构","组织机构","健康","招聘","рус","珠宝","大拿","みんな","グーグル","世界","書籍","网址","닷넷","コム","天主教","游戏","vermögensberater","vermögensberatung","企业","信息","嘉里大酒店","嘉里","广东","政务","xyz","yachts","yahoo","yamaxun","yandex","yodobashi","yoga","yokohama","you","youtube","yun","zappos","zara","zero","zip","zone","zuerich","cc.ua","inf.ua","ltd.ua","adobeaemcloud.com","adobeaemcloud.net","*.dev.adobeaemcloud.com","beep.pl","barsy.ca","*.compute.estate","*.alces.network","altervista.org","alwaysdata.net","cloudfront.net","*.compute.amazonaws.com","*.compute-1.amazonaws.com","*.compute.amazonaws.com.cn","us-east-1.amazonaws.com","cn-north-1.eb.amazonaws.com.cn","cn-northwest-1.eb.amazonaws.com.cn","elasticbeanstalk.com","ap-northeast-1.elasticbeanstalk.com","ap-northeast-2.elasticbeanstalk.com","ap-northeast-3.elasticbeanstalk.com","ap-south-1.elasticbeanstalk.com","ap-southeast-1.elasticbeanstalk.com","ap-southeast-2.elasticbeanstalk.com","ca-central-1.elasticbeanstalk.com","eu-central-1.elasticbeanstalk.com","eu-west-1.elasticbeanstalk.com","eu-west-2.elasticbeanstalk.com","eu-west-3.elasticbeanstalk.com","sa-east-1.elasticbeanstalk.com","us-east-1.elasticbeanstalk.com","us-east-2.elasticbeanstalk.com","us-gov-west-1.elasticbeanstalk.com","us-west-1.elasticbeanstalk.com","us-west-2.elasticbeanstalk.com","*.elb.amazonaws.com","*.elb.amazonaws.com.cn","s3.amazonaws.com","s3-ap-northeast-1.amazonaws.com","s3-ap-northeast-2.amazonaws.com","s3-ap-south-1.amazonaws.com","s3-ap-southeast-1.amazonaws.com","s3-ap-southeast-2.amazonaws.com","s3-ca-central-1.amazonaws.com","s3-eu-central-1.amazonaws.com","s3-eu-west-1.amazonaws.com","s3-eu-west-2.amazonaws.com","s3-eu-west-3.amazonaws.com","s3-external-1.amazonaws.com","s3-fips-us-gov-west-1.amazonaws.com","s3-sa-east-1.amazonaws.com","s3-us-gov-west-1.amazonaws.com","s3-us-east-2.amazonaws.com","s3-us-west-1.amazonaws.com","s3-us-west-2.amazonaws.com","s3.ap-northeast-2.amazonaws.com","s3.ap-south-1.amazonaws.com","s3.cn-north-1.amazonaws.com.cn","s3.ca-central-1.amazonaws.com","s3.eu-central-1.amazonaws.com","s3.eu-west-2.amazonaws.com","s3.eu-west-3.amazonaws.com","s3.us-east-2.amazonaws.com","s3.dualstack.ap-northeast-1.amazonaws.com","s3.dualstack.ap-northeast-2.amazonaws.com","s3.dualstack.ap-south-1.amazonaws.com","s3.dualstack.ap-southeast-1.amazonaws.com","s3.dualstack.ap-southeast-2.amazonaws.com","s3.dualstack.ca-central-1.amazonaws.com","s3.dualstack.eu-central-1.amazonaws.com","s3.dualstack.eu-west-1.amazonaws.com","s3.dualstack.eu-west-2.amazonaws.com","s3.dualstack.eu-west-3.amazonaws.com","s3.dualstack.sa-east-1.amazonaws.com","s3.dualstack.us-east-1.amazonaws.com","s3.dualstack.us-east-2.amazonaws.com","s3-website-us-east-1.amazonaws.com","s3-website-us-west-1.amazonaws.com","s3-website-us-west-2.amazonaws.com","s3-website-ap-northeast-1.amazonaws.com","s3-website-ap-southeast-1.amazonaws.com","s3-website-ap-southeast-2.amazonaws.com","s3-website-eu-west-1.amazonaws.com","s3-website-sa-east-1.amazonaws.com","s3-website.ap-northeast-2.amazonaws.com","s3-website.ap-south-1.amazonaws.com","s3-website.ca-central-1.amazonaws.com","s3-website.eu-central-1.amazonaws.com","s3-website.eu-west-2.amazonaws.com","s3-website.eu-west-3.amazonaws.com","s3-website.us-east-2.amazonaws.com","amsw.nl","t3l3p0rt.net","tele.amune.org","apigee.io","on-aptible.com","user.aseinet.ne.jp","gv.vc","d.gv.vc","user.party.eus","pimienta.org","poivron.org","potager.org","sweetpepper.org","myasustor.com","myfritz.net","*.awdev.ca","*.advisor.ws","b-data.io","backplaneapp.io","balena-devices.com","app.banzaicloud.io","betainabox.com","bnr.la","blackbaudcdn.net","boomla.net","boxfuse.io","square7.ch","bplaced.com","bplaced.de","square7.de","bplaced.net","square7.net","browsersafetymark.io","uk0.bigv.io","dh.bytemark.co.uk","vm.bytemark.co.uk","mycd.eu","carrd.co","crd.co","uwu.ai","ae.org","ar.com","br.com","cn.com","com.de","com.se","de.com","eu.com","gb.com","gb.net","hu.com","hu.net","jp.net","jpn.com","kr.com","mex.com","no.com","qc.com","ru.com","sa.com","se.net","uk.com","uk.net","us.com","uy.com","za.bz","za.com","africa.com","gr.com","in.net","us.org","co.com","c.la","certmgr.org","xenapponazure.com","discourse.group","discourse.team","virtueeldomein.nl","cleverapps.io","*.lcl.dev","*.stg.dev","c66.me","cloud66.ws","cloud66.zone","jdevcloud.com","wpdevcloud.com","cloudaccess.host","freesite.host","cloudaccess.net","cloudcontrolled.com","cloudcontrolapp.com","cloudera.site","trycloudflare.com","workers.dev","wnext.app","co.ca","*.otap.co","co.cz","c.cdn77.org","cdn77-ssl.net","r.cdn77.net","rsc.cdn77.org","ssl.origin.cdn77-secure.org","cloudns.asia","cloudns.biz","cloudns.club","cloudns.cc","cloudns.eu","cloudns.in","cloudns.info","cloudns.org","cloudns.pro","cloudns.pw","cloudns.us","cloudeity.net","cnpy.gdn","co.nl","co.no","webhosting.be","hosting-cluster.nl","ac.ru","edu.ru","gov.ru","int.ru","mil.ru","test.ru","dyn.cosidns.de","dynamisches-dns.de","dnsupdater.de","internet-dns.de","l-o-g-i-n.de","dynamic-dns.info","feste-ip.net","knx-server.net","static-access.net","realm.cz","*.cryptonomic.net","cupcake.is","*.customer-oci.com","*.oci.customer-oci.com","*.ocp.customer-oci.com","*.ocs.customer-oci.com","cyon.link","cyon.site","daplie.me","localhost.daplie.me","dattolocal.com","dattorelay.com","dattoweb.com","mydatto.com","dattolocal.net","mydatto.net","biz.dk","co.dk","firm.dk","reg.dk","store.dk","*.dapps.earth","*.bzz.dapps.earth","builtwithdark.com","edgestack.me","debian.net","dedyn.io","dnshome.de","online.th","shop.th","drayddns.com","dreamhosters.com","mydrobo.com","drud.io","drud.us","duckdns.org","dy.fi","tunk.org","dyndns-at-home.com","dyndns-at-work.com","dyndns-blog.com","dyndns-free.com","dyndns-home.com","dyndns-ip.com","dyndns-mail.com","dyndns-office.com","dyndns-pics.com","dyndns-remote.com","dyndns-server.com","dyndns-web.com","dyndns-wiki.com","dyndns-work.com","dyndns.biz","dyndns.info","dyndns.org","dyndns.tv","at-band-camp.net","ath.cx","barrel-of-knowledge.info","barrell-of-knowledge.info","better-than.tv","blogdns.com","blogdns.net","blogdns.org","blogsite.org","boldlygoingnowhere.org","broke-it.net","buyshouses.net","cechire.com","dnsalias.com","dnsalias.net","dnsalias.org","dnsdojo.com","dnsdojo.net","dnsdojo.org","does-it.net","doesntexist.com","doesntexist.org","dontexist.com","dontexist.net","dontexist.org","doomdns.com","doomdns.org","dvrdns.org","dyn-o-saur.com","dynalias.com","dynalias.net","dynalias.org","dynathome.net","dyndns.ws","endofinternet.net","endofinternet.org","endoftheinternet.org","est-a-la-maison.com","est-a-la-masion.com","est-le-patron.com","est-mon-blogueur.com","for-better.biz","for-more.biz","for-our.info","for-some.biz","for-the.biz","forgot.her.name","forgot.his.name","from-ak.com","from-al.com","from-ar.com","from-az.net","from-ca.com","from-co.net","from-ct.com","from-dc.com","from-de.com","from-fl.com","from-ga.com","from-hi.com","from-ia.com","from-id.com","from-il.com","from-in.com","from-ks.com","from-ky.com","from-la.net","from-ma.com","from-md.com","from-me.org","from-mi.com","from-mn.com","from-mo.com","from-ms.com","from-mt.com","from-nc.com","from-nd.com","from-ne.com","from-nh.com","from-nj.com","from-nm.com","from-nv.com","from-ny.net","from-oh.com","from-ok.com","from-or.com","from-pa.com","from-pr.com","from-ri.com","from-sc.com","from-sd.com","from-tn.com","from-tx.com","from-ut.com","from-va.com","from-vt.com","from-wa.com","from-wi.com","from-wv.com","from-wy.com","ftpaccess.cc","fuettertdasnetz.de","game-host.org","game-server.cc","getmyip.com","gets-it.net","go.dyndns.org","gotdns.com","gotdns.org","groks-the.info","groks-this.info","ham-radio-op.net","here-for-more.info","hobby-site.com","hobby-site.org","home.dyndns.org","homedns.org","homeftp.net","homeftp.org","homeip.net","homelinux.com","homelinux.net","homelinux.org","homeunix.com","homeunix.net","homeunix.org","iamallama.com","in-the-band.net","is-a-anarchist.com","is-a-blogger.com","is-a-bookkeeper.com","is-a-bruinsfan.org","is-a-bulls-fan.com","is-a-candidate.org","is-a-caterer.com","is-a-celticsfan.org","is-a-chef.com","is-a-chef.net","is-a-chef.org","is-a-conservative.com","is-a-cpa.com","is-a-cubicle-slave.com","is-a-democrat.com","is-a-designer.com","is-a-doctor.com","is-a-financialadvisor.com","is-a-geek.com","is-a-geek.net","is-a-geek.org","is-a-green.com","is-a-guru.com","is-a-hard-worker.com","is-a-hunter.com","is-a-knight.org","is-a-landscaper.com","is-a-lawyer.com","is-a-liberal.com","is-a-libertarian.com","is-a-linux-user.org","is-a-llama.com","is-a-musician.com","is-a-nascarfan.com","is-a-nurse.com","is-a-painter.com","is-a-patsfan.org","is-a-personaltrainer.com","is-a-photographer.com","is-a-player.com","is-a-republican.com","is-a-rockstar.com","is-a-socialist.com","is-a-soxfan.org","is-a-student.com","is-a-teacher.com","is-a-techie.com","is-a-therapist.com","is-an-accountant.com","is-an-actor.com","is-an-actress.com","is-an-anarchist.com","is-an-artist.com","is-an-engineer.com","is-an-entertainer.com","is-by.us","is-certified.com","is-found.org","is-gone.com","is-into-anime.com","is-into-cars.com","is-into-cartoons.com","is-into-games.com","is-leet.com","is-lost.org","is-not-certified.com","is-saved.org","is-slick.com","is-uberleet.com","is-very-bad.org","is-very-evil.org","is-very-good.org","is-very-nice.org","is-very-sweet.org","is-with-theband.com","isa-geek.com","isa-geek.net","isa-geek.org","isa-hockeynut.com","issmarterthanyou.com","isteingeek.de","istmein.de","kicks-ass.net","kicks-ass.org","knowsitall.info","land-4-sale.us","lebtimnetz.de","leitungsen.de","likes-pie.com","likescandy.com","merseine.nu","mine.nu","misconfused.org","mypets.ws","myphotos.cc","neat-url.com","office-on-the.net","on-the-web.tv","podzone.net","podzone.org","readmyblog.org","saves-the-whales.com","scrapper-site.net","scrapping.cc","selfip.biz","selfip.com","selfip.info","selfip.net","selfip.org","sells-for-less.com","sells-for-u.com","sells-it.net","sellsyourhome.org","servebbs.com","servebbs.net","servebbs.org","serveftp.net","serveftp.org","servegame.org","shacknet.nu","simple-url.com","space-to-rent.com","stuff-4-sale.org","stuff-4-sale.us","teaches-yoga.com","thruhere.net","traeumtgerade.de","webhop.biz","webhop.info","webhop.net","webhop.org","worse-than.tv","writesthisblog.com","ddnss.de","dyn.ddnss.de","dyndns.ddnss.de","dyndns1.de","dyn-ip24.de","home-webserver.de","dyn.home-webserver.de","myhome-server.de","ddnss.org","definima.net","definima.io","bci.dnstrace.pro","ddnsfree.com","ddnsgeek.com","giize.com","gleeze.com","kozow.com","loseyourip.com","ooguy.com","theworkpc.com","casacam.net","dynu.net","accesscam.org","camdvr.org","freeddns.org","mywire.org","webredirect.org","myddns.rocks","blogsite.xyz","dynv6.net","e4.cz","en-root.fr","mytuleap.com","onred.one","staging.onred.one","enonic.io","customer.enonic.io","eu.org","al.eu.org","asso.eu.org","at.eu.org","au.eu.org","be.eu.org","bg.eu.org","ca.eu.org","cd.eu.org","ch.eu.org","cn.eu.org","cy.eu.org","cz.eu.org","de.eu.org","dk.eu.org","edu.eu.org","ee.eu.org","es.eu.org","fi.eu.org","fr.eu.org","gr.eu.org","hr.eu.org","hu.eu.org","ie.eu.org","il.eu.org","in.eu.org","int.eu.org","is.eu.org","it.eu.org","jp.eu.org","kr.eu.org","lt.eu.org","lu.eu.org","lv.eu.org","mc.eu.org","me.eu.org","mk.eu.org","mt.eu.org","my.eu.org","net.eu.org","ng.eu.org","nl.eu.org","no.eu.org","nz.eu.org","paris.eu.org","pl.eu.org","pt.eu.org","q-a.eu.org","ro.eu.org","ru.eu.org","se.eu.org","si.eu.org","sk.eu.org","tr.eu.org","uk.eu.org","us.eu.org","eu-1.evennode.com","eu-2.evennode.com","eu-3.evennode.com","eu-4.evennode.com","us-1.evennode.com","us-2.evennode.com","us-3.evennode.com","us-4.evennode.com","twmail.cc","twmail.net","twmail.org","mymailer.com.tw","url.tw","apps.fbsbx.com","ru.net","adygeya.ru","bashkiria.ru","bir.ru","cbg.ru","com.ru","dagestan.ru","grozny.ru","kalmykia.ru","kustanai.ru","marine.ru","mordovia.ru","msk.ru","mytis.ru","nalchik.ru","nov.ru","pyatigorsk.ru","spb.ru","vladikavkaz.ru","vladimir.ru","abkhazia.su","adygeya.su","aktyubinsk.su","arkhangelsk.su","armenia.su","ashgabad.su","azerbaijan.su","balashov.su","bashkiria.su","bryansk.su","bukhara.su","chimkent.su","dagestan.su","east-kazakhstan.su","exnet.su","georgia.su","grozny.su","ivanovo.su","jambyl.su","kalmykia.su","kaluga.su","karacol.su","karaganda.su","karelia.su","khakassia.su","krasnodar.su","kurgan.su","kustanai.su","lenug.su","mangyshlak.su","mordovia.su","msk.su","murmansk.su","nalchik.su","navoi.su","north-kazakhstan.su","nov.su","obninsk.su","penza.su","pokrovsk.su","sochi.su","spb.su","tashkent.su","termez.su","togliatti.su","troitsk.su","tselinograd.su","tula.su","tuva.su","vladikavkaz.su","vladimir.su","vologda.su","channelsdvr.net","u.channelsdvr.net","fastly-terrarium.com","fastlylb.net","map.fastlylb.net","freetls.fastly.net","map.fastly.net","a.prod.fastly.net","global.prod.fastly.net","a.ssl.fastly.net","b.ssl.fastly.net","global.ssl.fastly.net","fastpanel.direct","fastvps-server.com","fhapp.xyz","fedorainfracloud.org","fedorapeople.org","cloud.fedoraproject.org","app.os.fedoraproject.org","app.os.stg.fedoraproject.org","mydobiss.com","filegear.me","filegear-au.me","filegear-de.me","filegear-gb.me","filegear-ie.me","filegear-jp.me","filegear-sg.me","firebaseapp.com","flynnhub.com","flynnhosting.net","0e.vc","freebox-os.com","freeboxos.com","fbx-os.fr","fbxos.fr","freebox-os.fr","freeboxos.fr","freedesktop.org","*.futurecms.at","*.ex.futurecms.at","*.in.futurecms.at","futurehosting.at","futuremailing.at","*.ex.ortsinfo.at","*.kunden.ortsinfo.at","*.statics.cloud","service.gov.uk","gehirn.ne.jp","usercontent.jp","gentapps.com","lab.ms","github.io","githubusercontent.com","gitlab.io","glitch.me","lolipop.io","cloudapps.digital","london.cloudapps.digital","homeoffice.gov.uk","ro.im","shop.ro","goip.de","run.app","a.run.app","web.app","*.0emm.com","appspot.com","*.r.appspot.com","blogspot.ae","blogspot.al","blogspot.am","blogspot.ba","blogspot.be","blogspot.bg","blogspot.bj","blogspot.ca","blogspot.cf","blogspot.ch","blogspot.cl","blogspot.co.at","blogspot.co.id","blogspot.co.il","blogspot.co.ke","blogspot.co.nz","blogspot.co.uk","blogspot.co.za","blogspot.com","blogspot.com.ar","blogspot.com.au","blogspot.com.br","blogspot.com.by","blogspot.com.co","blogspot.com.cy","blogspot.com.ee","blogspot.com.eg","blogspot.com.es","blogspot.com.mt","blogspot.com.ng","blogspot.com.tr","blogspot.com.uy","blogspot.cv","blogspot.cz","blogspot.de","blogspot.dk","blogspot.fi","blogspot.fr","blogspot.gr","blogspot.hk","blogspot.hr","blogspot.hu","blogspot.ie","blogspot.in","blogspot.is","blogspot.it","blogspot.jp","blogspot.kr","blogspot.li","blogspot.lt","blogspot.lu","blogspot.md","blogspot.mk","blogspot.mr","blogspot.mx","blogspot.my","blogspot.nl","blogspot.no","blogspot.pe","blogspot.pt","blogspot.qa","blogspot.re","blogspot.ro","blogspot.rs","blogspot.ru","blogspot.se","blogspot.sg","blogspot.si","blogspot.sk","blogspot.sn","blogspot.td","blogspot.tw","blogspot.ug","blogspot.vn","cloudfunctions.net","cloud.goog","codespot.com","googleapis.com","googlecode.com","pagespeedmobilizer.com","publishproxy.com","withgoogle.com","withyoutube.com","awsmppl.com","fin.ci","free.hr","caa.li","ua.rs","conf.se","hs.zone","hs.run","hashbang.sh","hasura.app","hasura-app.io","hepforge.org","herokuapp.com","herokussl.com","myravendb.com","ravendb.community","ravendb.me","development.run","ravendb.run","bpl.biz","orx.biz","ng.city","biz.gl","ng.ink","col.ng","firm.ng","gen.ng","ltd.ng","ngo.ng","ng.school","sch.so","häkkinen.fi","*.moonscale.io","moonscale.net","iki.fi","dyn-berlin.de","in-berlin.de","in-brb.de","in-butter.de","in-dsl.de","in-dsl.net","in-dsl.org","in-vpn.de","in-vpn.net","in-vpn.org","biz.at","info.at","info.cx","ac.leg.br","al.leg.br","am.leg.br","ap.leg.br","ba.leg.br","ce.leg.br","df.leg.br","es.leg.br","go.leg.br","ma.leg.br","mg.leg.br","ms.leg.br","mt.leg.br","pa.leg.br","pb.leg.br","pe.leg.br","pi.leg.br","pr.leg.br","rj.leg.br","rn.leg.br","ro.leg.br","rr.leg.br","rs.leg.br","sc.leg.br","se.leg.br","sp.leg.br","to.leg.br","pixolino.com","ipifony.net","mein-iserv.de","test-iserv.de","iserv.dev","iobb.net","myjino.ru","*.hosting.myjino.ru","*.landing.myjino.ru","*.spectrum.myjino.ru","*.vps.myjino.ru","*.triton.zone","*.cns.joyent.com","js.org","kaas.gg","khplay.nl","keymachine.de","kinghost.net","uni5.net","knightpoint.systems","oya.to","co.krd","edu.krd","git-repos.de","lcube-server.de","svn-repos.de","leadpages.co","lpages.co","lpusercontent.com","lelux.site","co.business","co.education","co.events","co.financial","co.network","co.place","co.technology","app.lmpm.com","linkitools.space","linkyard.cloud","linkyard-cloud.ch","members.linode.com","nodebalancer.linode.com","we.bs","loginline.app","loginline.dev","loginline.io","loginline.services","loginline.site","krasnik.pl","leczna.pl","lubartow.pl","lublin.pl","poniatowa.pl","swidnik.pl","uklugs.org","glug.org.uk","lug.org.uk","lugs.org.uk","barsy.bg","barsy.co.uk","barsyonline.co.uk","barsycenter.com","barsyonline.com","barsy.club","barsy.de","barsy.eu","barsy.in","barsy.info","barsy.io","barsy.me","barsy.menu","barsy.mobi","barsy.net","barsy.online","barsy.org","barsy.pro","barsy.pub","barsy.shop","barsy.site","barsy.support","barsy.uk","*.magentosite.cloud","mayfirst.info","mayfirst.org","hb.cldmail.ru","miniserver.com","memset.net","cloud.metacentrum.cz","custom.metacentrum.cz","flt.cloud.muni.cz","usr.cloud.muni.cz","meteorapp.com","eu.meteorapp.com","co.pl","azurecontainer.io","azurewebsites.net","azure-mobile.net","cloudapp.net","mozilla-iot.org","bmoattachments.org","net.ru","org.ru","pp.ru","ui.nabu.casa","pony.club","of.fashion","on.fashion","of.football","in.london","of.london","for.men","and.mom","for.mom","for.one","for.sale","of.work","to.work","nctu.me","bitballoon.com","netlify.com","4u.com","ngrok.io","nh-serv.co.uk","nfshost.com","dnsking.ch","mypi.co","n4t.co","001www.com","ddnslive.com","myiphost.com","forumz.info","16-b.it","32-b.it","64-b.it","soundcast.me","tcp4.me","dnsup.net","hicam.net","now-dns.net","ownip.net","vpndns.net","dynserv.org","now-dns.org","x443.pw","now-dns.top","ntdll.top","freeddns.us","crafting.xyz","zapto.xyz","nsupdate.info","nerdpol.ovh","blogsyte.com","brasilia.me","cable-modem.org","ciscofreak.com","collegefan.org","couchpotatofries.org","damnserver.com","ddns.me","ditchyourip.com","dnsfor.me","dnsiskinky.com","dvrcam.info","dynns.com","eating-organic.net","fantasyleague.cc","geekgalaxy.com","golffan.us","health-carereform.com","homesecuritymac.com","homesecuritypc.com","hopto.me","ilovecollege.info","loginto.me","mlbfan.org","mmafan.biz","myactivedirectory.com","mydissent.net","myeffect.net","mymediapc.net","mypsx.net","mysecuritycamera.com","mysecuritycamera.net","mysecuritycamera.org","net-freaks.com","nflfan.org","nhlfan.net","no-ip.ca","no-ip.co.uk","no-ip.net","noip.us","onthewifi.com","pgafan.net","point2this.com","pointto.us","privatizehealthinsurance.net","quicksytes.com","read-books.org","securitytactics.com","serveexchange.com","servehumour.com","servep2p.com","servesarcasm.com","stufftoread.com","ufcfan.org","unusualperson.com","workisboring.com","3utilities.com","bounceme.net","ddns.net","ddnsking.com","gotdns.ch","hopto.org","myftp.biz","myftp.org","myvnc.com","no-ip.biz","no-ip.info","no-ip.org","noip.me","redirectme.net","servebeer.com","serveblog.net","servecounterstrike.com","serveftp.com","servegame.com","servehalflife.com","servehttp.com","serveirc.com","serveminecraft.net","servemp3.com","servepics.com","servequake.com","sytes.net","webhop.me","zapto.org","stage.nodeart.io","nodum.co","nodum.io","pcloud.host","nyc.mn","nom.ae","nom.af","nom.ai","nom.al","nym.by","nom.bz","nym.bz","nom.cl","nym.ec","nom.gd","nom.ge","nom.gl","nym.gr","nom.gt","nym.gy","nym.hk","nom.hn","nym.ie","nom.im","nom.ke","nym.kz","nym.la","nym.lc","nom.li","nym.li","nym.lt","nym.lu","nom.lv","nym.me","nom.mk","nym.mn","nym.mx","nom.nu","nym.nz","nym.pe","nym.pt","nom.pw","nom.qa","nym.ro","nom.rs","nom.si","nym.sk","nom.st","nym.su","nym.sx","nom.tj","nym.tw","nom.ug","nom.uy","nom.vc","nom.vg","static.observableusercontent.com","cya.gg","cloudycluster.net","nid.io","opencraft.hosting","operaunite.com","skygearapp.com","outsystemscloud.com","ownprovider.com","own.pm","ox.rs","oy.lc","pgfog.com","pagefrontapp.com","art.pl","gliwice.pl","krakow.pl","poznan.pl","wroc.pl","zakopane.pl","pantheonsite.io","gotpantheon.com","mypep.link","perspecta.cloud","on-web.fr","*.platform.sh","*.platformsh.site","dyn53.io","co.bn","xen.prgmr.com","priv.at","prvcy.page","*.dweb.link","protonet.io","chirurgiens-dentistes-en-france.fr","byen.site","pubtls.org","qualifioapp.com","qbuser.com","instantcloud.cn","ras.ru","qa2.com","qcx.io","*.sys.qcx.io","dev-myqnapcloud.com","alpha-myqnapcloud.com","myqnapcloud.com","*.quipelements.com","vapor.cloud","vaporcloud.io","rackmaze.com","rackmaze.net","*.on-k3s.io","*.on-rancher.cloud","*.on-rio.io","readthedocs.io","rhcloud.com","app.render.com","onrender.com","repl.co","repl.run","resindevice.io","devices.resinstaging.io","hzc.io","wellbeingzone.eu","ptplus.fit","wellbeingzone.co.uk","git-pages.rit.edu","sandcats.io","logoip.de","logoip.com","schokokeks.net","gov.scot","scrysec.com","firewall-gateway.com","firewall-gateway.de","my-gateway.de","my-router.de","spdns.de","spdns.eu","firewall-gateway.net","my-firewall.org","myfirewall.org","spdns.org","senseering.net","biz.ua","co.ua","pp.ua","shiftedit.io","myshopblocks.com","shopitsite.com","mo-siemens.io","1kapp.com","appchizi.com","applinzi.com","sinaapp.com","vipsinaapp.com","siteleaf.net","bounty-full.com","alpha.bounty-full.com","beta.bounty-full.com","stackhero-network.com","static.land","dev.static.land","sites.static.land","apps.lair.io","*.stolos.io","spacekit.io","customer.speedpartner.de","api.stdlib.com","storj.farm","utwente.io","soc.srcf.net","user.srcf.net","temp-dns.com","applicationcloud.io","scapp.io","*.s5y.io","*.sensiosite.cloud","syncloud.it","diskstation.me","dscloud.biz","dscloud.me","dscloud.mobi","dsmynas.com","dsmynas.net","dsmynas.org","familyds.com","familyds.net","familyds.org","i234.me","myds.me","synology.me","vpnplus.to","direct.quickconnect.to","taifun-dns.de","gda.pl","gdansk.pl","gdynia.pl","med.pl","sopot.pl","edugit.org","telebit.app","telebit.io","*.telebit.xyz","gwiddle.co.uk","thingdustdata.com","cust.dev.thingdust.io","cust.disrec.thingdust.io","cust.prod.thingdust.io","cust.testing.thingdust.io","arvo.network","azimuth.network","bloxcms.com","townnews-staging.com","12hp.at","2ix.at","4lima.at","lima-city.at","12hp.ch","2ix.ch","4lima.ch","lima-city.ch","trafficplex.cloud","de.cool","12hp.de","2ix.de","4lima.de","lima-city.de","1337.pictures","clan.rip","lima-city.rocks","webspace.rocks","lima.zone","*.transurl.be","*.transurl.eu","*.transurl.nl","tuxfamily.org","dd-dns.de","diskstation.eu","diskstation.org","dray-dns.de","draydns.de","dyn-vpn.de","dynvpn.de","mein-vigor.de","my-vigor.de","my-wan.de","syno-ds.de","synology-diskstation.de","synology-ds.de","uber.space","*.uberspace.de","hk.com","hk.org","ltd.hk","inc.hk","virtualuser.de","virtual-user.de","urown.cloud","dnsupdate.info","lib.de.us","2038.io","router.management","v-info.info","voorloper.cloud","v.ua","wafflecell.com","*.webhare.dev","wedeploy.io","wedeploy.me","wedeploy.sh","remotewd.com","wmflabs.org","myforum.community","community-pro.de","diskussionsbereich.de","community-pro.net","meinforum.net","half.host","xnbay.com","u2.xnbay.com","u2-local.xnbay.com","cistron.nl","demon.nl","xs4all.space","yandexcloud.net","storage.yandexcloud.net","website.yandexcloud.net","official.academy","yolasite.com","ybo.faith","yombo.me","homelink.one","ybo.party","ybo.review","ybo.science","ybo.trade","nohost.me","noho.st","za.net","za.org","now.sh","bss.design","basicserver.io","virtualserver.io","enterprisecloud.nu"]; /***/ }), -/* 53 */, -/* 54 */, -/* 55 */ +/* 51 */, +/* 52 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -const figgyPudding = __webpack_require__(122) -const npa = __webpack_require__(482) -const semver = __webpack_require__(280) +module.exports = { + config: __webpack_require__(374), + parseArg: __webpack_require__(508), + readJSON: __webpack_require__(218), + logicalTree: __webpack_require__(4), + getPrefix: __webpack_require__(367), + verifyLock: __webpack_require__(873), + stringifyPackage: __webpack_require__(572), + manifest: __webpack_require__(638), + tarball: __webpack_require__(915), + extract: __webpack_require__(113), + packument: __webpack_require__(863), + hook: __webpack_require__(771), + access: __webpack_require__(704), + search: __webpack_require__(709), + team: __webpack_require__(449), + org: __webpack_require__(714), + fetch: __webpack_require__(270), + login: __webpack_require__(838), + adduser: __webpack_require__(495), + profile: __webpack_require__(244), + publish: __webpack_require__(760), + unpublish: __webpack_require__(671), + runScript: __webpack_require__(85), + log: __webpack_require__(230), + linkBin: __webpack_require__(953) +} -const PickerOpts = figgyPudding({ - defaultTag: { default: 'latest' }, - enjoyBy: {}, + +/***/ }), +/* 53 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NoopContextManager = void 0; +var context_1 = __webpack_require__(560); +var NoopContextManager = /** @class */ (function () { + function NoopContextManager() { + } + NoopContextManager.prototype.active = function () { + return context_1.Context.ROOT_CONTEXT; + }; + NoopContextManager.prototype.with = function (context, fn) { + return fn(); + }; + NoopContextManager.prototype.bind = function (target, context) { + return target; + }; + NoopContextManager.prototype.enable = function () { + return this; + }; + NoopContextManager.prototype.disable = function () { + return this; + }; + return NoopContextManager; +}()); +exports.NoopContextManager = NoopContextManager; +//# sourceMappingURL=NoopContextManager.js.map + +/***/ }), +/* 54 */, +/* 55 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const figgyPudding = __webpack_require__(122) +const npa = __webpack_require__(482) +const semver = __webpack_require__(280) + +const PickerOpts = figgyPudding({ + defaultTag: { default: 'latest' }, + enjoyBy: {}, includeDeprecated: { default: false } }) @@ -4087,305 +4200,10 @@ function pickManifest (packument, wanted, opts) { /* 58 */ /***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; - -// parse a 512-byte header block to a data object, or vice-versa -// encode returns `true` if a pax extended header is needed, because -// the data could not be faithfully encoded in a simple header. -// (Also, check header.needPax to see if it needs a pax header.) - -const Buffer = __webpack_require__(197) -const types = __webpack_require__(554) -const pathModule = __webpack_require__(622).posix -const large = __webpack_require__(858) - -const SLURP = Symbol('slurp') -const TYPE = Symbol('type') - -class Header { - constructor (data, off, ex, gex) { - this.cksumValid = false - this.needPax = false - this.nullBlock = false - - this.block = null - this.path = null - this.mode = null - this.uid = null - this.gid = null - this.size = null - this.mtime = null - this.cksum = null - this[TYPE] = '0' - this.linkpath = null - this.uname = null - this.gname = null - this.devmaj = 0 - this.devmin = 0 - this.atime = null - this.ctime = null - - if (Buffer.isBuffer(data)) - this.decode(data, off || 0, ex, gex) - else if (data) - this.set(data) - } - - decode (buf, off, ex, gex) { - if (!off) - off = 0 - - if (!buf || !(buf.length >= off + 512)) - throw new Error('need 512 bytes for header') - - this.path = decString(buf, off, 100) - this.mode = decNumber(buf, off + 100, 8) - this.uid = decNumber(buf, off + 108, 8) - this.gid = decNumber(buf, off + 116, 8) - this.size = decNumber(buf, off + 124, 12) - this.mtime = decDate(buf, off + 136, 12) - this.cksum = decNumber(buf, off + 148, 12) - - // if we have extended or global extended headers, apply them now - // See https://github.com/npm/node-tar/pull/187 - this[SLURP](ex) - this[SLURP](gex, true) - - // old tar versions marked dirs as a file with a trailing / - this[TYPE] = decString(buf, off + 156, 1) - if (this[TYPE] === '') - this[TYPE] = '0' - if (this[TYPE] === '0' && this.path.substr(-1) === '/') - this[TYPE] = '5' - - // tar implementations sometimes incorrectly put the stat(dir).size - // as the size in the tarball, even though Directory entries are - // not able to have any body at all. In the very rare chance that - // it actually DOES have a body, we weren't going to do anything with - // it anyway, and it'll just be a warning about an invalid header. - if (this[TYPE] === '5') - this.size = 0 - - this.linkpath = decString(buf, off + 157, 100) - if (buf.slice(off + 257, off + 265).toString() === 'ustar\u000000') { - this.uname = decString(buf, off + 265, 32) - this.gname = decString(buf, off + 297, 32) - this.devmaj = decNumber(buf, off + 329, 8) - this.devmin = decNumber(buf, off + 337, 8) - if (buf[off + 475] !== 0) { - // definitely a prefix, definitely >130 chars. - const prefix = decString(buf, off + 345, 155) - this.path = prefix + '/' + this.path - } else { - const prefix = decString(buf, off + 345, 130) - if (prefix) - this.path = prefix + '/' + this.path - this.atime = decDate(buf, off + 476, 12) - this.ctime = decDate(buf, off + 488, 12) - } - } - - let sum = 8 * 0x20 - for (let i = off; i < off + 148; i++) { - sum += buf[i] - } - for (let i = off + 156; i < off + 512; i++) { - sum += buf[i] - } - this.cksumValid = sum === this.cksum - if (this.cksum === null && sum === 8 * 0x20) - this.nullBlock = true - } - - [SLURP] (ex, global) { - for (let k in ex) { - // we slurp in everything except for the path attribute in - // a global extended header, because that's weird. - if (ex[k] !== null && ex[k] !== undefined && - !(global && k === 'path')) - this[k] = ex[k] - } - } - - encode (buf, off) { - if (!buf) { - buf = this.block = Buffer.alloc(512) - off = 0 - } - - if (!off) - off = 0 - - if (!(buf.length >= off + 512)) - throw new Error('need 512 bytes for header') - - const prefixSize = this.ctime || this.atime ? 130 : 155 - const split = splitPrefix(this.path || '', prefixSize) - const path = split[0] - const prefix = split[1] - this.needPax = split[2] - - this.needPax = encString(buf, off, 100, path) || this.needPax - this.needPax = encNumber(buf, off + 100, 8, this.mode) || this.needPax - this.needPax = encNumber(buf, off + 108, 8, this.uid) || this.needPax - this.needPax = encNumber(buf, off + 116, 8, this.gid) || this.needPax - this.needPax = encNumber(buf, off + 124, 12, this.size) || this.needPax - this.needPax = encDate(buf, off + 136, 12, this.mtime) || this.needPax - buf[off + 156] = this[TYPE].charCodeAt(0) - this.needPax = encString(buf, off + 157, 100, this.linkpath) || this.needPax - buf.write('ustar\u000000', off + 257, 8) - this.needPax = encString(buf, off + 265, 32, this.uname) || this.needPax - this.needPax = encString(buf, off + 297, 32, this.gname) || this.needPax - this.needPax = encNumber(buf, off + 329, 8, this.devmaj) || this.needPax - this.needPax = encNumber(buf, off + 337, 8, this.devmin) || this.needPax - this.needPax = encString(buf, off + 345, prefixSize, prefix) || this.needPax - if (buf[off + 475] !== 0) - this.needPax = encString(buf, off + 345, 155, prefix) || this.needPax - else { - this.needPax = encString(buf, off + 345, 130, prefix) || this.needPax - this.needPax = encDate(buf, off + 476, 12, this.atime) || this.needPax - this.needPax = encDate(buf, off + 488, 12, this.ctime) || this.needPax - } - - let sum = 8 * 0x20 - for (let i = off; i < off + 148; i++) { - sum += buf[i] - } - for (let i = off + 156; i < off + 512; i++) { - sum += buf[i] - } - this.cksum = sum - encNumber(buf, off + 148, 8, this.cksum) - this.cksumValid = true - - return this.needPax - } - - set (data) { - for (let i in data) { - if (data[i] !== null && data[i] !== undefined) - this[i] = data[i] - } - } - - get type () { - return types.name.get(this[TYPE]) || this[TYPE] - } - - get typeKey () { - return this[TYPE] - } - - set type (type) { - if (types.code.has(type)) - this[TYPE] = types.code.get(type) - else - this[TYPE] = type - } -} - -const splitPrefix = (p, prefixSize) => { - const pathSize = 100 - let pp = p - let prefix = '' - let ret - const root = pathModule.parse(p).root || '.' - - if (Buffer.byteLength(pp) < pathSize) - ret = [pp, prefix, false] - else { - // first set prefix to the dir, and path to the base - prefix = pathModule.dirname(pp) - pp = pathModule.basename(pp) - - do { - // both fit! - if (Buffer.byteLength(pp) <= pathSize && - Buffer.byteLength(prefix) <= prefixSize) - ret = [pp, prefix, false] - - // prefix fits in prefix, but path doesn't fit in path - else if (Buffer.byteLength(pp) > pathSize && - Buffer.byteLength(prefix) <= prefixSize) - ret = [pp.substr(0, pathSize - 1), prefix, true] - - else { - // make path take a bit from prefix - pp = pathModule.join(pathModule.basename(prefix), pp) - prefix = pathModule.dirname(prefix) - } - } while (prefix !== root && !ret) - - // at this point, found no resolution, just truncate - if (!ret) - ret = [p.substr(0, pathSize - 1), '', true] - } - return ret -} - -const decString = (buf, off, size) => - buf.slice(off, off + size).toString('utf8').replace(/\0.*/, '') - -const decDate = (buf, off, size) => - numToDate(decNumber(buf, off, size)) - -const numToDate = num => num === null ? null : new Date(num * 1000) - -const decNumber = (buf, off, size) => - buf[off] & 0x80 ? large.parse(buf.slice(off, off + size)) - : decSmallNumber(buf, off, size) - -const nanNull = value => isNaN(value) ? null : value - -const decSmallNumber = (buf, off, size) => - nanNull(parseInt( - buf.slice(off, off + size) - .toString('utf8').replace(/\0.*$/, '').trim(), 8)) - -// the maximum encodable as a null-terminated octal, by field size -const MAXNUM = { - 12: 0o77777777777, - 8 : 0o7777777 -} - -const encNumber = (buf, off, size, number) => - number === null ? false : - number > MAXNUM[size] || number < 0 - ? (large.encode(number, buf.slice(off, off + size)), true) - : (encSmallNumber(buf, off, size, number), false) - -const encSmallNumber = (buf, off, size, number) => - buf.write(octalString(number, size), off, size, 'ascii') - -const octalString = (number, size) => - padOctal(Math.floor(number).toString(8), size) - -const padOctal = (string, size) => - (string.length === size - 1 ? string - : new Array(size - string.length - 1).join('0') + string + ' ') + '\0' - -const encDate = (buf, off, size, date) => - date === null ? false : - encNumber(buf, off, size, date.getTime() / 1000) - -// enough to fill the longest string we've got -const NULLS = new Array(156).join('\0') -// pad with nulls, return true if it's longer or non-ascii -const encString = (buf, off, size, string) => - string === null ? false : - (buf.write(string + NULLS, off, size, 'utf8'), - string.length !== Buffer.byteLength(string) || string.length > size) - -module.exports = Header - - -/***/ }), -/* 59 */ -/***/ (function(module) { - -module.exports = {"name":"cacache","publishConfig":{"tag":"legacy"},"version":"12.0.4","cache-version":{"content":"2","index":"5"},"description":"Fast, fault-tolerant, cross-platform, disk-based, data-agnostic, content-addressable cache.","main":"index.js","files":["*.js","lib","locales"],"scripts":{"benchmarks":"node test/benchmarks","prerelease":"npm t","postrelease":"npm publish && git push --follow-tags","pretest":"standard","release":"standard-version -s","test":"cross-env CACACHE_UPDATE_LOCALE_FILES=true tap --coverage --nyc-arg=--all -J test/*.js","test-docker":"docker run -it --rm --name pacotest -v \"$PWD\":/tmp -w /tmp node:latest npm test"},"repository":"https://github.com/npm/cacache","keywords":["cache","caching","content-addressable","sri","sri hash","subresource integrity","cache","storage","store","file store","filesystem","disk cache","disk storage"],"author":{"name":"Kat Marchán","email":"kzm@sykosomatic.org","twitter":"maybekatz"},"contributors":[{"name":"Charlotte Spencer","email":"charlottelaspencer@gmail.com","twitter":"charlotteis"},{"name":"Rebecca Turner","email":"me@re-becca.org","twitter":"ReBeccaOrg"}],"license":"ISC","dependencies":{"bluebird":"^3.5.5","chownr":"^1.1.1","figgy-pudding":"^3.5.1","glob":"^7.1.4","graceful-fs":"^4.1.15","infer-owner":"^1.0.3","lru-cache":"^5.1.1","mississippi":"^3.0.0","mkdirp":"^0.5.1","move-concurrently":"^1.0.1","promise-inflight":"^1.0.1","rimraf":"^2.6.3","ssri":"^6.0.1","unique-filename":"^1.1.1","y18n":"^4.0.0"},"devDependencies":{"benchmark":"^2.1.4","chalk":"^2.4.2","cross-env":"^5.1.4","require-inject":"^1.4.4","standard":"^12.0.1","standard-version":"^6.0.1","tacks":"^1.3.0","tap":"^12.7.0"},"config":{"nyc":{"exclude":["node_modules/**","test/**"]}}}; +module.exports = __webpack_require__(600); /***/ }), +/* 59 */, /* 60 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -4512,7 +4330,7 @@ module.exports = Object.freeze(Object.assign(Object.create(null), { "use strict"; -var numberIsNan = __webpack_require__(753); +var numberIsNan = __webpack_require__(530); module.exports = function (x) { if (numberIsNan(x)) { @@ -4772,7 +4590,7 @@ const Parser = __webpack_require__(203) const fs = __webpack_require__(747) const fsm = __webpack_require__(827) const path = __webpack_require__(622) -const mkdir = __webpack_require__(491) +const mkdir = __webpack_require__(34) const mkdirSync = mkdir.sync const wc = __webpack_require__(478) @@ -5470,80 +5288,20 @@ module.exports.default = envPaths; /***/ }), /* 65 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -const eu = encodeURIComponent -const fetch = __webpack_require__(789) -const figgyPudding = __webpack_require__(122) -const getStream = __webpack_require__(145) -const validate = __webpack_require__(772) - -const OrgConfig = figgyPudding({ - Promise: { default: () => Promise } -}) - -// From https://github.com/npm/registry/blob/master/docs/orgs/memberships.md -const cmd = module.exports = {} - -class MembershipDetail {} -cmd.set = (org, user, role, opts) => { - if (typeof role === 'object' && !opts) { - opts = role - role = undefined - } - opts = OrgConfig(opts) - return new opts.Promise((resolve, reject) => { - validate('SSSO|SSZO', [org, user, role, opts]) - user = user.replace(/^@?/, '') - org = org.replace(/^@?/, '') - fetch.json(`/-/org/${eu(org)}/user`, opts.concat({ - method: 'PUT', - body: { user, role } - })).then(resolve, reject) - }).then(ret => Object.assign(new MembershipDetail(), ret)) -} - -cmd.rm = (org, user, opts) => { - opts = OrgConfig(opts) - return new opts.Promise((resolve, reject) => { - validate('SSO', [org, user, opts]) - user = user.replace(/^@?/, '') - org = org.replace(/^@?/, '') - fetch(`/-/org/${eu(org)}/user`, opts.concat({ - method: 'DELETE', - body: { user }, - ignoreBody: true - })).then(resolve, reject) - }).then(() => null) -} +/***/ (function(module) { -class Roster {} -cmd.ls = (org, opts) => { - opts = OrgConfig(opts) - return new opts.Promise((resolve, reject) => { - getStream.array(cmd.ls.stream(org, opts)).then(entries => { - const obj = {} - for (let [key, val] of entries) { - obj[key] = val - } - return obj - }).then(resolve, reject) - }).then(ret => Object.assign(new Roster(), ret)) -} +// Generated by CoffeeScript 1.12.7 +(function() { + module.exports = { + Disconnected: 1, + Preceding: 2, + Following: 4, + Contains: 8, + ContainedBy: 16, + ImplementationSpecific: 32 + }; -cmd.ls.stream = (org, opts) => { - opts = OrgConfig(opts) - validate('SO', [org, opts]) - org = org.replace(/^@?/, '') - return fetch.json.stream(`/-/org/${eu(org)}/user`, '*', opts.concat({ - mapJson (value, [key]) { - return [key, value] - } - })) -} +}).call(this); /***/ }), @@ -5896,83 +5654,41 @@ module.exports = Headers /***/ }), /* 69 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - +/***/ (function(module) { -const LRU = __webpack_require__(702) +// populates missing values +module.exports = function(dst, src) { -const MAX_SIZE = 50 * 1024 * 1024 // 50MB -const MAX_AGE = 3 * 60 * 1000 + Object.keys(src).forEach(function(prop) + { + dst[prop] = dst[prop] || src[prop]; + }); -let MEMOIZED = new LRU({ - max: MAX_SIZE, - maxAge: MAX_AGE, - length: (entry, key) => { - if (key.startsWith('key:')) { - return entry.data.length - } else if (key.startsWith('digest:')) { - return entry.length - } - } -}) + return dst; +}; -module.exports.clearMemoized = clearMemoized -function clearMemoized () { - const old = {} - MEMOIZED.forEach((v, k) => { - old[k] = v - }) - MEMOIZED.reset() - return old -} -module.exports.put = put -function put (cache, entry, data, opts) { - pickMem(opts).set(`key:${cache}:${entry.key}`, { entry, data }) - putDigest(cache, entry.integrity, data, opts) -} +/***/ }), +/* 70 */ +/***/ (function(__unusedmodule, exports) { -module.exports.put.byDigest = putDigest -function putDigest (cache, integrity, data, opts) { - pickMem(opts).set(`digest:${cache}:${integrity}`, data) -} +"use strict"; -module.exports.get = get -function get (cache, key, opts) { - return pickMem(opts).get(`key:${cache}:${key}`) -} +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=trace_state.js.map -module.exports.get.byDigest = getDigest -function getDigest (cache, integrity, opts) { - return pickMem(opts).get(`digest:${cache}:${integrity}`) -} +/***/ }), +/* 71 */ +/***/ (function() { -class ObjProxy { - constructor (obj) { - this.obj = obj - } - get (key) { return this.obj[key] } - set (key, val) { this.obj[key] = val } -} +"use strict"; -function pickMem (opts) { - if (!opts || !opts.memoize) { - return MEMOIZED - } else if (opts.memoize.get && opts.memoize.set) { - return opts.memoize - } else if (typeof opts.memoize === 'object') { - return new ObjProxy(opts.memoize) - } else { - return MEMOIZED - } +if (typeof Symbol === undefined || !Symbol.asyncIterator) { + Symbol.asyncIterator = Symbol.for("Symbol.asyncIterator"); } - +//# sourceMappingURL=index.js.map /***/ }), -/* 70 */, -/* 71 */, /* 72 */ /***/ (function(module) { @@ -5992,8 +5708,181 @@ module.exports.default = pTry; /* 73 */, /* 74 */, /* 75 */, -/* 76 */, -/* 77 */, +/* 76 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Buffer = __webpack_require__(254).Buffer; +var util = __webpack_require__(669); + +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; +}(); + +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; +} + +/***/ }), +/* 77 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ContextAPI = void 0; +var context_base_1 = __webpack_require__(459); +var global_utils_1 = __webpack_require__(976); +var NOOP_CONTEXT_MANAGER = new context_base_1.NoopContextManager(); +/** + * Singleton object which represents the entry point to the OpenTelemetry Context API + */ +var ContextAPI = /** @class */ (function () { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + function ContextAPI() { + } + /** Get the singleton instance of the Context API */ + ContextAPI.getInstance = function () { + if (!this._instance) { + this._instance = new ContextAPI(); + } + return this._instance; + }; + /** + * Set the current context manager. Returns the initialized context manager + */ + ContextAPI.prototype.setGlobalContextManager = function (contextManager) { + if (global_utils_1._global[global_utils_1.GLOBAL_CONTEXT_MANAGER_API_KEY]) { + // global context manager has already been set + return this._getContextManager(); + } + global_utils_1._global[global_utils_1.GLOBAL_CONTEXT_MANAGER_API_KEY] = global_utils_1.makeGetter(global_utils_1.API_BACKWARDS_COMPATIBILITY_VERSION, contextManager, NOOP_CONTEXT_MANAGER); + return contextManager; + }; + /** + * Get the currently active context + */ + ContextAPI.prototype.active = function () { + return this._getContextManager().active(); + }; + /** + * Execute a function with an active context + * + * @param context context to be active during function execution + * @param fn function to execute in a context + */ + ContextAPI.prototype.with = function (context, fn) { + return this._getContextManager().with(context, fn); + }; + /** + * Bind a context to a target function or event emitter + * + * @param target function or event emitter to bind + * @param context context to bind to the event emitter or function. Defaults to the currently active context + */ + ContextAPI.prototype.bind = function (target, context) { + if (context === void 0) { context = this.active(); } + return this._getContextManager().bind(target, context); + }; + ContextAPI.prototype._getContextManager = function () { + var _a, _b; + return ((_b = (_a = global_utils_1._global[global_utils_1.GLOBAL_CONTEXT_MANAGER_API_KEY]) === null || _a === void 0 ? void 0 : _a.call(global_utils_1._global, global_utils_1.API_BACKWARDS_COMPATIBILITY_VERSION)) !== null && _b !== void 0 ? _b : NOOP_CONTEXT_MANAGER); + }; + /** Disable and remove the global context manager */ + ContextAPI.prototype.disable = function () { + this._getContextManager().disable(); + delete global_utils_1._global[global_utils_1.GLOBAL_CONTEXT_MANAGER_API_KEY]; + }; + return ContextAPI; +}()); +exports.ContextAPI = ContextAPI; +//# sourceMappingURL=context.js.map + +/***/ }), /* 78 */, /* 79 */, /* 80 */ @@ -6042,7 +5931,31 @@ function parseJson (txt, reviver, context) { /***/ }), /* 81 */, -/* 82 */, +/* 82 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; + } + else if (typeof input === 'string' || input instanceof String) { + return input; + } + return JSON.stringify(input); +} +exports.toCommandValue = toCommandValue; +//# sourceMappingURL=utils.js.map + +/***/ }), /* 83 */, /* 84 */, /* 85 */ @@ -6055,7 +5968,121 @@ module.exports = __webpack_require__(260) /***/ }), -/* 86 */, +/* 86 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +var rng = __webpack_require__(139); +var bytesToUuid = __webpack_require__(105); + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +var _nodeId; +var _clockseq; + +// Previous uuid creation time +var _lastMSecs = 0; +var _lastNSecs = 0; + +// See https://github.com/uuidjs/uuid for API details +function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || []; + + options = options || {}; + var node = options.node || _nodeId; + var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; + + // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + if (node == null || clockseq == null) { + var seedBytes = rng(); + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [ + seedBytes[0] | 0x01, + seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5] + ]; + } + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } + + // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); + + // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; + + // Time since last uuid creation (in msecs) + var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; + + // Per 4.2.1.2, Bump clockseq on clock regression + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } + + // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } + + // Per 4.2.1.2 Throw error if too many uuids are requested + if (nsecs >= 10000) { + throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; + + // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + msecs += 12219292800000; + + // `time_low` + var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; + + // `time_mid` + var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; + + // `time_high_and_version` + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + b[i++] = tmh >>> 16 & 0xff; + + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + b[i++] = clockseq >>> 8 | 0x80; + + // `clock_seq_low` + b[i++] = clockseq & 0xff; + + // `node` + for (var n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf ? buf : bytesToUuid(b); +} + +module.exports = v1; + + +/***/ }), /* 87 */ /***/ (function(module) { @@ -6063,9 +6090,128 @@ module.exports = require("os"); /***/ }), /* 88 */, -/* 89 */, -/* 90 */, -/* 91 */, +/* 89 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +const pubsuffix = __webpack_require__(562); + +// Gives the permutation of all possible domainMatch()es of a given domain. The +// array is in shortest-to-longest order. Handy for indexing. +const SPECIAL_USE_DOMAINS = ["local"]; // RFC 6761 +function permuteDomain(domain, allowSpecialUseDomain) { + let pubSuf = null; + if (allowSpecialUseDomain) { + const domainParts = domain.split("."); + if (SPECIAL_USE_DOMAINS.includes(domainParts[domainParts.length - 1])) { + pubSuf = `${domainParts[domainParts.length - 2]}.${ + domainParts[domainParts.length - 1] + }`; + } else { + pubSuf = pubsuffix.getPublicSuffix(domain); + } + } else { + pubSuf = pubsuffix.getPublicSuffix(domain); + } + + if (!pubSuf) { + return null; + } + if (pubSuf == domain) { + return [domain]; + } + + const prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com" + const parts = prefix.split(".").reverse(); + let cur = pubSuf; + const permutations = [cur]; + while (parts.length) { + cur = `${parts.shift()}.${cur}`; + permutations.push(cur); + } + return permutations; +} + +exports.permuteDomain = permuteDomain; + + +/***/ }), +/* 90 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(__webpack_require__(241)); + +var _sha = _interopRequireDefault(__webpack_require__(616)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports.default = _default; + +/***/ }), +/* 91 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +var serialOrdered = __webpack_require__(892); + +// Public API +module.exports = serial; + +/** + * Runs iterator over provided array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serial(list, iterator, callback) +{ + return serialOrdered(list, iterator, null, callback); +} + + +/***/ }), /* 92 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -6190,7 +6336,7 @@ module.exports = { '949': 'cp949', 'cp949': { type: '_dbcs', - table: function() { return __webpack_require__(216) }, + table: function() { return __webpack_require__(488) }, }, 'cseuckr': 'cp949', @@ -6231,14 +6377,14 @@ module.exports = { '950': 'cp950', 'cp950': { type: '_dbcs', - table: function() { return __webpack_require__(393) }, + table: function() { return __webpack_require__(801) }, }, // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. 'big5': 'big5hkscs', 'big5hkscs': { type: '_dbcs', - table: function() { return __webpack_require__(393).concat(__webpack_require__(958)) }, + table: function() { return __webpack_require__(801).concat(__webpack_require__(958)) }, encodeSkipVals: [0xa2cc], }, @@ -6252,1183 +6398,1458 @@ module.exports = { /* 93 */ /***/ (function(module, __unusedexports, __webpack_require__) { -var Stream = __webpack_require__(794).Stream - -module.exports = legacy +module.exports = minimatch +minimatch.Minimatch = Minimatch -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } +var path = { sep: '/' } +try { + path = __webpack_require__(622) +} catch (er) {} - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = __webpack_require__(306) - Stream.call(this); +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} - var self = this; +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; +// * => any number of characters +var star = qmark + '*?' - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' - options = options || {}; +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') - if (this.encoding) this.setEncoding(this.encoding); +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } +// normalizes slashes. +var slashSplit = /\/+/ - if (this.start > this.end) { - throw new Error('start must be <= end'); - } +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} - this.pos = this.start; - } +function ext (a, b) { + a = a || {} + b = b || {} + var t = {} + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + return t +} - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } + var orig = minimatch - self.fd = fd; - self.emit('open', fd); - self._read(); - }) + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) } - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } - Stream.call(this); + return m +} - this.path = path; - this.fd = null; - this.writable = true; +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +} - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; +function minimatch (p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } - options = options || {}; + if (!options) options = {} - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } + // "" only matches "" + if (pattern.trim() === '') return p === '' - this.pos = this.start; - } + return new Minimatch(pattern, options).match(p) +} - this.busy = false; - this._queue = []; +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') } -} + if (!options) options = {} + pattern = pattern.trim() -/***/ }), -/* 94 */, -/* 95 */, -/* 96 */, -/* 97 */, -/* 98 */ -/***/ (function(module) { + // windows support: need to use /, not \ + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } -"use strict"; + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + // make the set of regexps etc. + this.make() +} -module.exports = stringifyPackage +Minimatch.prototype.debug = function () {} -const DEFAULT_INDENT = 2 -const CRLF = '\r\n' -const LF = '\n' +Minimatch.prototype.make = make +function make () { + // don't do it more than once. + if (this._made) return -function stringifyPackage (data, indent, newline) { - indent = indent || (indent === 0 ? 0 : DEFAULT_INDENT) - const json = JSON.stringify(data, null, indent) + var pattern = this.pattern + var options = this.options - if (newline === CRLF) { - return json.replace(/\n/g, CRLF) + CRLF + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return } - return json + LF -} + // step 1: figure out negation, etc. + this.parseNegate() + // step 2: expand braces + var set = this.globSet = this.braceExpand() -/***/ }), -/* 99 */, -/* 100 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + if (options.debug) this.debug = console.error -"use strict"; + this.debug(this.pattern, set) -// try to find the most reasonable prefix to use + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) -module.exports = findPrefix + this.debug(this.pattern, set) -const fs = __webpack_require__(747) -const path = __webpack_require__(622) + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) -function findPrefix (dir) { - return new Promise((resolve, reject) => { - dir = path.resolve(dir) + this.debug(this.pattern, set) - // this is a weird special case where an infinite recurse of - // node_modules folders resolves to the level that contains the - // very first node_modules folder - let walkedUp = false - while (path.basename(dir) === 'node_modules') { - dir = path.dirname(dir) - walkedUp = true - } - if (walkedUp) { - resolve(dir) - } else { - resolve(findPrefix_(dir)) - } + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 }) -} - -function findPrefix_ (dir, original) { - if (!original) original = dir - const parent = path.dirname(dir) - // this is a platform independent way of checking if we're in the root - // directory - if (parent === dir) return Promise.resolve(original) + this.debug(this.pattern, set) - return new Promise((resolve, reject) => { - fs.readdir(dir, (err, files) => { - if (err) { - // an error right away is a bad sign. - // unless the prefix was simply a non - // existent directory. - if (err && dir === original && err.code !== 'ENOENT') { - reject(err) - } else { - resolve(original) - } - } else if (files.indexOf('node_modules') !== -1 || - files.indexOf('package.json') !== -1) { - resolve(dir) - } else { - resolve(findPrefix_(parent, original)) - } - }) - }) + this.set = set } +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 -/***/ }), -/* 101 */, -/* 102 */, -/* 103 */, -/* 104 */, -/* 105 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -var __awaiter = (this && this.__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 }); -const httpm = __webpack_require__(874); -const util = __webpack_require__(729); -class RestClient { - /** - * Creates an instance of the RestClient - * @constructor - * @param {string} userAgent - userAgent for requests - * @param {string} baseUrl - (Optional) If not specified, use full urls per request. If supplied and a function passes a relative url, it will be appended to this - * @param {ifm.IRequestHandler[]} handlers - handlers are typically auth handlers (basic, bearer, ntlm supplied) - * @param {ifm.IRequestOptions} requestOptions - options for each http requests (http proxy setting, socket timeout) - */ - constructor(userAgent, baseUrl, handlers, requestOptions) { - this.client = new httpm.HttpClient(userAgent, handlers, requestOptions); - if (baseUrl) { - this._baseUrl = baseUrl; - } - } - /** - * Gets a resource from an endpoint - * Be aware that not found returns a null. Other error conditions reject the promise - * @param {string} requestUrl - fully qualified or relative url - * @param {IRequestOptions} requestOptions - (optional) requestOptions object - */ - options(requestUrl, options) { - return __awaiter(this, void 0, void 0, function* () { - let url = util.getUrl(requestUrl, this._baseUrl); - let res = yield this.client.options(url, this._headersFromOptions(options)); - return this.processResponse(res, options); - }); - } - /** - * Gets a resource from an endpoint - * Be aware that not found returns a null. Other error conditions reject the promise - * @param {string} resource - fully qualified url or relative path - * @param {IRequestOptions} requestOptions - (optional) requestOptions object - */ - get(resource, options) { - return __awaiter(this, void 0, void 0, function* () { - let url = util.getUrl(resource, this._baseUrl, (options || {}).queryParameters); - let res = yield this.client.get(url, this._headersFromOptions(options)); - return this.processResponse(res, options); - }); - } - /** - * Deletes a resource from an endpoint - * Be aware that not found returns a null. Other error conditions reject the promise - * @param {string} resource - fully qualified or relative url - * @param {IRequestOptions} requestOptions - (optional) requestOptions object - */ - del(resource, options) { - return __awaiter(this, void 0, void 0, function* () { - let url = util.getUrl(resource, this._baseUrl); - let res = yield this.client.del(url, this._headersFromOptions(options)); - return this.processResponse(res, options); - }); - } - /** - * Creates resource(s) from an endpoint - * T type of object returned. - * Be aware that not found returns a null. Other error conditions reject the promise - * @param {string} resource - fully qualified or relative url - * @param {IRequestOptions} requestOptions - (optional) requestOptions object - */ - create(resource, resources, options) { - return __awaiter(this, void 0, void 0, function* () { - let url = util.getUrl(resource, this._baseUrl); - let headers = this._headersFromOptions(options, true); - let data = JSON.stringify(resources, null, 2); - let res = yield this.client.post(url, data, headers); - return this.processResponse(res, options); - }); - } - /** - * Updates resource(s) from an endpoint - * T type of object returned. - * Be aware that not found returns a null. Other error conditions reject the promise - * @param {string} resource - fully qualified or relative url - * @param {IRequestOptions} requestOptions - (optional) requestOptions object - */ - update(resource, resources, options) { - return __awaiter(this, void 0, void 0, function* () { - let url = util.getUrl(resource, this._baseUrl); - let headers = this._headersFromOptions(options, true); - let data = JSON.stringify(resources, null, 2); - let res = yield this.client.patch(url, data, headers); - return this.processResponse(res, options); - }); - } - /** - * Replaces resource(s) from an endpoint - * T type of object returned. - * Be aware that not found returns a null. Other error conditions reject the promise - * @param {string} resource - fully qualified or relative url - * @param {IRequestOptions} requestOptions - (optional) requestOptions object - */ - replace(resource, resources, options) { - return __awaiter(this, void 0, void 0, function* () { - let url = util.getUrl(resource, this._baseUrl); - let headers = this._headersFromOptions(options, true); - let data = JSON.stringify(resources, null, 2); - let res = yield this.client.put(url, data, headers); - return this.processResponse(res, options); - }); - } - uploadStream(verb, requestUrl, stream, options) { - return __awaiter(this, void 0, void 0, function* () { - let url = util.getUrl(requestUrl, this._baseUrl); - let headers = this._headersFromOptions(options, true); - let res = yield this.client.sendStream(verb, url, stream, headers); - return this.processResponse(res, options); - }); - } - _headersFromOptions(options, contentType) { - options = options || {}; - let headers = options.additionalHeaders || {}; - headers["Accept"] = options.acceptHeader || "application/json"; - if (contentType) { - let found = false; - for (let header in headers) { - if (header.toLowerCase() == "content-type") { - found = true; - } - } - if (!found) { - headers["Content-Type"] = 'application/json; charset=utf-8'; - } - } - return headers; - } - static dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - let a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - processResponse(res, options) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - const statusCode = res.message.statusCode; - const response = { - statusCode: statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode == httpm.HttpCodes.NotFound) { - resolve(response); - } - let obj; - let contents; - // get the result from the body - try { - contents = yield res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, RestClient.dateTimeDeserializer); - } - else { - obj = JSON.parse(contents); - } - if (options && options.responseProcessor) { - response.result = options.responseProcessor(obj); - } - else { - response.result = obj; - } - } - response.headers = res.message.headers; - } - catch (err) { - // Invalid resource (contents not json); leaving result obj null - } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; - } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; - } - else { - msg = "Failed request: (" + statusCode + ")"; - } - let err = new Error(msg); - // attach statusCode and body obj (if available) to the error object - err['statusCode'] = statusCode; - if (response.result) { - err['result'] = response.result; - } - reject(err); - } - else { - resolve(response); - } - })); - }); - } -} -exports.RestClient = RestClient; - - -/***/ }), -/* 106 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -var path = __webpack_require__(622) + if (options.nonegate) return -var uniqueSlug = __webpack_require__(336) + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } -module.exports = function (filepath, prefix, uniq) { - return path.join(filepath, (prefix ? prefix + '-' : '') + uniqueSlug(uniq)) + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate } +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} -/***/ }), -/* 107 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var assert = __webpack_require__(357) -var dirname = __webpack_require__(622).dirname -var resolve = __webpack_require__(622).resolve -var isInside = __webpack_require__(994) - -var rimraf = __webpack_require__(376) -var lstat = __webpack_require__(598).lstat -var readdir = __webpack_require__(598).readdir -var rmdir = __webpack_require__(598).rmdir -var unlink = __webpack_require__(598).unlink - -module.exports = vacuum +Minimatch.prototype.braceExpand = braceExpand -function vacuum (leaf, options, cb) { - assert(typeof leaf === 'string', 'must pass in path to remove') - assert(typeof cb === 'function', 'must pass in callback') +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } - if (!options) options = {} - assert(typeof options === 'object', 'options must be an object') + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern - var log = options.log ? options.log : function () {} + if (typeof pattern === 'undefined') { + throw new TypeError('undefined pattern') + } - leaf = leaf && resolve(leaf) - var base = options.base && resolve(options.base) - if (base && !isInside(leaf, base)) { - return cb(new Error(leaf + ' is not a child of ' + base)) + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] } - lstat(leaf, function (error, stat) { - if (error) { - if (error.code === 'ENOENT') return cb(null) + return expand(pattern) +} - log(error.stack) - return cb(error) - } +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + if (pattern.length > 1024 * 64) { + throw new TypeError('pattern is too long') + } - if (!(stat && (stat.isDirectory() || stat.isSymbolicLink() || stat.isFile()))) { - log(leaf, 'is not a directory, file, or link') - return cb(new Error(leaf + ' is not a directory, file, or link')) - } + var options = this.options - if (options.purge) { - log('purging', leaf) - rimraf(leaf, function (error) { - if (error) return cb(error) + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' - next(dirname(leaf)) - }) - } else if (!stat.isDirectory()) { - log('removing', leaf) - unlink(leaf, function (error) { - if (error) return cb(error) + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this - next(dirname(leaf)) - }) - } else { - next(leaf) + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false } - }) + } - function next (branch) { - branch = branch && resolve(branch) - // either we've reached the base or we've reached the root - if ((base && branch === base) || branch === dirname(branch)) { - log('finished vacuuming up to', branch) - return cb(null) + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue } - readdir(branch, function (error, files) { - if (error) { - if (error.code === 'ENOENT') return cb(null) + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false - log('unable to check directory', branch, 'due to', error.message) - return cb(error) - } + case '\\': + clearStateChar() + escaping = true + continue - if (files.length > 0) { - log('quitting because other entries in', branch) - return cb(null) - } + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) - if (branch === process.env.HOME) { - log('quitting because cannot remove home directory', branch) - return cb(null) - } + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } - log('removing', branch) - lstat(branch, function (error, stat) { - if (error) { - if (error.code === 'ENOENT') return cb(null) + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue - log('unable to lstat', branch, 'due to', error.message) - return cb(error) + case '(': + if (inClass) { + re += '(' + continue } - var remove = stat.isDirectory() ? rmdir : unlink - remove(branch, function (error) { - if (error) { - if (error.code === 'ENOENT') { - log('quitting because lost the race to remove', branch) - return cb(null) - } - if (error.code === 'ENOTEMPTY' || error.code === 'EEXIST') { - log('quitting because new (racy) entries in', branch) - return cb(null) - } - - log('unable to remove', branch, 'due to', error.message) - return cb(error) - } + if (!stateChar) { + re += '\\(' + continue + } - next(dirname(branch)) + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close }) - }) - }) - } -} - + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue -/***/ }), -/* 108 */, -/* 109 */, -/* 110 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } -"use strict"; + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } -// Do a two-pass walk, first to get the list of packages that need to be -// bundled, then again to get the actual files and folders. -// Keep a cache of node_modules content and package.json data, so that the -// second walk doesn't have to re-do all the same work. + clearStateChar() + re += '|' + continue -const bundleWalk = __webpack_require__(650) -const BundleWalker = bundleWalk.BundleWalker -const BundleWalkerSync = bundleWalk.BundleWalkerSync + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() -const ignoreWalk = __webpack_require__(656) -const IgnoreWalker = ignoreWalk.Walker -const IgnoreWalkerSync = ignoreWalk.WalkerSync + if (inClass) { + re += '\\' + c + continue + } -const rootBuiltinRules = Symbol('root-builtin-rules') -const packageNecessaryRules = Symbol('package-necessary-rules') -const path = __webpack_require__(622) + inClass = true + classStart = i + reClassStart = re.length + re += c + continue -const normalizePackageBin = __webpack_require__(787) + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } -const defaultRules = [ - '.npmignore', - '.gitignore', - '**/.git', - '**/.svn', - '**/.hg', - '**/CVS', - '**/.git/**', - '**/.svn/**', - '**/.hg/**', - '**/CVS/**', - '/.lock-wscript', - '/.wafpickle-*', - '/build/config.gypi', - 'npm-debug.log', - '**/.npmrc', - '.*.swp', - '.DS_Store', - '**/.DS_Store/**', - '._*', - '**/._*/**', - '*.orig', - '/package-lock.json', - '/yarn.lock', - 'archived-packages/**', - 'core', - '!core/', - '!**/core/', - '*.core', - '*.vgcore', - 'vgcore.*', - 'core.+([0-9])', -] + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + } -// There may be others, but :?|<> are handled by node-tar -const nameIsBadForWindows = file => /\*/.test(file) + // finish up the class. + hasMagic = true + inClass = false + re += c + continue -// a decorator that applies our custom rules to an ignore walker -const npmWalker = Class => class Walker extends Class { - constructor (opt) { - opt = opt || {} + default: + // swallow any state char that wasn't consumed + clearStateChar() - // the order in which rules are applied. - opt.ignoreFiles = [ - rootBuiltinRules, - 'package.json', - '.npmignore', - '.gitignore', - packageNecessaryRules - ] + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } - opt.includeEmpty = false - opt.path = opt.path || process.cwd() - const dirName = path.basename(opt.path) - const parentName = path.basename(path.dirname(opt.path)) - opt.follow = - dirName === 'node_modules' || - (parentName === 'node_modules' && /^@/.test(dirName)) - super(opt) + re += c - // ignore a bunch of things by default at the root level. - // also ignore anything in node_modules, except bundled dependencies - if (!this.parent) { - this.bundled = opt.bundled || [] - this.bundledScopes = Array.from(new Set( - this.bundled.filter(f => /^@/.test(f)) - .map(f => f.split('/')[0]))) - const rules = defaultRules.join('\n') + '\n' - this.packageJsonCache = opt.packageJsonCache || new Map() - super.onReadIgnoreFile(rootBuiltinRules, rules, _=>_) - } else { - this.bundled = [] - this.bundledScopes = [] - this.packageJsonCache = this.parent.packageJsonCache - } - } + } // switch + } // for - onReaddir (entries) { - if (!this.parent) { - entries = entries.filter(e => - e !== '.git' && - !(e === 'node_modules' && this.bundled.length === 0) - ) - } - return super.onReaddir(entries) + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] } - filterEntry (entry, partial) { - // get the partial path from the root of the walk - const p = this.path.substr(this.root.length + 1) - const pkgre = /^node_modules\/(@[^\/]+\/?[^\/]+|[^\/]+)(\/.*)?$/ - const isRoot = !this.parent - const pkg = isRoot && pkgre.test(entry) ? - entry.replace(pkgre, '$1') : null - const rootNM = isRoot && entry === 'node_modules' - const rootPJ = isRoot && entry === 'package.json' - - return ( - // if we're in a bundled package, check with the parent. - /^node_modules($|\/)/i.test(p) ? this.parent.filterEntry( - this.basename + '/' + entry, partial) + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } - // if package is bundled, all files included - // also include @scope dirs for bundled scoped deps - // they'll be ignored if no files end up in them. - // However, this only matters if we're in the root. - // node_modules folders elsewhere, like lib/node_modules, - // should be included normally unless ignored. - : pkg ? -1 !== this.bundled.indexOf(pkg) || - -1 !== this.bundledScopes.indexOf(pkg) + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) - // only walk top node_modules if we want to bundle something - : rootNM ? !!this.bundled.length + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type - // always include package.json at the root. - : rootPJ ? true + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } - // otherwise, follow ignore-walk's logic - : super.filterEntry(entry, partial) - ) + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' } - filterEntries () { - if (this.ignoreRules['package.json']) - this.ignoreRules['.gitignore'] = this.ignoreRules['.npmignore'] = null - else if (this.ignoreRules['.npmignore']) - this.ignoreRules['.gitignore'] = null - this.filterEntries = super.filterEntries - super.filterEntries() + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true } - addIgnoreFile (file, then) { - const ig = path.resolve(this.path, file) - if (this.packageJsonCache.has(ig)) - this.onPackageJson(ig, this.packageJsonCache.get(ig), then) - else - super.addIgnoreFile(file, then) - } + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] - onPackageJson (ig, pkg, then) { - this.packageJsonCache.set(ig, pkg) + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) - // if there's a bin, browser or main, make sure we don't ignore it - // also, don't ignore the package.json itself! - // - // Weird side-effect of this: a readme (etc) file will be included - // if it exists anywhere within a folder with a package.json file. - // The original intent was only to include these files in the root, - // but now users in the wild are dependent on that behavior for - // localized documentation and other use cases. Adding a `/` to - // these rules, while tempting and arguably more "correct", is a - // breaking change. - const rules = [ - pkg.browser ? '!' + pkg.browser : '', - pkg.main ? '!' + pkg.main : '', - '!package.json', - '!npm-shrinkwrap.json', - '!@(readme|copying|license|licence|notice|changes|changelog|history){,.*[^~$]}' - ] - if (pkg.bin) { - // always an object, because normalized already - for (const key in pkg.bin) - rules.push('!' + pkg.bin[key]) + nlLast += nlAfter + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') } + nlAfter = cleanAfter - const data = rules.filter(f => f).join('\n') + '\n' - super.onReadIgnoreFile(packageNecessaryRules, data, _=>_) + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe + } - if (Array.isArray(pkg.files)) - super.onReadIgnoreFile('package.json', '*\n' + pkg.files.map( - f => '!' + f + '\n!' + f.replace(/\/+$/, '') + '/**' - ).join('\n') + '\n', then) - else - then() + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re } - // override parent stat function to completely skip any filenames - // that will break windows entirely. - // XXX(isaacs) Next major version should make this an error instead. - stat (entry, file, dir, then) { - if (nameIsBadForWindows(entry)) - then() - else - super.stat(entry, file, dir, then) + if (addPatternStart) { + re = patternStart + re } - // override parent onstat function to nix all symlinks - onstat (st, entry, file, dir, then) { - if (st.isSymbolicLink()) - then() - else - super.onstat(st, entry, file, dir, then) + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] } - onReadIgnoreFile (file, data, then) { - if (file === 'package.json') - try { - const ig = path.resolve(this.path, file) - this.onPackageJson(ig, normalizePackageBin(JSON.parse(data)), then) - } catch (er) { - // ignore package.json files that are not json - then() - } - else - super.onReadIgnoreFile(file, data, then) + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) } - sort (a, b) { - return sort(a, b) + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') } + + regExp._glob = pattern + regExp._src = re + + return regExp } -class Walker extends npmWalker(IgnoreWalker) { - walker (entry, then) { - new Walker(this.walkerOpt(entry)).on('done', then).start() - } +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() } -class WalkerSync extends npmWalker(IgnoreWalkerSync) { - walker (entry, then) { - new WalkerSync(this.walkerOpt(entry)).start() - then() +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) { + this.regexp = false } + return this.regexp } -const walk = (options, callback) => { +minimatch.match = function (list, pattern, options) { options = options || {} - const p = new Promise((resolve, reject) => { - const bw = new BundleWalker(options) - bw.on('done', bundled => { - options.bundled = bundled - options.packageJsonCache = bw.packageJsonCache - new Walker(options).on('done', resolve).on('error', reject).start() - }) - bw.start() + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) }) - return callback ? p.then(res => callback(null, res), callback) : p + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list } -const walkSync = options => { - options = options || {} - const bw = new BundleWalkerSync(options).start() - options.bundled = bw.result - options.packageJsonCache = bw.packageJsonCache - const walker = new WalkerSync(options) - walker.start() - return walker.result -} +Minimatch.prototype.match = match +function match (f, partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' -// optimize for compressibility -// extname, then basename, then locale alphabetically -// https://twitter.com/isntitvacant/status/1131094910923231232 -const sort = (a, b) => { - const exta = path.extname(a).toLowerCase() - const extb = path.extname(b).toLowerCase() - const basea = path.basename(a).toLowerCase() - const baseb = path.basename(b).toLowerCase() + if (f === '/' && partial) return true - return exta.localeCompare(extb) || - basea.localeCompare(baseb) || - a.localeCompare(b) -} + var options = this.options + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } -module.exports = walk -walk.sync = walkSync -walk.Walker = Walker -walk.WalkerSync = WalkerSync + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. -/***/ }), -/* 111 */ -/***/ (function(module) { + var set = this.set + this.debug(this.pattern, 'set', set) -module.exports = bindActor -function bindActor () { - var args = - Array.prototype.slice.call - (arguments) // jswtf. - , obj = null - , fn - if (typeof args[0] === "object") { - obj = args.shift() - fn = args.shift() - if (typeof fn === "string") - fn = obj[ fn ] - } else fn = args.shift() - return function (cb) { - fn.apply(obj, args.concat(cb)) } -} + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } -/***/ }), -/* 112 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} -"use strict"; +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) -module.exports = __webpack_require__(146); -module.exports.HttpsAgent = __webpack_require__(601); + this.debug('matchOne', file.length, pattern.length) + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] -/***/ }), -/* 113 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + this.debug(pattern, p, f) -"use strict"; + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) -module.exports = __webpack_require__(964) + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] -/***/ }), -/* 114 */ -/***/ (function(__unusedmodule, __unusedexports, __webpack_require__) { + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) -"use strict"; + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } -const url = __webpack_require__(835); -const https = __webpack_require__(211); + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } -/** - * This currently needs to be applied to all Node.js versions - * in order to determine if the `req` is an HTTP or HTTPS request. - * - * There is currently no PR attempting to move this property upstream. - */ -https.request = (function(request) { - return function(_options, cb) { - let options; - if (typeof _options === 'string') { - options = url.parse(_options); - } else { - options = Object.assign({}, _options); + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false } - if (null == options.port) { - options.port = 443; + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) } - options.secureEndpoint = true; - return request.call(https, options, cb); - }; -})(https.request); -/** - * This is needed for Node.js >= 9.0.0 to make sure `https.get()` uses the - * patched `https.request()`. - * - * Ref: https://github.com/nodejs/node/commit/5118f31 - */ -https.get = function(options, cb) { - const req = https.request(options, cb); - req.end(); - return req; -}; + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') + return emptyFileEnd + } + + // should be unreachable. + throw new Error('wtf?') +} + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} /***/ }), -/* 115 */, -/* 116 */ +/* 94 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +var path = __webpack_require__(622) -const figgyPudding = __webpack_require__(122) -const getStream = __webpack_require__(145) -const npa = __webpack_require__(482) -const npmFetch = __webpack_require__(789) -const {PassThrough} = __webpack_require__(794) -const validate = __webpack_require__(772) +var uniqueSlug = __webpack_require__(336) -const AccessConfig = figgyPudding({ - Promise: {default: () => Promise} -}) +module.exports = function (filepath, prefix, uniq) { + return path.join(filepath, (prefix ? prefix + '-' : '') + uniqueSlug(uniq)) +} -const eu = encodeURIComponent -const npar = spec => { - spec = npa(spec) - if (!spec.registry) { - throw new Error('`spec` must be a registry spec') + +/***/ }), +/* 95 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=link.js.map + +/***/ }), +/* 96 */, +/* 97 */, +/* 98 */ +/***/ (function(module) { + +"use strict"; + + +module.exports = stringifyPackage + +const DEFAULT_INDENT = 2 +const CRLF = '\r\n' +const LF = '\n' + +function stringifyPackage (data, indent, newline) { + indent = indent || (indent === 0 ? 0 : DEFAULT_INDENT) + const json = JSON.stringify(data, null, indent) + + if (newline === CRLF) { + return json.replace(/\n/g, CRLF) + CRLF } - return spec + + return json + LF } -const cmd = module.exports = {} -cmd.public = (spec, opts) => setAccess(spec, 'public', opts) -cmd.restricted = (spec, opts) => setAccess(spec, 'restricted', opts) -function setAccess (spec, access, opts) { - opts = AccessConfig(opts) - return pwrap(opts, () => { - spec = npar(spec) - validate('OSO', [spec, access, opts]) - const uri = `/-/package/${eu(spec.name)}/access` - return npmFetch(uri, opts.concat({ - method: 'POST', - body: {access}, - spec - })) - }).then(res => res.body.resume() && true) -} +/***/ }), +/* 99 */, +/* 100 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -cmd.grant = (spec, entity, permissions, opts) => { - opts = AccessConfig(opts) - return pwrap(opts, () => { - spec = npar(spec) - const {scope, team} = splitEntity(entity) - validate('OSSSO', [spec, scope, team, permissions, opts]) - if (permissions !== 'read-write' && permissions !== 'read-only') { - throw new Error('`permissions` must be `read-write` or `read-only`. Got `' + permissions + '` instead') - } - const uri = `/-/team/${eu(scope)}/${eu(team)}/package` - return npmFetch(uri, opts.concat({ - method: 'PUT', - body: {package: spec.name, permissions}, - scope, - spec, - ignoreBody: true - })) - }).then(() => true) -} +"use strict"; -cmd.revoke = (spec, entity, opts) => { - opts = AccessConfig(opts) - return pwrap(opts, () => { - spec = npar(spec) - const {scope, team} = splitEntity(entity) - validate('OSSO', [spec, scope, team, opts]) - const uri = `/-/team/${eu(scope)}/${eu(team)}/package` - return npmFetch(uri, opts.concat({ - method: 'DELETE', - body: {package: spec.name}, - scope, - spec, - ignoreBody: true - })) - }).then(() => true) -} +// try to find the most reasonable prefix to use -cmd.lsPackages = (entity, opts) => { - opts = AccessConfig(opts) - return pwrap(opts, () => { - return getStream.array( - cmd.lsPackages.stream(entity, opts) - ).then(data => data.reduce((acc, [key, val]) => { - if (!acc) { - acc = {} - } - acc[key] = val - return acc - }, null)) - }) -} +module.exports = findPrefix -cmd.lsPackages.stream = (entity, opts) => { - validate('SO|SZ', [entity, opts]) - opts = AccessConfig(opts) - const {scope, team} = splitEntity(entity) - let uri - if (team) { - uri = `/-/team/${eu(scope)}/${eu(team)}/package` - } else { - uri = `/-/org/${eu(scope)}/package` - } - opts = opts.concat({ - query: {format: 'cli'}, - mapJson (value, [key]) { - if (value === 'read') { - return [key, 'read-only'] - } else if (value === 'write') { - return [key, 'read-write'] - } else { - return [key, value] - } +const fs = __webpack_require__(747) +const path = __webpack_require__(622) + +function findPrefix (dir) { + return new Promise((resolve, reject) => { + dir = path.resolve(dir) + + // this is a weird special case where an infinite recurse of + // node_modules folders resolves to the level that contains the + // very first node_modules folder + let walkedUp = false + while (path.basename(dir) === 'node_modules') { + dir = path.dirname(dir) + walkedUp = true } - }) - const ret = new PassThrough({objectMode: true}) - npmFetch.json.stream(uri, '*', opts).on('error', err => { - if (err.code === 'E404' && !team) { - uri = `/-/user/${eu(scope)}/package` - npmFetch.json.stream(uri, '*', opts).on( - 'error', err => ret.emit('error', err) - ).pipe(ret) + if (walkedUp) { + resolve(dir) } else { - ret.emit('error', err) + resolve(findPrefix_(dir)) } - }).pipe(ret) - return ret + }) } -cmd.lsCollaborators = (spec, user, opts) => { - if (typeof user === 'object' && !opts) { - opts = user - user = undefined - } - opts = AccessConfig(opts) - return pwrap(opts, () => { - return getStream.array( - cmd.lsCollaborators.stream(spec, user, opts) - ).then(data => data.reduce((acc, [key, val]) => { - if (!acc) { - acc = {} +function findPrefix_ (dir, original) { + if (!original) original = dir + + const parent = path.dirname(dir) + // this is a platform independent way of checking if we're in the root + // directory + if (parent === dir) return Promise.resolve(original) + + return new Promise((resolve, reject) => { + fs.readdir(dir, (err, files) => { + if (err) { + // an error right away is a bad sign. + // unless the prefix was simply a non + // existent directory. + if (err && dir === original && err.code !== 'ENOENT') { + reject(err) + } else { + resolve(original) + } + } else if (files.indexOf('node_modules') !== -1 || + files.indexOf('package.json') !== -1) { + resolve(dir) + } else { + resolve(findPrefix_(parent, original)) } - acc[key] = val - return acc - }, null)) + }) }) } -cmd.lsCollaborators.stream = (spec, user, opts) => { - if (typeof user === 'object' && !opts) { - opts = user - user = undefined - } - opts = AccessConfig(opts) - spec = npar(spec) - validate('OSO|OZO', [spec, user, opts]) - const uri = `/-/package/${eu(spec.name)}/collaborators` - return npmFetch.json.stream(uri, '*', opts.concat({ - query: {format: 'cli', user: user || undefined}, - mapJson (value, [key]) { - if (value === 'read') { - return [key, 'read-only'] - } else if (value === 'write') { - return [key, 'read-write'] - } else { - return [key, value] - } + +/***/ }), +/* 101 */, +/* 102 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +// For internal use, subject to change. +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +const fs = __importStar(__webpack_require__(747)); +const os = __importStar(__webpack_require__(87)); +const utils_1 = __webpack_require__(82); +function issueCommand(command, message) { + const filePath = process.env[`GITHUB_${command}`]; + if (!filePath) { + throw new Error(`Unable to find environment variable for file command ${command}`); } - })) + if (!fs.existsSync(filePath)) { + throw new Error(`Missing file at path: ${filePath}`); + } + fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { + encoding: 'utf8' + }); } +exports.issueCommand = issueCommand; +//# sourceMappingURL=file-command.js.map -cmd.tfaRequired = (spec, opts) => setRequires2fa(spec, true, opts) -cmd.tfaNotRequired = (spec, opts) => setRequires2fa(spec, false, opts) -function setRequires2fa (spec, required, opts) { - opts = AccessConfig(opts) - return new opts.Promise((resolve, reject) => { - spec = npar(spec) - validate('OBO', [spec, required, opts]) - const uri = `/-/package/${eu(spec.name)}/access` - return npmFetch(uri, opts.concat({ - method: 'POST', - body: {publish_requires_tfa: required}, - spec, - ignoreBody: true - })).then(resolve, reject) - }).then(() => true) -} +/***/ }), +/* 103 */, +/* 104 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -cmd.edit = () => { - throw new Error('Not implemented yet') +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(__webpack_require__(676)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.substr(14, 1), 16); } -function splitEntity (entity = '') { - let [, scope, team] = entity.match(/^@?([^:]+)(?::(.*))?$/) || [] - return {scope, team} +var _default = version; +exports.default = _default; + +/***/ }), +/* 105 */ +/***/ (function(module) { + +/** + * 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[i] = (i + 0x100).toString(16).substr(1); } -function pwrap (opts, fn) { - return new opts.Promise((resolve, reject) => { - fn().then(resolve, reject) - }) +function bytesToUuid(buf, offset) { + var i = offset || 0; + var bth = byteToHex; + // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 + return ([ + bth[buf[i++]], bth[buf[i++]], + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], + bth[buf[i++]], bth[buf[i++]], + bth[buf[i++]], bth[buf[i++]] + ]).join(''); } +module.exports = bytesToUuid; + /***/ }), -/* 117 */ +/* 106 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { +"use strict"; + + +Object.defineProperty(exports, '__esModule', { value: true }); + +var tslib = __webpack_require__(422); + +var listenersMap = new WeakMap(); +var abortedMap = new WeakMap(); +/** + * An aborter instance implements AbortSignal interface, can abort HTTP requests. + * + * - Call AbortSignal.none to create a new AbortSignal instance that cannot be cancelled. + * Use `AbortSignal.none` when you are required to pass a cancellation token but the operation + * cannot or will not ever be cancelled. + * + * @example + * // Abort without timeout + * await doAsyncWork(AbortSignal.none); + * + * @export + * @class AbortSignal + * @implements {AbortSignalLike} + */ +var AbortSignal = /** @class */ (function () { + function AbortSignal() { + /** + * onabort event listener. + * + * @memberof AbortSignal + */ + this.onabort = null; + listenersMap.set(this, []); + abortedMap.set(this, false); + } + Object.defineProperty(AbortSignal.prototype, "aborted", { + /** + * Status of whether aborted or not. + * + * @readonly + * @type {boolean} + * @memberof AbortSignal + */ + get: function () { + if (!abortedMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); + } + return abortedMap.get(this); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbortSignal, "none", { + /** + * Creates a new AbortSignal instance that will never be aborted. + * + * @readonly + * @static + * @type {AbortSignal} + * @memberof AbortSignal + */ + get: function () { + return new AbortSignal(); + }, + enumerable: true, + configurable: true + }); + /** + * Added new "abort" event listener, only support "abort" event. + * + * @param {"abort"} _type Only support "abort" event + * @param {(this: AbortSignalLike, ev: any) => any} listener + * @memberof AbortSignal + */ + AbortSignal.prototype.addEventListener = function ( + // tslint:disable-next-line:variable-name + _type, listener) { + if (!listenersMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); + } + var listeners = listenersMap.get(this); + listeners.push(listener); + }; + /** + * Remove "abort" event listener, only support "abort" event. + * + * @param {"abort"} _type Only support "abort" event + * @param {(this: AbortSignalLike, ev: any) => any} listener + * @memberof AbortSignal + */ + AbortSignal.prototype.removeEventListener = function ( + // tslint:disable-next-line:variable-name + _type, listener) { + if (!listenersMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); + } + var listeners = listenersMap.get(this); + var index = listeners.indexOf(listener); + if (index > -1) { + listeners.splice(index, 1); + } + }; + /** + * Dispatches a synthetic event to the AbortSignal. + */ + AbortSignal.prototype.dispatchEvent = function (_event) { + throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes."); + }; + return AbortSignal; +}()); +/** + * Helper to trigger an abort event immediately, the onabort and all abort event listeners will be triggered. + * Will try to trigger abort event for all linked AbortSignal nodes. + * + * - If there is a timeout, the timer will be cancelled. + * - If aborted is true, nothing will happen. + * + * @returns + * @internal + */ +function abortSignal(signal) { + if (signal.aborted) { + return; + } + if (signal.onabort) { + signal.onabort.call(signal); + } + var listeners = listenersMap.get(signal); + if (listeners) { + listeners.forEach(function (listener) { + listener.call(signal, { type: "abort" }); + }); + } + abortedMap.set(signal, true); +} + +/** + * This error is thrown when an asynchronous operation has been aborted. + * Check for this error by testing the `name` that the name property of the + * error matches `"AbortError"`. + * + * @example + * const controller = new AbortController(); + * controller.abort(); + * try { + * doAsyncWork(controller.signal) + * } catch (e) { + * if (e.name === 'AbortError') { + * // handle abort error here. + * } + * } + */ +var AbortError = /** @class */ (function (_super) { + tslib.__extends(AbortError, _super); + function AbortError(message) { + var _this = _super.call(this, message) || this; + _this.name = "AbortError"; + return _this; + } + return AbortError; +}(Error)); +/** + * An AbortController provides an AbortSignal and the associated controls to signal + * that an asynchronous operation should be aborted. + * + * @example + * // Abort an operation when another event fires + * const controller = new AbortController(); + * const signal = controller.signal; + * doAsyncWork(signal); + * button.addEventListener('click', () => controller.abort()); + * + * @example + * // Share aborter cross multiple operations in 30s + * // Upload the same data to 2 different data centers at the same time, + * // abort another when any of them is finished + * const controller = AbortController.withTimeout(30 * 1000); + * doAsyncWork(controller.signal).then(controller.abort); + * doAsyncWork(controller.signal).then(controller.abort); + * + * @example + * // Cascaded aborting + * // All operations can't take more than 30 seconds + * const aborter = Aborter.timeout(30 * 1000); + * + * // Following 2 operations can't take more than 25 seconds + * await doAsyncWork(aborter.withTimeout(25 * 1000)); + * await doAsyncWork(aborter.withTimeout(25 * 1000)); + * + * @export + * @class AbortController + * @implements {AbortSignalLike} + */ +var AbortController = /** @class */ (function () { + function AbortController(parentSignals) { + var _this = this; + this._signal = new AbortSignal(); + if (!parentSignals) { + return; + } + // coerce parentSignals into an array + if (!Array.isArray(parentSignals)) { + parentSignals = arguments; + } + for (var _i = 0, parentSignals_1 = parentSignals; _i < parentSignals_1.length; _i++) { + var parentSignal = parentSignals_1[_i]; + // if the parent signal has already had abort() called, + // then call abort on this signal as well. + if (parentSignal.aborted) { + this.abort(); + } + else { + // when the parent signal aborts, this signal should as well. + parentSignal.addEventListener("abort", function () { + _this.abort(); + }); + } + } + } + Object.defineProperty(AbortController.prototype, "signal", { + /** + * The AbortSignal associated with this controller that will signal aborted + * when the abort method is called on this controller. + * + * @readonly + * @type {AbortSignal} + * @memberof AbortController + */ + get: function () { + return this._signal; + }, + enumerable: true, + configurable: true + }); + /** + * Signal that any operations passed this controller's associated abort signal + * to cancel any remaining work and throw an `AbortError`. + * + * @memberof AbortController + */ + AbortController.prototype.abort = function () { + abortSignal(this._signal); + }; + /** + * Creates a new AbortSignal instance that will abort after the provided ms. + * + * @static + * @params {number} ms Elapsed time in milliseconds to trigger an abort. + * @returns {AbortSignal} + */ + AbortController.timeout = function (ms) { + var signal = new AbortSignal(); + var timer = setTimeout(abortSignal, ms, signal); + // Prevent the active Timer from keeping the Node.js event loop active. + if (typeof timer.unref === "function") { + timer.unref(); + } + return signal; + }; + return AbortController; +}()); + +exports.AbortController = AbortController; +exports.AbortError = AbortError; +exports.AbortSignal = AbortSignal; +//# sourceMappingURL=index.js.map + + +/***/ }), +/* 107 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Observation.js.map + +/***/ }), +/* 108 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -7450,843 +7871,2634 @@ function pwrap (opts, fn) { // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -var pathModule = __webpack_require__(622); -var isWindows = process.platform === 'win32'; -var fs = __webpack_require__(747); -// JavaScript implementation of realpath, ported from node pre-v6 -var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); +/**/ -function rethrow() { - // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and - // is fairly slow to generate. - var callback; - if (DEBUG) { - var backtrace = new Error; - callback = debugCallback; - } else - callback = missingCallback; +var pna = __webpack_require__(822); +/**/ - return callback; +module.exports = Readable; - function debugCallback(err) { - if (err) { - backtrace.message = err.message; - err = backtrace; - missingCallback(err); - } - } +/**/ +var isArray = __webpack_require__(262); +/**/ - function missingCallback(err) { - if (err) { - if (process.throwDeprecation) - throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs - else if (!process.noDeprecation) { - var msg = 'fs: missing callback ' + (err.stack || err.message); - if (process.traceDeprecation) - console.trace(msg); - else - console.error(msg); - } - } - } -} +/**/ +var Duplex; +/**/ -function maybeCallback(cb) { - return typeof cb === 'function' ? cb : rethrow(); -} +Readable.ReadableState = ReadableState; -var normalize = pathModule.normalize; +/**/ +var EE = __webpack_require__(614).EventEmitter; -// Regexp that finds the next partion of a (partial) path -// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] -if (isWindows) { - var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; -} else { - var nextPartRe = /(.*?)(?:[\/]+|$)/g; +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = __webpack_require__(427); +/**/ + +/**/ + +var Buffer = __webpack_require__(254).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } -// Regex to find the device root, including trailing slash. E.g. 'c:\\'. -if (isWindows) { - var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +/**/ + +/**/ +var util = Object.create(__webpack_require__(286)); +util.inherits = __webpack_require__(689); +/**/ + +/**/ +var debugUtil = __webpack_require__(669); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); } else { - var splitRootRe = /^[\/]*/; + debug = function () {}; } +/**/ -exports.realpathSync = function realpathSync(p, cache) { - // make p is absolute - p = pathModule.resolve(p); +var BufferList = __webpack_require__(76); +var destroyImpl = __webpack_require__(232); +var StringDecoder; - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return cache[p]; +util.inherits(Readable, Stream); + +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream) { + Duplex = Duplex || __webpack_require__(907); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = __webpack_require__(432).StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; } +} - var original = p, - seenLinks = {}, - knownHard = {}; +function Readable(options) { + Duplex = Duplex || __webpack_require__(907); - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; + if (!(this instanceof Readable)) return new Readable(options); - start(); + this._readableState = new ReadableState(options, this); - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; + // legacy + this.readable = true; - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstatSync(base); - knownHard[base] = true; - } + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; } - // walk down the path, swapping out linked pathparts for their real - // values - // NB: p.length changes. - while (pos < p.length) { - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; + Stream.call(this); +} - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - continue; +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; } - var resolvedLink; - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // some known symbolic link. no need to stat again. - resolvedLink = cache[base]; - } else { - var stat = fs.lstatSync(base); - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - continue; - } + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); - // read the link if it wasn't read before - // dev/ino always return 0 on windows, so skip the check. - var linkTarget = null; - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - linkTarget = seenLinks[id]; - } - } - if (linkTarget === null) { - fs.statSync(base); - linkTarget = fs.readlinkSync(base); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; } - resolvedLink = pathModule.resolve(previous, linkTarget); - // track this, if given a cache. - if (cache) cache[base] = resolvedLink; - if (!isWindows) seenLinks[id] = linkTarget; + skipChunkCheck = true; } - - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); + } else { + skipChunkCheck = true; } - if (cache) cache[original] = p; + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; - return p; +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); }; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } -exports.realpath = function realpath(p, cache, cb) { - if (typeof cb !== 'function') { - cb = maybeCallback(cache); - cache = null; + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } } - // make p is absolute - p = pathModule.resolve(p); + return needMoreData(state); +} - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return process.nextTick(cb.bind(null, null, cache[p])); +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); } + maybeReadMore(stream, state); +} - var original = p, - seenLinks = {}, - knownHard = {}; +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} - start(); +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = __webpack_require__(432).StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstat(base, function(err) { - if (err) return cb(err); - knownHard[base] = true; - LOOP(); - }); - } else { - process.nextTick(LOOP); - } +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; } + return n; +} - // walk down the path, swapping out linked pathparts for their real - // values - function LOOP() { - // stop if scanned past end of path - if (pos >= p.length) { - if (cache) cache[original] = p; - return cb(null, p); - } +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - return process.nextTick(LOOP); - } + if (n !== 0) state.emittedReadable = false; - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // known symbolic link. no need to stat again. - return gotResolvedLink(cache[base]); - } + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } - return fs.lstat(base, gotStat); + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; } - function gotStat(err, stat) { - if (err) return cb(err); + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. - // if not a symlink, skip to the next path part - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - return process.nextTick(LOOP); - } + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); - // stat & read the link if not read before - // call gotTarget as soon as the link target is known - // dev/ino always return 0 on windows, so skip the check. - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - return gotTarget(null, seenLinks[id], base); - } - } - fs.stat(base, function(err) { - if (err) return cb(err); + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } - fs.readlink(base, function(err, target) { - if (!isWindows) seenLinks[id] = target; - gotTarget(err, target); - }); - }); + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); } - function gotTarget(err, target, base) { - if (err) return cb(err); + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; - var resolvedLink = pathModule.resolve(previous, target); - if (cache) cache[base] = resolvedLink; - gotResolvedLink(resolvedLink); + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; } - function gotResolvedLink(resolvedLink) { - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); - } -}; + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } -/***/ }), -/* 118 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { + if (ret !== null) this.emit('data', ret); -"use strict"; + return ret; +}; -Object.defineProperty(exports, "__esModule", { value: true }); -const utils_1 = __webpack_require__(756); -// The default Buffer size if one is not provided. -const DEFAULT_SMARTBUFFER_SIZE = 4096; -// The default string encoding to use for reading/writing strings. -const DEFAULT_SMARTBUFFER_ENCODING = 'utf8'; -class SmartBuffer { - /** - * Creates a new SmartBuffer instance. - * - * @param options { SmartBufferOptions } The SmartBufferOptions to apply to this instance. - */ - constructor(options) { - this.length = 0; - this._encoding = DEFAULT_SMARTBUFFER_ENCODING; - this._writeOffset = 0; - this._readOffset = 0; - if (SmartBuffer.isSmartBufferOptions(options)) { - // Checks for encoding - if (options.encoding) { - utils_1.checkEncoding(options.encoding); - this._encoding = options.encoding; - } - // Checks for initial size length - if (options.size) { - if (utils_1.isFiniteInteger(options.size) && options.size > 0) { - this._buff = Buffer.allocUnsafe(options.size); - } - else { - throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_SIZE); - } - // Check for initial Buffer - } - else if (options.buff) { - if (options.buff instanceof Buffer) { - this._buff = options.buff; - this.length = options.buff.length; - } - else { - throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_BUFFER); - } - } - else { - this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); - } - } - else { - // If something was passed but it's not a SmartBufferOptions object - if (typeof options !== 'undefined') { - throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_OBJECT); - } - // Otherwise default to sane options - this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); - } - } - /** - * Creates a new SmartBuffer instance with the provided internal Buffer size and optional encoding. - * - * @param size { Number } The size of the internal Buffer. - * @param encoding { String } The BufferEncoding to use for strings. - * - * @return { SmartBuffer } - */ - static fromSize(size, encoding) { - return new this({ - size: size, - encoding: encoding - }); +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; } - /** - * Creates a new SmartBuffer instance with the provided Buffer and optional encoding. - * - * @param buffer { Buffer } The Buffer to use as the internal Buffer value. - * @param encoding { String } The BufferEncoding to use for strings. - * - * @return { SmartBuffer } - */ - static fromBuffer(buff, encoding) { - return new this({ - buff: buff, - encoding: encoding - }); + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } } - /** - * Creates a new SmartBuffer instance with the provided SmartBufferOptions options. - * - * @param options { SmartBufferOptions } The options to use when creating the SmartBuffer instance. - */ - static fromOptions(options) { - return new this(options); + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); } - /** - * Type checking function that determines if an object is a SmartBufferOptions object. - */ - static isSmartBufferOptions(options) { - const castOptions = options; - return (castOptions && - (castOptions.encoding !== undefined || castOptions.size !== undefined || castOptions.buff !== undefined)); + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); } - // Signed integers - /** - * Reads an Int8 value from the current read position or an optionally provided offset. - * - * @param offset { Number } The offset to read data from (optional) - * @return { Number } - */ - readInt8(offset) { - return this._readNumberValue(Buffer.prototype.readInt8, 1, offset); + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this, unpipeInfo); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } } - /** - * Reads an Int16BE value from the current read position or an optionally provided offset. - * - * @param offset { Number } The offset to read data from (optional) - * @return { Number } - */ - readInt16BE(offset) { - return this._readNumberValue(Buffer.prototype.readInt16BE, 2, offset); + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); } - /** - * Reads an Int16LE value from the current read position or an optionally provided offset. - * - * @param offset { Number } The offset to read data from (optional) - * @return { Number } - */ - readInt16LE(offset) { - return this._readNumberValue(Buffer.prototype.readInt16LE, 2, offset); + + _this.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); } - /** - * Reads an Int32BE value from the current read position or an optionally provided offset. - * - * @param offset { Number } The offset to read data from (optional) - * @return { Number } - */ - readInt32BE(offset) { - return this._readNumberValue(Buffer.prototype.readInt32BE, 4, offset); + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); } - /** - * Reads an Int32LE value from the current read position or an optionally provided offset. - * - * @param offset { Number } The offset to read data from (optional) - * @return { Number } - */ - readInt32LE(offset) { - return this._readNumberValue(Buffer.prototype.readInt32LE, 4, offset); - } - /** - * Reads a BigInt64BE value from the current read position or an optionally provided offset. - * - * @param offset { Number } The offset to read data from (optional) - * @return { BigInt } - */ - readBigInt64BE(offset) { - utils_1.bigIntAndBufferInt64Check('readBigInt64BE'); - return this._readNumberValue(Buffer.prototype.readBigInt64BE, 8, offset); - } - /** - * Reads a BigInt64LE value from the current read position or an optionally provided offset. - * - * @param offset { Number } The offset to read data from (optional) - * @return { BigInt } - */ - readBigInt64LE(offset) { - utils_1.bigIntAndBufferInt64Check('readBigInt64LE'); - return this._readNumberValue(Buffer.prototype.readBigInt64LE, 8, offset); - } - /** - * Writes an Int8 value to the current write position (or at optional offset). - * - * @param value { Number } The value to write. - * @param offset { Number } The offset to write the value at. - * - * @return this - */ - writeInt8(value, offset) { - this._writeNumberValue(Buffer.prototype.writeInt8, 1, value, offset); - return this; - } - /** - * Inserts an Int8 value at the given offset value. - * - * @param value { Number } The value to insert. - * @param offset { Number } The offset to insert the value at. - * - * @return this - */ - insertInt8(value, offset) { - return this._insertNumberValue(Buffer.prototype.writeInt8, 1, value, offset); - } - /** - * Writes an Int16BE value to the current write position (or at optional offset). - * - * @param value { Number } The value to write. - * @param offset { Number } The offset to write the value at. - * - * @return this - */ - writeInt16BE(value, offset) { - return this._writeNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset); - } - /** - * Inserts an Int16BE value at the given offset value. - * - * @param value { Number } The value to insert. - * @param offset { Number } The offset to insert the value at. - * - * @return this - */ - insertInt16BE(value, offset) { - return this._insertNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset); - } - /** - * Writes an Int16LE value to the current write position (or at optional offset). - * - * @param value { Number } The value to write. - * @param offset { Number } The offset to write the value at. - * - * @return this - */ - writeInt16LE(value, offset) { - return this._writeNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset); - } - /** - * Inserts an Int16LE value at the given offset value. - * - * @param value { Number } The value to insert. - * @param offset { Number } The offset to insert the value at. - * - * @return this - */ - insertInt16LE(value, offset) { - return this._insertNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset); - } - /** - * Writes an Int32BE value to the current write position (or at optional offset). - * - * @param value { Number } The value to write. - * @param offset { Number } The offset to write the value at. - * - * @return this - */ - writeInt32BE(value, offset) { - return this._writeNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset); - } - /** - * Inserts an Int32BE value at the given offset value. - * - * @param value { Number } The value to insert. - * @param offset { Number } The offset to insert the value at. - * - * @return this - */ - insertInt32BE(value, offset) { - return this._insertNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset); + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); } - /** - * Writes an Int32LE value to the current write position (or at optional offset). - * - * @param value { Number } The value to write. - * @param offset { Number } The offset to write the value at. - * - * @return this - */ - writeInt32LE(value, offset) { - return this._writeNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset); + }; + + return this; +}; + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; } - /** - * Inserts an Int32LE value at the given offset value. - * - * @param value { Number } The value to insert. - * @param offset { Number } The offset to insert the value at. - * - * @return this - */ - insertInt32LE(value, offset) { - return this._insertNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset); + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; } - /** - * Writes a BigInt64BE value to the current write position (or at optional offset). - * - * @param value { BigInt } The value to write. - * @param offset { Number } The offset to write the value at. - * - * @return this - */ - writeBigInt64BE(value, offset) { - utils_1.bigIntAndBufferInt64Check('writeBigInt64BE'); - return this._writeNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset); + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +/***/ }), +/* 109 */, +/* 110 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +// Do a two-pass walk, first to get the list of packages that need to be +// bundled, then again to get the actual files and folders. +// Keep a cache of node_modules content and package.json data, so that the +// second walk doesn't have to re-do all the same work. + +const bundleWalk = __webpack_require__(650) +const BundleWalker = bundleWalk.BundleWalker +const BundleWalkerSync = bundleWalk.BundleWalkerSync + +const ignoreWalk = __webpack_require__(418) +const IgnoreWalker = ignoreWalk.Walker +const IgnoreWalkerSync = ignoreWalk.WalkerSync + +const rootBuiltinRules = Symbol('root-builtin-rules') +const packageNecessaryRules = Symbol('package-necessary-rules') +const path = __webpack_require__(622) + +const normalizePackageBin = __webpack_require__(787) + +const defaultRules = [ + '.npmignore', + '.gitignore', + '**/.git', + '**/.svn', + '**/.hg', + '**/CVS', + '**/.git/**', + '**/.svn/**', + '**/.hg/**', + '**/CVS/**', + '/.lock-wscript', + '/.wafpickle-*', + '/build/config.gypi', + 'npm-debug.log', + '**/.npmrc', + '.*.swp', + '.DS_Store', + '**/.DS_Store/**', + '._*', + '**/._*/**', + '*.orig', + '/package-lock.json', + '/yarn.lock', + 'archived-packages/**', + 'core', + '!core/', + '!**/core/', + '*.core', + '*.vgcore', + 'vgcore.*', + 'core.+([0-9])', +] + +// There may be others, but :?|<> are handled by node-tar +const nameIsBadForWindows = file => /\*/.test(file) + +// a decorator that applies our custom rules to an ignore walker +const npmWalker = Class => class Walker extends Class { + constructor (opt) { + opt = opt || {} + + // the order in which rules are applied. + opt.ignoreFiles = [ + rootBuiltinRules, + 'package.json', + '.npmignore', + '.gitignore', + packageNecessaryRules + ] + + opt.includeEmpty = false + opt.path = opt.path || process.cwd() + const dirName = path.basename(opt.path) + const parentName = path.basename(path.dirname(opt.path)) + opt.follow = + dirName === 'node_modules' || + (parentName === 'node_modules' && /^@/.test(dirName)) + super(opt) + + // ignore a bunch of things by default at the root level. + // also ignore anything in node_modules, except bundled dependencies + if (!this.parent) { + this.bundled = opt.bundled || [] + this.bundledScopes = Array.from(new Set( + this.bundled.filter(f => /^@/.test(f)) + .map(f => f.split('/')[0]))) + const rules = defaultRules.join('\n') + '\n' + this.packageJsonCache = opt.packageJsonCache || new Map() + super.onReadIgnoreFile(rootBuiltinRules, rules, _=>_) + } else { + this.bundled = [] + this.bundledScopes = [] + this.packageJsonCache = this.parent.packageJsonCache } - /** - * Inserts a BigInt64BE value at the given offset value. - * - * @param value { BigInt } The value to insert. - * @param offset { Number } The offset to insert the value at. - * - * @return this - */ - insertBigInt64BE(value, offset) { - utils_1.bigIntAndBufferInt64Check('writeBigInt64BE'); - return this._insertNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset); + } + + onReaddir (entries) { + if (!this.parent) { + entries = entries.filter(e => + e !== '.git' && + !(e === 'node_modules' && this.bundled.length === 0) + ) } - /** - * Writes a BigInt64LE value to the current write position (or at optional offset). - * - * @param value { BigInt } The value to write. - * @param offset { Number } The offset to write the value at. - * - * @return this - */ - writeBigInt64LE(value, offset) { - utils_1.bigIntAndBufferInt64Check('writeBigInt64LE'); - return this._writeNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset); + return super.onReaddir(entries) + } + + filterEntry (entry, partial) { + // get the partial path from the root of the walk + const p = this.path.substr(this.root.length + 1) + const pkgre = /^node_modules\/(@[^\/]+\/?[^\/]+|[^\/]+)(\/.*)?$/ + const isRoot = !this.parent + const pkg = isRoot && pkgre.test(entry) ? + entry.replace(pkgre, '$1') : null + const rootNM = isRoot && entry === 'node_modules' + const rootPJ = isRoot && entry === 'package.json' + + return ( + // if we're in a bundled package, check with the parent. + /^node_modules($|\/)/i.test(p) ? this.parent.filterEntry( + this.basename + '/' + entry, partial) + + // if package is bundled, all files included + // also include @scope dirs for bundled scoped deps + // they'll be ignored if no files end up in them. + // However, this only matters if we're in the root. + // node_modules folders elsewhere, like lib/node_modules, + // should be included normally unless ignored. + : pkg ? -1 !== this.bundled.indexOf(pkg) || + -1 !== this.bundledScopes.indexOf(pkg) + + // only walk top node_modules if we want to bundle something + : rootNM ? !!this.bundled.length + + // always include package.json at the root. + : rootPJ ? true + + // otherwise, follow ignore-walk's logic + : super.filterEntry(entry, partial) + ) + } + + filterEntries () { + if (this.ignoreRules['package.json']) + this.ignoreRules['.gitignore'] = this.ignoreRules['.npmignore'] = null + else if (this.ignoreRules['.npmignore']) + this.ignoreRules['.gitignore'] = null + this.filterEntries = super.filterEntries + super.filterEntries() + } + + addIgnoreFile (file, then) { + const ig = path.resolve(this.path, file) + if (this.packageJsonCache.has(ig)) + this.onPackageJson(ig, this.packageJsonCache.get(ig), then) + else + super.addIgnoreFile(file, then) + } + + onPackageJson (ig, pkg, then) { + this.packageJsonCache.set(ig, pkg) + + // if there's a bin, browser or main, make sure we don't ignore it + // also, don't ignore the package.json itself! + // + // Weird side-effect of this: a readme (etc) file will be included + // if it exists anywhere within a folder with a package.json file. + // The original intent was only to include these files in the root, + // but now users in the wild are dependent on that behavior for + // localized documentation and other use cases. Adding a `/` to + // these rules, while tempting and arguably more "correct", is a + // breaking change. + const rules = [ + pkg.browser ? '!' + pkg.browser : '', + pkg.main ? '!' + pkg.main : '', + '!package.json', + '!npm-shrinkwrap.json', + '!@(readme|copying|license|licence|notice|changes|changelog|history){,.*[^~$]}' + ] + if (pkg.bin) { + // always an object, because normalized already + for (const key in pkg.bin) + rules.push('!' + pkg.bin[key]) } - /** - * Inserts a Int64LE value at the given offset value. - * - * @param value { BigInt } The value to insert. - * @param offset { Number } The offset to insert the value at. - * - * @return this - */ - insertBigInt64LE(value, offset) { - utils_1.bigIntAndBufferInt64Check('writeBigInt64LE'); - return this._insertNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset); + + const data = rules.filter(f => f).join('\n') + '\n' + super.onReadIgnoreFile(packageNecessaryRules, data, _=>_) + + if (Array.isArray(pkg.files)) + super.onReadIgnoreFile('package.json', '*\n' + pkg.files.map( + f => '!' + f + '\n!' + f.replace(/\/+$/, '') + '/**' + ).join('\n') + '\n', then) + else + then() + } + + // override parent stat function to completely skip any filenames + // that will break windows entirely. + // XXX(isaacs) Next major version should make this an error instead. + stat (entry, file, dir, then) { + if (nameIsBadForWindows(entry)) + then() + else + super.stat(entry, file, dir, then) + } + + // override parent onstat function to nix all symlinks + onstat (st, entry, file, dir, then) { + if (st.isSymbolicLink()) + then() + else + super.onstat(st, entry, file, dir, then) + } + + onReadIgnoreFile (file, data, then) { + if (file === 'package.json') + try { + const ig = path.resolve(this.path, file) + this.onPackageJson(ig, normalizePackageBin(JSON.parse(data)), then) + } catch (er) { + // ignore package.json files that are not json + then() + } + else + super.onReadIgnoreFile(file, data, then) + } + + sort (a, b) { + return sort(a, b) + } +} + +class Walker extends npmWalker(IgnoreWalker) { + walker (entry, then) { + new Walker(this.walkerOpt(entry)).on('done', then).start() + } +} + +class WalkerSync extends npmWalker(IgnoreWalkerSync) { + walker (entry, then) { + new WalkerSync(this.walkerOpt(entry)).start() + then() + } +} + +const walk = (options, callback) => { + options = options || {} + const p = new Promise((resolve, reject) => { + const bw = new BundleWalker(options) + bw.on('done', bundled => { + options.bundled = bundled + options.packageJsonCache = bw.packageJsonCache + new Walker(options).on('done', resolve).on('error', reject).start() + }) + bw.start() + }) + return callback ? p.then(res => callback(null, res), callback) : p +} + +const walkSync = options => { + options = options || {} + const bw = new BundleWalkerSync(options).start() + options.bundled = bw.result + options.packageJsonCache = bw.packageJsonCache + const walker = new WalkerSync(options) + walker.start() + return walker.result +} + +// optimize for compressibility +// extname, then basename, then locale alphabetically +// https://twitter.com/isntitvacant/status/1131094910923231232 +const sort = (a, b) => { + const exta = path.extname(a).toLowerCase() + const extb = path.extname(b).toLowerCase() + const basea = path.basename(a).toLowerCase() + const baseb = path.basename(b).toLowerCase() + + return exta.localeCompare(extb) || + basea.localeCompare(baseb) || + a.localeCompare(b) +} + + +module.exports = walk +walk.sync = walkSync +walk.Walker = Walker +walk.WalkerSync = WalkerSync + + +/***/ }), +/* 111 */ +/***/ (function(module) { + +module.exports = bindActor +function bindActor () { + var args = + Array.prototype.slice.call + (arguments) // jswtf. + , obj = null + , fn + if (typeof args[0] === "object") { + obj = args.shift() + fn = args.shift() + if (typeof fn === "string") + fn = obj[ fn ] + } else fn = args.shift() + return function (cb) { + fn.apply(obj, args.concat(cb)) } +} + + +/***/ }), +/* 112 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +module.exports = __webpack_require__(146); +module.exports.HttpsAgent = __webpack_require__(21); + + +/***/ }), +/* 113 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +module.exports = __webpack_require__(964) + + +/***/ }), +/* 114 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(470)); +const http_client_1 = __webpack_require__(539); +const auth_1 = __webpack_require__(226); +const crypto = __importStar(__webpack_require__(417)); +const fs = __importStar(__webpack_require__(747)); +const url_1 = __webpack_require__(835); +const utils = __importStar(__webpack_require__(15)); +const constants_1 = __webpack_require__(931); +const downloadUtils_1 = __webpack_require__(251); +const options_1 = __webpack_require__(538); +const requestUtils_1 = __webpack_require__(899); +const versionSalt = '1.0'; +function getCacheApiUrl(resource) { + // Ideally we just use ACTIONS_CACHE_URL + const baseUrl = (process.env['ACTIONS_CACHE_URL'] || + process.env['ACTIONS_RUNTIME_URL'] || + '').replace('pipelines', 'artifactcache'); + if (!baseUrl) { + throw new Error('Cache Service Url not found, unable to restore cache.'); + } + const url = `${baseUrl}_apis/artifactcache/${resource}`; + core.debug(`Resource Url: ${url}`); + return url; +} +function createAcceptHeader(type, apiVersion) { + return `${type};api-version=${apiVersion}`; +} +function getRequestOptions() { + const requestOptions = { + headers: { + Accept: createAcceptHeader('application/json', '6.0-preview.1') + } + }; + return requestOptions; +} +function createHttpClient() { + const token = process.env['ACTIONS_RUNTIME_TOKEN'] || ''; + const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token); + return new http_client_1.HttpClient('actions/cache', [bearerCredentialHandler], getRequestOptions()); +} +function getCacheVersion(paths, compressionMethod) { + const components = paths.concat(!compressionMethod || compressionMethod === constants_1.CompressionMethod.Gzip + ? [] + : [compressionMethod]); + // Add salt to cache version to support breaking changes in cache entry + components.push(versionSalt); + return crypto + .createHash('sha256') + .update(components.join('|')) + .digest('hex'); +} +exports.getCacheVersion = getCacheVersion; +function getCacheEntry(keys, paths, options) { + return __awaiter(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod); + const resource = `cache?keys=${encodeURIComponent(keys.join(','))}&version=${version}`; + const response = yield requestUtils_1.retryTypedResponse('getCacheEntry', () => __awaiter(this, void 0, void 0, function* () { return httpClient.getJson(getCacheApiUrl(resource)); })); + if (response.statusCode === 204) { + return null; + } + if (!requestUtils_1.isSuccessStatusCode(response.statusCode)) { + throw new Error(`Cache service responded with ${response.statusCode}`); + } + const cacheResult = response.result; + const cacheDownloadUrl = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.archiveLocation; + if (!cacheDownloadUrl) { + throw new Error('Cache not found.'); + } + core.setSecret(cacheDownloadUrl); + core.debug(`Cache Result:`); + core.debug(JSON.stringify(cacheResult)); + return cacheResult; + }); +} +exports.getCacheEntry = getCacheEntry; +function downloadCache(archiveLocation, archivePath, options) { + return __awaiter(this, void 0, void 0, function* () { + const archiveUrl = new url_1.URL(archiveLocation); + const downloadOptions = options_1.getDownloadOptions(options); + if (downloadOptions.useAzureSdk && + archiveUrl.hostname.endsWith('.blob.core.windows.net')) { + // Use Azure storage SDK to download caches hosted on Azure to improve speed and reliability. + yield downloadUtils_1.downloadCacheStorageSDK(archiveLocation, archivePath, downloadOptions); + } + else { + // Otherwise, download using the Actions http-client. + yield downloadUtils_1.downloadCacheHttpClient(archiveLocation, archivePath); + } + }); +} +exports.downloadCache = downloadCache; +// Reserve Cache +function reserveCache(key, paths, options) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod); + const reserveCacheRequest = { + key, + version + }; + const response = yield requestUtils_1.retryTypedResponse('reserveCache', () => __awaiter(this, void 0, void 0, function* () { + return httpClient.postJson(getCacheApiUrl('caches'), reserveCacheRequest); + })); + return (_b = (_a = response === null || response === void 0 ? void 0 : response.result) === null || _a === void 0 ? void 0 : _a.cacheId) !== null && _b !== void 0 ? _b : -1; + }); +} +exports.reserveCache = reserveCache; +function getContentRange(start, end) { + // Format: `bytes start-end/filesize + // start and end are inclusive + // filesize can be * + // For a 200 byte chunk starting at byte 0: + // Content-Range: bytes 0-199/* + return `bytes ${start}-${end}/*`; +} +function uploadChunk(httpClient, resourceUrl, openStream, start, end) { + return __awaiter(this, void 0, void 0, function* () { + core.debug(`Uploading chunk of size ${end - + start + + 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`); + const additionalHeaders = { + 'Content-Type': 'application/octet-stream', + 'Content-Range': getContentRange(start, end) + }; + yield requestUtils_1.retryHttpClientResponse(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter(this, void 0, void 0, function* () { + return httpClient.sendStream('PATCH', resourceUrl, openStream(), additionalHeaders); + })); + }); +} +function uploadFile(httpClient, cacheId, archivePath, options) { + return __awaiter(this, void 0, void 0, function* () { + // Upload Chunks + const fileSize = fs.statSync(archivePath).size; + const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); + const fd = fs.openSync(archivePath, 'r'); + const uploadOptions = options_1.getUploadOptions(options); + const concurrency = utils.assertDefined('uploadConcurrency', uploadOptions.uploadConcurrency); + const maxChunkSize = utils.assertDefined('uploadChunkSize', uploadOptions.uploadChunkSize); + const parallelUploads = [...new Array(concurrency).keys()]; + core.debug('Awaiting all uploads'); + let offset = 0; + try { + yield Promise.all(parallelUploads.map(() => __awaiter(this, void 0, void 0, function* () { + while (offset < fileSize) { + const chunkSize = Math.min(fileSize - offset, maxChunkSize); + const start = offset; + const end = offset + chunkSize - 1; + offset += maxChunkSize; + yield uploadChunk(httpClient, resourceUrl, () => fs + .createReadStream(archivePath, { + fd, + start, + end, + autoClose: false + }) + .on('error', error => { + throw new Error(`Cache upload failed because file read failed with ${error.message}`); + }), start, end); + } + }))); + } + finally { + fs.closeSync(fd); + } + return; + }); +} +function commitCache(httpClient, cacheId, filesize) { + return __awaiter(this, void 0, void 0, function* () { + const commitCacheRequest = { size: filesize }; + return yield requestUtils_1.retryTypedResponse('commitCache', () => __awaiter(this, void 0, void 0, function* () { + return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest); + })); + }); +} +function saveCache(cacheId, archivePath, options) { + return __awaiter(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + core.debug('Upload cache'); + yield uploadFile(httpClient, cacheId, archivePath, options); + // Commit Cache + core.debug('Commiting cache'); + const cacheSize = utils.getArchiveFileSizeIsBytes(archivePath); + const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize); + if (!requestUtils_1.isSuccessStatusCode(commitCacheResponse.statusCode)) { + throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`); + } + core.info('Cache saved successfully'); + }); +} +exports.saveCache = saveCache; +//# sourceMappingURL=cacheHttpClient.js.map + +/***/ }), +/* 115 */, +/* 116 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const figgyPudding = __webpack_require__(122) +const getStream = __webpack_require__(341) +const npa = __webpack_require__(482) +const npmFetch = __webpack_require__(789) +const {PassThrough} = __webpack_require__(794) +const validate = __webpack_require__(772) + +const AccessConfig = figgyPudding({ + Promise: {default: () => Promise} +}) + +const eu = encodeURIComponent +const npar = spec => { + spec = npa(spec) + if (!spec.registry) { + throw new Error('`spec` must be a registry spec') + } + return spec +} + +const cmd = module.exports = {} + +cmd.public = (spec, opts) => setAccess(spec, 'public', opts) +cmd.restricted = (spec, opts) => setAccess(spec, 'restricted', opts) +function setAccess (spec, access, opts) { + opts = AccessConfig(opts) + return pwrap(opts, () => { + spec = npar(spec) + validate('OSO', [spec, access, opts]) + const uri = `/-/package/${eu(spec.name)}/access` + return npmFetch(uri, opts.concat({ + method: 'POST', + body: {access}, + spec + })) + }).then(res => res.body.resume() && true) +} + +cmd.grant = (spec, entity, permissions, opts) => { + opts = AccessConfig(opts) + return pwrap(opts, () => { + spec = npar(spec) + const {scope, team} = splitEntity(entity) + validate('OSSSO', [spec, scope, team, permissions, opts]) + if (permissions !== 'read-write' && permissions !== 'read-only') { + throw new Error('`permissions` must be `read-write` or `read-only`. Got `' + permissions + '` instead') } - // Unsigned Integers - /** - * Reads an UInt8 value from the current read position or an optionally provided offset. - * - * @param offset { Number } The offset to read data from (optional) - * @return { Number } - */ - readUInt8(offset) { - return this._readNumberValue(Buffer.prototype.readUInt8, 1, offset); + const uri = `/-/team/${eu(scope)}/${eu(team)}/package` + return npmFetch(uri, opts.concat({ + method: 'PUT', + body: {package: spec.name, permissions}, + scope, + spec, + ignoreBody: true + })) + }).then(() => true) +} + +cmd.revoke = (spec, entity, opts) => { + opts = AccessConfig(opts) + return pwrap(opts, () => { + spec = npar(spec) + const {scope, team} = splitEntity(entity) + validate('OSSO', [spec, scope, team, opts]) + const uri = `/-/team/${eu(scope)}/${eu(team)}/package` + return npmFetch(uri, opts.concat({ + method: 'DELETE', + body: {package: spec.name}, + scope, + spec, + ignoreBody: true + })) + }).then(() => true) +} + +cmd.lsPackages = (entity, opts) => { + opts = AccessConfig(opts) + return pwrap(opts, () => { + return getStream.array( + cmd.lsPackages.stream(entity, opts) + ).then(data => data.reduce((acc, [key, val]) => { + if (!acc) { + acc = {} + } + acc[key] = val + return acc + }, null)) + }) +} + +cmd.lsPackages.stream = (entity, opts) => { + validate('SO|SZ', [entity, opts]) + opts = AccessConfig(opts) + const {scope, team} = splitEntity(entity) + let uri + if (team) { + uri = `/-/team/${eu(scope)}/${eu(team)}/package` + } else { + uri = `/-/org/${eu(scope)}/package` + } + opts = opts.concat({ + query: {format: 'cli'}, + mapJson (value, [key]) { + if (value === 'read') { + return [key, 'read-only'] + } else if (value === 'write') { + return [key, 'read-write'] + } else { + return [key, value] + } } - /** - * Reads an UInt16BE value from the current read position or an optionally provided offset. - * - * @param offset { Number } The offset to read data from (optional) - * @return { Number } - */ - readUInt16BE(offset) { - return this._readNumberValue(Buffer.prototype.readUInt16BE, 2, offset); + }) + const ret = new PassThrough({objectMode: true}) + npmFetch.json.stream(uri, '*', opts).on('error', err => { + if (err.code === 'E404' && !team) { + uri = `/-/user/${eu(scope)}/package` + npmFetch.json.stream(uri, '*', opts).on( + 'error', err => ret.emit('error', err) + ).pipe(ret) + } else { + ret.emit('error', err) } - /** - * Reads an UInt16LE value from the current read position or an optionally provided offset. - * - * @param offset { Number } The offset to read data from (optional) - * @return { Number } - */ - readUInt16LE(offset) { - return this._readNumberValue(Buffer.prototype.readUInt16LE, 2, offset); + }).pipe(ret) + return ret +} + +cmd.lsCollaborators = (spec, user, opts) => { + if (typeof user === 'object' && !opts) { + opts = user + user = undefined + } + opts = AccessConfig(opts) + return pwrap(opts, () => { + return getStream.array( + cmd.lsCollaborators.stream(spec, user, opts) + ).then(data => data.reduce((acc, [key, val]) => { + if (!acc) { + acc = {} + } + acc[key] = val + return acc + }, null)) + }) +} + +cmd.lsCollaborators.stream = (spec, user, opts) => { + if (typeof user === 'object' && !opts) { + opts = user + user = undefined + } + opts = AccessConfig(opts) + spec = npar(spec) + validate('OSO|OZO', [spec, user, opts]) + const uri = `/-/package/${eu(spec.name)}/collaborators` + return npmFetch.json.stream(uri, '*', opts.concat({ + query: {format: 'cli', user: user || undefined}, + mapJson (value, [key]) { + if (value === 'read') { + return [key, 'read-only'] + } else if (value === 'write') { + return [key, 'read-write'] + } else { + return [key, value] + } } - /** - * Reads an UInt32BE value from the current read position or an optionally provided offset. - * - * @param offset { Number } The offset to read data from (optional) - * @return { Number } - */ - readUInt32BE(offset) { - return this._readNumberValue(Buffer.prototype.readUInt32BE, 4, offset); + })) +} + +cmd.tfaRequired = (spec, opts) => setRequires2fa(spec, true, opts) +cmd.tfaNotRequired = (spec, opts) => setRequires2fa(spec, false, opts) +function setRequires2fa (spec, required, opts) { + opts = AccessConfig(opts) + return new opts.Promise((resolve, reject) => { + spec = npar(spec) + validate('OBO', [spec, required, opts]) + const uri = `/-/package/${eu(spec.name)}/access` + return npmFetch(uri, opts.concat({ + method: 'POST', + body: {publish_requires_tfa: required}, + spec, + ignoreBody: true + })).then(resolve, reject) + }).then(() => true) +} + +cmd.edit = () => { + throw new Error('Not implemented yet') +} + +function splitEntity (entity = '') { + let [, scope, team] = entity.match(/^@?([^:]+)(?::(.*))?$/) || [] + return {scope, team} +} + +function pwrap (opts, fn) { + return new opts.Promise((resolve, reject) => { + fn().then(resolve, reject) + }) +} + + +/***/ }), +/* 117 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var pathModule = __webpack_require__(622); +var isWindows = process.platform === 'win32'; +var fs = __webpack_require__(747); + +// JavaScript implementation of realpath, ported from node pre-v6 + +var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); + +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; + + return callback; + + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); } - /** - * Reads an UInt32LE value from the current read position or an optionally provided offset. - * - * @param offset { Number } The offset to read data from (optional) - * @return { Number } - */ - readUInt32LE(offset) { - return this._readNumberValue(Buffer.prototype.readUInt32LE, 4, offset); + } + + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); + } + } + } +} + +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); +} + +var normalize = pathModule.normalize; + +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; +} + +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; +} + +exports.realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = pathModule.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstatSync(base); + knownHard[base] = true; + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; + } + + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; + } + + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; + } + } + if (linkTarget === null) { + fs.statSync(base); + linkTarget = fs.readlinkSync(base); + } + resolvedLink = pathModule.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows) seenLinks[id] = linkTarget; + } + + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } + + if (cache) cache[original] = p; + + return p; +}; + + +exports.realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; + } + + // make p is absolute + p = pathModule.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); + } else { + process.nextTick(LOOP); + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); + } + + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); + } + + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); + } + + return fs.lstat(base, gotStat); + } + + function gotStat(err, stat) { + if (err) return cb(err); + + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); + } + + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } + } + fs.stat(base, function(err) { + if (err) return cb(err); + + fs.readlink(base, function(err, target) { + if (!isWindows) seenLinks[id] = target; + gotTarget(err, target); + }); + }); + } + + function gotTarget(err, target, base) { + if (err) return cb(err); + + var resolvedLink = pathModule.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); + } + + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } +}; + + +/***/ }), +/* 118 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = __webpack_require__(756); +// The default Buffer size if one is not provided. +const DEFAULT_SMARTBUFFER_SIZE = 4096; +// The default string encoding to use for reading/writing strings. +const DEFAULT_SMARTBUFFER_ENCODING = 'utf8'; +class SmartBuffer { + /** + * Creates a new SmartBuffer instance. + * + * @param options { SmartBufferOptions } The SmartBufferOptions to apply to this instance. + */ + constructor(options) { + this.length = 0; + this._encoding = DEFAULT_SMARTBUFFER_ENCODING; + this._writeOffset = 0; + this._readOffset = 0; + if (SmartBuffer.isSmartBufferOptions(options)) { + // Checks for encoding + if (options.encoding) { + utils_1.checkEncoding(options.encoding); + this._encoding = options.encoding; + } + // Checks for initial size length + if (options.size) { + if (utils_1.isFiniteInteger(options.size) && options.size > 0) { + this._buff = Buffer.allocUnsafe(options.size); + } + else { + throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_SIZE); + } + // Check for initial Buffer + } + else if (options.buff) { + if (options.buff instanceof Buffer) { + this._buff = options.buff; + this.length = options.buff.length; + } + else { + throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_BUFFER); + } + } + else { + this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); + } + } + else { + // If something was passed but it's not a SmartBufferOptions object + if (typeof options !== 'undefined') { + throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_OBJECT); + } + // Otherwise default to sane options + this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); + } } /** - * Reads a BigUInt64BE value from the current read position or an optionally provided offset. + * Creates a new SmartBuffer instance with the provided internal Buffer size and optional encoding. + * + * @param size { Number } The size of the internal Buffer. + * @param encoding { String } The BufferEncoding to use for strings. + * + * @return { SmartBuffer } + */ + static fromSize(size, encoding) { + return new this({ + size: size, + encoding: encoding + }); + } + /** + * Creates a new SmartBuffer instance with the provided Buffer and optional encoding. + * + * @param buffer { Buffer } The Buffer to use as the internal Buffer value. + * @param encoding { String } The BufferEncoding to use for strings. + * + * @return { SmartBuffer } + */ + static fromBuffer(buff, encoding) { + return new this({ + buff: buff, + encoding: encoding + }); + } + /** + * Creates a new SmartBuffer instance with the provided SmartBufferOptions options. + * + * @param options { SmartBufferOptions } The options to use when creating the SmartBuffer instance. + */ + static fromOptions(options) { + return new this(options); + } + /** + * Type checking function that determines if an object is a SmartBufferOptions object. + */ + static isSmartBufferOptions(options) { + const castOptions = options; + return (castOptions && + (castOptions.encoding !== undefined || castOptions.size !== undefined || castOptions.buff !== undefined)); + } + // Signed integers + /** + * Reads an Int8 value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) - * @return { BigInt } + * @return { Number } */ - readBigUInt64BE(offset) { - utils_1.bigIntAndBufferInt64Check('readBigUInt64BE'); - return this._readNumberValue(Buffer.prototype.readBigUInt64BE, 8, offset); + readInt8(offset) { + return this._readNumberValue(Buffer.prototype.readInt8, 1, offset); } /** - * Reads a BigUInt64LE value from the current read position or an optionally provided offset. + * Reads an Int16BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) - * @return { BigInt } + * @return { Number } */ - readBigUInt64LE(offset) { - utils_1.bigIntAndBufferInt64Check('readBigUInt64LE'); - return this._readNumberValue(Buffer.prototype.readBigUInt64LE, 8, offset); + readInt16BE(offset) { + return this._readNumberValue(Buffer.prototype.readInt16BE, 2, offset); } /** - * Writes an UInt8 value to the current write position (or at optional offset). + * Reads an Int16LE value from the current read position or an optionally provided offset. * - * @param value { Number } The value to write. - * @param offset { Number } The offset to write the value at. + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readInt16LE(offset) { + return this._readNumberValue(Buffer.prototype.readInt16LE, 2, offset); + } + /** + * Reads an Int32BE value from the current read position or an optionally provided offset. * - * @return this + * @param offset { Number } The offset to read data from (optional) + * @return { Number } */ - writeUInt8(value, offset) { - return this._writeNumberValue(Buffer.prototype.writeUInt8, 1, value, offset); + readInt32BE(offset) { + return this._readNumberValue(Buffer.prototype.readInt32BE, 4, offset); } /** - * Inserts an UInt8 value at the given offset value. + * Reads an Int32LE value from the current read position or an optionally provided offset. * - * @param value { Number } The value to insert. - * @param offset { Number } The offset to insert the value at. + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readInt32LE(offset) { + return this._readNumberValue(Buffer.prototype.readInt32LE, 4, offset); + } + /** + * Reads a BigInt64BE value from the current read position or an optionally provided offset. * - * @return this + * @param offset { Number } The offset to read data from (optional) + * @return { BigInt } */ - insertUInt8(value, offset) { - return this._insertNumberValue(Buffer.prototype.writeUInt8, 1, value, offset); + readBigInt64BE(offset) { + utils_1.bigIntAndBufferInt64Check('readBigInt64BE'); + return this._readNumberValue(Buffer.prototype.readBigInt64BE, 8, offset); } /** - * Writes an UInt16BE value to the current write position (or at optional offset). + * Reads a BigInt64LE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { BigInt } + */ + readBigInt64LE(offset) { + utils_1.bigIntAndBufferInt64Check('readBigInt64LE'); + return this._readNumberValue(Buffer.prototype.readBigInt64LE, 8, offset); + } + /** + * Writes an Int8 value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ - writeUInt16BE(value, offset) { - return this._writeNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset); + writeInt8(value, offset) { + this._writeNumberValue(Buffer.prototype.writeInt8, 1, value, offset); + return this; } /** - * Inserts an UInt16BE value at the given offset value. + * Inserts an Int8 value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ - insertUInt16BE(value, offset) { - return this._insertNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset); + insertInt8(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeInt8, 1, value, offset); } /** - * Writes an UInt16LE value to the current write position (or at optional offset). + * Writes an Int16BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ - writeUInt16LE(value, offset) { - return this._writeNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset); + writeInt16BE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset); } /** - * Inserts an UInt16LE value at the given offset value. + * Inserts an Int16BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ - insertUInt16LE(value, offset) { - return this._insertNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset); + insertInt16BE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset); } /** - * Writes an UInt32BE value to the current write position (or at optional offset). + * Writes an Int16LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ - writeUInt32BE(value, offset) { - return this._writeNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset); + writeInt16LE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset); } /** - * Inserts an UInt32BE value at the given offset value. + * Inserts an Int16LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ - insertUInt32BE(value, offset) { - return this._insertNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset); + insertInt16LE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset); } /** - * Writes an UInt32LE value to the current write position (or at optional offset). + * Writes an Int32BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ - writeUInt32LE(value, offset) { - return this._writeNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset); + writeInt32BE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset); } /** - * Inserts an UInt32LE value at the given offset value. + * Inserts an Int32BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ - insertUInt32LE(value, offset) { - return this._insertNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset); + insertInt32BE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset); } /** - * Writes a BigUInt64BE value to the current write position (or at optional offset). + * Writes an Int32LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ - writeBigUInt64BE(value, offset) { - utils_1.bigIntAndBufferInt64Check('writeBigUInt64BE'); - return this._writeNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset); + writeInt32LE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset); } /** - * Inserts a BigUInt64BE value at the given offset value. + * Inserts an Int32LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ - insertBigUInt64BE(value, offset) { - utils_1.bigIntAndBufferInt64Check('writeBigUInt64BE'); - return this._insertNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset); + insertInt32LE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset); } /** - * Writes a BigUInt64LE value to the current write position (or at optional offset). + * Writes a BigInt64BE value to the current write position (or at optional offset). * - * @param value { Number } The value to write. + * @param value { BigInt } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ - writeBigUInt64LE(value, offset) { - utils_1.bigIntAndBufferInt64Check('writeBigUInt64LE'); - return this._writeNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset); + writeBigInt64BE(value, offset) { + utils_1.bigIntAndBufferInt64Check('writeBigInt64BE'); + return this._writeNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset); } /** - * Inserts a BigUInt64LE value at the given offset value. + * Inserts a BigInt64BE value at the given offset value. * - * @param value { Number } The value to insert. + * @param value { BigInt } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ - insertBigUInt64LE(value, offset) { - utils_1.bigIntAndBufferInt64Check('writeBigUInt64LE'); - return this._insertNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset); + insertBigInt64BE(value, offset) { + utils_1.bigIntAndBufferInt64Check('writeBigInt64BE'); + return this._insertNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset); + } + /** + * Writes a BigInt64LE value to the current write position (or at optional offset). + * + * @param value { BigInt } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeBigInt64LE(value, offset) { + utils_1.bigIntAndBufferInt64Check('writeBigInt64LE'); + return this._writeNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset); + } + /** + * Inserts a Int64LE value at the given offset value. + * + * @param value { BigInt } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertBigInt64LE(value, offset) { + utils_1.bigIntAndBufferInt64Check('writeBigInt64LE'); + return this._insertNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset); + } + // Unsigned Integers + /** + * Reads an UInt8 value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readUInt8(offset) { + return this._readNumberValue(Buffer.prototype.readUInt8, 1, offset); + } + /** + * Reads an UInt16BE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readUInt16BE(offset) { + return this._readNumberValue(Buffer.prototype.readUInt16BE, 2, offset); + } + /** + * Reads an UInt16LE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readUInt16LE(offset) { + return this._readNumberValue(Buffer.prototype.readUInt16LE, 2, offset); + } + /** + * Reads an UInt32BE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readUInt32BE(offset) { + return this._readNumberValue(Buffer.prototype.readUInt32BE, 4, offset); + } + /** + * Reads an UInt32LE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readUInt32LE(offset) { + return this._readNumberValue(Buffer.prototype.readUInt32LE, 4, offset); + } + /** + * Reads a BigUInt64BE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { BigInt } + */ + readBigUInt64BE(offset) { + utils_1.bigIntAndBufferInt64Check('readBigUInt64BE'); + return this._readNumberValue(Buffer.prototype.readBigUInt64BE, 8, offset); + } + /** + * Reads a BigUInt64LE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { BigInt } + */ + readBigUInt64LE(offset) { + utils_1.bigIntAndBufferInt64Check('readBigUInt64LE'); + return this._readNumberValue(Buffer.prototype.readBigUInt64LE, 8, offset); + } + /** + * Writes an UInt8 value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeUInt8(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeUInt8, 1, value, offset); + } + /** + * Inserts an UInt8 value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertUInt8(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeUInt8, 1, value, offset); + } + /** + * Writes an UInt16BE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeUInt16BE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset); + } + /** + * Inserts an UInt16BE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertUInt16BE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset); + } + /** + * Writes an UInt16LE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeUInt16LE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset); + } + /** + * Inserts an UInt16LE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertUInt16LE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset); + } + /** + * Writes an UInt32BE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeUInt32BE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset); + } + /** + * Inserts an UInt32BE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertUInt32BE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset); + } + /** + * Writes an UInt32LE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeUInt32LE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset); + } + /** + * Inserts an UInt32LE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertUInt32LE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset); + } + /** + * Writes a BigUInt64BE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeBigUInt64BE(value, offset) { + utils_1.bigIntAndBufferInt64Check('writeBigUInt64BE'); + return this._writeNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset); + } + /** + * Inserts a BigUInt64BE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertBigUInt64BE(value, offset) { + utils_1.bigIntAndBufferInt64Check('writeBigUInt64BE'); + return this._insertNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset); + } + /** + * Writes a BigUInt64LE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeBigUInt64LE(value, offset) { + utils_1.bigIntAndBufferInt64Check('writeBigUInt64LE'); + return this._writeNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset); + } + /** + * Inserts a BigUInt64LE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertBigUInt64LE(value, offset) { + utils_1.bigIntAndBufferInt64Check('writeBigUInt64LE'); + return this._insertNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset); } // Floating Point /** @@ -9221,7 +11433,7 @@ function entries (obj) { const path = __webpack_require__(622) const nopt = __webpack_require__(401) -const log = __webpack_require__(851) +const log = __webpack_require__(412) const childProcess = __webpack_require__(129) const EE = __webpack_require__(614).EventEmitter const inherits = __webpack_require__(669).inherits @@ -9430,7 +11642,78 @@ module.exports = exports = gyp /***/ }), -/* 128 */, +/* 128 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +module.exports = spawn + +const _spawn = __webpack_require__(129).spawn +const EventEmitter = __webpack_require__(614).EventEmitter + +let progressEnabled +let running = 0 + +function startRunning (log) { + if (progressEnabled == null) progressEnabled = log.progressEnabled + if (progressEnabled) log.disableProgress() + ++running +} + +function stopRunning (log) { + --running + if (progressEnabled && running === 0) log.enableProgress() +} + +function willCmdOutput (stdio) { + if (stdio === 'inherit') return true + if (!Array.isArray(stdio)) return false + for (let fh = 1; fh <= 2; ++fh) { + if (stdio[fh] === 'inherit') return true + if (stdio[fh] === 1 || stdio[fh] === 2) return true + } + return false +} + +function spawn (cmd, args, options, log) { + const cmdWillOutput = willCmdOutput(options && options.stdio) + + if (cmdWillOutput) startRunning(log) + const raw = _spawn(cmd, args, options) + const cooked = new EventEmitter() + + raw.on('error', function (er) { + if (cmdWillOutput) stopRunning(log) + er.file = cmd + cooked.emit('error', er) + }).on('close', function (code, signal) { + if (cmdWillOutput) stopRunning(log) + // Create ENOENT error because Node.js v8.0 will not emit + // an `error` event if the command could not be found. + if (code === 127) { + const er = new Error('spawn ENOENT') + er.code = 'ENOENT' + er.errno = 'ENOENT' + er.syscall = 'spawn' + er.file = cmd + cooked.emit('error', er) + } else { + cooked.emit('close', code, signal) + } + }) + + cooked.stdin = raw.stdin + cooked.stdout = raw.stdout + cooked.stderr = raw.stderr + cooked.kill = function (sig) { return raw.kill(sig) } + + return cooked +} + + +/***/ }), /* 129 */ /***/ (function(module) { @@ -9440,27 +11723,9 @@ module.exports = require("child_process"); /* 130 */, /* 131 */, /* 132 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var Inputs; -(function (Inputs) { - Inputs.Key = "key"; - Inputs.Path = "path"; - Inputs.RestoreKeys = "restore-keys"; -})(Inputs = exports.Inputs || (exports.Inputs = {})); -var Outputs; -(function (Outputs) { - Outputs.CacheHit = "cache-hit"; -})(Outputs = exports.Outputs || (exports.Outputs = {})); -var State; -(function (State) { - State.CacheKey = "CACHE_KEY"; - State.CacheResult = "CACHE_RESULT"; -})(State = exports.State || (exports.State = {})); +/***/ (function(module) { +module.exports = {"repositories":"'repositories' (plural) Not supported. Please pick one as the 'repository' field","missingRepository":"No repository field.","brokenGitUrl":"Probably broken git url: %s","nonObjectScripts":"scripts must be an object","nonStringScript":"script values must be string commands","nonArrayFiles":"Invalid 'files' member","invalidFilename":"Invalid filename in 'files' list: %s","nonArrayBundleDependencies":"Invalid 'bundleDependencies' list. Must be array of package names","nonStringBundleDependency":"Invalid bundleDependencies member: %s","nonDependencyBundleDependency":"Non-dependency in bundleDependencies: %s","nonObjectDependencies":"%s field must be an object","nonStringDependency":"Invalid dependency: %s %s","deprecatedArrayDependencies":"specifying %s as array is deprecated","deprecatedModules":"modules field is deprecated","nonArrayKeywords":"keywords should be an array of strings","nonStringKeyword":"keywords should be an array of strings","conflictingName":"%s is also the name of a node core module.","nonStringDescription":"'description' field should be a string","missingDescription":"No description","missingReadme":"No README data","missingLicense":"No license field.","nonEmailUrlBugsString":"Bug string field must be url, email, or {email,url}","nonUrlBugsUrlField":"bugs.url field must be a string url. Deleted.","nonEmailBugsEmailField":"bugs.email field must be a string email. Deleted.","emptyNormalizedBugs":"Normalized value of bugs field is an empty object. Deleted.","nonUrlHomepage":"homepage field must be a string url. Deleted.","invalidLicense":"license should be a valid SPDX license expression","typo":"%s should probably be %s."}; /***/ }), /* 133 */ @@ -9469,9 +11734,9 @@ var State; "use strict"; -const BB = __webpack_require__(440) +const BB = __webpack_require__(489) -const chownr = BB.promisify(__webpack_require__(427)) +const chownr = BB.promisify(__webpack_require__(941)) const mkdirp = BB.promisify(__webpack_require__(626)) const inflight = __webpack_require__(593) const inferOwner = __webpack_require__(686) @@ -9604,7 +11869,7 @@ function mkdirfixSync (cache, p) { "use strict"; -const BB = __webpack_require__(440) +const BB = __webpack_require__(489) const fetch = __webpack_require__(789) const manifest = __webpack_require__(935) @@ -9708,8 +11973,143 @@ function getTarballUrl (spec, registry, mani, opts) { /***/ }), /* 135 */, -/* 136 */, -/* 137 */, +/* 136 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MetricsAPI = void 0; +var NoopMeterProvider_1 = __webpack_require__(450); +var global_utils_1 = __webpack_require__(976); +/** + * Singleton object which represents the entry point to the OpenTelemetry Metrics API + */ +var MetricsAPI = /** @class */ (function () { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + function MetricsAPI() { + } + /** Get the singleton instance of the Metrics API */ + MetricsAPI.getInstance = function () { + if (!this._instance) { + this._instance = new MetricsAPI(); + } + return this._instance; + }; + /** + * Set the current global meter. Returns the initialized global meter provider. + */ + MetricsAPI.prototype.setGlobalMeterProvider = function (provider) { + if (global_utils_1._global[global_utils_1.GLOBAL_METRICS_API_KEY]) { + // global meter provider has already been set + return this.getMeterProvider(); + } + global_utils_1._global[global_utils_1.GLOBAL_METRICS_API_KEY] = global_utils_1.makeGetter(global_utils_1.API_BACKWARDS_COMPATIBILITY_VERSION, provider, NoopMeterProvider_1.NOOP_METER_PROVIDER); + return provider; + }; + /** + * Returns the global meter provider. + */ + MetricsAPI.prototype.getMeterProvider = function () { + var _a, _b; + return ((_b = (_a = global_utils_1._global[global_utils_1.GLOBAL_METRICS_API_KEY]) === null || _a === void 0 ? void 0 : _a.call(global_utils_1._global, global_utils_1.API_BACKWARDS_COMPATIBILITY_VERSION)) !== null && _b !== void 0 ? _b : NoopMeterProvider_1.NOOP_METER_PROVIDER); + }; + /** + * Returns a meter from the global meter provider. + */ + MetricsAPI.prototype.getMeter = function (name, version) { + return this.getMeterProvider().getMeter(name, version); + }; + /** Remove the global meter provider */ + MetricsAPI.prototype.disable = function () { + delete global_utils_1._global[global_utils_1.GLOBAL_METRICS_API_KEY]; + }; + return MetricsAPI; +}()); +exports.MetricsAPI = MetricsAPI; +//# sourceMappingURL=metrics.js.map + +/***/ }), +/* 137 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +var eos = __webpack_require__(3) +var shift = __webpack_require__(475) + +module.exports = each + +function each (stream, fn, cb) { + var want = true + var error = null + var ended = false + var running = false + var calling = false + + stream.on('readable', onreadable) + onreadable() + + if (cb) eos(stream, {readable: true, writable: false}, done) + return stream + + function done (err) { + if (!error) error = err + ended = true + if (!running) cb(error) + } + + function onreadable () { + if (want) read() + } + + function afterRead (err) { + running = false + + if (err) { + error = err + if (ended) return cb(error) + stream.destroy(err) + return + } + if (ended) return cb(error) + if (!calling) read() + } + + function read () { + while (!running && !ended) { + want = false + + var data = shift(stream) + if (ended) return + if (data === null) { + want = true + return + } + + running = true + calling = true + fn(data, afterRead) + calling = false + } + } +} + + +/***/ }), /* 138 */, /* 139 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -10249,182 +12649,331 @@ function whichSync (cmd, opt) { /***/ }), -/* 143 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -const path = __webpack_require__(622); -const Module = __webpack_require__(649); -const fs = __webpack_require__(747); - -const resolveFrom = (fromDir, moduleId, silent) => { - if (typeof fromDir !== 'string') { - throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDir}\``); - } - - if (typeof moduleId !== 'string') { - throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``); - } - - try { - fromDir = fs.realpathSync(fromDir); - } catch (err) { - if (err.code === 'ENOENT') { - fromDir = path.resolve(fromDir); - } else if (silent) { - return null; - } else { - throw err; - } - } - - const fromFile = path.join(fromDir, 'noop.js'); - - const resolveFileName = () => Module._resolveFilename(moduleId, { - id: fromFile, - filename: fromFile, - paths: Module._nodeModulePaths(fromDir) - }); - - if (silent) { - try { - return resolveFileName(); - } catch (err) { - return null; - } - } - - return resolveFileName(); -}; - -module.exports = (fromDir, moduleId) => resolveFrom(fromDir, moduleId); -module.exports.silent = (fromDir, moduleId) => resolveFrom(fromDir, moduleId, true); - - -/***/ }), +/* 143 */, /* 144 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ (function(module) { -var crypto = __webpack_require__(417); +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. -function zeroextend(str, len) -{ - while (str.length < len) - str = '0' + str; - return (str); -} +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. -/* - * Fix (odd) parity bits in a 64-bit DES key. - */ -function oddpar(buf) -{ - for (var j = 0; j < buf.length; j++) { - var par = 1; - for (var i = 1; i < 8; i++) { - par = (par + ((buf[j] >> i) & 1)) % 2; +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. +***************************************************************************** */ +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __createBinding; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); } - buf[j] |= par & 1; - } - return buf; -} + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; -/* - * Expand a 56-bit key buffer to the full 64-bits for DES. - * - * Based on code sample in: - * http://www.innovation.ch/personal/ronald/ntlm.html - */ -function expandkey(key56) -{ - var key64 = new Buffer(8); + __extends = function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; - key64[0] = key56[0] & 0xFE; - key64[1] = ((key56[0] << 7) & 0xFF) | (key56[1] >> 1); - key64[2] = ((key56[1] << 6) & 0xFF) | (key56[2] >> 2); - key64[3] = ((key56[2] << 5) & 0xFF) | (key56[3] >> 3); - key64[4] = ((key56[3] << 4) & 0xFF) | (key56[4] >> 4); - key64[5] = ((key56[4] << 3) & 0xFF) | (key56[5] >> 5); - key64[6] = ((key56[5] << 2) & 0xFF) | (key56[6] >> 6); - key64[7] = (key56[6] << 1) & 0xFF; + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; - return key64; -} + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; -/* - * Convert a binary string to a hex string - */ -function bintohex(bin) -{ - var buf = (Buffer.isBuffer(buf) ? buf : new Buffer(bin, 'binary')); - var str = buf.toString('hex').toUpperCase(); - return zeroextend(str, 32); -} + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + }; -module.exports.zeroextend = zeroextend; -module.exports.oddpar = oddpar; -module.exports.expandkey = expandkey; -module.exports.bintohex = bintohex; + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); /***/ }), /* 145 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ (function(__unusedmodule, exports) { "use strict"; -const pump = __webpack_require__(284); -const bufferStream = __webpack_require__(158); - -class MaxBufferError extends Error { - constructor() { - super('maxBuffer exceeded'); - this.name = 'MaxBufferError'; - } -} - -function getStream(inputStream, options) { - if (!inputStream) { - return Promise.reject(new Error('Expected a stream')); - } - - options = Object.assign({maxBuffer: Infinity}, options); - - const {maxBuffer} = options; - - let stream; - return new Promise((resolve, reject) => { - const rejectPromise = error => { - if (error) { // A null check - error.bufferedData = stream.getBufferedValue(); - } - reject(error); - }; - - stream = pump(inputStream, bufferStream(options), error => { - if (error) { - rejectPromise(error); - return; - } - - resolve(); - }); - - stream.on('data', () => { - if (stream.getBufferedLength() > maxBuffer) { - rejectPromise(new MaxBufferError()); - } - }); - }).then(() => stream.getBufferedValue()); -} - -module.exports = getStream; -module.exports.buffer = (stream, options) => getStream(stream, Object.assign({}, options, {encoding: 'buffer'})); -module.exports.array = (stream, options) => getStream(stream, Object.assign({}, options, {array: true})); -module.exports.MaxBufferError = MaxBufferError; - +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports._globalThis = void 0; +/** only globals that common to node and browsers are allowed */ +// eslint-disable-next-line node/no-unsupported-features/es-builtins +exports._globalThis = typeof globalThis === 'object' ? globalThis : global; +//# sourceMappingURL=globalThis.js.map /***/ }), /* 146 */ @@ -10568,243 +13117,35 @@ function inspect(obj) { /***/ }), /* 147 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var stream = __webpack_require__(914) -var eos = __webpack_require__(562) -var inherits = __webpack_require__(689) -var shift = __webpack_require__(475) - -var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from) - ? Buffer.from([0]) - : new Buffer([0]) - -var onuncork = function(self, fn) { - if (self._corked) self.once('uncork', fn) - else fn() -} - -var autoDestroy = function (self, err) { - if (self._autoDestroy) self.destroy(err) -} - -var destroyer = function(self, end) { - return function(err) { - if (err) autoDestroy(self, err.message === 'premature close' ? null : err) - else if (end && !self._ended) self.end() - } -} - -var end = function(ws, fn) { - if (!ws) return fn() - if (ws._writableState && ws._writableState.finished) return fn() - if (ws._writableState) return ws.end(fn) - ws.end() - fn() -} - -var toStreams2 = function(rs) { - return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs) -} - -var Duplexify = function(writable, readable, opts) { - if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts) - stream.Duplex.call(this, opts) - - this._writable = null - this._readable = null - this._readable2 = null - - this._autoDestroy = !opts || opts.autoDestroy !== false - this._forwardDestroy = !opts || opts.destroy !== false - this._forwardEnd = !opts || opts.end !== false - this._corked = 1 // start corked - this._ondrain = null - this._drained = false - this._forwarding = false - this._unwrite = null - this._unread = null - this._ended = false - - this.destroyed = false - - if (writable) this.setWritable(writable) - if (readable) this.setReadable(readable) -} - -inherits(Duplexify, stream.Duplex) - -Duplexify.obj = function(writable, readable, opts) { - if (!opts) opts = {} - opts.objectMode = true - opts.highWaterMark = 16 - return new Duplexify(writable, readable, opts) -} - -Duplexify.prototype.cork = function() { - if (++this._corked === 1) this.emit('cork') -} - -Duplexify.prototype.uncork = function() { - if (this._corked && --this._corked === 0) this.emit('uncork') -} - -Duplexify.prototype.setWritable = function(writable) { - if (this._unwrite) this._unwrite() - - if (this.destroyed) { - if (writable && writable.destroy) writable.destroy() - return - } - - if (writable === null || writable === false) { - this.end() - return - } - - var self = this - var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd)) - - var ondrain = function() { - var ondrain = self._ondrain - self._ondrain = null - if (ondrain) ondrain() - } - - var clear = function() { - self._writable.removeListener('drain', ondrain) - unend() - } - - if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks - - this._writable = writable - this._writable.on('drain', ondrain) - this._unwrite = clear - - this.uncork() // always uncork setWritable -} - -Duplexify.prototype.setReadable = function(readable) { - if (this._unread) this._unread() - - if (this.destroyed) { - if (readable && readable.destroy) readable.destroy() - return - } - - if (readable === null || readable === false) { - this.push(null) - this.resume() - return - } - - var self = this - var unend = eos(readable, {writable:false, readable:true}, destroyer(this)) - - var onreadable = function() { - self._forward() - } - - var onend = function() { - self.push(null) - } - - var clear = function() { - self._readable2.removeListener('readable', onreadable) - self._readable2.removeListener('end', onend) - unend() - } - - this._drained = true - this._readable = readable - this._readable2 = readable._readableState ? readable : toStreams2(readable) - this._readable2.on('readable', onreadable) - this._readable2.on('end', onend) - this._unread = clear - - this._forward() -} - -Duplexify.prototype._read = function() { - this._drained = true - this._forward() -} - -Duplexify.prototype._forward = function() { - if (this._forwarding || !this._readable2 || !this._drained) return - this._forwarding = true - - var data - - while (this._drained && (data = shift(this._readable2)) !== null) { - if (this.destroyed) continue - this._drained = this.push(data) - } - - this._forwarding = false -} - -Duplexify.prototype.destroy = function(err) { - if (this.destroyed) return - this.destroyed = true - - var self = this - process.nextTick(function() { - self._destroy(err) - }) -} - -Duplexify.prototype._destroy = function(err) { - if (err) { - var ondrain = this._ondrain - this._ondrain = null - if (ondrain) ondrain(err) - else this.emit('error', err) - } - - if (this._forwardDestroy) { - if (this._readable && this._readable.destroy) this._readable.destroy() - if (this._writable && this._writable.destroy) this._writable.destroy() - } - - this.emit('close') -} +/***/ (function(__unusedmodule, exports) { -Duplexify.prototype._write = function(data, enc, cb) { - if (this.destroyed) return cb() - if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb)) - if (data === SIGNAL_FLUSH) return this._finish(cb) - if (!this._writable) return cb() +"use strict"; - if (this._writable.write(data) === false) this._ondrain = cb - else cb() -} -Duplexify.prototype._finish = function(cb) { - var self = this - this.emit('preend') - onuncork(this, function() { - end(self._forwardEnd && self._writable, function() { - // haxx to not emit prefinish twice - if (self._writableState.prefinished === false) self._writableState.prefinished = true - self.emit('prefinish') - onuncork(self, cb) - }) - }) +exports.fromCallback = function (fn) { + return Object.defineProperty(function () { + if (typeof arguments[arguments.length - 1] === 'function') fn.apply(this, arguments) + else { + return new Promise((resolve, reject) => { + arguments[arguments.length] = (err, res) => { + if (err) return reject(err) + resolve(res) + } + arguments.length++ + fn.apply(this, arguments) + }) + } + }, 'name', { value: fn.name }) } -Duplexify.prototype.end = function(data, enc, cb) { - if (typeof data === 'function') return this.end(null, null, data) - if (typeof enc === 'function') return this.end(data, null, enc) - this._ended = true - if (data) this.write(data) - if (!this._writableState.ending) this.write(SIGNAL_FLUSH) - return stream.Writable.prototype.end.call(this, cb) +exports.fromPromise = function (fn) { + return Object.defineProperty(function () { + const cb = arguments[arguments.length - 1] + if (typeof cb !== 'function') return fn.apply(this, arguments) + else fn.apply(this, arguments).then(r => cb(null, r), cb) + }, 'name', { value: fn.name }) } -module.exports = Duplexify - /***/ }), /* 148 */, @@ -10863,8 +13204,168 @@ Promise.prototype.settle = function () { /***/ }), /* 150 */, -/* 151 */, -/* 152 */, +/* 151 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NOOP_TRACER = exports.NoopTracer = void 0; +var NoopSpan_1 = __webpack_require__(767); +/** + * No-op implementations of {@link Tracer}. + */ +var NoopTracer = /** @class */ (function () { + function NoopTracer() { + } + NoopTracer.prototype.getCurrentSpan = function () { + return NoopSpan_1.NOOP_SPAN; + }; + // startSpan starts a noop span. + NoopTracer.prototype.startSpan = function (name, options) { + return NoopSpan_1.NOOP_SPAN; + }; + NoopTracer.prototype.withSpan = function (span, fn) { + return fn(); + }; + NoopTracer.prototype.bind = function (target, span) { + return target; + }; + return NoopTracer; +}()); +exports.NoopTracer = NoopTracer; +exports.NOOP_TRACER = new NoopTracer(); +//# sourceMappingURL=NoopTracer.js.map + +/***/ }), +/* 152 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +var Stream = __webpack_require__(794).Stream; +var util = __webpack_require__(669); + +module.exports = DelayedStream; +function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; + + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; +} +util.inherits(DelayedStream, Stream); + +DelayedStream.create = function(source, options) { + var delayedStream = new this(); + + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; + } + + delayedStream.source = source; + + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; + + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); + } + + return delayedStream; +}; + +Object.defineProperty(DelayedStream.prototype, 'readable', { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; + } +}); + +DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); +}; + +DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); + } + + this.source.resume(); +}; + +DelayedStream.prototype.pause = function() { + this.source.pause(); +}; + +DelayedStream.prototype.release = function() { + this._released = true; + + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; +}; + +DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; +}; + +DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; + } + + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); + } + + this._bufferedEvents.push(args); +}; + +DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; + } + + if (this.dataSize <= this.maxDataSize) { + return; + } + + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' + this.emit('error', new Error(message)); +}; + + +/***/ }), /* 153 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -10884,8 +13385,8 @@ module.exports = function isCore(x) { const figgyPudding = __webpack_require__(122) const index = __webpack_require__(407) -const memo = __webpack_require__(69) -const write = __webpack_require__(544) +const memo = __webpack_require__(521) +const write = __webpack_require__(186) const to = __webpack_require__(371).to const PutOpts = figgyPudding({ @@ -10990,63 +13491,94 @@ function extractDescription (d) { /***/ }), /* 156 */, -/* 157 */, -/* 158 */ +/* 157 */ /***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; - -const {PassThrough} = __webpack_require__(794); - -module.exports = options => { - options = Object.assign({}, options); +var async = __webpack_require__(751) + , abort = __webpack_require__(566) + ; - const {array} = options; - let {encoding} = options; - const buffer = encoding === 'buffer'; - let objectMode = false; +// API +module.exports = iterate; - if (array) { - objectMode = !(encoding || buffer); - } else { - encoding = encoding || 'utf8'; - } +/** + * Iterates over each job object + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {object} state - current job status + * @param {function} callback - invoked when all elements processed + */ +function iterate(list, iterator, state, callback) +{ + // store current index + var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; + + state.jobs[key] = runJob(iterator, key, list[key], function(error, output) + { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) + { + return; + } - if (buffer) { - encoding = null; - } + // clean up jobs + delete state.jobs[key]; - let len = 0; - const ret = []; - const stream = new PassThrough({objectMode}); + if (error) + { + // don't process rest of the results + // stop still active jobs + // and reset the list + abort(state); + } + else + { + state.results[key] = output; + } - if (encoding) { - stream.setEncoding(encoding); - } + // return salvaged results + callback(error, state.results); + }); +} - stream.on('data', chunk => { - ret.push(chunk); +/** + * Runs iterator over provided job element + * + * @param {function} iterator - iterator to invoke + * @param {string|number} key - key/index of the element in the list of jobs + * @param {mixed} item - job description + * @param {function} callback - invoked after iterator is done with the job + * @returns {function|mixed} - job abort function or something else + */ +function runJob(iterator, key, item, callback) +{ + var aborter; - if (objectMode) { - len = ret.length; - } else { - len += chunk.length; - } - }); + // allow shortcut if iterator expects only two arguments + if (iterator.length == 2) + { + aborter = iterator(item, async(callback)); + } + // otherwise go with full three arguments + else + { + aborter = iterator(item, key, async(callback)); + } - stream.getBufferedValue = () => { - if (array) { - return ret; - } + return aborter; +} - return buffer ? Buffer.concat(ret, len) : ret.join(''); - }; - stream.getBufferedLength = () => len; +/***/ }), +/* 158 */ +/***/ (function(__unusedmodule, exports) { - return stream; -}; +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Time.js.map /***/ }), /* 159 */ @@ -11056,12 +13588,12 @@ module.exports = options => { // tar -c -const hlo = __webpack_require__(29) +const hlo = __webpack_require__(891) const Pack = __webpack_require__(415) const fs = __webpack_require__(747) const fsm = __webpack_require__(827) -const t = __webpack_require__(381) +const t = __webpack_require__(579) const path = __webpack_require__(622) const c = module.exports = (opt_, files, cb) => { @@ -11178,7 +13710,7 @@ var util = __webpack_require__(669); * Expose `debug()` as the module. */ -exports = module.exports = __webpack_require__(595); +exports = module.exports = __webpack_require__(778); exports.init = init; exports.log = log; exports.formatArgs = formatArgs; @@ -11564,7 +14096,7 @@ InternalDecoderCesu8.prototype.end = function() { /***/ (function(module, __unusedexports, __webpack_require__) { var once = __webpack_require__(49) -var eos = __webpack_require__(562) +var eos = __webpack_require__(3) var fs = __webpack_require__(747) // we only need fs to get the ReadStream and WriteStream prototypes var noop = function () {} @@ -11648,7 +14180,30 @@ module.exports = pump /***/ }), -/* 165 */, +/* 165 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Plugin.js.map + +/***/ }), /* 166 */, /* 167 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -11723,7 +14278,119 @@ Role.roleKeyName = Symbol('roles') /* 170 */, /* 171 */, /* 172 */, -/* 173 */, +/* 173 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rng = _interopRequireDefault(__webpack_require__(733)); + +var _stringify = _interopRequireDefault(__webpack_require__(855)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || (0, _stringify.default)(b); +} + +var _default = v1; +exports.default = _default; + +/***/ }), /* 174 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -11853,193 +14520,9 @@ module.exports = function spin (spinstr, spun) { /* 176 */, /* 177 */, /* 178 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -const path = __webpack_require__(622) -const fs = __webpack_require__(598) -const BB = __webpack_require__(440) -const gentleFs = __webpack_require__(311) -const linkIfExists = BB.promisify(gentleFs.linkIfExists) -const gentleFsBinLink = BB.promisify(gentleFs.binLink) -const open = BB.promisify(fs.open) -const close = BB.promisify(fs.close) -const read = BB.promisify(fs.read, {multiArgs: true}) -const chmod = BB.promisify(fs.chmod) -const readFile = BB.promisify(fs.readFile) -const writeFileAtomic = BB.promisify(__webpack_require__(182)) -const normalize = __webpack_require__(787) - -module.exports = BB.promisify(binLinks) - -function binLinks (pkg, folder, global, opts, cb) { - pkg = normalize(pkg) - folder = path.resolve(folder) - - // if it's global, and folder is in {prefix}/node_modules, - // then bins are in {prefix}/bin - // otherwise, then bins are in folder/../.bin - var parent = pkg.name && pkg.name[0] === '@' ? path.dirname(path.dirname(folder)) : path.dirname(folder) - var gnm = global && opts.globalDir - var gtop = parent === gnm - - opts.log.info('linkStuff', opts.pkgId) - opts.log.silly('linkStuff', opts.pkgId, 'has', parent, 'as its parent node_modules') - if (global) opts.log.silly('linkStuff', opts.pkgId, 'is part of a global install') - if (gnm) opts.log.silly('linkStuff', opts.pkgId, 'is installed into a global node_modules') - if (gtop) opts.log.silly('linkStuff', opts.pkgId, 'is installed into the top-level global node_modules') - - return BB.join( - linkBins(pkg, folder, parent, gtop, opts), - linkMans(pkg, folder, parent, gtop, opts) - ).asCallback(cb) -} - -function isHashbangFile (file) { - return open(file, 'r').then(fileHandle => { - return read(fileHandle, Buffer.alloc(2), 0, 2, 0).spread((_, buf) => { - if (!hasHashbang(buf)) return [] - return read(fileHandle, Buffer.alloc(2048), 0, 2048, 0) - }).spread((_, buf) => buf && hasCR(buf), /* istanbul ignore next */ () => false) - .finally(() => close(fileHandle)) - }).catch(/* istanbul ignore next */ () => false) -} - -function hasHashbang (buf) { - const str = buf.toString() - return str.slice(0, 2) === '#!' -} - -function hasCR (buf) { - return /^#![^\n]+\r\n/.test(buf) -} - -function dos2Unix (file) { - return readFile(file, 'utf8').then(content => { - return writeFileAtomic(file, content.replace(/^(#![^\n]+)\r\n/, '$1\n')) - }) -} - -function getLinkOpts (opts, gently) { - return Object.assign({}, opts, { gently: gently }) -} - -function linkBins (pkg, folder, parent, gtop, opts) { - if (!pkg.bin || (!gtop && path.basename(parent) !== 'node_modules')) { - return - } - var linkOpts = getLinkOpts(opts, gtop && folder) - var execMode = parseInt('0777', 8) & (~opts.umask) - var binRoot = gtop ? opts.globalBin - : path.resolve(parent, '.bin') - opts.log.verbose('linkBins', [pkg.bin, binRoot, gtop]) - - return BB.map(Object.keys(pkg.bin), bin => { - var dest = path.resolve(binRoot, bin) - var src = path.resolve(folder, pkg.bin[bin]) - - /* istanbul ignore if - that unpossible */ - if (src.indexOf(folder) !== 0) { - throw new Error('invalid bin entry for package ' + - pkg._id + '. key=' + bin + ', value=' + pkg.bin[bin]) - } - - return linkBin(src, dest, linkOpts).then(() => { - // bins should always be executable. - // XXX skip chmod on windows? - return chmod(src, execMode) - }).then(() => { - return isHashbangFile(src) - }).then(isHashbang => { - if (!isHashbang) return - opts.log.silly('linkBins', 'Converting line endings of hashbang file:', src) - return dos2Unix(src) - }).then(() => { - if (!gtop) return - var dest = path.resolve(binRoot, bin) - var out = opts.parseable - ? dest + '::' + src + ':BINFILE' - : dest + ' -> ' + src - - if (!opts.json && !opts.parseable) { - opts.log.clearProgress() - console.log(out) - opts.log.showProgress() - } - }).catch(err => { - /* istanbul ignore next */ - if (err.code === 'ENOENT' && opts.ignoreScripts) return - throw err - }) - }) -} - -function linkBin (from, to, opts) { - // do not clobber global bins - if (opts.globalBin && to.indexOf(opts.globalBin) === 0) { - opts.clobberLinkGently = true - } - return gentleFsBinLink(from, to, opts) -} - -function linkMans (pkg, folder, parent, gtop, opts) { - if (!pkg.man || !gtop || process.platform === 'win32') return - - var manRoot = path.resolve(opts.prefix, 'share', 'man') - opts.log.verbose('linkMans', 'man files are', pkg.man, 'in', manRoot) - - // make sure that the mans are unique. - // otherwise, if there are dupes, it'll fail with EEXIST - var set = pkg.man.reduce(function (acc, man) { - if (typeof man !== 'string') { - return acc - } - const cleanMan = path.join('/', man).replace(/\\|:/g, '/').substr(1) - acc[path.basename(man)] = cleanMan - return acc - }, {}) - var manpages = pkg.man.filter(function (man) { - if (typeof man !== 'string') { - return false - } - const cleanMan = path.join('/', man).replace(/\\|:/g, '/').substr(1) - return set[path.basename(man)] === cleanMan - }) - - return BB.map(manpages, man => { - opts.log.silly('linkMans', 'preparing to link', man) - var parseMan = man.match(/(.*\.([0-9]+)(\.gz)?)$/) - if (!parseMan) { - throw new Error( - man + ' is not a valid name for a man file. ' + - 'Man files must end with a number, ' + - 'and optionally a .gz suffix if they are compressed.' - ) - } - - var stem = parseMan[1] - var sxn = parseMan[2] - var bn = path.basename(stem) - var manSrc = path.resolve(folder, man) - /* istanbul ignore if - that unpossible */ - if (manSrc.indexOf(folder) !== 0) { - throw new Error('invalid man entry for package ' + - pkg._id + '. man=' + manSrc) - } - - var manDest = path.join(manRoot, 'man' + sxn, bn) - - // man pages should always be clobbering gently, because they are - // only installed for top-level global packages, so never destroy - // a link if it doesn't point into the folder we're linking - opts.clobberLinkGently = true - - return linkIfExists(manSrc, manDest, getLinkOpts(opts, gtop && folder)) - }) -} +/***/ (function(module) { +module.exports = ["389-exception","Autoconf-exception-2.0","Autoconf-exception-3.0","Bison-exception-2.2","Bootloader-exception","Classpath-exception-2.0","CLISP-exception-2.0","DigiRule-FOSS-exception","eCos-exception-2.0","Fawkes-Runtime-exception","FLTK-exception","Font-exception-2.0","freertos-exception-2.0","GCC-exception-2.0","GCC-exception-3.1","gnu-javamail-exception","GPL-3.0-linking-exception","GPL-3.0-linking-source-exception","GPL-CC-1.0","i2p-gpl-java-exception","Libtool-exception","Linux-syscall-note","LLVM-exception","LZMA-exception","mif-exception","Nokia-Qt-exception-1.1","OCaml-LGPL-linking-exception","OCCT-exception-1.0","OpenJDK-assembly-exception-1.0","openvpn-openssl-exception","PS-or-PDF-font-exception-20170817","Qt-GPL-exception-1.0","Qt-LGPL-exception-1.1","Qwt-exception-1.0","Swift-exception","u-boot-exception-2.0","Universal-FOSS-exception-1.0","WxWindows-exception-3.1"]; /***/ }), /* 179 */, @@ -12047,43 +14530,43 @@ function linkMans (pkg, folder, parent, gtop, opts) { /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.run = void 0; -const core_1 = __webpack_require__(470); -const expo_1 = __webpack_require__(265); -const install_1 = __webpack_require__(655); -const system_1 = __webpack_require__(913); -function run() { - return __awaiter(this, void 0, void 0, function* () { - const path = yield install_1.install({ - version: core_1.getInput('expo-version') || 'latest', - packager: core_1.getInput('expo-packager') || 'yarn', - cache: (core_1.getInput('expo-cache') || 'false') === 'true', - cacheKey: core_1.getInput('expo-cache-key') || undefined, - }); - core_1.addPath(path); - yield expo_1.authenticate({ - token: core_1.getInput('expo-token') || undefined, - username: core_1.getInput('expo-username') || undefined, - password: core_1.getInput('expo-password') || undefined, - }); - const shouldPatchWatchers = core_1.getInput('expo-patch-watchers') || 'true'; - if (shouldPatchWatchers !== 'false') { - yield system_1.patchWatchers(); - } - }); -} -exports.run = run; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.run = void 0; +const core_1 = __webpack_require__(470); +const expo_1 = __webpack_require__(265); +const install_1 = __webpack_require__(655); +const system_1 = __webpack_require__(913); +function run() { + return __awaiter(this, void 0, void 0, function* () { + const path = yield install_1.install({ + version: core_1.getInput('expo-version') || 'latest', + packager: core_1.getInput('expo-packager') || 'yarn', + cache: (core_1.getInput('expo-cache') || 'false') === 'true', + cacheKey: core_1.getInput('expo-cache-key') || undefined, + }); + core_1.addPath(path); + yield expo_1.authenticate({ + token: core_1.getInput('expo-token') || undefined, + username: core_1.getInput('expo-username') || undefined, + password: core_1.getInput('expo-password') || undefined, + }); + const shouldPatchWatchers = core_1.getInput('expo-patch-watchers') || 'true'; + if (shouldPatchWatchers !== 'false') { + yield system_1.patchWatchers(); + } + }); +} +exports.run = run; /***/ }), @@ -12093,12 +14576,12 @@ exports.run = run; "use strict"; -const BB = __webpack_require__(440) +const BB = __webpack_require__(489) -const cacache = __webpack_require__(764) -const cacheKey = __webpack_require__(819) -const Fetcher = __webpack_require__(488) -const git = __webpack_require__(40) +const cacache = __webpack_require__(426) +const cacheKey = __webpack_require__(279) +const Fetcher = __webpack_require__(404) +const git = __webpack_require__(729) const mkdirp = BB.promisify(__webpack_require__(626)) const pickManifest = __webpack_require__(55) const optCheck = __webpack_require__(420) @@ -12108,7 +14591,7 @@ const PassThrough = __webpack_require__(794).PassThrough const path = __webpack_require__(622) const pipe = BB.promisify(__webpack_require__(371).pipe) const rimraf = BB.promisify(__webpack_require__(985)) -const uniqueFilename = __webpack_require__(106) +const uniqueFilename = __webpack_require__(94) // `git` dependencies are fetched from git repositories and packed up. const fetchGit = module.exports = Object.create(null) @@ -12292,7 +14775,7 @@ var activeFiles = {} /* istanbul ignore next */ var threadId = (function getId () { try { - var workerThreads = __webpack_require__(754) + var workerThreads = __webpack_require__(13) /// if we are in main thread, this is set to `0` return workerThreads.threadId @@ -12675,7 +15158,7 @@ module.exports = move var nodeFs = __webpack_require__(747) var rimraf = __webpack_require__(993) -var validate = __webpack_require__(463) +var validate = __webpack_require__(997) var copy = __webpack_require__(555) var RunQueue = __webpack_require__(399) var extend = Object.assign || __webpack_require__(669)._extend @@ -12763,7 +15246,7 @@ function move (from, to, opts) { "use strict"; -const BB = __webpack_require__(440) +const BB = __webpack_require__(489) const contentPath = __webpack_require__(969) const figgyPudding = __webpack_require__(122) @@ -12960,169 +15443,172 @@ function integrityError (sri, path) { /***/ }), /* 186 */ -/***/ (function(module) { +/***/ (function(module, __unusedexports, __webpack_require__) { -/** - * Helpers. - */ +"use strict"; -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ +const BB = __webpack_require__(489) -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; +const contentPath = __webpack_require__(969) +const fixOwner = __webpack_require__(133) +const fs = __webpack_require__(598) +const moveFile = __webpack_require__(201) +const PassThrough = __webpack_require__(794).PassThrough +const path = __webpack_require__(622) +const pipe = BB.promisify(__webpack_require__(371).pipe) +const rimraf = BB.promisify(__webpack_require__(503)) +const ssri = __webpack_require__(951) +const to = __webpack_require__(371).to +const uniqueFilename = __webpack_require__(94) +const Y = __webpack_require__(945) -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ +const writeFileAsync = BB.promisify(fs.writeFile) -function parse(str) { - str = String(str); - if (str.length > 100) { - return; +module.exports = write +function write (cache, data, opts) { + opts = opts || {} + if (opts.algorithms && opts.algorithms.length > 1) { + throw new Error( + Y`opts.algorithms only supports a single algorithm for now` + ) } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; + if (typeof opts.size === 'number' && data.length !== opts.size) { + return BB.reject(sizeError(opts.size, data.length)) } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; + const sri = ssri.fromData(data, { + algorithms: opts.algorithms + }) + if (opts.integrity && !ssri.checkData(data, opts.integrity, opts)) { + return BB.reject(checksumError(opts.integrity, sri)) } + return BB.using(makeTmp(cache, opts), tmp => ( + writeFileAsync( + tmp.target, data, { flag: 'wx' } + ).then(() => ( + moveToDestination(tmp, cache, sri, opts) + )) + )).then(() => ({ integrity: sri, size: data.length })) } -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; +module.exports.stream = writeStream +function writeStream (cache, opts) { + opts = opts || {} + const inputStream = new PassThrough() + let inputErr = false + function errCheck () { + if (inputErr) { throw inputErr } } - return ms + 'ms'; + + let allDone + const ret = to((c, n, cb) => { + if (!allDone) { + allDone = handleContent(inputStream, cache, opts, errCheck) + } + inputStream.write(c, n, cb) + }, cb => { + inputStream.end(() => { + if (!allDone) { + const e = new Error(Y`Cache input stream was empty`) + e.code = 'ENODATA' + return ret.emit('error', e) + } + allDone.then(res => { + res.integrity && ret.emit('integrity', res.integrity) + res.size !== null && ret.emit('size', res.size) + cb() + }, e => { + ret.emit('error', e) + }) + }) + }) + ret.once('error', e => { + inputErr = e + }) + return ret } -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +function handleContent (inputStream, cache, opts, errCheck) { + return BB.using(makeTmp(cache, opts), tmp => { + errCheck() + return pipeToTmp( + inputStream, cache, tmp.target, opts, errCheck + ).then(res => { + return moveToDestination( + tmp, cache, res.integrity, opts, errCheck + ).then(() => res) + }) + }) +} -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - return ms + ' ms'; +function pipeToTmp (inputStream, cache, tmpTarget, opts, errCheck) { + return BB.resolve().then(() => { + let integrity + let size + const hashStream = ssri.integrityStream({ + integrity: opts.integrity, + algorithms: opts.algorithms, + size: opts.size + }).on('integrity', s => { + integrity = s + }).on('size', s => { + size = s + }) + const outStream = fs.createWriteStream(tmpTarget, { + flags: 'wx' + }) + errCheck() + return pipe(inputStream, hashStream, outStream).then(() => { + return { integrity, size } + }).catch(err => { + return rimraf(tmpTarget).then(() => { throw err }) + }) + }) } -/** - * Pluralization helper. - */ +function makeTmp (cache, opts) { + const tmpTarget = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) + return fixOwner.mkdirfix( + cache, path.dirname(tmpTarget) + ).then(() => ({ + target: tmpTarget, + moved: false + })).disposer(tmp => (!tmp.moved && rimraf(tmp.target))) +} -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +function moveToDestination (tmp, cache, sri, opts, errCheck) { + errCheck && errCheck() + const destination = contentPath(cache, sri) + const destDir = path.dirname(destination) + + return fixOwner.mkdirfix( + cache, destDir + ).then(() => { + errCheck && errCheck() + return moveFile(tmp.target, destination) + }).then(() => { + errCheck && errCheck() + tmp.moved = true + return fixOwner.chownr(cache, destination) + }) +} + +function sizeError (expected, found) { + var err = new Error(Y`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`) + err.expected = expected + err.found = found + err.code = 'EBADSIZE' + return err +} + +function checksumError (expected, found) { + var err = new Error(Y`Integrity check failed: + Wanted: ${expected} + Found: ${found}`) + err.code = 'EINTEGRITY' + err.expected = expected + err.found = found + return err } @@ -14058,21 +16544,54 @@ module.exports = require("querystring"); /* 195 */, /* 196 */, /* 197 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; -// Buffer in node 4.x < 4.5.0 doesn't have working Buffer.from -// or Buffer.alloc, and Buffer in node 10 deprecated the ctor. -// .M, this is fine .\^/M.. -let B = Buffer -/* istanbul ignore next */ -if (!B.alloc) { - B = __webpack_require__(918).Buffer +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(__webpack_require__(676)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; } -module.exports = B +var _default = parse; +exports.default = _default; /***/ }), /* 198 */ @@ -14103,13 +16622,70 @@ module.exports = function () { /***/ }), -/* 201 */, +/* 201 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const fs = __webpack_require__(598) +const BB = __webpack_require__(489) +const chmod = BB.promisify(fs.chmod) +const unlink = BB.promisify(fs.unlink) +let move +let pinflight + +module.exports = moveFile +function moveFile (src, dest) { + // This isn't quite an fs.rename -- the assumption is that + // if `dest` already exists, and we get certain errors while + // trying to move it, we should just not bother. + // + // In the case of cache corruption, users will receive an + // EINTEGRITY error elsewhere, and can remove the offending + // content their own way. + // + // Note that, as the name suggests, this strictly only supports file moves. + return BB.fromNode(cb => { + fs.link(src, dest, err => { + if (err) { + if (err.code === 'EEXIST' || err.code === 'EBUSY') { + // file already exists, so whatever + } else if (err.code === 'EPERM' && process.platform === 'win32') { + // file handle stayed open even past graceful-fs limits + } else { + return cb(err) + } + } + return cb() + }) + }).then(() => { + // content should never change for any reason, so make it read-only + return BB.join(unlink(src), process.platform !== 'win32' && chmod(dest, '0444')) + }).catch(() => { + if (!pinflight) { pinflight = __webpack_require__(593) } + return pinflight('cacache-move-file:' + dest, () => { + return BB.promisify(fs.stat)(dest).catch(err => { + if (err.code !== 'ENOENT') { + // Something else is wrong here. Bail bail bail + throw err + } + // file doesn't already exist! let's try a rename -> copy fallback + if (!move) { move = __webpack_require__(184) } + return move(src, dest, { BB, fs }) + }) + }) + }) +} + + +/***/ }), /* 202 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -var process = __webpack_require__(348) +var process = __webpack_require__(356) try { module.exports = setImmediate } catch (ex) { @@ -14144,16 +16720,16 @@ try { // // ignored entries get .resume() called on them straight away -const warner = __webpack_require__(796) +const warner = __webpack_require__(571) const path = __webpack_require__(622) -const Header = __webpack_require__(58) +const Header = __webpack_require__(725) const EE = __webpack_require__(614) const Yallist = __webpack_require__(612) const maxMetaEntrySize = 1024 * 1024 const Entry = __webpack_require__(589) const Pax = __webpack_require__(480) const zlib = __webpack_require__(268) -const Buffer = __webpack_require__(197) +const Buffer = __webpack_require__(921) const gzipHeader = Buffer.from([0x1f, 0x8b]) const STATE = Symbol('state') @@ -14669,7 +17245,24 @@ exports.SocksClientState = SocksClientState; /* 207 */, /* 208 */, /* 209 */, -/* 210 */, +/* 210 */ +/***/ (function(__unusedmodule, exports) { + +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + exports.stripBOM = function(str) { + if (str[0] === '\uFEFF') { + return str.substring(1); + } else { + return str; + } + }; + +}).call(this); + + +/***/ }), /* 211 */ /***/ (function(module) { @@ -14682,10 +17275,10 @@ module.exports = require("https"); "use strict"; -const BB = __webpack_require__(440) +const BB = __webpack_require__(489) -const cacache = __webpack_require__(764) -const Fetcher = __webpack_require__(488) +const cacache = __webpack_require__(426) +const Fetcher = __webpack_require__(404) const fs = __webpack_require__(747) const pipe = BB.promisify(__webpack_require__(371).pipe) const through = __webpack_require__(371).through @@ -14764,7 +17357,7 @@ Fetcher.impl(fetchFile, { /* 213 */ /***/ (function(module) { -module.exports = require("timers"); +module.exports = require("punycode"); /***/ }), /* 214 */, @@ -14852,12337 +17445,12298 @@ module.exports = safer /***/ }), -/* 216 */ -/***/ (function(module) { +/* 216 */, +/* 217 */, +/* 218 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +module.exports = __webpack_require__(489).promisify(__webpack_require__(687)) -module.exports = [["0","\u0000",127],["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"],["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"],["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"],["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5],["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"],["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18],["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7],["8361","긝",18,"긲긳긵긶긹긻긼"],["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8],["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8],["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18],["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"],["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4],["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"],["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"],["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"],["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10],["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"],["8741","놞",9,"놩",15],["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"],["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4],["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4],["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"],["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"],["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"],["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"],["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15],["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"],["8a61","둧",4,"둭",18,"뒁뒂"],["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"],["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"],["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8],["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18],["8c41","똀",15,"똒똓똕똖똗똙",4],["8c61","똞",6,"똦",5,"똭",6,"똵",5],["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16],["8d41","뛃",16,"뛕",8],["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"],["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"],["8e41","랟랡",6,"랪랮",5,"랶랷랹",8],["8e61","럂",4,"럈럊",19],["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7],["8f41","뢅",7,"뢎",17],["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4],["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5],["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"],["9061","륾",5,"릆릈릋릌릏",15],["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"],["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5],["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5],["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6],["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"],["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4],["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"],["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"],["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8],["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"],["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8],["9461","봞",5,"봥",6,"봭",12],["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24],["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"],["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"],["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14],["9641","뺸",23,"뻒뻓"],["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8],["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44],["9741","뾃",16,"뾕",8],["9761","뾞",17,"뾱",7],["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"],["9841","쁀",16,"쁒",5,"쁙쁚쁛"],["9861","쁝쁞쁟쁡",6,"쁪",15],["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"],["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"],["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"],["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"],["9a41","숤숥숦숧숪숬숮숰숳숵",16],["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"],["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"],["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8],["9b61","쌳",17,"썆",7],["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"],["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5],["9c61","쏿",8,"쐉",6,"쐑",9],["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12],["9d41","쒪",13,"쒹쒺쒻쒽",8],["9d61","쓆",25],["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"],["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"],["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"],["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"],["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"],["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"],["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"],["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"],["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13],["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"],["a141","좥좦좧좩",18,"좾좿죀죁"],["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"],["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃­―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"],["a241","줐줒",5,"줙",18],["a261","줭",6,"줵",18],["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"],["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"],["a361","즑",6,"즚즜즞",16],["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"],["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"],["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12],["a481","쨦쨧쨨쨪",28,"ㄱ",93],["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"],["a561","쩫",17,"쩾",5,"쪅쪆"],["a581","쪇",16,"쪙",14,"ⅰ",9],["a5b0","Ⅰ",9],["a5c1","Α",16,"Σ",6],["a5e1","α",16,"σ",6],["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"],["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6],["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7],["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7],["a761","쬪",22,"쭂쭃쭄"],["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"],["a841","쭭",10,"쭺",14],["a861","쮉",18,"쮝",6],["a881","쮤",19,"쮹",11,"ÆЪĦ"],["a8a6","IJ"],["a8a8","ĿŁØŒºÞŦŊ"],["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"],["a941","쯅",14,"쯕",10],["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18],["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"],["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"],["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"],["aa81","챳챴챶",29,"ぁ",82],["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"],["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5],["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85],["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"],["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4],["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25],["acd1","а",5,"ёж",25],["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7],["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"],["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"],["ae41","췆",5,"췍췎췏췑",16],["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4],["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"],["af41","츬츭츮츯츲츴츶",19],["af61","칊",13,"칚칛칝칞칢",5,"칪칬"],["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"],["b041","캚",5,"캢캦",5,"캮",12],["b061","캻",5,"컂",19],["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"],["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"],["b161","켥",6,"켮켲",5,"켹",11],["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"],["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"],["b261","쾎",18,"쾢",5,"쾩"],["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"],["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"],["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5],["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"],["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5],["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"],["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"],["b541","킕",14,"킦킧킩킪킫킭",5],["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4],["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"],["b641","턅",7,"턎",17],["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"],["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"],["b741","텮",13,"텽",6,"톅톆톇톉톊"],["b761","톋",20,"톢톣톥톦톧"],["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"],["b841","퇐",7,"퇙",17],["b861","퇫",8,"퇵퇶퇷퇹",13],["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"],["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"],["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"],["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"],["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"],["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5],["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"],["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"],["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"],["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"],["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"],["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"],["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"],["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"],["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13],["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"],["be41","퐸",7,"푁푂푃푅",14],["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"],["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"],["bf41","풞",10,"풪",14],["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"],["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"],["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5],["c061","픞",25],["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"],["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"],["c161","햌햍햎햏햑",19,"햦햧"],["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"],["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"],["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"],["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"],["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4],["c361","홢",4,"홨홪",5,"홲홳홵",11],["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"],["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"],["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4],["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"],["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"],["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4],["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"],["c641","힍힎힏힑",6,"힚힜힞",5],["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"],["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"],["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"],["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"],["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"],["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"],["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"],["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"],["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"],["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"],["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"],["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"],["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"],["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"],["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"],["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"],["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"],["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"],["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"],["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"],["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"],["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"],["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"],["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"],["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"],["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"],["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"],["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"],["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"],["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"],["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"],["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"],["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"],["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"],["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"],["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"],["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"],["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"],["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"],["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"],["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"],["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"],["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"],["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"],["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"],["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"],["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"],["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"],["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"],["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"],["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"],["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"],["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"],["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"],["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"]]; /***/ }), -/* 217 */, -/* 218 */, /* 219 */, /* 220 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ (function(__unusedmodule, exports) { "use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var util = __webpack_require__(248); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; - -function MappingPromiseArray(promises, fn, limit, _filter) { - this.constructor$(promises); - this._promise._captureStackTrace(); - var context = Promise._getContext(); - this._callback = util.contextBind(context, fn); - this._preservedValues = _filter === INTERNAL - ? new Array(this.length()) - : null; - this._limit = limit; - this._inFlight = 0; - this._queue = []; - async.invoke(this._asyncInit, this, undefined); - if (util.isArray(promises)) { - for (var i = 0; i < promises.length; ++i) { - var maybePromise = promises[i]; - if (maybePromise instanceof Promise) { - maybePromise.suppressUnhandledRejections(); - } - } - } -} -util.inherits(MappingPromiseArray, PromiseArray); +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SpanOptions.js.map -MappingPromiseArray.prototype._asyncInit = function() { - this._init$(undefined, -2); -}; +/***/ }), +/* 221 */, +/* 222 */, +/* 223 */, +/* 224 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -MappingPromiseArray.prototype._init = function () {}; +"use strict"; -MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { - var values = this._values; - var length = this.length(); - var preservedValues = this._preservedValues; - var limit = this._limit; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NOOP_TRACER_PROVIDER = exports.NoopTracerProvider = void 0; +var NoopTracer_1 = __webpack_require__(151); +/** + * An implementation of the {@link TracerProvider} which returns an impotent + * Tracer for all calls to `getTracer`. + * + * All operations are no-op. + */ +var NoopTracerProvider = /** @class */ (function () { + function NoopTracerProvider() { + } + NoopTracerProvider.prototype.getTracer = function (_name, _version) { + return NoopTracer_1.NOOP_TRACER; + }; + return NoopTracerProvider; +}()); +exports.NoopTracerProvider = NoopTracerProvider; +exports.NOOP_TRACER_PROVIDER = new NoopTracerProvider(); +//# sourceMappingURL=NoopTracerProvider.js.map - if (index < 0) { - index = (index * -1) - 1; - values[index] = value; - if (limit >= 1) { - this._inFlight--; - this._drainQueue(); - if (this._isResolved()) return true; - } - } else { - if (limit >= 1 && this._inFlight >= limit) { - values[index] = value; - this._queue.push(index); - return false; - } - if (preservedValues !== null) preservedValues[index] = value; +/***/ }), +/* 225 */, +/* 226 */ +/***/ (function(__unusedmodule, exports) { - var promise = this._promise; - var callback = this._callback; - var receiver = promise._boundValue(); - promise._pushContext(); - var ret = tryCatch(callback).call(receiver, value, index, length); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - preservedValues !== null ? "Promise.filter" : "Promise.map", - promise - ); - if (ret === errorObj) { - this._reject(ret.e); - return true; - } +"use strict"; - var maybePromise = tryConvertToPromise(ret, this._promise); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - if (limit >= 1) this._inFlight++; - values[index] = maybePromise; - maybePromise._proxy(this, (index + 1) * -1); - return false; - } else if (((bitField & 33554432) !== 0)) { - ret = maybePromise._value(); - } else if (((bitField & 16777216) !== 0)) { - this._reject(maybePromise._reason()); - return true; - } else { - this._cancel(); - return true; - } - } - values[index] = ret; +Object.defineProperty(exports, "__esModule", { value: true }); +class BasicCredentialHandler { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + options.headers['Authorization'] = + 'Basic ' + + Buffer.from(this.username + ':' + this.password).toString('base64'); + } + // This handler cannot handle 401 + canHandleAuthentication(response) { + return false; } - var totalResolved = ++this._totalResolved; - if (totalResolved >= length) { - if (preservedValues !== null) { - this._filter(values, preservedValues); - } else { - this._resolve(values); - } - return true; + handleAuthentication(httpClient, requestInfo, objs) { + return null; } - return false; -}; - -MappingPromiseArray.prototype._drainQueue = function () { - var queue = this._queue; - var limit = this._limit; - var values = this._values; - while (queue.length > 0 && this._inFlight < limit) { - if (this._isResolved()) return; - var index = queue.pop(); - this._promiseFulfilled(values[index], index); +} +exports.BasicCredentialHandler = BasicCredentialHandler; +class BearerCredentialHandler { + constructor(token) { + this.token = token; } -}; - -MappingPromiseArray.prototype._filter = function (booleans, values) { - var len = values.length; - var ret = new Array(len); - var j = 0; - for (var i = 0; i < len; ++i) { - if (booleans[i]) ret[j++] = values[i]; + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + options.headers['Authorization'] = 'Bearer ' + this.token; } - ret.length = j; - this._resolve(ret); -}; - -MappingPromiseArray.prototype.preservedValues = function () { - return this._preservedValues; -}; - -function map(promises, fn, options, _filter) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); + // This handler cannot handle 401 + canHandleAuthentication(response) { + return false; } - - var limit = 0; - if (options !== undefined) { - if (typeof options === "object" && options !== null) { - if (typeof options.concurrency !== "number") { - return Promise.reject( - new TypeError("'concurrency' must be a number but it is " + - util.classString(options.concurrency))); - } - limit = options.concurrency; - } else { - return Promise.reject(new TypeError( - "options argument must be an object but it is " + - util.classString(options))); - } + handleAuthentication(httpClient, requestInfo, objs) { + return null; + } +} +exports.BearerCredentialHandler = BearerCredentialHandler; +class PersonalAccessTokenCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + options.headers['Authorization'] = + 'Basic ' + Buffer.from('PAT:' + this.token).toString('base64'); + } + // This handler cannot handle 401 + canHandleAuthentication(response) { + return false; + } + handleAuthentication(httpClient, requestInfo, objs) { + return null; } - limit = typeof limit === "number" && - isFinite(limit) && limit >= 1 ? limit : 0; - return new MappingPromiseArray(promises, fn, limit, _filter).promise(); } +exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; -Promise.prototype.map = function (fn, options) { - return map(this, fn, options, null); -}; -Promise.map = function (promises, fn, options, _filter) { - return map(promises, fn, options, _filter); -}; +/***/ }), +/* 227 */, +/* 228 */, +/* 229 */ +/***/ (function(__unusedmodule, exports) { +"use strict"; -}; +Object.defineProperty(exports, '__esModule', { value: true }); -/***/ }), -/* 221 */, -/* 222 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * A static-key-based credential that supports updating + * the underlying key value. + */ +var AzureKeyCredential = /** @class */ (function () { + /** + * Create an instance of an AzureKeyCredential for use + * with a service client. + * + * @param key the initial value of the key to use in authentication + */ + function AzureKeyCredential(key) { + if (!key) { + throw new Error("key must be a non-empty string"); + } + this._key = key; + } + Object.defineProperty(AzureKeyCredential.prototype, "key", { + /** + * The value of the key to be used in authentication + */ + get: function () { + return this._key; + }, + enumerable: false, + configurable: true + }); + /** + * Change the value of the key. + * + * Updates will take effect upon the next request after + * updating the key value. + * + * @param newKey the new key value to be used + */ + AzureKeyCredential.prototype.update = function (newKey) { + this._key = newKey; + }; + return AzureKeyCredential; +}()); -var log = console.log; -var crypto = __webpack_require__(417); -var $ = __webpack_require__(144); -var lmhashbuf = __webpack_require__(826).lmhashbuf; -var nthashbuf = __webpack_require__(826).nthashbuf; - - -function encodeType1(hostname, ntdomain) { - hostname = hostname.toUpperCase(); - ntdomain = ntdomain.toUpperCase(); - var hostnamelen = Buffer.byteLength(hostname, 'ascii'); - var ntdomainlen = Buffer.byteLength(ntdomain, 'ascii'); - - var pos = 0; - var buf = new Buffer(32 + hostnamelen + ntdomainlen); - - buf.write('NTLMSSP', pos, 7, 'ascii'); // byte protocol[8]; - pos += 7; - buf.writeUInt8(0, pos); - pos++; - - buf.writeUInt8(0x01, pos); // byte type; - pos++; - - buf.fill(0x00, pos, pos + 3); // byte zero[3]; - pos += 3; - - buf.writeUInt16LE(0xb203, pos); // short flags; - pos += 2; - - buf.fill(0x00, pos, pos + 2); // byte zero[2]; - pos += 2; - - buf.writeUInt16LE(ntdomainlen, pos); // short dom_len; - pos += 2; - buf.writeUInt16LE(ntdomainlen, pos); // short dom_len; - pos += 2; - - var ntdomainoff = 0x20 + hostnamelen; - buf.writeUInt16LE(ntdomainoff, pos); // short dom_off; - pos += 2; - - buf.fill(0x00, pos, pos + 2); // byte zero[2]; - pos += 2; - - buf.writeUInt16LE(hostnamelen, pos); // short host_len; - pos += 2; - buf.writeUInt16LE(hostnamelen, pos); // short host_len; - pos += 2; - - buf.writeUInt16LE(0x20, pos); // short host_off; - pos += 2; - - buf.fill(0x00, pos, pos + 2); // byte zero[2]; - pos += 2; - - buf.write(hostname, 0x20, hostnamelen, 'ascii'); - buf.write(ntdomain, ntdomainoff, ntdomainlen, 'ascii'); - - return buf; -} - - -/* - * - */ -function decodeType2(buf) -{ - var proto = buf.toString('ascii', 0, 7); - if (buf[7] !== 0x00 || proto !== 'NTLMSSP') - throw new Error('magic was not NTLMSSP'); - - var type = buf.readUInt8(8); - if (type !== 0x02) - throw new Error('message was not NTLMSSP type 0x02'); - - //var msg_len = buf.readUInt16LE(16); - - //var flags = buf.readUInt16LE(20); - - var nonce = buf.slice(24, 32); - return nonce; -} - -function encodeType3(username, hostname, ntdomain, nonce, password) { - hostname = hostname.toUpperCase(); - ntdomain = ntdomain.toUpperCase(); - - var lmh = new Buffer(21); - lmhashbuf(password).copy(lmh); - lmh.fill(0x00, 16); // null pad to 21 bytes - var nth = new Buffer(21); - nthashbuf(password).copy(nth); - nth.fill(0x00, 16); // null pad to 21 bytes - - var lmr = makeResponse(lmh, nonce); - var ntr = makeResponse(nth, nonce); - - var usernamelen = Buffer.byteLength(username, 'ucs2'); - var hostnamelen = Buffer.byteLength(hostname, 'ucs2'); - var ntdomainlen = Buffer.byteLength(ntdomain, 'ucs2'); - var lmrlen = 0x18; - var ntrlen = 0x18; - - var ntdomainoff = 0x40; - var usernameoff = ntdomainoff + ntdomainlen; - var hostnameoff = usernameoff + usernamelen; - var lmroff = hostnameoff + hostnamelen; - var ntroff = lmroff + lmrlen; - - var pos = 0; - var msg_len = 64 + ntdomainlen + usernamelen + hostnamelen + lmrlen + ntrlen; - var buf = new Buffer(msg_len); - - buf.write('NTLMSSP', pos, 7, 'ascii'); // byte protocol[8]; - pos += 7; - buf.writeUInt8(0, pos); - pos++; - - buf.writeUInt8(0x03, pos); // byte type; - pos++; - - buf.fill(0x00, pos, pos + 3); // byte zero[3]; - pos += 3; - - buf.writeUInt16LE(lmrlen, pos); // short lm_resp_len; - pos += 2; - buf.writeUInt16LE(lmrlen, pos); // short lm_resp_len; - pos += 2; - buf.writeUInt16LE(lmroff, pos); // short lm_resp_off; - pos += 2; - buf.fill(0x00, pos, pos + 2); // byte zero[2]; - pos += 2; - - buf.writeUInt16LE(ntrlen, pos); // short nt_resp_len; - pos += 2; - buf.writeUInt16LE(ntrlen, pos); // short nt_resp_len; - pos += 2; - buf.writeUInt16LE(ntroff, pos); // short nt_resp_off; - pos += 2; - buf.fill(0x00, pos, pos + 2); // byte zero[2]; - pos += 2; - - buf.writeUInt16LE(ntdomainlen, pos); // short dom_len; - pos += 2; - buf.writeUInt16LE(ntdomainlen, pos); // short dom_len; - pos += 2; - buf.writeUInt16LE(ntdomainoff, pos); // short dom_off; - pos += 2; - buf.fill(0x00, pos, pos + 2); // byte zero[2]; - pos += 2; - - buf.writeUInt16LE(usernamelen, pos); // short user_len; - pos += 2; - buf.writeUInt16LE(usernamelen, pos); // short user_len; - pos += 2; - buf.writeUInt16LE(usernameoff, pos); // short user_off; - pos += 2; - buf.fill(0x00, pos, pos + 2); // byte zero[2]; - pos += 2; - - buf.writeUInt16LE(hostnamelen, pos); // short host_len; - pos += 2; - buf.writeUInt16LE(hostnamelen, pos); // short host_len; - pos += 2; - buf.writeUInt16LE(hostnameoff, pos); // short host_off; - pos += 2; - buf.fill(0x00, pos, pos + 6); // byte zero[6]; - pos += 6; - - buf.writeUInt16LE(msg_len, pos); // short msg_len; - pos += 2; - buf.fill(0x00, pos, pos + 2); // byte zero[2]; - pos += 2; - - buf.writeUInt16LE(0x8201, pos); // short flags; - pos += 2; - buf.fill(0x00, pos, pos + 2); // byte zero[2]; - pos += 2; - - buf.write(ntdomain, ntdomainoff, ntdomainlen, 'ucs2'); - buf.write(username, usernameoff, usernamelen, 'ucs2'); - buf.write(hostname, hostnameoff, hostnamelen, 'ucs2'); - lmr.copy(buf, lmroff, 0, lmrlen); - ntr.copy(buf, ntroff, 0, ntrlen); - - return buf; -} - -function makeResponse(hash, nonce) -{ - var out = new Buffer(24); - for (var i = 0; i < 3; i++) { - var keybuf = $.oddpar($.expandkey(hash.slice(i * 7, i * 7 + 7))); - var des = crypto.createCipheriv('DES-ECB', keybuf, ''); - var str = des.update(nonce.toString('binary'), 'binary', 'binary'); - out.write(str, i * 8, i * 8 + 8, 'binary'); - } - return out; -} - -exports.encodeType1 = encodeType1; -exports.decodeType2 = decodeType2; -exports.encodeType3 = encodeType3; - -// Convenience methods. - -exports.challengeHeader = function (hostname, domain) { - return 'NTLM ' + exports.encodeType1(hostname, domain).toString('base64'); -}; - -exports.responseHeader = function (res, url, domain, username, password) { - var serverNonce = new Buffer((res.headers['www-authenticate'].match(/^NTLM\s+(.+?)(,|\s+|$)/) || [])[1], 'base64'); - var hostname = __webpack_require__(835).parse(url).hostname; - return 'NTLM ' + exports.encodeType3(username, hostname, domain, exports.decodeType2(serverNonce), password).toString('base64') -}; - -// Import smbhash module. - -exports.smbhash = __webpack_require__(826); +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Tests an object to determine whether it implements TokenCredential. + * + * @param credential The assumed TokenCredential to be tested. + */ +function isTokenCredential(credential) { + // Check for an object with a 'getToken' function and possibly with + // a 'signRequest' function. We do this check to make sure that + // a ServiceClientCredentials implementor (like TokenClientCredentials + // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if + // it doesn't actually implement TokenCredential also. + return (credential && + typeof credential.getToken === "function" && + (credential.signRequest === undefined || credential.getToken.length > 0)); +} + +exports.AzureKeyCredential = AzureKeyCredential; +exports.isTokenCredential = isTokenCredential; +//# sourceMappingURL=index.js.map /***/ }), -/* 223 */, -/* 224 */ +/* 230 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -let Cache -const url = __webpack_require__(835) -const CachePolicy = __webpack_require__(27) -const fetch = __webpack_require__(269) -const pkg = __webpack_require__(237) -const retry = __webpack_require__(312) -let ssri -const Stream = __webpack_require__(794) -const getAgent = __webpack_require__(240) -const setWarning = __webpack_require__(965) - -const isURL = /^https?:/ -const USER_AGENT = `${pkg.name}/${pkg.version} (+https://npm.im/${pkg.name})` - -const RETRY_ERRORS = [ - 'ECONNRESET', // remote socket closed on us - 'ECONNREFUSED', // remote host refused to open connection - 'EADDRINUSE', // failed to bind to a local port (proxy?) - 'ETIMEDOUT' // someone in the transaction is WAY TOO SLOW - // Known codes we do NOT retry on: - // ENOTFOUND (getaddrinfo failure. Either bad hostname, or offline) -] +module.exports = __webpack_require__(412) -const RETRY_TYPES = [ - 'request-timeout' -] -// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch -module.exports = cachingFetch -cachingFetch.defaults = function (_uri, _opts) { - const fetch = this - if (typeof _uri === 'object') { - _opts = _uri - _uri = null - } +/***/ }), +/* 231 */, +/* 232 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - function defaultedFetch (uri, opts) { - const finalOpts = Object.assign({}, _opts || {}, opts || {}) - return fetch(uri || _uri, finalOpts) - } +"use strict"; - defaultedFetch.defaults = fetch.defaults - defaultedFetch.delete = fetch.delete - return defaultedFetch -} -cachingFetch.delete = cacheDelete -function cacheDelete (uri, opts) { - opts = configureOptions(opts) - if (opts.cacheManager) { - const req = new fetch.Request(uri, { - method: opts.method, - headers: opts.headers - }) - return opts.cacheManager.delete(req, opts) - } -} +/**/ -function initializeCache (opts) { - if (typeof opts.cacheManager === 'string') { - if (!Cache) { - // Default cacache-based cache - Cache = __webpack_require__(259) - } +var pna = __webpack_require__(822); +/**/ - opts.cacheManager = new Cache(opts.cacheManager, opts) - } +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; - opts.cache = opts.cache || 'default' + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; - if (opts.cache === 'default' && isHeaderConditional(opts.headers)) { - // If header list contains `If-Modified-Since`, `If-None-Match`, - // `If-Unmodified-Since`, `If-Match`, or `If-Range`, fetch will set cache - // mode to "no-store" if it is "default". - opts.cache = 'no-store' + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + pna.nextTick(emitErrorNT, this, err); + } + return this; } -} -function configureOptions (_opts) { - const opts = Object.assign({}, _opts || {}) - opts.method = (opts.method || 'GET').toUpperCase() + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks - if (opts.retry && typeof opts.retry === 'number') { - opts.retry = { retries: opts.retry } + if (this._readableState) { + this._readableState.destroyed = true; } - if (opts.retry === false) { - opts.retry = { retries: 0 } + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; } - if (opts.cacheManager) { - initializeCache(opts) - } + this._destroy(err || null, function (err) { + if (!cb && err) { + pna.nextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); + } + }); - return opts + return this; } -function initializeSsri () { - if (!ssri) { - ssri = __webpack_require__(951) +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; } -} -function cachingFetch (uri, _opts) { - const opts = configureOptions(_opts) - - if (opts.integrity) { - initializeSsri() - // if verifying integrity, node-fetch must not decompress - opts.compress = false + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; } +} - const isCachable = (opts.method === 'GET' || opts.method === 'HEAD') && - opts.cacheManager && - opts.cache !== 'no-store' && - opts.cache !== 'reload' - - if (isCachable) { - const req = new fetch.Request(uri, { - method: opts.method, - headers: opts.headers - }) - - return opts.cacheManager.match(req, opts).then(res => { - if (res) { - const warningCode = (res.headers.get('Warning') || '').match(/^\d+/) - if (warningCode && +warningCode >= 100 && +warningCode < 200) { - // https://tools.ietf.org/html/rfc7234#section-4.3.4 - // - // If a stored response is selected for update, the cache MUST: - // - // * delete any Warning header fields in the stored response with - // warn-code 1xx (see Section 5.5); - // - // * retain any Warning header fields in the stored response with - // warn-code 2xx; - // - res.headers.delete('Warning') - } - - if (opts.cache === 'default' && !isStale(req, res)) { - return res - } - - if (opts.cache === 'default' || opts.cache === 'no-cache') { - return conditionalFetch(req, res, opts) - } +function emitErrorNT(self, err) { + self.emit('error', err); +} - if (opts.cache === 'force-cache' || opts.cache === 'only-if-cached') { - // 112 Disconnected operation - // SHOULD be included if the cache is intentionally disconnected from - // the rest of the network for a period of time. - // (https://tools.ietf.org/html/rfc2616#section-14.46) - setWarning(res, 112, 'Disconnected operation') - return res - } - } +module.exports = { + destroy: destroy, + undestroy: undestroy +}; - if (!res && opts.cache === 'only-if-cached') { - const errorMsg = `request to ${ - uri - } failed: cache mode is 'only-if-cached' but no cached response available.` +/***/ }), +/* 233 */ +/***/ (function(module, exports, __webpack_require__) { - const err = new Error(errorMsg) - err.code = 'ENOTCACHED' - throw err - } +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(293) +var Buffer = buffer.Buffer - // Missing cache entry, or mode is default (if stale), reload, no-store - return remoteFetch(req.url, opts) - }) +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} - return remoteFetch(uri, opts) +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) } -function iterableToObject (iter) { - const obj = {} - for (let k of iter.keys()) { - obj[k] = iter.get(k) +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') } - return obj + return Buffer(arg, encodingOrOffset, length) } -function makePolicy (req, res) { - const _req = { - url: req.url, - method: req.method, - headers: iterableToObject(req.headers) +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } - const _res = { - status: res.status, - headers: iterableToObject(res.headers) + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) } - - return new CachePolicy(_req, _res, { shared: false }) + return buf } -// https://tools.ietf.org/html/rfc7234#section-4.2 -function isStale (req, res) { - if (!res) { - return null +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } + return Buffer(size) +} - const _req = { - url: req.url, - method: req.method, - headers: iterableToObject(req.headers) +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } + return buffer.SlowBuffer(size) +} - const policy = makePolicy(req, res) - const responseTime = res.headers.get('x-local-cache-time') || - res.headers.get('date') || - 0 +/***/ }), +/* 234 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - policy._responseTime = new Date(responseTime) +"use strict"; - const bool = !policy.satisfiesWithoutRevalidation(_req) - return bool -} +__webpack_require__(812); +const inherits = __webpack_require__(669).inherits; +const promisify = __webpack_require__(662); +const EventEmitter = __webpack_require__(614).EventEmitter; -function mustRevalidate (res) { - return (res.headers.get('cache-control') || '').match(/must-revalidate/i) +module.exports = Agent; + +function isAgent(v) { + return v && typeof v.addRequest === 'function'; } -function conditionalFetch (req, cachedRes, opts) { - const _req = { - url: req.url, - method: req.method, - headers: Object.assign({}, opts.headers || {}) +/** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ +function Agent(callback, _opts) { + if (!(this instanceof Agent)) { + return new Agent(callback, _opts); } - const policy = makePolicy(req, cachedRes) - opts.headers = policy.revalidationHeaders(_req) - - return remoteFetch(req.url, opts) - .then(condRes => { - const revalidatedPolicy = policy.revalidatedPolicy(_req, { - status: condRes.status, - headers: iterableToObject(condRes.headers) - }) + EventEmitter.call(this); - if (condRes.status >= 500 && !mustRevalidate(cachedRes)) { - // 111 Revalidation failed - // MUST be included if a cache returns a stale response because an - // attempt to revalidate the response failed, due to an inability to - // reach the server. - // (https://tools.ietf.org/html/rfc2616#section-14.46) - setWarning(cachedRes, 111, 'Revalidation failed') - return cachedRes - } + // The callback gets promisified if it has 3 parameters + // (i.e. it has a callback function) lazily + this._promisifiedCallback = false; - if (condRes.status === 304) { // 304 Not Modified - condRes.body = cachedRes.body - return opts.cacheManager.put(req, condRes, opts) - .then(newRes => { - newRes.headers = new fetch.Headers(revalidatedPolicy.policy.responseHeaders()) - return newRes - }) - } + let opts = _opts; + if ('function' === typeof callback) { + this.callback = callback; + } else if (callback) { + opts = callback; + } - return condRes - }) - .then(res => res) - .catch(err => { - if (mustRevalidate(cachedRes)) { - throw err - } else { - // 111 Revalidation failed - // MUST be included if a cache returns a stale response because an - // attempt to revalidate the response failed, due to an inability to - // reach the server. - // (https://tools.ietf.org/html/rfc2616#section-14.46) - setWarning(cachedRes, 111, 'Revalidation failed') - // 199 Miscellaneous warning - // The warning text MAY include arbitrary information to be presented to - // a human user, or logged. A system receiving this warning MUST NOT take - // any automated action, besides presenting the warning to the user. - // (https://tools.ietf.org/html/rfc2616#section-14.46) - setWarning( - cachedRes, - 199, - `Miscellaneous Warning ${err.code}: ${err.message}` - ) + // timeout for the socket to be returned from the callback + this.timeout = (opts && opts.timeout) || null; - return cachedRes - } - }) + this.options = opts; } +inherits(Agent, EventEmitter); -function remoteFetchHandleIntegrity (res, integrity) { - const oldBod = res.body - const newBod = ssri.integrityStream({ - integrity - }) - oldBod.pipe(newBod) - res.body = newBod - oldBod.once('error', err => { - newBod.emit('error', err) - }) - newBod.once('error', err => { - oldBod.emit('error', err) - }) -} +/** + * Override this function in your subclass! + */ +Agent.prototype.callback = function callback(req, opts) { + throw new Error( + '"agent-base" has no default implementation, you must subclass and override `callback()`' + ); +}; -function remoteFetch (uri, opts) { - const agent = getAgent(uri, opts) - const headers = Object.assign({ - 'connection': agent ? 'keep-alive' : 'close', - 'user-agent': USER_AGENT - }, opts.headers || {}) +/** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ +Agent.prototype.addRequest = function addRequest(req, _opts) { + const ownOpts = Object.assign({}, _opts); - const reqOpts = { - agent, - body: opts.body, - compress: opts.compress, - follow: opts.follow, - headers: new fetch.Headers(headers), - method: opts.method, - redirect: 'manual', - size: opts.size, - counter: opts.counter, - timeout: opts.timeout + // Set default `host` for HTTP to localhost + if (null == ownOpts.host) { + ownOpts.host = 'localhost'; } - return retry( - (retryHandler, attemptNum) => { - const req = new fetch.Request(uri, reqOpts) - return fetch(req) - .then(res => { - res.headers.set('x-fetch-attempts', attemptNum) + // Set default `port` for HTTP if none was explicitly specified + if (null == ownOpts.port) { + ownOpts.port = ownOpts.secureEndpoint ? 443 : 80; + } - if (opts.integrity) { - remoteFetchHandleIntegrity(res, opts.integrity) - } + const opts = Object.assign({}, this.options, ownOpts); - const isStream = req.body instanceof Stream + if (opts.host && opts.path) { + // If both a `host` and `path` are specified then it's most likely the + // result of a `url.parse()` call... we need to remove the `path` portion so + // that `net.connect()` doesn't attempt to open that as a unix socket file. + delete opts.path; + } - if (opts.cacheManager) { - const isMethodGetHead = req.method === 'GET' || - req.method === 'HEAD' + delete opts.agent; + delete opts.hostname; + delete opts._defaultAgent; + delete opts.defaultPort; + delete opts.createConnection; - const isCachable = opts.cache !== 'no-store' && - isMethodGetHead && - makePolicy(req, res).storable() && - res.status === 200 // No other statuses should be stored! + // Hint to use "Connection: close" + // XXX: non-documented `http` module API :( + req._last = true; + req.shouldKeepAlive = false; - if (isCachable) { - return opts.cacheManager.put(req, res, opts) - } + // Create the `stream.Duplex` instance + let timeout; + let timedOut = false; + const timeoutMs = this.timeout; + const freeSocket = this.freeSocket; - if (!isMethodGetHead) { - return opts.cacheManager.delete(req).then(() => { - if (res.status >= 500 && req.method !== 'POST' && !isStream) { - if (typeof opts.onRetry === 'function') { - opts.onRetry(res) - } + function onerror(err) { + if (req._hadError) return; + req.emit('error', err); + // For Safety. Some additional errors might fire later on + // and we need to make sure we don't double-fire the error event. + req._hadError = true; + } - return retryHandler(res) - } + function ontimeout() { + timeout = null; + timedOut = true; + const err = new Error( + 'A "socket" was not created for HTTP request before ' + timeoutMs + 'ms' + ); + err.code = 'ETIMEOUT'; + onerror(err); + } - return res - }) - } - } + function callbackError(err) { + if (timedOut) return; + if (timeout != null) { + clearTimeout(timeout); + timeout = null; + } + onerror(err); + } - const isRetriable = req.method !== 'POST' && - !isStream && ( - res.status === 408 || // Request Timeout - res.status === 420 || // Enhance Your Calm (usually Twitter rate-limit) - res.status === 429 || // Too Many Requests ("standard" rate-limiting) - res.status >= 500 // Assume server errors are momentary hiccups - ) + function onsocket(socket) { + if (timedOut) return; + if (timeout != null) { + clearTimeout(timeout); + timeout = null; + } + if (isAgent(socket)) { + // `socket` is actually an http.Agent instance, so relinquish + // responsibility for this `req` to the Agent from here on + socket.addRequest(req, opts); + } else if (socket) { + function onfree() { + freeSocket(socket, opts); + } + socket.on('free', onfree); + req.onSocket(socket); + } else { + const err = new Error( + 'no Duplex stream was returned to agent-base for `' + req.method + ' ' + req.path + '`' + ); + onerror(err); + } + } - if (isRetriable) { - if (typeof opts.onRetry === 'function') { - opts.onRetry(res) - } + if (!this._promisifiedCallback && this.callback.length >= 3) { + // Legacy callback function - convert to a Promise + this.callback = promisify(this.callback, this); + this._promisifiedCallback = true; + } - return retryHandler(res) - } + if (timeoutMs > 0) { + timeout = setTimeout(ontimeout, timeoutMs); + } - if (!fetch.isRedirect(res.status) || opts.redirect === 'manual') { - return res - } + try { + Promise.resolve(this.callback(req, opts)).then(onsocket, callbackError); + } catch (err) { + Promise.reject(err).catch(callbackError); + } +}; - // handle redirects - matches behavior of npm-fetch: https://github.com/bitinn/node-fetch - if (opts.redirect === 'error') { - const err = new Error(`redirect mode is set to error: ${uri}`) - err.code = 'ENOREDIRECT' - throw err - } +Agent.prototype.freeSocket = function freeSocket(socket, opts) { + // TODO reuse sockets + socket.destroy(); +}; - if (!res.headers.get('location')) { - const err = new Error(`redirect location header missing at: ${uri}`) - err.code = 'EINVALIDREDIRECT' - throw err - } - if (req.counter >= req.follow) { - const err = new Error(`maximum redirect reached at: ${uri}`) - err.code = 'EMAXREDIRECT' - throw err - } +/***/ }), +/* 235 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - const resolvedUrl = url.resolve(req.url, res.headers.get('location')) - let redirectURL = url.parse(resolvedUrl) +"use strict"; - if (isURL.test(res.headers.get('location'))) { - redirectURL = url.parse(res.headers.get('location')) - } +var util = __webpack_require__(669) +var stream = __webpack_require__(914) +var delegate = __webpack_require__(967) +var Tracker = __webpack_require__(623) - // Remove authorization if changing hostnames (but not if just - // changing ports or protocols). This matches the behavior of request: - // https://github.com/request/request/blob/b12a6245/lib/redirect.js#L134-L138 - if (url.parse(req.url).hostname !== redirectURL.hostname) { - req.headers.delete('authorization') - } +var TrackerStream = module.exports = function (name, size, options) { + stream.Transform.call(this, options) + this.tracker = new Tracker(name, size) + this.name = name + this.id = this.tracker.id + this.tracker.on('change', delegateChange(this)) +} +util.inherits(TrackerStream, stream.Transform) - // for POST request with 301/302 response, or any request with 303 response, - // use GET when following redirect - if (res.status === 303 || - ((res.status === 301 || res.status === 302) && req.method === 'POST')) { - opts.method = 'GET' - opts.body = null - req.headers.delete('content-length') - } +function delegateChange (trackerStream) { + return function (name, completion, tracker) { + trackerStream.emit('change', name, completion, trackerStream) + } +} - opts.headers = {} - req.headers.forEach((value, name) => { - opts.headers[name] = value - }) +TrackerStream.prototype._transform = function (data, encoding, cb) { + this.tracker.completeWork(data.length ? data.length : 1) + this.push(data) + cb() +} - opts.counter = ++req.counter - return cachingFetch(resolvedUrl, opts) - }) - .catch(err => { - const code = err.code === 'EPROMISERETRY' ? err.retried.code : err.code +TrackerStream.prototype._flush = function (cb) { + this.tracker.finish() + cb() +} - const isRetryError = RETRY_ERRORS.indexOf(code) === -1 && - RETRY_TYPES.indexOf(err.type) === -1 - - if (req.method === 'POST' || isRetryError) { - throw err - } +delegate(TrackerStream.prototype, 'tracker') + .method('completed') + .method('addWork') + .method('finish') - if (typeof opts.onRetry === 'function') { - opts.onRetry(err) - } - return retryHandler(err) - }) - }, - opts.retry - ).catch(err => { - if (err.status >= 400) { - return err - } +/***/ }), +/* 236 */, +/* 237 */ +/***/ (function(module) { - throw err - }) -} +module.exports = {"name":"make-fetch-happen","version":"5.0.2","description":"Opinionated, caching, retrying fetch client","main":"index.js","files":["*.js","lib"],"scripts":{"prerelease":"npm t","release":"standard-version -s","postrelease":"npm publish --tag=legacy && git push --follow-tags","pretest":"standard","test":"tap --coverage --nyc-arg=--all --timeout=35 -J test/*.js","update-coc":"weallbehave -o . && git add CODE_OF_CONDUCT.md && git commit -m 'docs(coc): updated CODE_OF_CONDUCT.md'","update-contrib":"weallcontribute -o . && git add CONTRIBUTING.md && git commit -m 'docs(contributing): updated CONTRIBUTING.md'"},"repository":"https://github.com/zkat/make-fetch-happen","keywords":["http","request","fetch","mean girls","caching","cache","subresource integrity"],"author":{"name":"Kat Marchán","email":"kzm@zkat.tech","twitter":"maybekatz"},"license":"ISC","dependencies":{"agentkeepalive":"^3.4.1","cacache":"^12.0.0","http-cache-semantics":"^3.8.1","http-proxy-agent":"^2.1.0","https-proxy-agent":"^2.2.3","lru-cache":"^5.1.1","mississippi":"^3.0.0","node-fetch-npm":"^2.0.2","promise-retry":"^1.1.1","socks-proxy-agent":"^4.0.0","ssri":"^6.0.0"},"devDependencies":{"bluebird":"^3.5.1","mkdirp":"^0.5.1","nock":"^9.2.3","npmlog":"^4.1.2","require-inject":"^1.4.2","rimraf":"^2.6.2","safe-buffer":"^5.1.1","standard":"^11.0.1","standard-version":"^4.3.0","tacks":"^1.2.6","tap":"^12.7.0","weallbehave":"^1.0.0","weallcontribute":"^1.0.7"}}; -function isHeaderConditional (headers) { - if (!headers || typeof headers !== 'object') { - return false - } +/***/ }), +/* 238 */ +/***/ (function(__unusedmodule, exports) { - const modifiers = [ - 'if-modified-since', - 'if-none-match', - 'if-unmodified-since', - 'if-match', - 'if-range' - ] +"use strict"; - return Object.keys(headers) - .some(h => modifiers.indexOf(h.toLowerCase()) !== -1) -} +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +exports.default = _default; /***/ }), -/* 225 */, -/* 226 */ +/* 239 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. +var validate = __webpack_require__(285) +var renderTemplate = __webpack_require__(874) +var wideTruncate = __webpack_require__(504) +var stringWidth = __webpack_require__(66) +module.exports = function (theme, width, completed) { + validate('ONN', [theme, width, completed]) + if (completed < 0) completed = 0 + if (completed > 1) completed = 1 + if (width <= 0) return '' + var sofar = Math.round(width * completed) + var rest = width - sofar + var template = [ + {type: 'complete', value: repeat(theme.complete, sofar), length: sofar}, + {type: 'remaining', value: repeat(theme.remaining, rest), length: rest} + ] + return renderTemplate(width, template, theme) +} -/**/ +// lodash's way of repeating +function repeat (string, width) { + var result = '' + var n = width + do { + if (n % 2) { + result += string + } + n = Math.floor(n / 2) + /*eslint no-self-assign: 0*/ + string += string + } while (n && stringWidth(result) < width) -var pna = __webpack_require__(822); -/**/ + return wideTruncate(result, width) +} -module.exports = Readable; -/**/ -var isArray = __webpack_require__(262); -/**/ +/***/ }), +/* 240 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -/**/ -var Duplex; -/**/ +"use strict"; -Readable.ReadableState = ReadableState; +const LRU = __webpack_require__(567) +const url = __webpack_require__(835) -/**/ -var EE = __webpack_require__(614).EventEmitter; +let AGENT_CACHE = new LRU({ max: 50 }) +let HttpsAgent +let HttpAgent -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ +module.exports = getAgent -/**/ -var Stream = __webpack_require__(41); -/**/ +function getAgent (uri, opts) { + const parsedUri = url.parse(typeof uri === 'string' ? uri : uri.url) + const isHttps = parsedUri.protocol === 'https:' + const pxuri = getProxyUri(uri, opts) -/**/ + const key = [ + `https:${isHttps}`, + pxuri + ? `proxy:${pxuri.protocol}//${pxuri.host}:${pxuri.port}` + : '>no-proxy<', + `local-address:${opts.localAddress || '>no-local-address<'}`, + `strict-ssl:${isHttps ? !!opts.strictSSL : '>no-strict-ssl<'}`, + `ca:${(isHttps && opts.ca) || '>no-ca<'}`, + `cert:${(isHttps && opts.cert) || '>no-cert<'}`, + `key:${(isHttps && opts.key) || '>no-key<'}` + ].join(':') -var Buffer = __webpack_require__(254).Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} + if (opts.agent != null) { // `agent: false` has special behavior! + return opts.agent + } -/**/ + if (AGENT_CACHE.peek(key)) { + return AGENT_CACHE.get(key) + } -/**/ -var util = Object.create(__webpack_require__(286)); -util.inherits = __webpack_require__(689); -/**/ + if (pxuri) { + const proxy = getProxy(pxuri, opts, isHttps) + AGENT_CACHE.set(key, proxy) + return proxy + } -/**/ -var debugUtil = __webpack_require__(669); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; + if (isHttps && !HttpsAgent) { + HttpsAgent = __webpack_require__(112).HttpsAgent + } else if (!isHttps && !HttpAgent) { + HttpAgent = __webpack_require__(112) + } + + // If opts.timeout is zero, set the agentTimeout to zero as well. A timeout + // of zero disables the timeout behavior (OS limits still apply). Else, if + // opts.timeout is a non-zero value, set it to timeout + 1, to ensure that + // the node-fetch-npm timeout will always fire first, giving us more + // consistent errors. + const agentTimeout = opts.timeout === 0 ? 0 : opts.timeout + 1 + + const agent = isHttps ? new HttpsAgent({ + maxSockets: opts.maxSockets || 15, + ca: opts.ca, + cert: opts.cert, + key: opts.key, + localAddress: opts.localAddress, + rejectUnauthorized: opts.strictSSL, + timeout: agentTimeout + }) : new HttpAgent({ + maxSockets: opts.maxSockets || 15, + localAddress: opts.localAddress, + timeout: agentTimeout + }) + AGENT_CACHE.set(key, agent) + return agent } -/**/ -var BufferList = __webpack_require__(931); -var destroyImpl = __webpack_require__(232); -var StringDecoder; +function checkNoProxy (uri, opts) { + const host = url.parse(uri).hostname.split('.').reverse() + let noproxy = (opts.noProxy || getProcessEnv('no_proxy')) + if (typeof noproxy === 'string') { + noproxy = noproxy.split(/\s*,\s*/g) + } + return noproxy && noproxy.some(no => { + const noParts = no.split('.').filter(x => x).reverse() + if (!noParts.length) { return false } + for (let i = 0; i < noParts.length; i++) { + if (host[i] !== noParts[i]) { + return false + } + } + return true + }) +} -util.inherits(Readable, Stream); +module.exports.getProcessEnv = getProcessEnv -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +function getProcessEnv (env) { + if (!env) { return } -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + let value - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} + if (Array.isArray(env)) { + for (let e of env) { + value = process.env[e] || + process.env[e.toUpperCase()] || + process.env[e.toLowerCase()] + if (typeof value !== 'undefined') { break } + } + } -function ReadableState(options, stream) { - Duplex = Duplex || __webpack_require__(907); + if (typeof env === 'string') { + value = process.env[env] || + process.env[env.toUpperCase()] || + process.env[env.toLowerCase()] + } - options = options || {}; + return value +} - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; +function getProxyUri (uri, opts) { + const protocol = url.parse(uri).protocol - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; + const proxy = opts.proxy || ( + protocol === 'https:' && getProcessEnv('https_proxy') + ) || ( + protocol === 'http:' && getProcessEnv(['https_proxy', 'http_proxy', 'proxy']) + ) + if (!proxy) { return null } - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + const parsedProxy = (typeof proxy === 'string') ? url.parse(proxy) : proxy - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var readableHwm = options.readableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; + return !checkNoProxy(uri, opts) && parsedProxy +} - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; +let HttpProxyAgent +let HttpsProxyAgent +let SocksProxyAgent +function getProxy (proxyUrl, opts, isHttps) { + let popts = { + host: proxyUrl.hostname, + port: proxyUrl.port, + protocol: proxyUrl.protocol, + path: proxyUrl.path, + auth: proxyUrl.auth, + ca: opts.ca, + cert: opts.cert, + key: opts.key, + timeout: opts.timeout === 0 ? 0 : opts.timeout + 1, + localAddress: opts.localAddress, + maxSockets: opts.maxSockets || 15, + rejectUnauthorized: opts.strictSSL + } - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); + if (proxyUrl.protocol === 'http:' || proxyUrl.protocol === 'https:') { + if (!isHttps) { + if (!HttpProxyAgent) { + HttpProxyAgent = __webpack_require__(934) + } - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; + return new HttpProxyAgent(popts) + } else { + if (!HttpsProxyAgent) { + HttpsProxyAgent = __webpack_require__(717) + } - // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - this.sync = true; + return new HttpsProxyAgent(popts) + } + } + if (proxyUrl.protocol.startsWith('socks')) { + if (!SocksProxyAgent) { + SocksProxyAgent = __webpack_require__(310) + } - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; + return new SocksProxyAgent(popts) + } +} - // has it been destroyed - this.destroyed = false; - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; +/***/ }), +/* 241 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; +"use strict"; - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = __webpack_require__(432).StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; +exports.URL = exports.DNS = void 0; -function Readable(options) { - Duplex = Duplex || __webpack_require__(907); +var _stringify = _interopRequireDefault(__webpack_require__(855)); - if (!(this instanceof Readable)) return new Readable(options); +var _parse = _interopRequireDefault(__webpack_require__(197)); - this._readableState = new ReadableState(options, this); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - // legacy - this.readable = true; +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape - if (options) { - if (typeof options.read === 'function') this._read = options.read; + const bytes = []; - if (typeof options.destroy === 'function') this._destroy = options.destroy; + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); } - Stream.call(this); + return bytes; } -Object.defineProperty(Readable.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined) { - return false; +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +function _default(name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + if (typeof value === 'string') { + value = stringToBytes(value); } - return this._readableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; + + if (typeof namespace === 'string') { + namespace = (0, _parse.default)(namespace); } - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - } -}); + if (namespace.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; -Readable.prototype._destroy = function (err, cb) { - this.push(null); - cb(err); -}; -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; } - skipChunkCheck = true; + + return buf; } - } else { - skipChunkCheck = true; - } - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; + return (0, _stringify.default)(bytes); + } // Function#name is not settable on some platforms (#270) -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support - if (addToFront) { - if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); - } else if (state.ended) { - stream.emit('error', new Error('stream.push() after EOF')); - } else { - state.reading = false; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - } - } - return needMoreData(state); + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; } -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); +/***/ }), +/* 242 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - if (state.needReadable) emitReadable(stream); - } - maybeReadMore(stream, state); -} +"use strict"; -function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; +Object.defineProperty(exports, "__esModule", { value: true }); +__webpack_require__(71); + + +/***/ }), +/* 243 */ +/***/ (function(module) { + +"use strict"; + + +module.exports = isWin32() || isColorTerm() + +function isWin32 () { + return process.platform === 'win32' } -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +function isColorTerm () { + var termHasColor = /^screen|^xterm|^vt100|color|ansi|cygwin|linux/i + return !!process.env.COLORTERM || termHasColor.test(process.env.TERM) } -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = __webpack_require__(432).StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; +/***/ }), +/* 244 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; -} +"use strict"; -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; -} -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; +module.exports = __webpack_require__(442) - if (n !== 0) state.emittedReadable = false; - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } +/***/ }), +/* 245 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - n = howMuchToRead(n, state); +"use strict"; - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); +var _crypto = _interopRequireDefault(__webpack_require__(417)); - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); } - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } + return _crypto.default.createHash('md5').update(bytes).digest(); +} - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; +var _default = md5; +exports.default = _default; - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } +/***/ }), +/* 246 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (ret !== null) this.emit('data', ret); +"use strict"; - return ret; -}; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection, Proxyable) { +var util = __webpack_require__(248); +var isArray = util.isArray; -function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + case -6: return new Map(); } - } - state.ended = true; - - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); - } -} - -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - pna.nextTick(maybeReadMore_, stream, state); - } } -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + if (values instanceof Promise) { + promise._propagateFrom(values, 3); + values.suppressUnhandledRejections(); + } + promise._setOnCancel(this); + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); } +util.inherits(PromiseArray, Proxyable); -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); +PromiseArray.prototype.length = function () { + return this._length; }; -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; +PromiseArray.prototype.promise = function () { + return this._promise; +}; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); +PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { + var values = tryConvertToPromise(this._values, this._promise); + if (values instanceof Promise) { + values = values._target(); + var bitField = values._bitField; + ; + this._values = values; - dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } + if (((bitField & 50397184) === 0)) { + this._promise._setAsyncGuaranteed(); + return values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + } else if (((bitField & 33554432) !== 0)) { + values = values._value(); + } else if (((bitField & 16777216) !== 0)) { + return this._reject(values._reason()); + } else { + return this._cancel(); + } + } + values = util.asArray(values); + if (values === null) { + var err = apiRejection( + "expecting an array or an iterable object but got " + util.classString(values)).reason(); + this._promise._rejectCallback(err, false); + return; } - } - - function onend() { - debug('onend'); - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + this._iterate(values); +}; - cleanedUp = true; +PromiseArray.prototype._iterate = function(values) { + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var result = this._promise; + var isResolved = false; + var bitField = null; + for (var i = 0; i < len; ++i) { + var maybePromise = tryConvertToPromise(values[i], result); - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + bitField = maybePromise._bitField; + } else { + bitField = null; + } - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); + if (isResolved) { + if (bitField !== null) { + maybePromise.suppressUnhandledRejections(); + } + } else if (bitField !== null) { + if (((bitField & 50397184) === 0)) { + maybePromise._proxy(this, i); + this._values[i] = maybePromise; + } else if (((bitField & 33554432) !== 0)) { + isResolved = this._promiseFulfilled(maybePromise._value(), i); + } else if (((bitField & 16777216) !== 0)) { + isResolved = this._promiseRejected(maybePromise._reason(), i); + } else { + isResolved = this._promiseCancelled(i); + } + } else { + isResolved = this._promiseFulfilled(maybePromise, i); + } } - } + if (!isResolved) result._setAsyncGuaranteed(); +}; - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); - } +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); +PromiseArray.prototype._cancel = function() { + if (this._isResolved() || !this._promise._isCancellable()) return; + this._values = null; + this._promise._cancel(); +}; - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false); +}; - // tell the dest that it's being piped to - dest.emit('pipe', src); +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + return true; + } + return false; +}; - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } +PromiseArray.prototype._promiseCancelled = function() { + this._cancel(); + return true; +}; - return dest; +PromiseArray.prototype._promiseRejected = function (reason) { + this._totalResolved++; + this._reject(reason); + return true; }; -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); +PromiseArray.prototype._resultCancelled = function() { + if (this._isResolved()) return; + var values = this._values; + this._cancel(); + if (values instanceof Promise) { + values.cancel(); + } else { + for (var i = 0; i < values.length; ++i) { + if (values[i] instanceof Promise) { + values[i].cancel(); + } + } } - }; -} +}; -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { hasUnpiped: false }; +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; +return PromiseArray; +}; - if (!dest) dest = state.pipes; - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } +/***/ }), +/* 247 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - // slow case. multiple pipe destinations. +"use strict"; - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, unpipeInfo); - }return this; - } - - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - - dest.emit('unpipe', this, unpipeInfo); - - return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - pna.nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); - } - } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} +const os = __webpack_require__(87); +const tty = __webpack_require__(867); +const hasFlag = __webpack_require__(364); -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; -}; +const {env} = process; -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - pna.nextTick(resume_, stream, state); - } +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + forceColor = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = 1; } -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } - - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); +if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + forceColor = 1; + } else if (env.FORCE_COLOR === 'false') { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } } -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; -}; +function translateLevel(level) { + if (level === 0) { + return false; + } -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; } -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; +function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } - _this.push(null); - }); + if (hasFlag('color=256')) { + return 2; + } - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + const min = forceColor || 0; - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); + if (env.TERM === 'dumb') { + return min; + } - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } + return 1; + } - // when we try to consume some more bytes, simply unpause the - // underlying stream. - this._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } - return this; -}; + return min; + } -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._readableState.highWaterMark; - } -}); + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } -// exposed for testing purposes only. -Readable._fromList = fromList; + if (env.COLORTERM === 'truecolor') { + return 3; + } -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } - return ret; -} + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; -} + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} + if ('COLORTERM' in env) { + return 1; + } -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; + return min; } -function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - - if (!state.endEmitted) { - state.ended = true; - pna.nextTick(endReadableNT, state, stream); - } +function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); } -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } -} +module.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) +}; -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} /***/ }), -/* 227 */, -/* 228 */, -/* 229 */, -/* 230 */, -/* 231 */, -/* 232 */ +/* 248 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +var es5 = __webpack_require__(883); +var canEvaluate = typeof navigator == "undefined"; -/**/ - -var pna = __webpack_require__(822); -/**/ +var errorObj = {e: {}}; +var tryCatchTarget; +var globalObject = typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : + typeof global !== "undefined" ? global : + this !== undefined ? this : null; -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; +function tryCatcher() { + try { + var target = tryCatchTarget; + tryCatchTarget = null; + return target.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} +function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; +} - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; +var inherits = function(Child, Parent) { + var hasProp = {}.hasOwnProperty; - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { - pna.nextTick(emitErrorNT, this, err); + function T() { + this.constructor = Child; + this.constructor$ = Parent; + for (var propertyName in Parent.prototype) { + if (hasProp.call(Parent.prototype, propertyName) && + propertyName.charAt(propertyName.length-1) !== "$" + ) { + this[propertyName + "$"] = Parent.prototype[propertyName]; + } + } } - return this; - } - - // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks + T.prototype = Parent.prototype; + Child.prototype = new T(); + return Child.prototype; +}; - if (this._readableState) { - this._readableState.destroyed = true; - } - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; - } +function isPrimitive(val) { + return val == null || val === true || val === false || + typeof val === "string" || typeof val === "number"; - this._destroy(err || null, function (err) { - if (!cb && err) { - pna.nextTick(emitErrorNT, _this, err); - if (_this._writableState) { - _this._writableState.errorEmitted = true; - } - } else if (cb) { - cb(err); - } - }); +} - return this; +function isObject(value) { + return typeof value === "function" || + typeof value === "object" && value !== null; } -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } +function maybeWrapAsError(maybeError) { + if (!isPrimitive(maybeError)) return maybeError; - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } + return new Error(safeToString(maybeError)); } -function emitErrorNT(self, err) { - self.emit('error', err); +function withAppended(target, appendee) { + var len = target.length; + var ret = new Array(len + 1); + var i; + for (i = 0; i < len; ++i) { + ret[i] = target[i]; + } + ret[i] = appendee; + return ret; } -module.exports = { - destroy: destroy, - undestroy: undestroy -}; +function getDataPropertyOrDefault(obj, key, defaultValue) { + if (es5.isES5) { + var desc = Object.getOwnPropertyDescriptor(obj, key); -/***/ }), -/* 233 */ -/***/ (function(module, exports, __webpack_require__) { + if (desc != null) { + return desc.get == null && desc.set == null + ? desc.value + : defaultValue; + } + } else { + return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; + } +} -/* eslint-disable node/no-deprecated-api */ -var buffer = __webpack_require__(293) -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer +function notEnumerableProp(obj, name, value) { + if (isPrimitive(obj)) return obj; + var descriptor = { + value: value, + configurable: true, + enumerable: false, + writable: true + }; + es5.defineProperty(obj, name, descriptor); + return obj; } -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) +function thrower(r) { + throw r; } -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) +var inheritedDataKeys = (function() { + var excludedPrototypes = [ + Array.prototype, + Object.prototype, + Function.prototype + ]; -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} + var isExcludedProto = function(val) { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (excludedPrototypes[i] === val) { + return true; + } + } + return false; + }; -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) + if (es5.isES5) { + var getKeys = Object.getOwnPropertyNames; + return function(obj) { + var ret = []; + var visitedKeys = Object.create(null); + while (obj != null && !isExcludedProto(obj)) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; } else { - buf.fill(fill) + var hasProp = {}.hasOwnProperty; + return function(obj) { + if (isExcludedProto(obj)) return []; + var ret = []; + + /*jshint forin:false */ + enumeration: for (var key in obj) { + if (hasProp.call(obj, key)) { + ret.push(key); + } else { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (hasProp.call(excludedPrototypes[i], key)) { + continue enumeration; + } + } + ret.push(key); + } + } + return ret; + }; } - } else { - buf.fill(0) - } - return buf -} -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} +})(); -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} +var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + var hasMethods = es5.isES5 && keys.length > 1; + var hasMethodsOtherThanConstructor = keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + var hasThisAssignmentAndStaticMethods = + thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; -/***/ }), -/* 234 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + if (hasMethods || hasMethodsOtherThanConstructor || + hasThisAssignmentAndStaticMethods) { + return true; + } + } + return false; + } catch (e) { + return false; + } +} -"use strict"; +function toFastProperties(obj) { + /*jshint -W027,-W055,-W031*/ + function FakeConstructor() {} + FakeConstructor.prototype = obj; + var receiver = new FakeConstructor(); + function ic() { + return typeof receiver.foo; + } + ic(); + ic(); + return obj; + eval(obj); +} -__webpack_require__(114); -const inherits = __webpack_require__(669).inherits; -const promisify = __webpack_require__(662); -const EventEmitter = __webpack_require__(614).EventEmitter; +var rident = /^[a-z$_][a-z$_0-9]*$/i; +function isIdentifier(str) { + return rident.test(str); +} -module.exports = Agent; +function filledRange(count, prefix, suffix) { + var ret = new Array(count); + for(var i = 0; i < count; ++i) { + ret[i] = prefix + i + suffix; + } + return ret; +} -function isAgent(v) { - return v && typeof v.addRequest === 'function'; +function safeToString(obj) { + try { + return obj + ""; + } catch (e) { + return "[no string representation]"; + } } -/** - * Base `http.Agent` implementation. - * No pooling/keep-alive is implemented by default. - * - * @param {Function} callback - * @api public - */ -function Agent(callback, _opts) { - if (!(this instanceof Agent)) { - return new Agent(callback, _opts); - } +function isError(obj) { + return obj instanceof Error || + (obj !== null && + typeof obj === "object" && + typeof obj.message === "string" && + typeof obj.name === "string"); +} - EventEmitter.call(this); +function markAsOriginatingFromRejection(e) { + try { + notEnumerableProp(e, "isOperational", true); + } + catch(ignore) {} +} - // The callback gets promisified if it has 3 parameters - // (i.e. it has a callback function) lazily - this._promisifiedCallback = false; +function originatesFromRejection(e) { + if (e == null) return false; + return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || + e["isOperational"] === true); +} - let opts = _opts; - if ('function' === typeof callback) { - this.callback = callback; - } else if (callback) { - opts = callback; - } +function canAttachTrace(obj) { + return isError(obj) && es5.propertyIsWritable(obj, "stack"); +} - // timeout for the socket to be returned from the callback - this.timeout = (opts && opts.timeout) || null; +var ensureErrorObject = (function() { + if (!("stack" in new Error())) { + return function(value) { + if (canAttachTrace(value)) return value; + try {throw new Error(safeToString(value));} + catch(err) {return err;} + }; + } else { + return function(value) { + if (canAttachTrace(value)) return value; + return new Error(safeToString(value)); + }; + } +})(); - this.options = opts; +function classString(obj) { + return {}.toString.call(obj); } -inherits(Agent, EventEmitter); - -/** - * Override this function in your subclass! - */ -Agent.prototype.callback = function callback(req, opts) { - throw new Error( - '"agent-base" has no default implementation, you must subclass and override `callback()`' - ); -}; -/** - * Called by node-core's "_http_client.js" module when creating - * a new HTTP request with this Agent instance. - * - * @api public - */ -Agent.prototype.addRequest = function addRequest(req, _opts) { - const ownOpts = Object.assign({}, _opts); +function copyDescriptors(from, to, filter) { + var keys = es5.names(from); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (filter(key)) { + try { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } catch (ignore) {} + } + } +} - // Set default `host` for HTTP to localhost - if (null == ownOpts.host) { - ownOpts.host = 'localhost'; - } +var asArray = function(v) { + if (es5.isArray(v)) { + return v; + } + return null; +}; - // Set default `port` for HTTP if none was explicitly specified - if (null == ownOpts.port) { - ownOpts.port = ownOpts.secureEndpoint ? 443 : 80; - } +if (typeof Symbol !== "undefined" && Symbol.iterator) { + var ArrayFrom = typeof Array.from === "function" ? function(v) { + return Array.from(v); + } : function(v) { + var ret = []; + var it = v[Symbol.iterator](); + var itResult; + while (!((itResult = it.next()).done)) { + ret.push(itResult.value); + } + return ret; + }; - const opts = Object.assign({}, this.options, ownOpts); + asArray = function(v) { + if (es5.isArray(v)) { + return v; + } else if (v != null && typeof v[Symbol.iterator] === "function") { + return ArrayFrom(v); + } + return null; + }; +} - if (opts.host && opts.path) { - // If both a `host` and `path` are specified then it's most likely the - // result of a `url.parse()` call... we need to remove the `path` portion so - // that `net.connect()` doesn't attempt to open that as a unix socket file. - delete opts.path; - } +var isNode = typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]"; - delete opts.agent; - delete opts.hostname; - delete opts._defaultAgent; - delete opts.defaultPort; - delete opts.createConnection; +var hasEnvVariables = typeof process !== "undefined" && + typeof process.env !== "undefined"; - // Hint to use "Connection: close" - // XXX: non-documented `http` module API :( - req._last = true; - req.shouldKeepAlive = false; +function env(key) { + return hasEnvVariables ? process.env[key] : undefined; +} - // Create the `stream.Duplex` instance - let timeout; - let timedOut = false; - const timeoutMs = this.timeout; - const freeSocket = this.freeSocket; +function getNativePromise() { + if (typeof Promise === "function") { + try { + var promise = new Promise(function(){}); + if (classString(promise) === "[object Promise]") { + return Promise; + } + } catch (e) {} + } +} - function onerror(err) { - if (req._hadError) return; - req.emit('error', err); - // For Safety. Some additional errors might fire later on - // and we need to make sure we don't double-fire the error event. - req._hadError = true; - } +var reflectHandler; +function contextBind(ctx, cb) { + if (ctx === null || + typeof cb !== "function" || + cb === reflectHandler) { + return cb; + } - function ontimeout() { - timeout = null; - timedOut = true; - const err = new Error( - 'A "socket" was not created for HTTP request before ' + timeoutMs + 'ms' - ); - err.code = 'ETIMEOUT'; - onerror(err); - } + if (ctx.domain !== null) { + cb = ctx.domain.bind(cb); + } - function callbackError(err) { - if (timedOut) return; - if (timeout != null) { - clearTimeout(timeout); - timeout = null; + var async = ctx.async; + if (async !== null) { + var old = cb; + cb = function() { + var $_len = arguments.length + 2;var args = new Array($_len); for(var $_i = 2; $_i < $_len ; ++$_i) {args[$_i] = arguments[$_i - 2];}; + args[0] = old; + args[1] = this; + return async.runInAsyncScope.apply(async, args); + }; } - onerror(err); - } + return cb; +} - function onsocket(socket) { - if (timedOut) return; - if (timeout != null) { - clearTimeout(timeout); - timeout = null; +var ret = { + setReflectHandler: function(fn) { + reflectHandler = fn; + }, + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, + thrower: thrower, + isArray: es5.isArray, + asArray: asArray, + notEnumerableProp: notEnumerableProp, + isPrimitive: isPrimitive, + isObject: isObject, + isError: isError, + canEvaluate: canEvaluate, + errorObj: errorObj, + tryCatch: tryCatch, + inherits: inherits, + withAppended: withAppended, + maybeWrapAsError: maybeWrapAsError, + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + isNode: isNode, + hasEnvVariables: hasEnvVariables, + env: env, + global: globalObject, + getNativePromise: getNativePromise, + contextBind: contextBind +}; +ret.isRecentNode = ret.isNode && (function() { + var version; + if (process.versions && process.versions.node) { + version = process.versions.node.split(".").map(Number); + } else if (process.version) { + version = process.version.split(".").map(Number); } - if (isAgent(socket)) { - // `socket` is actually an http.Agent instance, so relinquish - // responsibility for this `req` to the Agent from here on - socket.addRequest(req, opts); - } else if (socket) { - function onfree() { - freeSocket(socket, opts); - } - socket.on('free', onfree); - req.onSocket(socket); - } else { - const err = new Error( - 'no Duplex stream was returned to agent-base for `' + req.method + ' ' + req.path + '`' - ); - onerror(err); + return (version[0] === 0 && version[1] > 10) || (version[0] > 0); +})(); +ret.nodeSupportsAsyncResource = ret.isNode && (function() { + var supportsAsync = false; + try { + var res = __webpack_require__(303).AsyncResource; + supportsAsync = typeof res.prototype.runInAsyncScope === "function"; + } catch (e) { + supportsAsync = false; } - } - - if (!this._promisifiedCallback && this.callback.length >= 3) { - // Legacy callback function - convert to a Promise - this.callback = promisify(this.callback, this); - this._promisifiedCallback = true; - } - - if (timeoutMs > 0) { - timeout = setTimeout(ontimeout, timeoutMs); - } + return supportsAsync; +})(); - try { - Promise.resolve(this.callback(req, opts)).then(onsocket, callbackError); - } catch (err) { - Promise.reject(err).catch(callbackError); - } -}; +if (ret.isNode) ret.toFastProperties(process); -Agent.prototype.freeSocket = function freeSocket(socket, opts) { - // TODO reuse sockets - socket.destroy(); -}; +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; /***/ }), -/* 235 */ +/* 249 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -var util = __webpack_require__(669) -var stream = __webpack_require__(914) -var delegate = __webpack_require__(967) -var Tracker = __webpack_require__(623) -var TrackerStream = module.exports = function (name, size, options) { - stream.Transform.call(this, options) - this.tracker = new Tracker(name, size) - this.name = name - this.id = this.tracker.id - this.tracker.on('change', delegateChange(this)) -} -util.inherits(TrackerStream, stream.Transform) +const BB = __webpack_require__(489) -function delegateChange (trackerStream) { - return function (name, completion, tracker) { - trackerStream.emit('change', name, completion, trackerStream) - } -} +const cacache = __webpack_require__(426) +const cacheKey = __webpack_require__(279) +const optCheck = __webpack_require__(420) +const packlist = __webpack_require__(110) +const pipe = BB.promisify(__webpack_require__(371).pipe) +const tar = __webpack_require__(591) -TrackerStream.prototype._transform = function (data, encoding, cb) { - this.tracker.completeWork(data.length ? data.length : 1) - this.push(data) - cb() -} - -TrackerStream.prototype._flush = function (cb) { - this.tracker.finish() - cb() -} +module.exports = packDir +function packDir (manifest, label, dir, target, opts) { + opts = optCheck(opts) -delegate(TrackerStream.prototype, 'tracker') - .method('completed') - .method('addWork') - .method('finish') + const packer = opts.dirPacker + ? BB.resolve(opts.dirPacker(manifest, dir)) + : mkPacker(dir) + if (!opts.cache) { + return packer.then(packer => pipe(packer, target)) + } else { + const cacher = cacache.put.stream( + opts.cache, cacheKey('packed-dir', label), opts + ).on('integrity', i => { + target.emit('integrity', i) + }) + return packer.then(packer => BB.all([ + pipe(packer, cacher), + pipe(packer, target) + ])) + } +} -/***/ }), -/* 236 */, -/* 237 */ -/***/ (function(module) { +function mkPacker (dir) { + return packlist({ path: dir }).then(files => { + return tar.c({ + cwd: dir, + gzip: true, + portable: true, + prefix: 'package/' + }, files) + }) +} -module.exports = {"name":"make-fetch-happen","version":"5.0.2","description":"Opinionated, caching, retrying fetch client","main":"index.js","files":["*.js","lib"],"scripts":{"prerelease":"npm t","release":"standard-version -s","postrelease":"npm publish --tag=legacy && git push --follow-tags","pretest":"standard","test":"tap --coverage --nyc-arg=--all --timeout=35 -J test/*.js","update-coc":"weallbehave -o . && git add CODE_OF_CONDUCT.md && git commit -m 'docs(coc): updated CODE_OF_CONDUCT.md'","update-contrib":"weallcontribute -o . && git add CONTRIBUTING.md && git commit -m 'docs(contributing): updated CONTRIBUTING.md'"},"repository":"https://github.com/zkat/make-fetch-happen","keywords":["http","request","fetch","mean girls","caching","cache","subresource integrity"],"author":{"name":"Kat Marchán","email":"kzm@zkat.tech","twitter":"maybekatz"},"license":"ISC","dependencies":{"agentkeepalive":"^3.4.1","cacache":"^12.0.0","http-cache-semantics":"^3.8.1","http-proxy-agent":"^2.1.0","https-proxy-agent":"^2.2.3","lru-cache":"^5.1.1","mississippi":"^3.0.0","node-fetch-npm":"^2.0.2","promise-retry":"^1.1.1","socks-proxy-agent":"^4.0.0","ssri":"^6.0.0"},"devDependencies":{"bluebird":"^3.5.1","mkdirp":"^0.5.1","nock":"^9.2.3","npmlog":"^4.1.2","require-inject":"^1.4.2","rimraf":"^2.6.2","safe-buffer":"^5.1.1","standard":"^11.0.1","standard-version":"^4.3.0","tacks":"^1.2.6","tap":"^12.7.0","weallbehave":"^1.0.0","weallcontribute":"^1.0.7"}}; /***/ }), -/* 238 */, -/* 239 */, -/* 240 */ +/* 250 */ /***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; +var constants = __webpack_require__(619) -const LRU = __webpack_require__(702) -const url = __webpack_require__(835) +var origCwd = process.cwd +var cwd = null -let AGENT_CACHE = new LRU({ max: 50 }) -let HttpsAgent -let HttpAgent +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform -module.exports = getAgent +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +try { + process.cwd() +} catch (er) {} -function getAgent (uri, opts) { - const parsedUri = url.parse(typeof uri === 'string' ? uri : uri.url) - const isHttps = parsedUri.protocol === 'https:' - const pxuri = getProxyUri(uri, opts) +var chdir = process.chdir +process.chdir = function(d) { + cwd = null + chdir.call(process, d) +} - const key = [ - `https:${isHttps}`, - pxuri - ? `proxy:${pxuri.protocol}//${pxuri.host}:${pxuri.port}` - : '>no-proxy<', - `local-address:${opts.localAddress || '>no-local-address<'}`, - `strict-ssl:${isHttps ? !!opts.strictSSL : '>no-strict-ssl<'}`, - `ca:${(isHttps && opts.ca) || '>no-ca<'}`, - `cert:${(isHttps && opts.cert) || '>no-cert<'}`, - `key:${(isHttps && opts.key) || '>no-key<'}` - ].join(':') +module.exports = patch - if (opts.agent != null) { // `agent: false` has special behavior! - return opts.agent - } +function patch (fs) { + // (re-)implement some things that are known busted or missing. - if (AGENT_CACHE.peek(key)) { - return AGENT_CACHE.get(key) + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) } - if (pxuri) { - const proxy = getProxy(pxuri, opts, isHttps) - AGENT_CACHE.set(key, proxy) - return proxy + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) } - if (isHttps && !HttpsAgent) { - HttpsAgent = __webpack_require__(112).HttpsAgent - } else if (!isHttps && !HttpAgent) { - HttpAgent = __webpack_require__(112) - } + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. - // If opts.timeout is zero, set the agentTimeout to zero as well. A timeout - // of zero disables the timeout behavior (OS limits still apply). Else, if - // opts.timeout is a non-zero value, set it to timeout + 1, to ensure that - // the node-fetch-npm timeout will always fire first, giving us more - // consistent errors. - const agentTimeout = opts.timeout === 0 ? 0 : opts.timeout + 1 + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) - const agent = isHttps ? new HttpsAgent({ - maxSockets: opts.maxSockets || 15, - ca: opts.ca, - cert: opts.cert, - key: opts.key, - localAddress: opts.localAddress, - rejectUnauthorized: opts.strictSSL, - timeout: agentTimeout - }) : new HttpAgent({ - maxSockets: opts.maxSockets || 15, - localAddress: opts.localAddress, - timeout: agentTimeout - }) - AGENT_CACHE.set(key, agent) - return agent -} + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) -function checkNoProxy (uri, opts) { - const host = url.parse(uri).hostname.split('.').reverse() - let noproxy = (opts.noProxy || getProcessEnv('no_proxy')) - if (typeof noproxy === 'string') { - noproxy = noproxy.split(/\s*,\s*/g) - } - return noproxy && noproxy.some(no => { - const noParts = no.split('.').filter(x => x).reverse() - if (!noParts.length) { return false } - for (let i = 0; i < noParts.length; i++) { - if (host[i] !== noParts[i]) { - return false - } - } - return true - }) -} + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) -module.exports.getProcessEnv = getProcessEnv + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) -function getProcessEnv (env) { - if (!env) { return } + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) - let value + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) - if (Array.isArray(env)) { - for (let e of env) { - value = process.env[e] || - process.env[e.toUpperCase()] || - process.env[e.toLowerCase()] - if (typeof value !== 'undefined') { break } + // if lchmod/lchown do not exist, then make them no-ops + if (!fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) + } + fs.lchmodSync = function () {} + } + if (!fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) } + fs.lchownSync = function () {} } - if (typeof env === 'string') { - value = process.env[env] || - process.env[env.toUpperCase()] || - process.env[env.toLowerCase()] + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. + + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = (function (fs$rename) { return function (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + }})(fs.rename) } - return value -} + // if read() returns EAGAIN, then just try it again. + fs.read = (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } -function getProxyUri (uri, opts) { - const protocol = url.parse(uri).protocol + // This ensures `util.promisify` works as it does for native `fs.read`. + read.__proto__ = fs$read + return read + })(fs.read) - const proxy = opts.proxy || ( - protocol === 'https:' && getProcessEnv('https_proxy') - ) || ( - protocol === 'http:' && getProcessEnv(['https_proxy', 'http_proxy', 'proxy']) - ) - if (!proxy) { return null } + fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) - const parsedProxy = (typeof proxy === 'string') ? url.parse(proxy) : proxy + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } - return !checkNoProxy(uri, opts) && parsedProxy -} + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) -let HttpProxyAgent -let HttpsProxyAgent -let SocksProxyAgent -function getProxy (proxyUrl, opts, isHttps) { - let popts = { - host: proxyUrl.hostname, - port: proxyUrl.port, - protocol: proxyUrl.protocol, - path: proxyUrl.path, - auth: proxyUrl.auth, - ca: opts.ca, - cert: opts.cert, - key: opts.key, - timeout: opts.timeout === 0 ? 0 : opts.timeout + 1, - localAddress: opts.localAddress, - maxSockets: opts.maxSockets || 15, - rejectUnauthorized: opts.strictSSL + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } } - if (proxyUrl.protocol === 'http:' || proxyUrl.protocol === 'https:') { - if (!isHttps) { - if (!HttpProxyAgent) { - HttpProxyAgent = __webpack_require__(934) + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) } - return new HttpProxyAgent(popts) - } else { - if (!HttpsProxyAgent) { - HttpsProxyAgent = __webpack_require__(717) + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret } - return new HttpsProxyAgent(popts) + } else { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} } } - if (proxyUrl.protocol.startsWith('socks')) { - if (!SocksProxyAgent) { - SocksProxyAgent = __webpack_require__(310) - } - return new SocksProxyAgent(popts) + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } } -} + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } -/***/ }), -/* 241 */ -/***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) + } + } + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + return stats; + } + } -/**/ + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true -var pna = __webpack_require__(822); -/**/ + if (er.code === "ENOSYS") + return true -module.exports = Writable; + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } -/* */ -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; + return false + } } -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; - this.next = null; - this.entry = null; - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ +/***/ }), +/* 251 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; -/**/ +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(470)); +const http_client_1 = __webpack_require__(539); +const storage_blob_1 = __webpack_require__(373); +const buffer = __importStar(__webpack_require__(293)); +const fs = __importStar(__webpack_require__(747)); +const stream = __importStar(__webpack_require__(794)); +const util = __importStar(__webpack_require__(669)); +const utils = __importStar(__webpack_require__(15)); +const constants_1 = __webpack_require__(931); +const requestUtils_1 = __webpack_require__(899); +/** + * Pipes the body of a HTTP response to a stream + * + * @param response the HTTP response + * @param output the writable stream + */ +function pipeResponseToStream(response, output) { + return __awaiter(this, void 0, void 0, function* () { + const pipeline = util.promisify(stream.pipeline); + yield pipeline(response.message, output); + }); +} +/** + * Class for tracking the download state and displaying stats. + */ +class DownloadProgress { + constructor(contentLength) { + this.contentLength = contentLength; + this.segmentIndex = 0; + this.segmentSize = 0; + this.segmentOffset = 0; + this.receivedBytes = 0; + this.displayedComplete = false; + this.startTime = Date.now(); + } + /** + * Progress to the next segment. Only call this method when the previous segment + * is complete. + * + * @param segmentSize the length of the next segment + */ + nextSegment(segmentSize) { + this.segmentOffset = this.segmentOffset + this.segmentSize; + this.segmentIndex = this.segmentIndex + 1; + this.segmentSize = segmentSize; + this.receivedBytes = 0; + core.debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`); + } + /** + * Sets the number of bytes received for the current segment. + * + * @param receivedBytes the number of bytes received + */ + setReceivedBytes(receivedBytes) { + this.receivedBytes = receivedBytes; + } + /** + * Returns the total number of bytes transferred. + */ + getTransferredBytes() { + return this.segmentOffset + this.receivedBytes; + } + /** + * Returns true if the download is complete. + */ + isDone() { + return this.getTransferredBytes() === this.contentLength; + } + /** + * Prints the current download stats. Once the download completes, this will print one + * last line and then stop. + */ + display() { + if (this.displayedComplete) { + return; + } + const transferredBytes = this.segmentOffset + this.receivedBytes; + const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); + const elapsedTime = Date.now() - this.startTime; + const downloadSpeed = (transferredBytes / + (1024 * 1024) / + (elapsedTime / 1000)).toFixed(1); + core.info(`Received ${transferredBytes} of ${this.contentLength} (${percentage}%), ${downloadSpeed} MBs/sec`); + if (this.isDone()) { + this.displayedComplete = true; + } + } + /** + * Returns a function used to handle TransferProgressEvents. + */ + onProgress() { + return (progress) => { + this.setReceivedBytes(progress.loadedBytes); + }; + } + /** + * Starts the timer that displays the stats. + * + * @param delayInMs the delay between each write + */ + startDisplayTimer(delayInMs = 1000) { + const displayCallback = () => { + this.display(); + if (!this.isDone()) { + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + }; + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + /** + * Stops the timer that displays the stats. As this typically indicates the download + * is complete, this will display one last line, unless the last line has already + * been written. + */ + stopDisplayTimer() { + if (this.timeoutHandle) { + clearTimeout(this.timeoutHandle); + this.timeoutHandle = undefined; + } + this.display(); + } +} +exports.DownloadProgress = DownloadProgress; +/** + * Download the cache using the Actions toolkit http-client + * + * @param archiveLocation the URL for the cache + * @param archivePath the local path where the cache is saved + */ +function downloadCacheHttpClient(archiveLocation, archivePath) { + return __awaiter(this, void 0, void 0, function* () { + const writeStream = fs.createWriteStream(archivePath); + const httpClient = new http_client_1.HttpClient('actions/cache'); + const downloadResponse = yield requestUtils_1.retryHttpClientResponse('downloadCache', () => __awaiter(this, void 0, void 0, function* () { return httpClient.get(archiveLocation); })); + // Abort download if no traffic received over the socket. + downloadResponse.message.socket.setTimeout(constants_1.SocketTimeout, () => { + downloadResponse.message.destroy(); + core.debug(`Aborting download, socket timed out after ${constants_1.SocketTimeout} ms`); + }); + yield pipeResponseToStream(downloadResponse, writeStream); + // Validate download size. + const contentLengthHeader = downloadResponse.message.headers['content-length']; + if (contentLengthHeader) { + const expectedLength = parseInt(contentLengthHeader); + const actualLength = utils.getArchiveFileSizeIsBytes(archivePath); + if (actualLength !== expectedLength) { + throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`); + } + } + else { + core.debug('Unable to validate download, no Content-Length header'); + } + }); +} +exports.downloadCacheHttpClient = downloadCacheHttpClient; +/** + * Download the cache using the Azure Storage SDK. Only call this method if the + * URL points to an Azure Storage endpoint. + * + * @param archiveLocation the URL for the cache + * @param archivePath the local path where the cache is saved + * @param options the download options with the defaults set + */ +function downloadCacheStorageSDK(archiveLocation, archivePath, options) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const client = new storage_blob_1.BlockBlobClient(archiveLocation, undefined, { + retryOptions: { + // Override the timeout used when downloading each 4 MB chunk + // The default is 2 min / MB, which is way too slow + tryTimeoutInMs: options.timeoutInMs + } + }); + const properties = yield client.getProperties(); + const contentLength = (_a = properties.contentLength) !== null && _a !== void 0 ? _a : -1; + if (contentLength < 0) { + // We should never hit this condition, but just in case fall back to downloading the + // file as one large stream + core.debug('Unable to determine content length, downloading file with http-client...'); + yield downloadCacheHttpClient(archiveLocation, archivePath); + } + else { + // Use downloadToBuffer for faster downloads, since internally it splits the + // file into 4 MB chunks which can then be parallelized and retried independently + // + // If the file exceeds the buffer maximum length (~1 GB on 32-bit systems and ~2 GB + // on 64-bit systems), split the download into multiple segments + const maxSegmentSize = buffer.constants.MAX_LENGTH; + const downloadProgress = new DownloadProgress(contentLength); + const fd = fs.openSync(archivePath, 'w'); + try { + downloadProgress.startDisplayTimer(); + while (!downloadProgress.isDone()) { + const segmentStart = downloadProgress.segmentOffset + downloadProgress.segmentSize; + const segmentSize = Math.min(maxSegmentSize, contentLength - segmentStart); + downloadProgress.nextSegment(segmentSize); + const result = yield client.downloadToBuffer(segmentStart, segmentSize, { + concurrency: options.downloadConcurrency, + onProgress: downloadProgress.onProgress() + }); + fs.writeFileSync(fd, result); + } + } + finally { + downloadProgress.stopDisplayTimer(); + fs.closeSync(fd); + } + } + }); +} +exports.downloadCacheStorageSDK = downloadCacheStorageSDK; +//# sourceMappingURL=downloadUtils.js.map -/**/ -var Duplex; -/**/ +/***/ }), +/* 252 */, +/* 253 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -Writable.WritableState = WritableState; +"use strict"; -/**/ -var util = Object.create(__webpack_require__(286)); -util.inherits = __webpack_require__(689); -/**/ +module.exports = function(NEXT_FILTER) { +var util = __webpack_require__(248); +var getKeys = __webpack_require__(883).keys; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; -/**/ -var internalUtil = { - deprecate: __webpack_require__(917) +function catchFilter(instances, cb, promise) { + return function(e) { + var boundTo = promise._boundValue(); + predicateLoop: for (var i = 0; i < instances.length; ++i) { + var item = instances[i]; + + if (item === Error || + (item != null && item.prototype instanceof Error)) { + if (e instanceof item) { + return tryCatch(cb).call(boundTo, e); + } + } else if (typeof item === "function") { + var matchesPredicate = tryCatch(item).call(boundTo, e); + if (matchesPredicate === errorObj) { + return matchesPredicate; + } else if (matchesPredicate) { + return tryCatch(cb).call(boundTo, e); + } + } else if (util.isObject(e)) { + var keys = getKeys(item); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + if (item[key] != e[key]) { + continue predicateLoop; + } + } + return tryCatch(cb).call(boundTo, e); + } + } + return NEXT_FILTER; + }; +} + +return catchFilter; }; -/**/ -/**/ -var Stream = __webpack_require__(41); -/**/ -/**/ +/***/ }), +/* 254 */ +/***/ (function(module, exports, __webpack_require__) { -var Buffer = __webpack_require__(254).Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(293) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } } -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer } -/**/ +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} -var destroyImpl = __webpack_require__(232); +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) -util.inherits(Writable, Stream); +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} -function nop() {} +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} -function WritableState(options, stream) { - Duplex = Duplex || __webpack_require__(907); +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} - options = options || {}; +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; +/***/ }), +/* 255 */, +/* 256 */, +/* 257 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; +// Generated by CoffeeScript 1.12.7 +(function() { + var DocumentPosition, NodeType, XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLDummy, XMLElement, XMLNamedNodeMap, XMLNode, XMLNodeList, XMLProcessingInstruction, XMLRaw, XMLText, getValue, isEmpty, isFunction, isObject, ref1, + hasProp = {}.hasOwnProperty; - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var writableHwm = options.writableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; + ref1 = __webpack_require__(582), isObject = ref1.isObject, isFunction = ref1.isFunction, isEmpty = ref1.isEmpty, getValue = ref1.getValue; - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + XMLElement = null; - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); + XMLCData = null; - // if _final has been called - this.finalCalled = false; + XMLComment = null; - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + XMLDeclaration = null; - // has it been destroyed - this.destroyed = false; + XMLDocType = null; - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; + XMLRaw = null; - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + XMLText = null; - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + XMLProcessingInstruction = null; - // a flag to see when we're in the middle of a write. - this.writing = false; + XMLDummy = null; - // when true all writes will be buffered until .uncork() call - this.corked = 0; + NodeType = null; - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + XMLNodeList = null; - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; + XMLNamedNodeMap = null; - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; + DocumentPosition = null; - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + module.exports = XMLNode = (function() { + function XMLNode(parent1) { + this.parent = parent1; + if (this.parent) { + this.options = this.parent.options; + this.stringify = this.parent.stringify; + } + this.value = null; + this.children = []; + this.baseURI = null; + if (!XMLElement) { + XMLElement = __webpack_require__(796); + XMLCData = __webpack_require__(657); + XMLComment = __webpack_require__(919); + XMLDeclaration = __webpack_require__(738); + XMLDocType = __webpack_require__(735); + XMLRaw = __webpack_require__(660); + XMLText = __webpack_require__(708); + XMLProcessingInstruction = __webpack_require__(491); + XMLDummy = __webpack_require__(956); + NodeType = __webpack_require__(683); + XMLNodeList = __webpack_require__(300); + XMLNamedNodeMap = __webpack_require__(451); + DocumentPosition = __webpack_require__(65); + } + } - // the amount that is being written when _write is called. - this.writelen = 0; + Object.defineProperty(XMLNode.prototype, 'nodeName', { + get: function() { + return this.name; + } + }); - this.bufferedRequest = null; - this.lastBufferedRequest = null; + Object.defineProperty(XMLNode.prototype, 'nodeType', { + get: function() { + return this.type; + } + }); - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; + Object.defineProperty(XMLNode.prototype, 'nodeValue', { + get: function() { + return this.value; + } + }); - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + Object.defineProperty(XMLNode.prototype, 'parentNode', { + get: function() { + return this.parent; + } + }); - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; + Object.defineProperty(XMLNode.prototype, 'childNodes', { + get: function() { + if (!this.childNodeList || !this.childNodeList.nodes) { + this.childNodeList = new XMLNodeList(this.children); + } + return this.childNodeList; + } + }); - // count buffered requests - this.bufferedRequestCount = 0; + Object.defineProperty(XMLNode.prototype, 'firstChild', { + get: function() { + return this.children[0] || null; + } + }); - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} + Object.defineProperty(XMLNode.prototype, 'lastChild', { + get: function() { + return this.children[this.children.length - 1] || null; + } + }); -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; -}; + Object.defineProperty(XMLNode.prototype, 'previousSibling', { + get: function() { + var i; + i = this.parent.children.indexOf(this); + return this.parent.children[i - 1] || null; + } + }); -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + Object.defineProperty(XMLNode.prototype, 'nextSibling', { + get: function() { + var i; + i = this.parent.children.indexOf(this); + return this.parent.children[i + 1] || null; + } }); - } catch (_) {} -})(); -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; + Object.defineProperty(XMLNode.prototype, 'ownerDocument', { + get: function() { + return this.document() || null; + } + }); - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; -} + Object.defineProperty(XMLNode.prototype, 'textContent', { + get: function() { + var child, j, len, ref2, str; + if (this.nodeType === NodeType.Element || this.nodeType === NodeType.DocumentFragment) { + str = ''; + ref2 = this.children; + for (j = 0, len = ref2.length; j < len; j++) { + child = ref2[j]; + if (child.textContent) { + str += child.textContent; + } + } + return str; + } else { + return null; + } + }, + set: function(value) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + } + }); -function Writable(options) { - Duplex = Duplex || __webpack_require__(907); + XMLNode.prototype.setParent = function(parent) { + var child, j, len, ref2, results; + this.parent = parent; + if (parent) { + this.options = parent.options; + this.stringify = parent.stringify; + } + ref2 = this.children; + results = []; + for (j = 0, len = ref2.length; j < len; j++) { + child = ref2[j]; + results.push(child.setParent(this)); + } + return results; + }; - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. + XMLNode.prototype.element = function(name, attributes, text) { + var childNode, item, j, k, key, lastChild, len, len1, ref2, ref3, val; + lastChild = null; + if (attributes === null && (text == null)) { + ref2 = [{}, null], attributes = ref2[0], text = ref2[1]; + } + if (attributes == null) { + attributes = {}; + } + attributes = getValue(attributes); + if (!isObject(attributes)) { + ref3 = [attributes, text], text = ref3[0], attributes = ref3[1]; + } + if (name != null) { + name = getValue(name); + } + if (Array.isArray(name)) { + for (j = 0, len = name.length; j < len; j++) { + item = name[j]; + lastChild = this.element(item); + } + } else if (isFunction(name)) { + lastChild = this.element(name.apply()); + } else if (isObject(name)) { + for (key in name) { + if (!hasProp.call(name, key)) continue; + val = name[key]; + if (isFunction(val)) { + val = val.apply(); + } + if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) { + lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val); + } else if (!this.options.separateArrayItems && Array.isArray(val) && isEmpty(val)) { + lastChild = this.dummy(); + } else if (isObject(val) && isEmpty(val)) { + lastChild = this.element(key); + } else if (!this.options.keepNullNodes && (val == null)) { + lastChild = this.dummy(); + } else if (!this.options.separateArrayItems && Array.isArray(val)) { + for (k = 0, len1 = val.length; k < len1; k++) { + item = val[k]; + childNode = {}; + childNode[key] = item; + lastChild = this.element(childNode); + } + } else if (isObject(val)) { + if (!this.options.ignoreDecorators && this.stringify.convertTextKey && key.indexOf(this.stringify.convertTextKey) === 0) { + lastChild = this.element(val); + } else { + lastChild = this.element(key); + lastChild.element(val); + } + } else { + lastChild = this.element(key, val); + } + } + } else if (!this.options.keepNullNodes && text === null) { + lastChild = this.dummy(); + } else { + if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) { + lastChild = this.text(text); + } else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) { + lastChild = this.cdata(text); + } else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) { + lastChild = this.comment(text); + } else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) { + lastChild = this.raw(text); + } else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && name.indexOf(this.stringify.convertPIKey) === 0) { + lastChild = this.instruction(name.substr(this.stringify.convertPIKey.length), text); + } else { + lastChild = this.node(name, attributes, text); + } + } + if (lastChild == null) { + throw new Error("Could not create any elements with: " + name + ". " + this.debugInfo()); + } + return lastChild; + }; - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); - } + XMLNode.prototype.insertBefore = function(name, attributes, text) { + var child, i, newChild, refChild, removed; + if (name != null ? name.type : void 0) { + newChild = name; + refChild = attributes; + newChild.setParent(this); + if (refChild) { + i = children.indexOf(refChild); + removed = children.splice(i); + children.push(newChild); + Array.prototype.push.apply(children, removed); + } else { + children.push(newChild); + } + return newChild; + } else { + if (this.isRoot) { + throw new Error("Cannot insert elements at root level. " + this.debugInfo(name)); + } + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i); + child = this.parent.element(name, attributes, text); + Array.prototype.push.apply(this.parent.children, removed); + return child; + } + }; - this._writableState = new WritableState(options, this); + XMLNode.prototype.insertAfter = function(name, attributes, text) { + var child, i, removed; + if (this.isRoot) { + throw new Error("Cannot insert elements at root level. " + this.debugInfo(name)); + } + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i + 1); + child = this.parent.element(name, attributes, text); + Array.prototype.push.apply(this.parent.children, removed); + return child; + }; - // legacy. - this.writable = true; + XMLNode.prototype.remove = function() { + var i, ref2; + if (this.isRoot) { + throw new Error("Cannot remove the root element. " + this.debugInfo()); + } + i = this.parent.children.indexOf(this); + [].splice.apply(this.parent.children, [i, i - i + 1].concat(ref2 = [])), ref2; + return this.parent; + }; - if (options) { - if (typeof options.write === 'function') this._write = options.write; + XMLNode.prototype.node = function(name, attributes, text) { + var child, ref2; + if (name != null) { + name = getValue(name); + } + attributes || (attributes = {}); + attributes = getValue(attributes); + if (!isObject(attributes)) { + ref2 = [attributes, text], text = ref2[0], attributes = ref2[1]; + } + child = new XMLElement(this, name, attributes); + if (text != null) { + child.text(text); + } + this.children.push(child); + return child; + }; - if (typeof options.writev === 'function') this._writev = options.writev; + XMLNode.prototype.text = function(value) { + var child; + if (isObject(value)) { + this.element(value); + } + child = new XMLText(this, value); + this.children.push(child); + return this; + }; - if (typeof options.destroy === 'function') this._destroy = options.destroy; + XMLNode.prototype.cdata = function(value) { + var child; + child = new XMLCData(this, value); + this.children.push(child); + return this; + }; - if (typeof options.final === 'function') this._final = options.final; - } + XMLNode.prototype.comment = function(value) { + var child; + child = new XMLComment(this, value); + this.children.push(child); + return this; + }; - Stream.call(this); -} + XMLNode.prototype.commentBefore = function(value) { + var child, i, removed; + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i); + child = this.parent.comment(value); + Array.prototype.push.apply(this.parent.children, removed); + return this; + }; -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); -}; + XMLNode.prototype.commentAfter = function(value) { + var child, i, removed; + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i + 1); + child = this.parent.comment(value); + Array.prototype.push.apply(this.parent.children, removed); + return this; + }; -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - pna.nextTick(cb, er); -} + XMLNode.prototype.raw = function(value) { + var child; + child = new XMLRaw(this, value); + this.children.push(child); + return this; + }; -// Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. -function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; + XMLNode.prototype.dummy = function() { + var child; + child = new XMLDummy(this); + return child; + }; - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - pna.nextTick(cb, er); - valid = false; - } - return valid; -} + XMLNode.prototype.instruction = function(target, value) { + var insTarget, insValue, instruction, j, len; + if (target != null) { + target = getValue(target); + } + if (value != null) { + value = getValue(value); + } + if (Array.isArray(target)) { + for (j = 0, len = target.length; j < len; j++) { + insTarget = target[j]; + this.instruction(insTarget); + } + } else if (isObject(target)) { + for (insTarget in target) { + if (!hasProp.call(target, insTarget)) continue; + insValue = target[insTarget]; + this.instruction(insTarget, insValue); + } + } else { + if (isFunction(value)) { + value = value.apply(); + } + instruction = new XMLProcessingInstruction(this, target, value); + this.children.push(instruction); + } + return this; + }; -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = !state.objectMode && _isUint8Array(chunk); + XMLNode.prototype.instructionBefore = function(target, value) { + var child, i, removed; + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i); + child = this.parent.instruction(target, value); + Array.prototype.push.apply(this.parent.children, removed); + return this; + }; - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } + XMLNode.prototype.instructionAfter = function(target, value) { + var child, i, removed; + i = this.parent.children.indexOf(this); + removed = this.parent.children.splice(i + 1); + child = this.parent.instruction(target, value); + Array.prototype.push.apply(this.parent.children, removed); + return this; + }; - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + XMLNode.prototype.declaration = function(version, encoding, standalone) { + var doc, xmldec; + doc = this.document(); + xmldec = new XMLDeclaration(doc, version, encoding, standalone); + if (doc.children.length === 0) { + doc.children.unshift(xmldec); + } else if (doc.children[0].type === NodeType.Declaration) { + doc.children[0] = xmldec; + } else { + doc.children.unshift(xmldec); + } + return doc.root() || doc; + }; - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + XMLNode.prototype.dtd = function(pubID, sysID) { + var child, doc, doctype, i, j, k, len, len1, ref2, ref3; + doc = this.document(); + doctype = new XMLDocType(doc, pubID, sysID); + ref2 = doc.children; + for (i = j = 0, len = ref2.length; j < len; i = ++j) { + child = ref2[i]; + if (child.type === NodeType.DocType) { + doc.children[i] = doctype; + return doctype; + } + } + ref3 = doc.children; + for (i = k = 0, len1 = ref3.length; k < len1; i = ++k) { + child = ref3[i]; + if (child.isRoot) { + doc.children.splice(i, 0, doctype); + return doctype; + } + } + doc.children.push(doctype); + return doctype; + }; - if (typeof cb !== 'function') cb = nop; + XMLNode.prototype.up = function() { + if (this.isRoot) { + throw new Error("The root node has no parent. Use doc() if you need to get the document object."); + } + return this.parent; + }; - if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } + XMLNode.prototype.root = function() { + var node; + node = this; + while (node) { + if (node.type === NodeType.Document) { + return node.rootObject; + } else if (node.isRoot) { + return node; + } else { + node = node.parent; + } + } + }; - return ret; -}; - -Writable.prototype.cork = function () { - var state = this._writableState; - - state.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; + XMLNode.prototype.document = function() { + var node; + node = this; + while (node) { + if (node.type === NodeType.Document) { + return node; + } else { + node = node.parent; + } + } + }; - if (state.corked) { - state.corked--; + XMLNode.prototype.end = function(options) { + return this.document().end(options); + }; - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; + XMLNode.prototype.prev = function() { + var i; + i = this.parent.children.indexOf(this); + if (i < 1) { + throw new Error("Already at the first node. " + this.debugInfo()); + } + return this.parent.children[i - 1]; + }; -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; + XMLNode.prototype.next = function() { + var i; + i = this.parent.children.indexOf(this); + if (i === -1 || i === this.parent.children.length - 1) { + throw new Error("Already at the last node. " + this.debugInfo()); + } + return this.parent.children[i + 1]; + }; -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - return chunk; -} + XMLNode.prototype.importDocument = function(doc) { + var clonedRoot; + clonedRoot = doc.root().clone(); + clonedRoot.parent = this; + clonedRoot.isRoot = false; + this.children.push(clonedRoot); + return this; + }; -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._writableState.highWaterMark; - } -}); + XMLNode.prototype.debugInfo = function(name) { + var ref2, ref3; + name = name || this.name; + if ((name == null) && !((ref2 = this.parent) != null ? ref2.name : void 0)) { + return ""; + } else if (name == null) { + return "parent: <" + this.parent.name + ">"; + } else if (!((ref3 = this.parent) != null ? ref3.name : void 0)) { + return "node: <" + name + ">"; + } else { + return "node: <" + name + ">, parent: <" + this.parent.name + ">"; + } + }; -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - var len = state.objectMode ? 1 : chunk.length; + XMLNode.prototype.ele = function(name, attributes, text) { + return this.element(name, attributes, text); + }; - state.length += len; + XMLNode.prototype.nod = function(name, attributes, text) { + return this.node(name, attributes, text); + }; - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; + XMLNode.prototype.txt = function(value) { + return this.text(value); + }; - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null + XMLNode.prototype.dat = function(value) { + return this.cdata(value); }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - return ret; -} + XMLNode.prototype.com = function(value) { + return this.comment(value); + }; -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} + XMLNode.prototype.ins = function(target, value) { + return this.instruction(target, value); + }; -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; + XMLNode.prototype.doc = function() { + return this.document(); + }; - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - pna.nextTick(cb, er); - // this can emit finish, and it will always happen - // after error - pna.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - // this can emit finish, but finish must - // always follow error - finishMaybe(stream, state); - } -} + XMLNode.prototype.dec = function(version, encoding, standalone) { + return this.declaration(version, encoding, standalone); + }; -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} + XMLNode.prototype.e = function(name, attributes, text) { + return this.element(name, attributes, text); + }; -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + XMLNode.prototype.n = function(name, attributes, text) { + return this.node(name, attributes, text); + }; - onwriteStateUpdate(state); + XMLNode.prototype.t = function(value) { + return this.text(value); + }; - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); + XMLNode.prototype.d = function(value) { + return this.cdata(value); + }; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } + XMLNode.prototype.c = function(value) { + return this.comment(value); + }; - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } -} + XMLNode.prototype.r = function(value) { + return this.raw(value); + }; -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} + XMLNode.prototype.i = function(target, value) { + return this.instruction(target, value); + }; -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} + XMLNode.prototype.u = function() { + return this.up(); + }; -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + XMLNode.prototype.importXMLBuilder = function(doc) { + return this.importDocument(doc); + }; - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; + XMLNode.prototype.replaceChild = function(newChild, oldChild) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - buffer.allBuffers = allBuffers; + XMLNode.prototype.removeChild = function(oldChild) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); + XMLNode.prototype.appendChild = function(newChild) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + XMLNode.prototype.hasChildNodes = function() { + return this.children.length !== 0; + }; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } + XMLNode.prototype.cloneNode = function(deep) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; - if (entry === null) state.lastBufferedRequest = null; - } + XMLNode.prototype.normalize = function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; - state.bufferedRequest = entry; - state.bufferProcessing = false; -} + XMLNode.prototype.isSupported = function(feature, version) { + return true; + }; -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('_write() is not implemented')); -}; + XMLNode.prototype.hasAttributes = function() { + return this.attribs.length !== 0; + }; -Writable.prototype._writev = null; + XMLNode.prototype.compareDocumentPosition = function(other) { + var ref, res; + ref = this; + if (ref === other) { + return 0; + } else if (this.document() !== other.document()) { + res = DocumentPosition.Disconnected | DocumentPosition.ImplementationSpecific; + if (Math.random() < 0.5) { + res |= DocumentPosition.Preceding; + } else { + res |= DocumentPosition.Following; + } + return res; + } else if (ref.isAncestor(other)) { + return DocumentPosition.Contains | DocumentPosition.Preceding; + } else if (ref.isDescendant(other)) { + return DocumentPosition.Contains | DocumentPosition.Following; + } else if (ref.isPreceding(other)) { + return DocumentPosition.Preceding; + } else { + return DocumentPosition.Following; + } + }; -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + XMLNode.prototype.isSameNode = function(other) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + XMLNode.prototype.lookupPrefix = function(namespaceURI) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + XMLNode.prototype.isDefaultNamespace = function(namespaceURI) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } + XMLNode.prototype.lookupNamespaceURI = function(prefix) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); -}; + XMLNode.prototype.isEqualNode = function(node) { + var i, j, ref2; + if (node.nodeType !== this.nodeType) { + return false; + } + if (node.children.length !== this.children.length) { + return false; + } + for (i = j = 0, ref2 = this.children.length - 1; 0 <= ref2 ? j <= ref2 : j >= ref2; i = 0 <= ref2 ? ++j : --j) { + if (!this.children[i].isEqualNode(node.children[i])) { + return false; + } + } + return true; + }; -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - if (err) { - stream.emit('error', err); - } - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function') { - state.pendingcb++; - state.finalCalled = true; - pna.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} + XMLNode.prototype.getFeature = function(feature, version) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - } - } - return need; -} + XMLNode.prototype.setUserData = function(key, data, handler) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; -} + XMLNode.prototype.getUserData = function(key) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = corkReq; - } else { - state.corkedRequestsFree = corkReq; - } -} + XMLNode.prototype.contains = function(other) { + if (!other) { + return false; + } + return other === this || this.isDescendant(other); + }; -Object.defineProperty(Writable.prototype, 'destroyed', { - get: function () { - if (this._writableState === undefined) { + XMLNode.prototype.isDescendant = function(node) { + var child, isDescendantChild, j, len, ref2; + ref2 = this.children; + for (j = 0, len = ref2.length; j < len; j++) { + child = ref2[j]; + if (node === child) { + return true; + } + isDescendantChild = child.isDescendant(node); + if (isDescendantChild) { + return true; + } + } return false; - } - return this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } + }; - // backward compatibility, the user is explicitly - // managing destroyed - this._writableState.destroyed = value; - } -}); + XMLNode.prototype.isAncestor = function(node) { + return node.isDescendant(this); + }; -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; -Writable.prototype._destroy = function (err, cb) { - this.end(); - cb(err); -}; + XMLNode.prototype.isPreceding = function(node) { + var nodePos, thisPos; + nodePos = this.treePosition(node); + thisPos = this.treePosition(this); + if (nodePos === -1 || thisPos === -1) { + return false; + } else { + return nodePos < thisPos; + } + }; -/***/ }), -/* 242 */, -/* 243 */ -/***/ (function(module) { + XMLNode.prototype.isFollowing = function(node) { + var nodePos, thisPos; + nodePos = this.treePosition(node); + thisPos = this.treePosition(this); + if (nodePos === -1 || thisPos === -1) { + return false; + } else { + return nodePos > thisPos; + } + }; -"use strict"; + XMLNode.prototype.treePosition = function(node) { + var found, pos; + pos = 0; + found = false; + this.foreachTreeNode(this.document(), function(childNode) { + pos++; + if (!found && childNode === node) { + return found = true; + } + }); + if (found) { + return pos; + } else { + return -1; + } + }; + XMLNode.prototype.foreachTreeNode = function(node, func) { + var child, j, len, ref2, res; + node || (node = this.document()); + ref2 = node.children; + for (j = 0, len = ref2.length; j < len; j++) { + child = ref2[j]; + if (res = func(child)) { + return res; + } else { + res = this.foreachTreeNode(child, func); + if (res) { + return res; + } + } + } + }; -module.exports = isWin32() || isColorTerm() + return XMLNode; -function isWin32 () { - return process.platform === 'win32' -} + })(); -function isColorTerm () { - var termHasColor = /^screen|^xterm|^vt100|color|ansi|cygwin|linux/i - return !!process.env.COLORTERM || termHasColor.test(process.env.TERM) -} +}).call(this); /***/ }), -/* 244 */ +/* 258 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -module.exports = __webpack_require__(676) +const ls = __webpack_require__(14) +const get = __webpack_require__(425) +const put = __webpack_require__(154) +const rm = __webpack_require__(435) +const verify = __webpack_require__(290) +const setLocale = __webpack_require__(945).setLocale +const clearMemoized = __webpack_require__(521).clearMemoized +const tmp = __webpack_require__(862) +setLocale('en') -/***/ }), -/* 245 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +const x = module.exports -module.exports = globSync -globSync.GlobSync = GlobSync +x.ls = cache => ls(cache) +x.ls.stream = cache => ls.stream(cache) -var fs = __webpack_require__(747) -var rp = __webpack_require__(302) -var minimatch = __webpack_require__(723) -var Minimatch = minimatch.Minimatch -var Glob = __webpack_require__(402).Glob -var util = __webpack_require__(669) -var path = __webpack_require__(622) -var assert = __webpack_require__(357) -var isAbsolute = __webpack_require__(681) -var common = __webpack_require__(856) -var alphasort = common.alphasort -var alphasorti = common.alphasorti -var setopts = common.setopts -var ownProp = common.ownProp -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored +x.get = (cache, key, opts) => get(cache, key, opts) +x.get.byDigest = (cache, hash, opts) => get.byDigest(cache, hash, opts) +x.get.sync = (cache, key, opts) => get.sync(cache, key, opts) +x.get.sync.byDigest = (cache, key, opts) => get.sync.byDigest(cache, key, opts) +x.get.stream = (cache, key, opts) => get.stream(cache, key, opts) +x.get.stream.byDigest = (cache, hash, opts) => get.stream.byDigest(cache, hash, opts) +x.get.copy = (cache, key, dest, opts) => get.copy(cache, key, dest, opts) +x.get.copy.byDigest = (cache, hash, dest, opts) => get.copy.byDigest(cache, hash, dest, opts) +x.get.info = (cache, key) => get.info(cache, key) +x.get.hasContent = (cache, hash) => get.hasContent(cache, hash) +x.get.hasContent.sync = (cache, hash) => get.hasContent.sync(cache, hash) -function globSync (pattern, options) { - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') +x.put = (cache, key, data, opts) => put(cache, key, data, opts) +x.put.stream = (cache, key, opts) => put.stream(cache, key, opts) - return new GlobSync(pattern, options).found -} +x.rm = (cache, key) => rm.entry(cache, key) +x.rm.all = cache => rm.all(cache) +x.rm.entry = x.rm +x.rm.content = (cache, hash) => rm.content(cache, hash) -function GlobSync (pattern, options) { - if (!pattern) - throw new Error('must provide pattern') +x.setLocale = lang => setLocale(lang) +x.clearMemoized = () => clearMemoized() - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') +x.tmp = {} +x.tmp.mkdir = (cache, opts) => tmp.mkdir(cache, opts) +x.tmp.withTmp = (cache, opts, cb) => tmp.withTmp(cache, opts, cb) - if (!(this instanceof GlobSync)) - return new GlobSync(pattern, options) +x.verify = (cache, opts) => verify(cache, opts) +x.verify.lastRun = cache => verify.lastRun(cache) - setopts(this, pattern, options) - if (this.noprocess) - return this +/***/ }), +/* 259 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - var n = this.minimatch.set.length - this.matches = new Array(n) - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false) - } - this._finish() -} +"use strict"; -GlobSync.prototype._finish = function () { - assert(this instanceof GlobSync) - if (this.realpath) { - var self = this - this.matches.forEach(function (matchset, index) { - var set = self.matches[index] = Object.create(null) - for (var p in matchset) { - try { - p = self._makeAbs(p) - var real = rp.realpathSync(p, self.realpathCache) - set[real] = true - } catch (er) { - if (er.syscall === 'stat') - set[self._makeAbs(p)] = true - else - throw er - } - } - }) - } - common.finish(this) -} +const cacache = __webpack_require__(426) +const fetch = __webpack_require__(269) +const pipe = __webpack_require__(371).pipe +const ssri = __webpack_require__(951) +const through = __webpack_require__(371).through +const to = __webpack_require__(371).to +const url = __webpack_require__(835) +const stream = __webpack_require__(794) -GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert(this instanceof GlobSync) - - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. - - // See if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index) - return - - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break - - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break - } - - var remain = pattern.slice(n) - - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix - - var abs = this._makeAbs(read) - - //if ignored, skip processing - if (childrenIgnored(this, read)) - return +const MAX_MEM_SIZE = 5 * 1024 * 1024 // 5MB - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar) +function cacheKey (req) { + const parsed = url.parse(req.url) + return `make-fetch-happen:request-cache:${ + url.format({ + protocol: parsed.protocol, + slashes: parsed.slashes, + host: parsed.host, + hostname: parsed.hostname, + pathname: parsed.pathname + }) + }` } +// This is a cacache-based implementation of the Cache standard, +// using node-fetch. +// docs: https://developer.mozilla.org/en-US/docs/Web/API/Cache +// +module.exports = class Cache { + constructor (path, opts) { + this._path = path + this.Promise = (opts && opts.Promise) || Promise + } -GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) - - // if the abs isn't a dir, then nothing can match! - if (!entries) - return + // Returns a Promise that resolves to the response associated with the first + // matching request in the Cache object. + match (req, opts) { + opts = opts || {} + const key = cacheKey(req) + return cacache.get.info(this._path, key).then(info => { + return info && cacache.get.hasContent( + this._path, info.integrity, opts + ).then(exists => exists && info) + }).then(info => { + if (info && info.metadata && matchDetails(req, { + url: info.metadata.url, + reqHeaders: new fetch.Headers(info.metadata.reqHeaders), + resHeaders: new fetch.Headers(info.metadata.resHeaders), + cacheIntegrity: info.integrity, + integrity: opts && opts.integrity + })) { + const resHeaders = new fetch.Headers(info.metadata.resHeaders) + addCacheHeaders(resHeaders, this._path, key, info.integrity, info.time) + if (req.method === 'HEAD') { + return new fetch.Response(null, { + url: req.url, + headers: resHeaders, + status: 200 + }) + } + let body + const cachePath = this._path + // avoid opening cache file handles until a user actually tries to + // read from it. + if (opts.memoize !== false && info.size > MAX_MEM_SIZE) { + body = new stream.PassThrough() + const realRead = body._read + body._read = function (size) { + body._read = realRead + pipe( + cacache.get.stream.byDigest(cachePath, info.integrity, { + memoize: opts.memoize + }), + body, + err => body.emit(err)) + return realRead.call(this, size) + } + } else { + let readOnce = false + // cacache is much faster at bulk reads + body = new stream.Readable({ + read () { + if (readOnce) return this.push(null) + readOnce = true + cacache.get.byDigest(cachePath, info.integrity, { + memoize: opts.memoize + }).then(data => { + this.push(data) + this.push(null) + }, err => this.emit('error', err)) + } + }) + } + return this.Promise.resolve(new fetch.Response(body, { + url: req.url, + headers: resHeaders, + status: 200, + size: info.size + })) + } + }) + } - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' + // Takes both a request and its response and adds it to the given cache. + put (req, response, opts) { + opts = opts || {} + const size = response.headers.get('content-length') + const fitInMemory = !!size && opts.memoize !== false && size < MAX_MEM_SIZE + const ckey = cacheKey(req) + const cacheOpts = { + algorithms: opts.algorithms, + metadata: { + url: req.url, + reqHeaders: req.headers.raw(), + resHeaders: response.headers.raw() + }, + size, + memoize: fitInMemory && opts.memoize + } + if (req.method === 'HEAD' || response.status === 304) { + // Update metadata without writing + return cacache.get.info(this._path, ckey).then(info => { + // Providing these will bypass content write + cacheOpts.integrity = info.integrity + addCacheHeaders( + response.headers, this._path, ckey, info.integrity, info.time + ) + return new this.Promise((resolve, reject) => { + pipe( + cacache.get.stream.byDigest(this._path, info.integrity, cacheOpts), + cacache.put.stream(this._path, cacheKey(req), cacheOpts), + err => err ? reject(err) : resolve(response) + ) + }) + }).then(() => response) + } + let buf = [] + let bufSize = 0 + let cacheTargetStream = false + const cachePath = this._path + let cacheStream = to((chunk, enc, cb) => { + if (!cacheTargetStream) { + if (fitInMemory) { + cacheTargetStream = + to({highWaterMark: MAX_MEM_SIZE}, (chunk, enc, cb) => { + buf.push(chunk) + bufSize += chunk.length + cb() + }, done => { + cacache.put( + cachePath, + cacheKey(req), + Buffer.concat(buf, bufSize), + cacheOpts + ).then( + () => done(), + done + ) + }) + } else { + cacheTargetStream = + cacache.put.stream(cachePath, cacheKey(req), cacheOpts) + } + } + cacheTargetStream.write(chunk, enc, cb) + }, done => { + cacheTargetStream ? cacheTargetStream.end(done) : done() + }) + const oldBody = response.body + const newBody = through({highWaterMark: MAX_MEM_SIZE}) + response.body = newBody + oldBody.once('error', err => newBody.emit('error', err)) + newBody.once('error', err => oldBody.emit('error', err)) + cacheStream.once('error', err => newBody.emit('error', err)) + pipe(oldBody, to((chunk, enc, cb) => { + cacheStream.write(chunk, enc, () => { + newBody.write(chunk, enc, cb) + }) + }, done => { + cacheStream.end(() => { + newBody.end(() => { + done() + }) + }) + }), err => err && newBody.emit('error', err)) + return response + } - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) + // Finds the Cache entry whose key is the request, and if found, deletes the + // Cache entry and returns a Promise that resolves to true. If no Cache entry + // is found, it returns false. + 'delete' (req, opts) { + opts = opts || {} + if (typeof opts.memoize === 'object') { + if (opts.memoize.reset) { + opts.memoize.reset() + } else if (opts.memoize.clear) { + opts.memoize.clear() } else { - m = e.match(pn) + Object.keys(opts.memoize).forEach(k => { + opts.memoize[k] = null + }) } - if (m) - matchedEntries.push(e) } + return cacache.rm.entry( + this._path, + cacheKey(req) + // TODO - true/false + ).then(() => false) } +} - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return - - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. - - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix.slice(-1) !== '/') - e = prefix + '/' + e - else - e = prefix + e - } - - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) +function matchDetails (req, cached) { + const reqUrl = url.parse(req.url) + const cacheUrl = url.parse(cached.url) + const vary = cached.resHeaders.get('Vary') + // https://tools.ietf.org/html/rfc7234#section-4.1 + if (vary) { + if (vary.match(/\*/)) { + return false + } else { + const fieldsMatch = vary.split(/\s*,\s*/).every(field => { + return cached.reqHeaders.get(field) === req.headers.get(field) + }) + if (!fieldsMatch) { + return false } - this._emitMatch(index, e) } - // This was the last one, and no stats were needed - return } - - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) - newPattern = [prefix, e] - else - newPattern = [e] - this._process(newPattern.concat(remain), index, inGlobStar) + if (cached.integrity) { + return ssri.parse(cached.integrity).match(cached.cacheIntegrity) } + reqUrl.hash = null + cacheUrl.hash = null + return url.format(reqUrl) === url.format(cacheUrl) } +function addCacheHeaders (resHeaders, path, key, hash, time) { + resHeaders.set('X-Local-Cache', encodeURIComponent(path)) + resHeaders.set('X-Local-Cache-Key', encodeURIComponent(key)) + resHeaders.set('X-Local-Cache-Hash', encodeURIComponent(hash)) + resHeaders.set('X-Local-Cache-Time', new Date(time).toUTCString()) +} -GlobSync.prototype._emitMatch = function (index, e) { - if (isIgnored(this, e)) - return - var abs = this._makeAbs(e) +/***/ }), +/* 260 */ +/***/ (function(module, exports, __webpack_require__) { - if (this.mark) - e = this._mark(e) +"use strict"; - if (this.absolute) { - e = abs - } - if (this.matches[index][e]) - return +exports = module.exports = lifecycle +exports.makeEnv = makeEnv +exports._incorrectWorkingDirectory = _incorrectWorkingDirectory - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } +// for testing +const platform = process.env.__TESTING_FAKE_PLATFORM__ || process.platform +const isWindows = platform === 'win32' +const spawn = __webpack_require__(128) +const path = __webpack_require__(622) +const Stream = __webpack_require__(794).Stream +const fs = __webpack_require__(598) +const chain = __webpack_require__(433).chain +const uidNumber = __webpack_require__(798) +const umask = __webpack_require__(696) +const which = __webpack_require__(142) +const byline = __webpack_require__(861) +const resolveFrom = __webpack_require__(484) - this.matches[index][e] = true +const DEFAULT_NODE_GYP_PATH = /*require.resolve*/( 693) +const hookStatCache = new Map() - if (this.stat) - this._stat(e) -} +let PATH = isWindows ? 'Path' : 'PATH' +exports._pathEnvName = PATH +const delimiter = path.delimiter +// windows calls its path 'Path' usually, but this is not guaranteed. +// merge them all together in the order they appear in the object. +const mergePath = env => + Object.keys(env).filter(p => /^path$/i.test(p) && env[p]) + .map(p => env[p].split(delimiter)) + .reduce((set, p) => set.concat(p.filter(p => !set.includes(p))), []) + .join(delimiter) +exports._mergePath = mergePath -GlobSync.prototype._readdirInGlobStar = function (abs) { - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false) +const setPathEnv = (env, path) => { + // first ensure that the canonical value is set. + env[PATH] = path + // also set any other case values, because windows. + Object.keys(env) + .filter(p => p !== PATH && /^path$/i.test(p)) + .forEach(p => { env[p] = path }) +} +exports._setPathEnv = setPathEnv - var entries - var lstat - var stat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - if (er.code === 'ENOENT') { - // lstat failed, doesn't exist - return null - } - } +function logid (pkg, stage) { + return pkg._id + '~' + stage + ':' +} - var isSym = lstat && lstat.isSymbolicLink() - this.symlinks[abs] = isSym +function hookStat (dir, stage, cb) { + const hook = path.join(dir, '.hooks', stage) + const cachedStatError = hookStatCache.get(hook) - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) - this.cache[abs] = 'FILE' - else - entries = this._readdir(abs, false) + if (cachedStatError === undefined) { + return fs.stat(hook, function (statError) { + hookStatCache.set(hook, statError) + cb(statError) + }) + } - return entries + return setImmediate(() => cb(cachedStatError)) } -GlobSync.prototype._readdir = function (abs, inGlobStar) { - var entries +function lifecycle (pkg, stage, wd, opts) { + return new Promise((resolve, reject) => { + while (pkg && pkg._data) pkg = pkg._data + if (!pkg) return reject(new Error('Invalid package data')) - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs) + opts.log.info('lifecycle', logid(pkg, stage), pkg._id) + if (!pkg.scripts) pkg.scripts = {} - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return null + if (stage === 'prepublish' && opts.ignorePrepublish) { + opts.log.info('lifecycle', logid(pkg, stage), 'ignored because ignore-prepublish is set to true', pkg._id) + delete pkg.scripts.prepublish + } - if (Array.isArray(c)) - return c - } + hookStat(opts.dir, stage, function (statError) { + // makeEnv is a slow operation. This guard clause prevents makeEnv being called + // and avoids a ton of unnecessary work, and results in a major perf boost. + if (!pkg.scripts[stage] && statError) return resolve() - try { - return this._readdirEntries(abs, fs.readdirSync(abs)) - } catch (er) { - this._readdirError(abs, er) - return null - } -} + validWd(wd || path.resolve(opts.dir, pkg.name), function (er, wd) { + if (er) return reject(er) -GlobSync.prototype._readdirEntries = function (abs, entries) { - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } - } + if ((wd.indexOf(opts.dir) !== 0 || _incorrectWorkingDirectory(wd, pkg)) && + !opts.unsafePerm && pkg.scripts[stage]) { + opts.log.warn('lifecycle', logid(pkg, stage), 'cannot run in wd', pkg._id, pkg.scripts[stage], `(wd=${wd})`) + return resolve() + } - this.cache[abs] = entries + // set the env variables, then run scripts as a child process. + var env = makeEnv(pkg, opts) + env.npm_lifecycle_event = stage + env.npm_node_execpath = env.NODE = env.NODE || process.execPath + env.npm_execpath = require.main.filename + env.INIT_CWD = process.cwd() + env.npm_config_node_gyp = env.npm_config_node_gyp || DEFAULT_NODE_GYP_PATH - // mark and cache dir-ness - return entries + // 'nobody' typically doesn't have permission to write to /tmp + // even if it's never used, sh freaks out. + if (!opts.unsafePerm) env.TMPDIR = wd + + lifecycle_(pkg, stage, wd, opts, env, (er) => { + if (er) return reject(er) + return resolve() + }) + }) + }) + }) } -GlobSync.prototype._readdirError = function (f, er) { - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - throw error - } - break +function _incorrectWorkingDirectory (wd, pkg) { + return wd.lastIndexOf(pkg.name) !== wd.length - pkg.name.length +} - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break +function lifecycle_ (pkg, stage, wd, opts, env, cb) { + var pathArr = [] + var p = wd.split(/[\\/]node_modules[\\/]/) + var acc = path.resolve(p.shift()) - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) - throw er - if (!this.silent) - console.error('glob error', er) - break + p.forEach(function (pp) { + pathArr.unshift(path.join(acc, 'node_modules', '.bin')) + acc = path.join(acc, 'node_modules', pp) + }) + pathArr.unshift(path.join(acc, 'node_modules', '.bin')) + + // we also unshift the bundled node-gyp-bin folder so that + // the bundled one will be used for installing things. + pathArr.unshift(path.join(__dirname, 'node-gyp-bin')) + + if (shouldPrependCurrentNodeDirToPATH(opts)) { + // prefer current node interpreter in child scripts + pathArr.push(path.dirname(process.execPath)) + } + + const existingPath = mergePath(env) + if (existingPath) pathArr.push(existingPath) + const envPath = pathArr.join(isWindows ? ';' : ':') + setPathEnv(env, envPath) + + var packageLifecycle = pkg.scripts && pkg.scripts.hasOwnProperty(stage) + + if (opts.ignoreScripts) { + opts.log.info('lifecycle', logid(pkg, stage), 'ignored because ignore-scripts is set to true', pkg._id) + packageLifecycle = false + } else if (packageLifecycle) { + // define this here so it's available to all scripts. + env.npm_lifecycle_script = pkg.scripts[stage] + } else { + opts.log.silly('lifecycle', logid(pkg, stage), 'no script for ' + stage + ', continuing') } + + function done (er) { + if (er) { + if (opts.force) { + opts.log.info('lifecycle', logid(pkg, stage), 'forced, continuing', er) + er = null + } else if (opts.failOk) { + opts.log.warn('lifecycle', logid(pkg, stage), 'continuing anyway', er.message) + er = null + } + } + cb(er) + } + + chain( + [ + packageLifecycle && [runPackageLifecycle, pkg, stage, env, wd, opts], + [runHookLifecycle, pkg, stage, env, wd, opts] + ], + done + ) } -GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { +function shouldPrependCurrentNodeDirToPATH (opts) { + const cfgsetting = opts.scriptsPrependNodePath + if (cfgsetting === false) return false + if (cfgsetting === true) return true - var entries = this._readdir(abs, inGlobStar) + var isDifferentNodeInPath - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return + var foundExecPath + try { + foundExecPath = which.sync(path.basename(process.execPath), { pathExt: isWindows ? ';' : ':' }) + // Apply `fs.realpath()` here to avoid false positives when `node` is a symlinked executable. + isDifferentNodeInPath = fs.realpathSync(process.execPath).toUpperCase() !== + fs.realpathSync(foundExecPath).toUpperCase() + } catch (e) { + isDifferentNodeInPath = true + } - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) + if (cfgsetting === 'warn-only') { + if (isDifferentNodeInPath && !shouldPrependCurrentNodeDirToPATH.hasWarned) { + if (foundExecPath) { + opts.log.warn('lifecycle', 'The node binary used for scripts is', foundExecPath, 'but npm is using', process.execPath, 'itself. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.') + } else { + opts.log.warn('lifecycle', 'npm is using', process.execPath, 'but there is no node binary in the current PATH. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.') + } + shouldPrependCurrentNodeDirToPATH.hasWarned = true + } - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false) + return false + } - var len = entries.length - var isSym = this.symlinks[abs] + return isDifferentNodeInPath +} - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) +function validWd (d, cb) { + fs.stat(d, function (er, st) { + if (er || !st.isDirectory()) { + var p = path.dirname(d) + if (p === d) { + return cb(new Error('Could not find suitable wd')) + } + return validWd(p, cb) + } + return cb(null, d) + }) +} + +function runPackageLifecycle (pkg, stage, env, wd, opts, cb) { + // run package lifecycle scripts in the package root, or the nearest parent. + var cmd = env.npm_lifecycle_script + + var note = '\n> ' + pkg._id + ' ' + stage + ' ' + wd + + '\n> ' + cmd + '\n' + runCmd(note, cmd, pkg, env, stage, wd, opts, cb) +} + +var running = false +var queue = [] +function dequeue () { + running = false + if (queue.length) { + var r = queue.shift() + runCmd.apply(null, r) + } +} + +function runCmd (note, cmd, pkg, env, stage, wd, opts, cb) { + if (running) { + queue.push([note, cmd, pkg, env, stage, wd, opts, cb]) return + } - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue + running = true + opts.log.pause() + var unsafe = opts.unsafePerm + var user = unsafe ? null : opts.user + var group = unsafe ? null : opts.group - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true) + if (opts.log.level !== 'silent') { + opts.log.clearProgress() + console.log(note) + opts.log.showProgress() + } + opts.log.verbose('lifecycle', logid(pkg, stage), 'unsafe-perm in lifecycle', unsafe) - var below = gspref.concat(entries[i], remain) - this._process(below, index, true) + if (isWindows) { + unsafe = true + } + + if (unsafe) { + runCmd_(cmd, pkg, env, wd, opts, stage, unsafe, 0, 0, cb) + } else { + uidNumber(user, group, function (er, uid, gid) { + if (er) { + er.code = 'EUIDLOOKUP' + opts.log.resume() + process.nextTick(dequeue) + return cb(er) + } + runCmd_(cmd, pkg, env, wd, opts, stage, unsafe, uid, gid, cb) + }) } } -GlobSync.prototype._processSimple = function (prefix, index) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var exists = this._stat(prefix) +const getSpawnArgs = ({ cmd, wd, opts, uid, gid, unsafe, env }) => { + const conf = { + cwd: wd, + env: env, + stdio: opts.stdio || [ 0, 1, 2 ] + } - if (!this.matches[index]) - this.matches[index] = Object.create(null) + if (!unsafe) { + conf.uid = uid ^ 0 + conf.gid = gid ^ 0 + } - // If it doesn't exist, then just mark the lack of results - if (!exists) - return + const customShell = opts.scriptShell - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' + let sh = 'sh' + let shFlag = '-c' + if (customShell) { + sh = customShell + } else if (isWindows || opts._TESTING_FAKE_WINDOWS_) { + sh = process.env.comspec || 'cmd' + // '/d /s /c' is used only for cmd.exe. + if (/^(?:.*\\)?cmd(?:\.exe)?$/i.test(sh)) { + shFlag = '/d /s /c' + conf.windowsVerbatimArguments = true } } - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') - - // Mark this as a match - this._emitMatch(index, prefix) + return [sh, [shFlag, cmd], conf] } -// Returns either 'DIR', 'FILE', or false -GlobSync.prototype._stat = function (f) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' +exports._getSpawnArgs = getSpawnArgs - if (f.length > this.maxLength) - return false +function runCmd_ (cmd, pkg, env, wd, opts, stage, unsafe, uid, gid, cb_) { + function cb (er) { + cb_.apply(null, arguments) + opts.log.resume() + process.nextTick(dequeue) + } - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] + const [sh, args, conf] = getSpawnArgs({ cmd, wd, opts, uid, gid, unsafe, env }) - if (Array.isArray(c)) - c = 'DIR' + opts.log.verbose('lifecycle', logid(pkg, stage), 'PATH:', env[PATH]) + opts.log.verbose('lifecycle', logid(pkg, stage), 'CWD:', wd) + opts.log.silly('lifecycle', logid(pkg, stage), 'Args:', args) - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return c + var proc = spawn(sh, args, conf, opts.log) - if (needDir && c === 'FILE') - return false + proc.on('error', procError) + proc.on('close', function (code, signal) { + opts.log.silly('lifecycle', logid(pkg, stage), 'Returned: code:', code, ' signal:', signal) + if (signal) { + process.kill(process.pid, signal) + } else if (code) { + var er = new Error('Exit status ' + code) + er.errno = code + } + procError(er) + }) + byline(proc.stdout).on('data', function (data) { + opts.log.verbose('lifecycle', logid(pkg, stage), 'stdout', data.toString()) + }) + byline(proc.stderr).on('data', function (data) { + opts.log.verbose('lifecycle', logid(pkg, stage), 'stderr', data.toString()) + }) + process.once('SIGTERM', procKill) + process.once('SIGINT', procInterupt) - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. + function procError (er) { + if (er) { + opts.log.info('lifecycle', logid(pkg, stage), 'Failed to exec ' + stage + ' script') + er.message = pkg._id + ' ' + stage + ': `' + cmd + '`\n' + + er.message + if (er.code !== 'EPERM') { + er.code = 'ELIFECYCLE' + } + fs.stat(opts.dir, function (statError, d) { + if (statError && statError.code === 'ENOENT' && opts.dir.split(path.sep).slice(-1)[0] === 'node_modules') { + opts.log.warn('', 'Local package.json exists, but node_modules missing, did you mean to install?') + } + }) + er.pkgid = pkg._id + er.stage = stage + er.script = cmd + er.pkgname = pkg.name + } + process.removeListener('SIGTERM', procKill) + process.removeListener('SIGTERM', procInterupt) + process.removeListener('SIGINT', procKill) + process.removeListener('SIGINT', procInterupt) + return cb(er) + } + function procKill () { + proc.kill() + } + function procInterupt () { + proc.kill('SIGINT') + proc.on('exit', function () { + process.exit() + }) + process.once('SIGINT', procKill) } +} - var exists - var stat = this.statCache[abs] - if (!stat) { - var lstat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return false +function runHookLifecycle (pkg, stage, env, wd, opts, cb) { + hookStat(opts.dir, stage, function (er) { + if (er) return cb() + var cmd = path.join(opts.dir, '.hooks', stage) + var note = '\n> ' + pkg._id + ' ' + stage + ' ' + wd + + '\n> ' + cmd + runCmd(note, cmd, pkg, env, stage, wd, opts, cb) + }) +} + +function makeEnv (data, opts, prefix, env) { + prefix = prefix || 'npm_package_' + if (!env) { + env = {} + for (var i in process.env) { + if (!i.match(/^npm_/)) { + env[i] = process.env[i] } } - if (lstat && lstat.isSymbolicLink()) { - try { - stat = fs.statSync(abs) - } catch (er) { - stat = lstat + // express and others respect the NODE_ENV value. + if (opts.production) env.NODE_ENV = 'production' + } else if (!data.hasOwnProperty('_lifecycleEnv')) { + Object.defineProperty(data, '_lifecycleEnv', + { + value: env, + enumerable: false + } + ) + } + + if (opts.nodeOptions) env.NODE_OPTIONS = opts.nodeOptions + + for (i in data) { + if (i.charAt(0) !== '_') { + var envKey = (prefix + i).replace(/[^a-zA-Z0-9_]/g, '_') + if (i === 'readme') { + continue + } + if (data[i] && typeof data[i] === 'object') { + try { + // quick and dirty detection for cyclical structures + JSON.stringify(data[i]) + makeEnv(data[i], opts, envKey + '_', env) + } catch (ex) { + // usually these are package objects. + // just get the path and basic details. + var d = data[i] + makeEnv( + { name: d.name, version: d.version, path: d.path }, + opts, + envKey + '_', + env + ) + } + } else { + env[envKey] = String(data[i]) + env[envKey] = env[envKey].indexOf('\n') !== -1 + ? JSON.stringify(env[envKey]) + : env[envKey] } - } else { - stat = lstat } } - this.statCache[abs] = stat + if (prefix !== 'npm_package_') return env - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' + prefix = 'npm_config_' + var pkgConfig = {} + var pkgVerConfig = {} + var namePref = data.name + ':' + var verPref = data.name + '@' + data.version + ':' - this.cache[abs] = this.cache[abs] || c + Object.keys(opts.config).forEach(function (i) { + // in some rare cases (e.g. working with nerf darts), there are segmented + // "private" (underscore-prefixed) config names -- don't export + if ((i.charAt(0) === '_' && i.indexOf('_' + namePref) !== 0) || i.match(/:_/)) { + return + } + var value = opts.config[i] + if (value instanceof Stream || Array.isArray(value) || typeof value === 'function') return + if (i.match(/umask/)) value = umask.toString(value) - if (needDir && c === 'FILE') - return false + if (!value) value = '' + else if (typeof value === 'number') value = '' + value + else if (typeof value !== 'string') value = JSON.stringify(value) - return c -} + if (typeof value !== 'string') { + return + } -GlobSync.prototype._mark = function (p) { - return common.mark(this, p) -} + value = value.indexOf('\n') !== -1 + ? JSON.stringify(value) + : value + i = i.replace(/^_+/, '') + var k + if (i.indexOf(namePref) === 0) { + k = i.substr(namePref.length).replace(/[^a-zA-Z0-9_]/g, '_') + pkgConfig[k] = value + } else if (i.indexOf(verPref) === 0) { + k = i.substr(verPref.length).replace(/[^a-zA-Z0-9_]/g, '_') + pkgVerConfig[k] = value + } + var envKey = (prefix + i).replace(/[^a-zA-Z0-9_]/g, '_') + env[envKey] = value + }) -GlobSync.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) + prefix = 'npm_package_config_' + ;[pkgConfig, pkgVerConfig].forEach(function (conf) { + for (var i in conf) { + var envKey = (prefix + i) + env[envKey] = conf[i] + } + }) + + return env } /***/ }), -/* 246 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 261 */, +/* 262 */ +/***/ (function(module) { -"use strict"; +var toString = {}.toString; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, - apiRejection, Proxyable) { -var util = __webpack_require__(248); -var isArray = util.isArray; +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; -function toResolutionValue(val) { - switch(val) { - case -2: return []; - case -3: return {}; - case -6: return new Map(); - } -} -function PromiseArray(values) { - var promise = this._promise = new Promise(INTERNAL); - if (values instanceof Promise) { - promise._propagateFrom(values, 3); - values.suppressUnhandledRejections(); - } - promise._setOnCancel(this); - this._values = values; - this._length = 0; - this._totalResolved = 0; - this._init(undefined, -2); -} -util.inherits(PromiseArray, Proxyable); +/***/ }), +/* 263 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -PromiseArray.prototype.length = function () { - return this._length; -}; +"use strict"; -PromiseArray.prototype.promise = function () { - return this._promise; -}; -PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { - var values = tryConvertToPromise(this._values, this._promise); - if (values instanceof Promise) { - values = values._target(); - var bitField = values._bitField; - ; - this._values = values; +Object.defineProperty(exports, '__esModule', { value: true }); - if (((bitField & 50397184) === 0)) { - this._promise._setAsyncGuaranteed(); - return values._then( - init, - this._reject, - undefined, - this, - resolveValueIfEmpty - ); - } else if (((bitField & 33554432) !== 0)) { - values = values._value(); - } else if (((bitField & 16777216) !== 0)) { - return this._reject(values._reason()); - } else { - return this._cancel(); - } +var api = __webpack_require__(440); +var tslib = __webpack_require__(144); + +// Copyright (c) Microsoft Corporation. +/** + * A no-op implementation of Span that can safely be used without side-effects. + */ +var NoOpSpan = /** @class */ (function () { + function NoOpSpan() { } - values = util.asArray(values); - if (values === null) { - var err = apiRejection( - "expecting an array or an iterable object but got " + util.classString(values)).reason(); - this._promise._rejectCallback(err, false); - return; + /** + * Returns the SpanContext associated with this Span. + */ + NoOpSpan.prototype.context = function () { + return { + spanId: "", + traceId: "", + traceFlags: api.TraceFlags.NONE + }; + }; + /** + * Marks the end of Span execution. + * @param _endTime The time to use as the Span's end time. Defaults to + * the current time. + */ + NoOpSpan.prototype.end = function (_endTime) { + /* Noop */ + }; + /** + * Sets an attribute on the Span + * @param _key the attribute key + * @param _value the attribute value + */ + NoOpSpan.prototype.setAttribute = function (_key, _value) { + return this; + }; + /** + * Sets attributes on the Span + * @param _attributes the attributes to add + */ + NoOpSpan.prototype.setAttributes = function (_attributes) { + return this; + }; + /** + * Adds an event to the Span + * @param _name The name of the event + * @param _attributes The associated attributes to add for this event + */ + NoOpSpan.prototype.addEvent = function (_name, _attributes) { + return this; + }; + /** + * Sets a status on the span. Overrides the default of CanonicalCode.OK. + * @param _status The status to set. + */ + NoOpSpan.prototype.setStatus = function (_status) { + return this; + }; + /** + * Updates the name of the Span + * @param _name the new Span name + */ + NoOpSpan.prototype.updateName = function (_name) { + return this; + }; + /** + * Returns whether this span will be recorded + */ + NoOpSpan.prototype.isRecording = function () { + return false; + }; + return NoOpSpan; +}()); + +// Copyright (c) Microsoft Corporation. +/** + * A no-op implementation of Tracer that can be used when tracing + * is disabled. + */ +var NoOpTracer = /** @class */ (function () { + function NoOpTracer() { } + /** + * Starts a new Span. + * @param _name The name of the span. + * @param _options The SpanOptions used during Span creation. + */ + NoOpTracer.prototype.startSpan = function (_name, _options) { + return new NoOpSpan(); + }; + /** + * Returns the current Span from the current context, if available. + */ + NoOpTracer.prototype.getCurrentSpan = function () { + return new NoOpSpan(); + }; + /** + * Executes the given function within the context provided by a Span. + * @param _span The span that provides the context. + * @param fn The function to be executed. + */ + NoOpTracer.prototype.withSpan = function (_span, fn) { + return fn(); + }; + /** + * Bind a Span as the target's scope + * @param target An object to bind the scope. + * @param _span A specific Span to use. Otherwise, use the current one. + */ + NoOpTracer.prototype.bind = function (target, _span) { + return target; + }; + return NoOpTracer; +}()); - if (values.length === 0) { - if (resolveValueIfEmpty === -5) { - this._resolveEmptyArray(); +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +function getGlobalObject() { + return global; +} + +// Copyright (c) Microsoft Corporation. +// V1 = OpenTelemetry 0.1 +// V2 = OpenTelemetry 0.2 +// V3 = OpenTelemetry 0.6.1 +var GLOBAL_TRACER_VERSION = 3; +// preview5 shipped with @azure/core-tracing.tracerCache +// and didn't have smart detection for collisions +var GLOBAL_TRACER_SYMBOL = Symbol.for("@azure/core-tracing.tracerCache2"); +var cache; +function loadTracerCache() { + var globalObj = getGlobalObject(); + var existingCache = globalObj[GLOBAL_TRACER_SYMBOL]; + var setGlobalCache = true; + if (existingCache) { + if (existingCache.version === GLOBAL_TRACER_VERSION) { + cache = existingCache; } else { - this._resolve(toResolutionValue(resolveValueIfEmpty)); + setGlobalCache = false; + if (existingCache.tracer) { + throw new Error("Two incompatible versions of @azure/core-tracing have been loaded.\n This library is " + GLOBAL_TRACER_VERSION + ", existing is " + existingCache.version + "."); + } } - return; } - this._iterate(values); -}; + if (!cache) { + cache = { + tracer: undefined, + version: GLOBAL_TRACER_VERSION + }; + } + if (setGlobalCache) { + globalObj[GLOBAL_TRACER_SYMBOL] = cache; + } +} +function getCache() { + if (!cache) { + loadTracerCache(); + } + return cache; +} -PromiseArray.prototype._iterate = function(values) { - var len = this.getActualLength(values.length); - this._length = len; - this._values = this.shouldCopyValues() ? new Array(len) : this._values; - var result = this._promise; - var isResolved = false; - var bitField = null; - for (var i = 0; i < len; ++i) { - var maybePromise = tryConvertToPromise(values[i], result); +// Copyright (c) Microsoft Corporation. +var defaultTracer; +function getDefaultTracer() { + if (!defaultTracer) { + defaultTracer = new NoOpTracer(); + } + return defaultTracer; +} +/** + * Sets the global tracer, enabling tracing for the Azure SDK. + * @param tracer An OpenTelemetry Tracer instance. + */ +function setTracer(tracer) { + var cache = getCache(); + cache.tracer = tracer; +} +/** + * Retrieves the active tracer, or returns a + * no-op implementation if one is not set. + */ +function getTracer() { + var cache = getCache(); + if (!cache.tracer) { + return getDefaultTracer(); + } + return cache.tracer; +} - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - bitField = maybePromise._bitField; - } else { - bitField = null; - } +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * @ignore + * @internal + */ +var OpenCensusTraceStateWrapper = /** @class */ (function () { + function OpenCensusTraceStateWrapper(state) { + this._state = state; + } + OpenCensusTraceStateWrapper.prototype.get = function (_key) { + throw new Error("Method not implemented."); + }; + OpenCensusTraceStateWrapper.prototype.set = function (_key, _value) { + throw new Error("Method not implemented."); + }; + OpenCensusTraceStateWrapper.prototype.unset = function (_key) { + throw new Error("Method not implemented"); + }; + OpenCensusTraceStateWrapper.prototype.serialize = function () { + return this._state || ""; + }; + return OpenCensusTraceStateWrapper; +}()); - if (isResolved) { - if (bitField !== null) { - maybePromise.suppressUnhandledRejections(); - } - } else if (bitField !== null) { - if (((bitField & 50397184) === 0)) { - maybePromise._proxy(this, i); - this._values[i] = maybePromise; - } else if (((bitField & 33554432) !== 0)) { - isResolved = this._promiseFulfilled(maybePromise._value(), i); - } else if (((bitField & 16777216) !== 0)) { - isResolved = this._promiseRejected(maybePromise._reason(), i); - } else { - isResolved = this._promiseCancelled(i); +// Copyright (c) Microsoft Corporation. +function isWrappedSpan(span) { + return !!span && span.getWrappedSpan !== undefined; +} +function isTracer(tracerOrSpan) { + return tracerOrSpan.getWrappedTracer !== undefined; +} +/** + * An implementation of OpenTelemetry Span that wraps an OpenCensus Span. + */ +var OpenCensusSpanWrapper = /** @class */ (function () { + function OpenCensusSpanWrapper(tracerOrSpan, name, options) { + if (name === void 0) { name = ""; } + if (options === void 0) { options = {}; } + if (isTracer(tracerOrSpan)) { + var parent = isWrappedSpan(options.parent) ? options.parent.getWrappedSpan() : undefined; + this._span = tracerOrSpan.getWrappedTracer().startChildSpan({ + name: name, + childOf: parent + }); + this._span.start(); + if (options.links) { + for (var _i = 0, _a = options.links; _i < _a.length; _i++) { + var link = _a[_i]; + // Since there is no way to set the link relationship, leave it as Unspecified. + this._span.addLink(link.context.traceId, link.context.spanId, 0 /* LinkType.UNSPECIFIED */, link.attributes); + } } - } else { - isResolved = this._promiseFulfilled(maybePromise, i); + } + else { + this._span = tracerOrSpan; } } - if (!isResolved) result._setAsyncGuaranteed(); -}; - -PromiseArray.prototype._isResolved = function () { - return this._values === null; -}; - -PromiseArray.prototype._resolve = function (value) { - this._values = null; - this._promise._fulfill(value); -}; - -PromiseArray.prototype._cancel = function() { - if (this._isResolved() || !this._promise._isCancellable()) return; - this._values = null; - this._promise._cancel(); -}; - -PromiseArray.prototype._reject = function (reason) { - this._values = null; - this._promise._rejectCallback(reason, false); -}; + /** + * The underlying OpenCensus Span + */ + OpenCensusSpanWrapper.prototype.getWrappedSpan = function () { + return this._span; + }; + /** + * Marks the end of Span execution. + * @param endTime The time to use as the Span's end time. Defaults to + * the current time. + */ + OpenCensusSpanWrapper.prototype.end = function (_endTime) { + this._span.end(); + }; + /** + * Returns the SpanContext associated with this Span. + */ + OpenCensusSpanWrapper.prototype.context = function () { + var openCensusSpanContext = this._span.spanContext; + return { + spanId: openCensusSpanContext.spanId, + traceId: openCensusSpanContext.traceId, + traceFlags: openCensusSpanContext.options, + traceState: new OpenCensusTraceStateWrapper(openCensusSpanContext.traceState) + }; + }; + /** + * Sets an attribute on the Span + * @param key the attribute key + * @param value the attribute value + */ + OpenCensusSpanWrapper.prototype.setAttribute = function (key, value) { + this._span.addAttribute(key, value); + return this; + }; + /** + * Sets attributes on the Span + * @param attributes the attributes to add + */ + OpenCensusSpanWrapper.prototype.setAttributes = function (attributes) { + this._span.attributes = attributes; + return this; + }; + /** + * Adds an event to the Span + * @param name The name of the event + * @param attributes The associated attributes to add for this event + */ + OpenCensusSpanWrapper.prototype.addEvent = function (_name, _attributes) { + throw new Error("Method not implemented."); + }; + /** + * Sets a status on the span. Overrides the default of CanonicalCode.OK. + * @param status The status to set. + */ + OpenCensusSpanWrapper.prototype.setStatus = function (status) { + this._span.setStatus(status.code, status.message); + return this; + }; + /** + * Updates the name of the Span + * @param name the new Span name + */ + OpenCensusSpanWrapper.prototype.updateName = function (name) { + this._span.name = name; + return this; + }; + /** + * Returns whether this span will be recorded + */ + OpenCensusSpanWrapper.prototype.isRecording = function () { + // NoRecordSpans have an empty traceId + return !!this._span.traceId; + }; + return OpenCensusSpanWrapper; +}()); -PromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; +// Copyright (c) Microsoft Corporation. +/** + * An implementation of OpenTelemetry Tracer that wraps an OpenCensus Tracer. + */ +var OpenCensusTracerWrapper = /** @class */ (function () { + /** + * Create a new wrapper around a given OpenCensus Tracer. + * @param tracer The OpenCensus Tracer to wrap. + */ + function OpenCensusTracerWrapper(tracer) { + this._tracer = tracer; } - return false; -}; - -PromiseArray.prototype._promiseCancelled = function() { - this._cancel(); - return true; -}; + /** + * The wrapped OpenCensus Tracer + */ + OpenCensusTracerWrapper.prototype.getWrappedTracer = function () { + return this._tracer; + }; + /** + * Starts a new Span. + * @param name The name of the span. + * @param options The SpanOptions used during Span creation. + */ + OpenCensusTracerWrapper.prototype.startSpan = function (name, options) { + return new OpenCensusSpanWrapper(this, name, options); + }; + /** + * Returns the current Span from the current context, if available. + */ + OpenCensusTracerWrapper.prototype.getCurrentSpan = function () { + return undefined; + }; + /** + * Executes the given function within the context provided by a Span. + * @param _span The span that provides the context. + * @param _fn The function to be executed. + */ + OpenCensusTracerWrapper.prototype.withSpan = function (_span, _fn) { + throw new Error("Method not implemented."); + }; + /** + * Bind a Span as the target's scope + * @param target An object to bind the scope. + * @param _span A specific Span to use. Otherwise, use the current one. + */ + OpenCensusTracerWrapper.prototype.bind = function (_target, _span) { + throw new Error("Method not implemented."); + }; + return OpenCensusTracerWrapper; +}()); -PromiseArray.prototype._promiseRejected = function (reason) { - this._totalResolved++; - this._reject(reason); - return true; -}; +// Copyright (c) Microsoft Corporation. +/** + * A mock span useful for testing. + */ +var TestSpan = /** @class */ (function (_super) { + tslib.__extends(TestSpan, _super); + /** + * Starts a new Span. + * @param parentTracer The tracer that created this Span + * @param name The name of the span. + * @param context The SpanContext this span belongs to + * @param kind The SpanKind of this Span + * @param parentSpanId The identifier of the parent Span + * @param startTime The startTime of the event (defaults to now) + */ + function TestSpan(parentTracer, name, context, kind, parentSpanId, startTime) { + if (startTime === void 0) { startTime = Date.now(); } + var _this = _super.call(this) || this; + _this._tracer = parentTracer; + _this.name = name; + _this.kind = kind; + _this.startTime = startTime; + _this.parentSpanId = parentSpanId; + _this.status = { + code: api.CanonicalCode.OK + }; + _this.endCalled = false; + _this._context = context; + _this.attributes = {}; + return _this; + } + /** + * Returns the Tracer that created this Span + */ + TestSpan.prototype.tracer = function () { + return this._tracer; + }; + /** + * Returns the SpanContext associated with this Span. + */ + TestSpan.prototype.context = function () { + return this._context; + }; + /** + * Marks the end of Span execution. + * @param _endTime The time to use as the Span's end time. Defaults to + * the current time. + */ + TestSpan.prototype.end = function (_endTime) { + this.endCalled = true; + }; + /** + * Sets a status on the span. Overrides the default of CanonicalCode.OK. + * @param status The status to set. + */ + TestSpan.prototype.setStatus = function (status) { + this.status = status; + return this; + }; + /** + * Returns whether this span will be recorded + */ + TestSpan.prototype.isRecording = function () { + return true; + }; + /** + * Sets an attribute on the Span + * @param key the attribute key + * @param value the attribute value + */ + TestSpan.prototype.setAttribute = function (key, value) { + this.attributes[key] = value; + return this; + }; + /** + * Sets attributes on the Span + * @param attributes the attributes to add + */ + TestSpan.prototype.setAttributes = function (attributes) { + for (var _i = 0, _a = Object.keys(attributes); _i < _a.length; _i++) { + var key = _a[_i]; + this.attributes[key] = attributes[key]; + } + return this; + }; + return TestSpan; +}(NoOpSpan)); -PromiseArray.prototype._resultCancelled = function() { - if (this._isResolved()) return; - var values = this._values; - this._cancel(); - if (values instanceof Promise) { - values.cancel(); - } else { - for (var i = 0; i < values.length; ++i) { - if (values[i] instanceof Promise) { - values[i].cancel(); +// Copyright (c) Microsoft Corporation. +/** + * A mock tracer useful for testing + */ +var TestTracer = /** @class */ (function (_super) { + tslib.__extends(TestTracer, _super); + function TestTracer() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.traceIdCounter = 0; + _this.spanIdCounter = 0; + _this.rootSpans = []; + _this.knownSpans = []; + return _this; + } + TestTracer.prototype.getNextTraceId = function () { + this.traceIdCounter++; + return String(this.traceIdCounter); + }; + TestTracer.prototype.getNextSpanId = function () { + this.spanIdCounter++; + return String(this.spanIdCounter); + }; + /** + * Returns all Spans that were created without a parent + */ + TestTracer.prototype.getRootSpans = function () { + return this.rootSpans; + }; + /** + * Returns all Spans this Tracer knows about + */ + TestTracer.prototype.getKnownSpans = function () { + return this.knownSpans; + }; + /** + * Returns all Spans where end() has not been called + */ + TestTracer.prototype.getActiveSpans = function () { + return this.knownSpans.filter(function (span) { + return !span.endCalled; + }); + }; + /** + * Return all Spans for a particular trace, grouped by their + * parent Span in a tree-like structure + * @param traceId The traceId to return the graph for + */ + TestTracer.prototype.getSpanGraph = function (traceId) { + var traceSpans = this.knownSpans.filter(function (span) { + return span.context().traceId === traceId; + }); + var roots = []; + var nodeMap = new Map(); + for (var _i = 0, traceSpans_1 = traceSpans; _i < traceSpans_1.length; _i++) { + var span = traceSpans_1[_i]; + var spanId = span.context().spanId; + var node = { + name: span.name, + children: [] + }; + nodeMap.set(spanId, node); + if (span.parentSpanId) { + var parent = nodeMap.get(span.parentSpanId); + if (!parent) { + throw new Error("Span with name " + node.name + " has an unknown parentSpan with id " + span.parentSpanId); + } + parent.children.push(node); + } + else { + roots.push(node); + } + } + return { + roots: roots + }; + }; + /** + * Starts a new Span. + * @param name The name of the span. + * @param options The SpanOptions used during Span creation. + */ + TestTracer.prototype.startSpan = function (name, options) { + if (options === void 0) { options = {}; } + var parentContext = this._getParentContext(options); + var traceId; + var isRootSpan = false; + if (parentContext && parentContext.traceId) { + traceId = parentContext.traceId; + } + else { + traceId = this.getNextTraceId(); + isRootSpan = true; + } + var context = { + traceId: traceId, + spanId: this.getNextSpanId(), + traceFlags: api.TraceFlags.NONE + }; + var span = new TestSpan(this, name, context, options.kind || api.SpanKind.INTERNAL, parentContext ? parentContext.spanId : undefined, options.startTime); + this.knownSpans.push(span); + if (isRootSpan) { + this.rootSpans.push(span); + } + return span; + }; + TestTracer.prototype._getParentContext = function (options) { + var parent = options.parent; + var result; + if (parent) { + if ("traceId" in parent) { + result = parent; + } + else { + result = parent.context(); } } + return result; + }; + return TestTracer; +}(NoOpTracer)); + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +var VERSION = "00"; +/** + * Generates a `SpanContext` given a `traceparent` header value. + * @param traceParent Serialized span context data as a `traceparent` header value. + * @returns The `SpanContext` generated from the `traceparent` value. + */ +function extractSpanContextFromTraceParentHeader(traceParentHeader) { + var parts = traceParentHeader.split("-"); + if (parts.length !== 4) { + return; } -}; + var version = parts[0], traceId = parts[1], spanId = parts[2], traceOptions = parts[3]; + if (version !== VERSION) { + return; + } + var traceFlags = parseInt(traceOptions, 16); + var spanContext = { + spanId: spanId, + traceId: traceId, + traceFlags: traceFlags + }; + return spanContext; +} +/** + * Generates a `traceparent` value given a span context. + * @param spanContext Contains context for a specific span. + * @returns The `spanContext` represented as a `traceparent` value. + */ +function getTraceParentHeader(spanContext) { + var missingFields = []; + if (!spanContext.traceId) { + missingFields.push("traceId"); + } + if (!spanContext.spanId) { + missingFields.push("spanId"); + } + if (missingFields.length) { + return; + } + var flags = spanContext.traceFlags || 0 /* NONE */; + var hexFlags = flags.toString(16); + var traceFlags = hexFlags.length === 1 ? "0" + hexFlags : hexFlags; + // https://www.w3.org/TR/trace-context/#traceparent-header-field-values + return VERSION + "-" + spanContext.traceId + "-" + spanContext.spanId + "-" + traceFlags; +} + +exports.NoOpSpan = NoOpSpan; +exports.NoOpTracer = NoOpTracer; +exports.OpenCensusSpanWrapper = OpenCensusSpanWrapper; +exports.OpenCensusTracerWrapper = OpenCensusTracerWrapper; +exports.TestSpan = TestSpan; +exports.TestTracer = TestTracer; +exports.extractSpanContextFromTraceParentHeader = extractSpanContextFromTraceParentHeader; +exports.getTraceParentHeader = getTraceParentHeader; +exports.getTracer = getTracer; +exports.setTracer = setTracer; +//# sourceMappingURL=index.js.map -PromiseArray.prototype.shouldCopyValues = function () { - return true; -}; -PromiseArray.prototype.getActualLength = function (len) { - return len; -}; +/***/ }), +/* 264 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -return PromiseArray; -}; +"use strict"; + +exports.TrackerGroup = __webpack_require__(174) +exports.Tracker = __webpack_require__(623) +exports.TrackerStream = __webpack_require__(235) /***/ }), -/* 247 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 265 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.authenticate = exports.authWithToken = exports.authWithCredentials = void 0; +const core = __importStar(__webpack_require__(470)); +const cli = __importStar(__webpack_require__(986)); +/** + * Authenticate at Expo using `expo login`. + * This step is required for publishing and building new apps. + * It uses the `EXPO_CLI_PASSWORD` environment variable for improved security. + */ +function authWithCredentials(username, password) { + return __awaiter(this, void 0, void 0, function* () { + if (!username || !password) { + return core.info('Skipping authentication: `expo-username` and/or `expo-password` not set...'); + } + // github actions toolkit will handle commands with `.cmd` on windows, we need that + const bin = process.platform === 'win32' ? 'expo.cmd' : 'expo'; + yield cli.exec(bin, ['login', `--username=${username}`], { + env: Object.assign(Object.assign({}, process.env), { EXPO_CLI_PASSWORD: password }), + }); + }); +} +exports.authWithCredentials = authWithCredentials; +/** + * Authenticate with Expo using `EXPO_TOKEN`. + * This exports the EXPO_TOKEN environment variable for all future steps within the workflow. + * It also double-checks if this token is valid and for what user, by running `expo whoami`. + * + * @see https://github.com/actions/toolkit/blob/905b2c7b0681b11056141a60055f1ba77358b7e9/packages/core/src/core.ts#L39 + */ +function authWithToken(token) { + return __awaiter(this, void 0, void 0, function* () { + if (!token) { + return core.info('Skipping authentication: `expo-token` not set...'); + } + // github actions toolkit will handle commands with `.cmd` on windows, we need that + const bin = process.platform === 'win32' ? 'expo.cmd' : 'expo'; + yield cli.exec(bin, ['whoami'], { + env: Object.assign(Object.assign({}, process.env), { EXPO_TOKEN: token }), + }); + core.exportVariable('EXPO_TOKEN', token); + }); +} +exports.authWithToken = authWithToken; +/** + * Authenticate with Expo using either the token or username/password method. + * If both of them are set, token has priority. + */ +function authenticate(options) { + if (options.token) { + return authWithToken(options.token); + } + if (options.username || options.password) { + return authWithCredentials(options.username, options.password); + } + core.info('Skipping authentication: `expo-token`, `expo-username`, and/or `expo-password` not set...'); +} +exports.authenticate = authenticate; -const os = __webpack_require__(87); -const tty = __webpack_require__(867); -const hasFlag = __webpack_require__(364); - -const {env} = process; -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false') || - hasFlag('color=never')) { - forceColor = 0; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = 1; -} +/***/ }), +/* 266 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -if ('FORCE_COLOR' in env) { - if (env.FORCE_COLOR === 'true') { - forceColor = 1; - } else if (env.FORCE_COLOR === 'false') { - forceColor = 0; - } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); - } -} +"use strict"; -function translateLevel(level) { - if (level === 0) { - return false; - } +var os = __webpack_require__(87); - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; -} +function homedir() { + var env = process.env; + var home = env.HOME; + var user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME; -function supportsColor(haveStream, streamIsTTY) { - if (forceColor === 0) { - return 0; + if (process.platform === 'win32') { + return env.USERPROFILE || env.HOMEDRIVE + env.HOMEPATH || home || null; } - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; + if (process.platform === 'darwin') { + return home || (user ? '/Users/' + user : null); } - if (hasFlag('color=256')) { - return 2; + if (process.platform === 'linux') { + return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null)); } - if (haveStream && !streamIsTTY && forceColor === undefined) { - return 0; - } + return home || null; +} - const min = forceColor || 0; +module.exports = typeof os.homedir === 'function' ? os.homedir : homedir; - if (env.TERM === 'dumb') { - return min; - } - if (process.platform === 'win32') { - // Windows 10 build 10586 is the first Windows release that supports 256 colors. - // Windows 10 build 14931 is the first release that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } +/***/ }), +/* 267 */, +/* 268 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - return 1; - } +"use strict"; - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } - return min; - } +const assert = __webpack_require__(357) +const Buffer = __webpack_require__(293).Buffer +const realZlib = __webpack_require__(761) - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } +const constants = exports.constants = __webpack_require__(60) +const Minipass = __webpack_require__(720) - if ('GITHUB_ACTIONS' in env) { - return 1; - } +const OriginalBufferConcat = Buffer.concat - if (env.COLORTERM === 'truecolor') { - return 3; - } +class ZlibError extends Error { + constructor (err) { + super('zlib: ' + err.message) + this.code = err.code + this.errno = err.errno + /* istanbul ignore if */ + if (!this.code) + this.code = 'ZLIB_ERROR' - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + this.message = 'zlib: ' + err.message + Error.captureStackTrace(this, this.constructor) + } - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } - - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - - if ('COLORTERM' in env) { - return 1; - } - - return min; -} - -function getSupportLevel(stream) { - const level = supportsColor(stream, stream && stream.isTTY); - return translateLevel(level); + get name () { + return 'ZlibError' + } } -module.exports = { - supportsColor: getSupportLevel, - stdout: translateLevel(supportsColor(true, tty.isatty(1))), - stderr: translateLevel(supportsColor(true, tty.isatty(2))) -}; +// the Zlib class they all inherit from +// This thing manages the queue of requests, and returns +// true or false if there is anything in the queue when +// you call the .write() method. +const _opts = Symbol('opts') +const _flushFlag = Symbol('flushFlag') +const _finishFlushFlag = Symbol('finishFlushFlag') +const _fullFlushFlag = Symbol('fullFlushFlag') +const _handle = Symbol('handle') +const _onError = Symbol('onError') +const _sawError = Symbol('sawError') +const _level = Symbol('level') +const _strategy = Symbol('strategy') +const _ended = Symbol('ended') +const _defaultFullFlush = Symbol('_defaultFullFlush') +class ZlibBase extends Minipass { + constructor (opts, mode) { + if (!opts || typeof opts !== 'object') + throw new TypeError('invalid options for ZlibBase constructor') -/***/ }), -/* 248 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + super(opts) + this[_ended] = false + this[_opts] = opts -"use strict"; + this[_flushFlag] = opts.flush + this[_finishFlushFlag] = opts.finishFlush + // this will throw if any options are invalid for the class selected + try { + this[_handle] = new realZlib[mode](opts) + } catch (er) { + // make sure that all errors get decorated properly + throw new ZlibError(er) + } -var es5 = __webpack_require__(883); -var canEvaluate = typeof navigator == "undefined"; + this[_onError] = (err) => { + this[_sawError] = true + // there is no way to cleanly recover. + // continuing only obscures problems. + this.close() + this.emit('error', err) + } -var errorObj = {e: {}}; -var tryCatchTarget; -var globalObject = typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : - typeof global !== "undefined" ? global : - this !== undefined ? this : null; + this[_handle].on('error', er => this[_onError](new ZlibError(er))) + this.once('end', () => this.close) + } -function tryCatcher() { - try { - var target = tryCatchTarget; - tryCatchTarget = null; - return target.apply(this, arguments); - } catch (e) { - errorObj.e = e; - return errorObj; + close () { + if (this[_handle]) { + this[_handle].close() + this[_handle] = null + this.emit('close') } -} -function tryCatch(fn) { - tryCatchTarget = fn; - return tryCatcher; -} - -var inherits = function(Child, Parent) { - var hasProp = {}.hasOwnProperty; + } - function T() { - this.constructor = Child; - this.constructor$ = Parent; - for (var propertyName in Parent.prototype) { - if (hasProp.call(Parent.prototype, propertyName) && - propertyName.charAt(propertyName.length-1) !== "$" - ) { - this[propertyName + "$"] = Parent.prototype[propertyName]; - } - } + reset () { + if (!this[_sawError]) { + assert(this[_handle], 'zlib binding closed') + return this[_handle].reset() } - T.prototype = Parent.prototype; - Child.prototype = new T(); - return Child.prototype; -}; + } + flush (flushFlag) { + if (this.ended) + return -function isPrimitive(val) { - return val == null || val === true || val === false || - typeof val === "string" || typeof val === "number"; + if (typeof flushFlag !== 'number') + flushFlag = this[_fullFlushFlag] + this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag })) + } -} + end (chunk, encoding, cb) { + if (chunk) + this.write(chunk, encoding) + this.flush(this[_finishFlushFlag]) + this[_ended] = true + return super.end(null, null, cb) + } -function isObject(value) { - return typeof value === "function" || - typeof value === "object" && value !== null; -} + get ended () { + return this[_ended] + } -function maybeWrapAsError(maybeError) { - if (!isPrimitive(maybeError)) return maybeError; + write (chunk, encoding, cb) { + // process the chunk using the sync process + // then super.write() all the outputted chunks + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' - return new Error(safeToString(maybeError)); -} + if (typeof chunk === 'string') + chunk = Buffer.from(chunk, encoding) -function withAppended(target, appendee) { - var len = target.length; - var ret = new Array(len + 1); - var i; - for (i = 0; i < len; ++i) { - ret[i] = target[i]; - } - ret[i] = appendee; - return ret; -} + if (this[_sawError]) + return + assert(this[_handle], 'zlib binding closed') -function getDataPropertyOrDefault(obj, key, defaultValue) { - if (es5.isES5) { - var desc = Object.getOwnPropertyDescriptor(obj, key); + // _processChunk tries to .close() the native handle after it's done, so we + // intercept that by temporarily making it a no-op. + const nativeHandle = this[_handle]._handle + const originalNativeClose = nativeHandle.close + nativeHandle.close = () => {} + const originalClose = this[_handle].close + this[_handle].close = () => {} + // It also calls `Buffer.concat()` at the end, which may be convenient + // for some, but which we are not interested in as it slows us down. + Buffer.concat = (args) => args + let result + try { + const flushFlag = typeof chunk[_flushFlag] === 'number' + ? chunk[_flushFlag] : this[_flushFlag] + result = this[_handle]._processChunk(chunk, flushFlag) + // if we don't throw, reset it back how it was + Buffer.concat = OriginalBufferConcat + } catch (err) { + // or if we do, put Buffer.concat() back before we emit error + // Error events call into user code, which may call Buffer.concat() + Buffer.concat = OriginalBufferConcat + this[_onError](new ZlibError(err)) + } finally { + if (this[_handle]) { + // Core zlib resets `_handle` to null after attempting to close the + // native handle. Our no-op handler prevented actual closure, but we + // need to restore the `._handle` property. + this[_handle]._handle = nativeHandle + nativeHandle.close = originalNativeClose + this[_handle].close = originalClose + // `_processChunk()` adds an 'error' listener. If we don't remove it + // after each call, these handlers start piling up. + this[_handle].removeAllListeners('error') + } + } - if (desc != null) { - return desc.get == null && desc.set == null - ? desc.value - : defaultValue; + let writeReturn + if (result) { + if (Array.isArray(result) && result.length > 0) { + // The first buffer is always `handle._outBuffer`, which would be + // re-used for later invocations; so, we always have to copy that one. + writeReturn = super.write(Buffer.from(result[0])) + for (let i = 1; i < result.length; i++) { + writeReturn = super.write(result[i]) } - } else { - return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; + } else { + writeReturn = super.write(Buffer.from(result)) + } } -} - -function notEnumerableProp(obj, name, value) { - if (isPrimitive(obj)) return obj; - var descriptor = { - value: value, - configurable: true, - enumerable: false, - writable: true - }; - es5.defineProperty(obj, name, descriptor); - return obj; -} -function thrower(r) { - throw r; + if (cb) + cb() + return writeReturn + } } -var inheritedDataKeys = (function() { - var excludedPrototypes = [ - Array.prototype, - Object.prototype, - Function.prototype - ]; - - var isExcludedProto = function(val) { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (excludedPrototypes[i] === val) { - return true; - } - } - return false; - }; +class Zlib extends ZlibBase { + constructor (opts, mode) { + opts = opts || {} - if (es5.isES5) { - var getKeys = Object.getOwnPropertyNames; - return function(obj) { - var ret = []; - var visitedKeys = Object.create(null); - while (obj != null && !isExcludedProto(obj)) { - var keys; - try { - keys = getKeys(obj); - } catch (e) { - return ret; - } - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (visitedKeys[key]) continue; - visitedKeys[key] = true; - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null && desc.get == null && desc.set == null) { - ret.push(key); - } - } - obj = es5.getPrototypeOf(obj); - } - return ret; - }; - } else { - var hasProp = {}.hasOwnProperty; - return function(obj) { - if (isExcludedProto(obj)) return []; - var ret = []; + opts.flush = opts.flush || constants.Z_NO_FLUSH + opts.finishFlush = opts.finishFlush || constants.Z_FINISH + super(opts, mode) - /*jshint forin:false */ - enumeration: for (var key in obj) { - if (hasProp.call(obj, key)) { - ret.push(key); - } else { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (hasProp.call(excludedPrototypes[i], key)) { - continue enumeration; - } - } - ret.push(key); - } - } - return ret; - }; - } + this[_fullFlushFlag] = constants.Z_FULL_FLUSH + this[_level] = opts.level + this[_strategy] = opts.strategy + } -})(); + params (level, strategy) { + if (this[_sawError]) + return -var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; -function isClass(fn) { - try { - if (typeof fn === "function") { - var keys = es5.names(fn.prototype); + if (!this[_handle]) + throw new Error('cannot switch params when binding is closed') - var hasMethods = es5.isES5 && keys.length > 1; - var hasMethodsOtherThanConstructor = keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); - var hasThisAssignmentAndStaticMethods = - thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; + // no way to test this without also not supporting params at all + /* istanbul ignore if */ + if (!this[_handle].params) + throw new Error('not supported in this implementation') - if (hasMethods || hasMethodsOtherThanConstructor || - hasThisAssignmentAndStaticMethods) { - return true; - } - } - return false; - } catch (e) { - return false; + if (this[_level] !== level || this[_strategy] !== strategy) { + this.flush(constants.Z_SYNC_FLUSH) + assert(this[_handle], 'zlib binding closed') + // .params() calls .flush(), but the latter is always async in the + // core zlib. We override .flush() temporarily to intercept that and + // flush synchronously. + const origFlush = this[_handle].flush + this[_handle].flush = (flushFlag, cb) => { + this.flush(flushFlag) + cb() + } + try { + this[_handle].params(level, strategy) + } finally { + this[_handle].flush = origFlush + } + /* istanbul ignore else */ + if (this[_handle]) { + this[_level] = level + this[_strategy] = strategy + } } + } } -function toFastProperties(obj) { - /*jshint -W027,-W055,-W031*/ - function FakeConstructor() {} - FakeConstructor.prototype = obj; - var receiver = new FakeConstructor(); - function ic() { - return typeof receiver.foo; - } - ic(); - ic(); - return obj; - eval(obj); +// minimal 2-byte header +class Deflate extends Zlib { + constructor (opts) { + super(opts, 'Deflate') + } } -var rident = /^[a-z$_][a-z$_0-9]*$/i; -function isIdentifier(str) { - return rident.test(str); +class Inflate extends Zlib { + constructor (opts) { + super(opts, 'Inflate') + } } -function filledRange(count, prefix, suffix) { - var ret = new Array(count); - for(var i = 0; i < count; ++i) { - ret[i] = prefix + i + suffix; - } - return ret; +// gzip - bigger header, same deflate compression +class Gzip extends Zlib { + constructor (opts) { + super(opts, 'Gzip') + } } -function safeToString(obj) { - try { - return obj + ""; - } catch (e) { - return "[no string representation]"; - } +class Gunzip extends Zlib { + constructor (opts) { + super(opts, 'Gunzip') + } } -function isError(obj) { - return obj instanceof Error || - (obj !== null && - typeof obj === "object" && - typeof obj.message === "string" && - typeof obj.name === "string"); +// raw - no header +class DeflateRaw extends Zlib { + constructor (opts) { + super(opts, 'DeflateRaw') + } } -function markAsOriginatingFromRejection(e) { - try { - notEnumerableProp(e, "isOperational", true); - } - catch(ignore) {} +class InflateRaw extends Zlib { + constructor (opts) { + super(opts, 'InflateRaw') + } } -function originatesFromRejection(e) { - if (e == null) return false; - return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || - e["isOperational"] === true); +// auto-detect header. +class Unzip extends Zlib { + constructor (opts) { + super(opts, 'Unzip') + } } -function canAttachTrace(obj) { - return isError(obj) && es5.propertyIsWritable(obj, "stack"); +class Brotli extends ZlibBase { + constructor (opts, mode) { + opts = opts || {} + + opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS + opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH + + super(opts, mode) + + this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH + } } -var ensureErrorObject = (function() { - if (!("stack" in new Error())) { - return function(value) { - if (canAttachTrace(value)) return value; - try {throw new Error(safeToString(value));} - catch(err) {return err;} - }; - } else { - return function(value) { - if (canAttachTrace(value)) return value; - return new Error(safeToString(value)); - }; - } -})(); +class BrotliCompress extends Brotli { + constructor (opts) { + super(opts, 'BrotliCompress') + } +} -function classString(obj) { - return {}.toString.call(obj); +class BrotliDecompress extends Brotli { + constructor (opts) { + super(opts, 'BrotliDecompress') + } } -function copyDescriptors(from, to, filter) { - var keys = es5.names(from); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (filter(key)) { - try { - es5.defineProperty(to, key, es5.getDescriptor(from, key)); - } catch (ignore) {} - } +exports.Deflate = Deflate +exports.Inflate = Inflate +exports.Gzip = Gzip +exports.Gunzip = Gunzip +exports.DeflateRaw = DeflateRaw +exports.InflateRaw = InflateRaw +exports.Unzip = Unzip +/* istanbul ignore else */ +if (typeof realZlib.BrotliCompress === 'function') { + exports.BrotliCompress = BrotliCompress + exports.BrotliDecompress = BrotliDecompress +} else { + exports.BrotliCompress = exports.BrotliDecompress = class { + constructor () { + throw new Error('Brotli is not supported in this version of Node.js') } + } } -var asArray = function(v) { - if (es5.isArray(v)) { - return v; - } - return null; -}; -if (typeof Symbol !== "undefined" && Symbol.iterator) { - var ArrayFrom = typeof Array.from === "function" ? function(v) { - return Array.from(v); - } : function(v) { - var ret = []; - var it = v[Symbol.iterator](); - var itResult; - while (!((itResult = it.next()).done)) { - ret.push(itResult.value); - } - return ret; - }; +/***/ }), +/* 269 */ +/***/ (function(module, exports, __webpack_require__) { - asArray = function(v) { - if (es5.isArray(v)) { - return v; - } else if (v != null && typeof v[Symbol.iterator] === "function") { - return ArrayFrom(v); - } - return null; - }; -} +"use strict"; -var isNode = typeof process !== "undefined" && - classString(process).toLowerCase() === "[object process]"; -var hasEnvVariables = typeof process !== "undefined" && - typeof process.env !== "undefined"; +/** + * index.js + * + * a request API compatible with window.fetch + */ -function env(key) { - return hasEnvVariables ? process.env[key] : undefined; -} +const url = __webpack_require__(835) +const http = __webpack_require__(605) +const https = __webpack_require__(211) +const zlib = __webpack_require__(761) +const PassThrough = __webpack_require__(794).PassThrough -function getNativePromise() { - if (typeof Promise === "function") { - try { - var promise = new Promise(function(){}); - if (classString(promise) === "[object Promise]") { - return Promise; - } - } catch (e) {} - } -} +const Body = __webpack_require__(542) +const writeToStream = Body.writeToStream +const Response = __webpack_require__(901) +const Headers = __webpack_require__(68) +const Request = __webpack_require__(988) +const getNodeRequestOptions = Request.getNodeRequestOptions +const FetchError = __webpack_require__(888) +const isURL = /^https?:/ -var reflectHandler; -function contextBind(ctx, cb) { - if (ctx === null || - typeof cb !== "function" || - cb === reflectHandler) { - return cb; - } +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +exports = module.exports = fetch +function fetch (uri, opts) { + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative') + } - if (ctx.domain !== null) { - cb = ctx.domain.bind(cb); - } + Body.Promise = fetch.Promise - var async = ctx.async; - if (async !== null) { - var old = cb; - cb = function() { - var $_len = arguments.length + 2;var args = new Array($_len); for(var $_i = 2; $_i < $_len ; ++$_i) {args[$_i] = arguments[$_i - 2];}; - args[0] = old; - args[1] = this; - return async.runInAsyncScope.apply(async, args); - }; - } - return cb; -} + // wrap http.request into fetch + return new fetch.Promise((resolve, reject) => { + // build request object + const request = new Request(uri, opts) + const options = getNodeRequestOptions(request) -var ret = { - setReflectHandler: function(fn) { - reflectHandler = fn; - }, - isClass: isClass, - isIdentifier: isIdentifier, - inheritedDataKeys: inheritedDataKeys, - getDataPropertyOrDefault: getDataPropertyOrDefault, - thrower: thrower, - isArray: es5.isArray, - asArray: asArray, - notEnumerableProp: notEnumerableProp, - isPrimitive: isPrimitive, - isObject: isObject, - isError: isError, - canEvaluate: canEvaluate, - errorObj: errorObj, - tryCatch: tryCatch, - inherits: inherits, - withAppended: withAppended, - maybeWrapAsError: maybeWrapAsError, - toFastProperties: toFastProperties, - filledRange: filledRange, - toString: safeToString, - canAttachTrace: canAttachTrace, - ensureErrorObject: ensureErrorObject, - originatesFromRejection: originatesFromRejection, - markAsOriginatingFromRejection: markAsOriginatingFromRejection, - classString: classString, - copyDescriptors: copyDescriptors, - isNode: isNode, - hasEnvVariables: hasEnvVariables, - env: env, - global: globalObject, - getNativePromise: getNativePromise, - contextBind: contextBind -}; -ret.isRecentNode = ret.isNode && (function() { - var version; - if (process.versions && process.versions.node) { - version = process.versions.node.split(".").map(Number); - } else if (process.version) { - version = process.version.split(".").map(Number); + const send = (options.protocol === 'https:' ? https : http).request + + // http.request only support string as host header, this hack make custom host header possible + if (options.headers.host) { + options.headers.host = options.headers.host[0] } - return (version[0] === 0 && version[1] > 10) || (version[0] > 0); -})(); -ret.nodeSupportsAsyncResource = ret.isNode && (function() { - var supportsAsync = false; - try { - var res = __webpack_require__(303).AsyncResource; - supportsAsync = typeof res.prototype.runInAsyncScope === "function"; - } catch (e) { - supportsAsync = false; + + // send request + const req = send(options) + let reqTimeout + + if (request.timeout) { + req.once('socket', socket => { + reqTimeout = setTimeout(() => { + req.abort() + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')) + }, request.timeout) + }) } - return supportsAsync; -})(); -if (ret.isNode) ret.toFastProperties(process); + req.on('error', err => { + clearTimeout(reqTimeout) + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)) + }) -try {throw new Error(); } catch (e) {ret.lastLineError = e;} -module.exports = ret; + req.on('response', res => { + clearTimeout(reqTimeout) + // handle redirect + if (fetch.isRedirect(res.statusCode) && request.redirect !== 'manual') { + if (request.redirect === 'error') { + reject(new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect')) + return + } -/***/ }), -/* 249 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')) + return + } -"use strict"; + if (!res.headers.location) { + reject(new FetchError(`redirect location header missing at: ${request.url}`, 'invalid-redirect')) + return + } + // Comment and logic below is used under the following license: + // Copyright (c) 2010-2012 Mikeal Rogers + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // http://www.apache.org/licenses/LICENSE-2.0 + // Unless required by applicable law or agreed to in writing, + // software distributed under the License is distributed on an "AS + // IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + // express or implied. See the License for the specific language + // governing permissions and limitations under the License. -const BB = __webpack_require__(440) + // Remove authorization if changing hostnames (but not if just + // changing ports or protocols). This matches the behavior of request: + // https://github.com/request/request/blob/b12a6245/lib/redirect.js#L134-L138 + const resolvedUrl = url.resolve(request.url, res.headers.location) + let redirectURL = '' + if (!isURL.test(res.headers.location)) { + redirectURL = url.parse(resolvedUrl) + } else { + redirectURL = url.parse(res.headers.location) + } + if (url.parse(request.url).hostname !== redirectURL.hostname) { + request.headers.delete('authorization') + } -const cacache = __webpack_require__(764) -const cacheKey = __webpack_require__(819) -const optCheck = __webpack_require__(420) -const packlist = __webpack_require__(110) -const pipe = BB.promisify(__webpack_require__(371).pipe) -const tar = __webpack_require__(885) + // per fetch spec, for POST request with 301/302 response, or any request with 303 response, use GET when following redirect + if (res.statusCode === 303 || + ((res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST')) { + request.method = 'GET' + request.body = null + request.headers.delete('content-length') + } -module.exports = packDir -function packDir (manifest, label, dir, target, opts) { - opts = optCheck(opts) + request.counter++ - const packer = opts.dirPacker - ? BB.resolve(opts.dirPacker(manifest, dir)) - : mkPacker(dir) + resolve(fetch(resolvedUrl, request)) + return + } - if (!opts.cache) { - return packer.then(packer => pipe(packer, target)) - } else { - const cacher = cacache.put.stream( - opts.cache, cacheKey('packed-dir', label), opts - ).on('integrity', i => { - target.emit('integrity', i) + // normalize location header for manual redirect mode + const headers = new Headers() + for (const name of Object.keys(res.headers)) { + if (Array.isArray(res.headers[name])) { + for (const val of res.headers[name]) { + headers.append(name, val) + } + } else { + headers.append(name, res.headers[name]) + } + } + if (request.redirect === 'manual' && headers.has('location')) { + headers.set('location', url.resolve(request.url, headers.get('location'))) + } + + // prepare response + let body = res.pipe(new PassThrough()) + const responseOptions = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout + } + + // HTTP-network fetch step 16.1.2 + const codings = headers.get('Content-Encoding') + + // HTTP-network fetch step 16.1.3: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + resolve(new Response(body, responseOptions)) + return + } + + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + } + + // for gzip + if (codings === 'gzip' || codings === 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)) + resolve(new Response(body, responseOptions)) + return + } + + // for deflate + if (codings === 'deflate' || codings === 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough()) + raw.once('data', chunk => { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate(zlibOptions)) + } else { + body = body.pipe(zlib.createInflateRaw(zlibOptions)) + } + resolve(new Response(body, responseOptions)) + }) + return + } + + // otherwise, use response as-is + resolve(new Response(body, responseOptions)) }) - return packer.then(packer => BB.all([ - pipe(packer, cacher), - pipe(packer, target) - ])) - } -} -function mkPacker (dir) { - return packlist({ path: dir }).then(files => { - return tar.c({ - cwd: dir, - gzip: true, - portable: true, - prefix: 'package/' - }, files) + writeToStream(req, request) }) -} +}; + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = code => code === 301 || code === 302 || code === 303 || code === 307 || code === 308 + +// expose Promise +fetch.Promise = global.Promise +exports.Headers = Headers +exports.Request = Request +exports.Response = Response +exports.FetchError = FetchError /***/ }), -/* 250 */ +/* 270 */ /***/ (function(module, __unusedexports, __webpack_require__) { -var constants = __webpack_require__(619) +"use strict"; -var origCwd = process.cwd -var cwd = null -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform +module.exports = __webpack_require__(789) -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd -} -try { - process.cwd() -} catch (er) {} -var chdir = process.chdir -process.chdir = function(d) { - cwd = null - chdir.call(process, d) -} +/***/ }), +/* 271 */ +/***/ (function(module) { -module.exports = patch +"use strict"; -function patch (fs) { - // (re-)implement some things that are known busted or missing. - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } +module.exports = hashToSegments - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } +function hashToSegments (hash) { + return [ + hash.slice(0, 2), + hash.slice(2, 4), + hash.slice(4) + ] +} - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) +/***/ }), +/* 272 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) +"use strict"; - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) +module.exports = function(Promise, Context, + enableAsyncHooks, disableAsyncHooks) { +var async = Promise._async; +var Warning = __webpack_require__(351).Warning; +var util = __webpack_require__(248); +var es5 = __webpack_require__(883); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; +var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; +var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var printWarning; +var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && + ( false || + util.env("BLUEBIRD_DEBUG") || + util.env("NODE_ENV") === "development")); - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) +var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && + (debugging || util.env("BLUEBIRD_WARNINGS"))); - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) +var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && + (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) +var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && + (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); - // if lchmod/lchown do not exist, then make them no-ops - if (!fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) +var deferUnhandledRejectionCheck; +(function() { + var promises = []; + + function unhandledRejectionCheck() { + for (var i = 0; i < promises.length; ++i) { + promises[i]._notifyUnhandledRejection(); + } + unhandledRejectionClear(); } - fs.lchmodSync = function () {} - } - if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) + + function unhandledRejectionClear() { + promises.length = 0; } - fs.lchownSync = function () {} - } - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. + deferUnhandledRejectionCheck = function(promise) { + promises.push(promise); + setTimeout(unhandledRejectionCheck, 1); + }; - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = (function (fs$rename) { return function (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - }})(fs.rename) - } + es5.defineProperty(Promise, "_unhandledRejectionCheck", { + value: unhandledRejectionCheck + }); + es5.defineProperty(Promise, "_unhandledRejectionClear", { + value: unhandledRejectionClear + }); +})(); - // if read() returns EAGAIN, then just try it again. - fs.read = (function (fs$read) { - function read (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } +Promise.prototype.suppressUnhandledRejections = function() { + var target = this._target(); + target._bitField = ((target._bitField & (~1048576)) | + 524288); +}; - // This ensures `util.promisify` works as it does for native `fs.read`. - read.__proto__ = fs$read - return read - })(fs.read) +Promise.prototype._ensurePossibleRejectionHandled = function () { + if ((this._bitField & 524288) !== 0) return; + this._setRejectionIsUnhandled(); + deferUnhandledRejectionCheck(this); +}; - fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue - } - throw er - } - } - }})(fs.readSync) +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) - } +Promise.prototype._setReturnedNonUndefined = function() { + this._bitField = this._bitField | 268435456; +}; - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) +Promise.prototype._returnedNonUndefined = function() { + return (this._bitField & 268435456) !== 0; +}; - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._settledValue(); + this._setUnhandledRejectionIsNotified(); + fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); } - } +}; - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK")) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 262144; +}; - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~262144); +}; - } else { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} - } - } +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 262144) > 0; +}; - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 1048576; +}; - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~1048576); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); } - } +}; +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 1048576) > 0; +}; - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } +Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { + return warn(message, shouldUseOwnTrace, promise || this); +}; - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } +Promise.onPossiblyUnhandledRejection = function (fn) { + var context = Promise._getContext(); + possiblyUnhandledRejection = util.contextBind(context, fn); +}; - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - function callback (er, stats) { - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - if (cb) cb.apply(this, arguments) - } - return options ? orig.call(fs, target, options, callback) - : orig.call(fs, target, callback) - } - } +Promise.onUnhandledRejectionHandled = function (fn) { + var context = Promise._getContext(); + unhandledRejectionHandled = util.contextBind(context, fn); +}; - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options) { - var stats = options ? orig.call(fs, target, options) - : orig.call(fs, target) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - return stats; +var disableLongStackTraces = function() {}; +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } - } - - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true - - if (er.code === "ENOSYS") - return true - - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true + if (!config.longStackTraces && longStackTracesIsSupported()) { + var Promise_captureStackTrace = Promise.prototype._captureStackTrace; + var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; + var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace; + config.longStackTraces = true; + disableLongStackTraces = function() { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + Promise.prototype._captureStackTrace = Promise_captureStackTrace; + Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; + Promise.prototype._dereferenceTrace = Promise_dereferenceTrace; + Context.deactivateLongStackTraces(); + config.longStackTraces = false; + }; + Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; + Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; + Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace; + Context.activateLongStackTraces(); } +}; - return false - } -} - - -/***/ }), -/* 251 */, -/* 252 */, -/* 253 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; +Promise.hasLongStackTraces = function () { + return config.longStackTraces && longStackTracesIsSupported(); +}; -module.exports = function(NEXT_FILTER) { -var util = __webpack_require__(248); -var getKeys = __webpack_require__(883).keys; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -function catchFilter(instances, cb, promise) { - return function(e) { - var boundTo = promise._boundValue(); - predicateLoop: for (var i = 0; i < instances.length; ++i) { - var item = instances[i]; +var legacyHandlers = { + unhandledrejection: { + before: function() { + var ret = util.global.onunhandledrejection; + util.global.onunhandledrejection = null; + return ret; + }, + after: function(fn) { + util.global.onunhandledrejection = fn; + } + }, + rejectionhandled: { + before: function() { + var ret = util.global.onrejectionhandled; + util.global.onrejectionhandled = null; + return ret; + }, + after: function(fn) { + util.global.onrejectionhandled = fn; + } + } +}; - if (item === Error || - (item != null && item.prototype instanceof Error)) { - if (e instanceof item) { - return tryCatch(cb).call(boundTo, e); - } - } else if (typeof item === "function") { - var matchesPredicate = tryCatch(item).call(boundTo, e); - if (matchesPredicate === errorObj) { - return matchesPredicate; - } else if (matchesPredicate) { - return tryCatch(cb).call(boundTo, e); - } - } else if (util.isObject(e)) { - var keys = getKeys(item); - for (var j = 0; j < keys.length; ++j) { - var key = keys[j]; - if (item[key] != e[key]) { - continue predicateLoop; - } - } - return tryCatch(cb).call(boundTo, e); +var fireDomEvent = (function() { + var dispatch = function(legacy, e) { + if (legacy) { + var fn; + try { + fn = legacy.before(); + return !util.global.dispatchEvent(e); + } finally { + legacy.after(fn); } + } else { + return !util.global.dispatchEvent(e); } - return NEXT_FILTER; }; -} - -return catchFilter; -}; - + try { + if (typeof CustomEvent === "function") { + var event = new CustomEvent("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + name = name.toLowerCase(); + var eventData = { + detail: event, + cancelable: true + }; + var domEvent = new CustomEvent(name, eventData); + es5.defineProperty( + domEvent, "promise", {value: event.promise}); + es5.defineProperty( + domEvent, "reason", {value: event.reason}); -/***/ }), -/* 254 */ -/***/ (function(module, exports, __webpack_require__) { + return dispatch(legacyHandlers[name], domEvent); + }; + } else if (typeof Event === "function") { + var event = new Event("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + name = name.toLowerCase(); + var domEvent = new Event(name, { + cancelable: true + }); + domEvent.detail = event; + es5.defineProperty(domEvent, "promise", {value: event.promise}); + es5.defineProperty(domEvent, "reason", {value: event.reason}); + return dispatch(legacyHandlers[name], domEvent); + }; + } else { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + util.global.dispatchEvent(event); + return function(name, event) { + name = name.toLowerCase(); + var domEvent = document.createEvent("CustomEvent"); + domEvent.initCustomEvent(name, false, true, + event); + return dispatch(legacyHandlers[name], domEvent); + }; + } + } catch (e) {} + return function() { + return false; + }; +})(); -/* eslint-disable node/no-deprecated-api */ -var buffer = __webpack_require__(293) -var Buffer = buffer.Buffer +var fireGlobalEvent = (function() { + if (util.isNode) { + return function() { + return process.emit.apply(process, arguments); + }; + } else { + if (!util.global) { + return function() { + return false; + }; + } + return function(name) { + var methodName = "on" + name.toLowerCase(); + var method = util.global[methodName]; + if (!method) return false; + method.apply(util.global, [].slice.call(arguments, 1)); + return true; + }; + } +})(); -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer +function generatePromiseLifecycleEventObject(name, promise) { + return {promise: promise}; } -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} +var eventToObjectGenerator = { + promiseCreated: generatePromiseLifecycleEventObject, + promiseFulfilled: generatePromiseLifecycleEventObject, + promiseRejected: generatePromiseLifecycleEventObject, + promiseResolved: generatePromiseLifecycleEventObject, + promiseCancelled: generatePromiseLifecycleEventObject, + promiseChained: function(name, promise, child) { + return {promise: promise, child: child}; + }, + warning: function(name, warning) { + return {warning: warning}; + }, + unhandledRejection: function (name, reason, promise) { + return {reason: reason, promise: promise}; + }, + rejectionHandled: generatePromiseLifecycleEventObject +}; -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) +var activeFireEvent = function (name) { + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent.apply(null, arguments); + } catch (e) { + async.throwLater(e); + globalEventFired = true; + } -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} + var domEventFired = false; + try { + domEventFired = fireDomEvent(name, + eventToObjectGenerator[name].apply(null, arguments)); + } catch (e) { + async.throwLater(e); + domEventFired = true; + } -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) + return domEventFired || globalEventFired; +}; + +Promise.config = function(opts) { + opts = Object(opts); + if ("longStackTraces" in opts) { + if (opts.longStackTraces) { + Promise.longStackTraces(); + } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { + disableLongStackTraces(); + } + } + if ("warnings" in opts) { + var warningsOption = opts.warnings; + config.warnings = !!warningsOption; + wForgottenReturn = config.warnings; + + if (util.isObject(warningsOption)) { + if ("wForgottenReturn" in warningsOption) { + wForgottenReturn = !!warningsOption.wForgottenReturn; + } + } + } + if ("cancellation" in opts && opts.cancellation && !config.cancellation) { + if (async.haveItemsQueued()) { + throw new Error( + "cannot enable cancellation after promises are in use"); + } + Promise.prototype._clearCancellationData = + cancellationClearCancellationData; + Promise.prototype._propagateFrom = cancellationPropagateFrom; + Promise.prototype._onCancel = cancellationOnCancel; + Promise.prototype._setOnCancel = cancellationSetOnCancel; + Promise.prototype._attachCancellationCallback = + cancellationAttachCancellationCallback; + Promise.prototype._execute = cancellationExecute; + propagateFromFunction = cancellationPropagateFrom; + config.cancellation = true; + } + if ("monitoring" in opts) { + if (opts.monitoring && !config.monitoring) { + config.monitoring = true; + Promise.prototype._fireEvent = activeFireEvent; + } else if (!opts.monitoring && config.monitoring) { + config.monitoring = false; + Promise.prototype._fireEvent = defaultFireEvent; + } + } + if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) { + var prev = config.asyncHooks; + var cur = !!opts.asyncHooks; + if (prev !== cur) { + config.asyncHooks = cur; + if (cur) { + enableAsyncHooks(); + } else { + disableAsyncHooks(); + } + } + } + return Promise; +}; + +function defaultFireEvent() { return false; } + +Promise.prototype._fireEvent = defaultFireEvent; +Promise.prototype._execute = function(executor, resolve, reject) { + try { + executor(resolve, reject); + } catch (e) { + return e; + } +}; +Promise.prototype._onCancel = function () {}; +Promise.prototype._setOnCancel = function (handler) { ; }; +Promise.prototype._attachCancellationCallback = function(onCancel) { + ; +}; +Promise.prototype._captureStackTrace = function () {}; +Promise.prototype._attachExtraTrace = function () {}; +Promise.prototype._dereferenceTrace = function () {}; +Promise.prototype._clearCancellationData = function() {}; +Promise.prototype._propagateFrom = function (parent, flags) { + ; + ; +}; + +function cancellationExecute(executor, resolve, reject) { + var promise = this; + try { + executor(resolve, reject, function(onCancel) { + if (typeof onCancel !== "function") { + throw new TypeError("onCancel must be a function, got: " + + util.toString(onCancel)); + } + promise._attachCancellationCallback(onCancel); + }); + } catch (e) { + return e; } - } else { - buf.fill(0) - } - return buf } -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) +function cancellationAttachCancellationCallback(onCancel) { + if (!this._isCancellable()) return this; + + var previousOnCancel = this._onCancel(); + if (previousOnCancel !== undefined) { + if (util.isArray(previousOnCancel)) { + previousOnCancel.push(onCancel); + } else { + this._setOnCancel([previousOnCancel, onCancel]); + } + } else { + this._setOnCancel(onCancel); + } } -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) +function cancellationOnCancel() { + return this._onCancelField; } +function cancellationSetOnCancel(onCancel) { + this._onCancelField = onCancel; +} -/***/ }), -/* 255 */, -/* 256 */, -/* 257 */, -/* 258 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +function cancellationClearCancellationData() { + this._cancellationParent = undefined; + this._onCancelField = undefined; +} -"use strict"; +function cancellationPropagateFrom(parent, flags) { + if ((flags & 1) !== 0) { + this._cancellationParent = parent; + var branchesRemainingToCancel = parent._branchesRemainingToCancel; + if (branchesRemainingToCancel === undefined) { + branchesRemainingToCancel = 0; + } + parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; + } + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} +function bindingPropagateFrom(parent, flags) { + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} +var propagateFromFunction = bindingPropagateFrom; -const ls = __webpack_require__(14) -const get = __webpack_require__(425) -const put = __webpack_require__(154) -const rm = __webpack_require__(706) -const verify = __webpack_require__(290) -const setLocale = __webpack_require__(945).setLocale -const clearMemoized = __webpack_require__(69).clearMemoized -const tmp = __webpack_require__(862) +function boundValueFunction() { + var ret = this._boundTo; + if (ret !== undefined) { + if (ret instanceof Promise) { + if (ret.isFulfilled()) { + return ret.value(); + } else { + return undefined; + } + } + } + return ret; +} -setLocale('en') +function longStackTracesCaptureStackTrace() { + this._trace = new CapturedTrace(this._peekContext()); +} -const x = module.exports +function longStackTracesAttachExtraTrace(error, ignoreSelf) { + if (canAttachTrace(error)) { + var trace = this._trace; + if (trace !== undefined) { + if (ignoreSelf) trace = trace._parent; + } + if (trace !== undefined) { + trace.attachExtraTrace(error); + } else if (!error.__stackCleaned__) { + var parsed = parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +} -x.ls = cache => ls(cache) -x.ls.stream = cache => ls.stream(cache) +function longStackTracesDereferenceTrace() { + this._trace = undefined; +} -x.get = (cache, key, opts) => get(cache, key, opts) -x.get.byDigest = (cache, hash, opts) => get.byDigest(cache, hash, opts) -x.get.sync = (cache, key, opts) => get.sync(cache, key, opts) -x.get.sync.byDigest = (cache, key, opts) => get.sync.byDigest(cache, key, opts) -x.get.stream = (cache, key, opts) => get.stream(cache, key, opts) -x.get.stream.byDigest = (cache, hash, opts) => get.stream.byDigest(cache, hash, opts) -x.get.copy = (cache, key, dest, opts) => get.copy(cache, key, dest, opts) -x.get.copy.byDigest = (cache, hash, dest, opts) => get.copy.byDigest(cache, hash, dest, opts) -x.get.info = (cache, key) => get.info(cache, key) -x.get.hasContent = (cache, hash) => get.hasContent(cache, hash) -x.get.hasContent.sync = (cache, hash) => get.hasContent.sync(cache, hash) +function checkForgottenReturns(returnValue, promiseCreated, name, promise, + parent) { + if (returnValue === undefined && promiseCreated !== null && + wForgottenReturn) { + if (parent !== undefined && parent._returnedNonUndefined()) return; + if ((promise._bitField & 65535) === 0) return; -x.put = (cache, key, data, opts) => put(cache, key, data, opts) -x.put.stream = (cache, key, opts) => put.stream(cache, key, opts) + if (name) name = name + " "; + var handlerLine = ""; + var creatorLine = ""; + if (promiseCreated._trace) { + var traceLines = promiseCreated._trace.stack.split("\n"); + var stack = cleanStack(traceLines); + for (var i = stack.length - 1; i >= 0; --i) { + var line = stack[i]; + if (!nodeFramePattern.test(line)) { + var lineMatches = line.match(parseLinePattern); + if (lineMatches) { + handlerLine = "at " + lineMatches[1] + + ":" + lineMatches[2] + ":" + lineMatches[3] + " "; + } + break; + } + } -x.rm = (cache, key) => rm.entry(cache, key) -x.rm.all = cache => rm.all(cache) -x.rm.entry = x.rm -x.rm.content = (cache, hash) => rm.content(cache, hash) + if (stack.length > 0) { + var firstUserLine = stack[0]; + for (var i = 0; i < traceLines.length; ++i) { -x.setLocale = lang => setLocale(lang) -x.clearMemoized = () => clearMemoized() + if (traceLines[i] === firstUserLine) { + if (i > 0) { + creatorLine = "\n" + traceLines[i - 1]; + } + break; + } + } -x.tmp = {} -x.tmp.mkdir = (cache, opts) => tmp.mkdir(cache, opts) -x.tmp.withTmp = (cache, opts, cb) => tmp.withTmp(cache, opts, cb) + } + } + var msg = "a promise was created in a " + name + + "handler " + handlerLine + "but was not returned from it, " + + "see http://goo.gl/rRqMUw" + + creatorLine; + promise._warn(msg, true, promiseCreated); + } +} -x.verify = (cache, opts) => verify(cache, opts) -x.verify.lastRun = cache => verify.lastRun(cache) +function deprecated(name, replacement) { + var message = name + + " is deprecated and will be removed in a future version."; + if (replacement) message += " Use " + replacement + " instead."; + return warn(message); +} +function warn(message, shouldUseOwnTrace, promise) { + if (!config.warnings) return; + var warning = new Warning(message); + var ctx; + if (shouldUseOwnTrace) { + promise._attachExtraTrace(warning); + } else if (config.longStackTraces && (ctx = Promise._peekContext())) { + ctx.attachExtraTrace(warning); + } else { + var parsed = parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } -/***/ }), -/* 259 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + if (!activeFireEvent("warning", warning)) { + formatAndLogError(warning, "", true); + } +} -"use strict"; +function reconstructStack(message, stacks) { + for (var i = 0; i < stacks.length - 1; ++i) { + stacks[i].push("From previous event:"); + stacks[i] = stacks[i].join("\n"); + } + if (i < stacks.length) { + stacks[i] = stacks[i].join("\n"); + } + return message + "\n" + stacks.join("\n"); +} +function removeDuplicateOrEmptyJumps(stacks) { + for (var i = 0; i < stacks.length; ++i) { + if (stacks[i].length === 0 || + ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { + stacks.splice(i, 1); + i--; + } + } +} -const cacache = __webpack_require__(764) -const fetch = __webpack_require__(269) -const pipe = __webpack_require__(371).pipe -const ssri = __webpack_require__(951) -const through = __webpack_require__(371).through -const to = __webpack_require__(371).to -const url = __webpack_require__(835) -const stream = __webpack_require__(794) +function removeCommonRoots(stacks) { + var current = stacks[0]; + for (var i = 1; i < stacks.length; ++i) { + var prev = stacks[i]; + var currentLastIndex = current.length - 1; + var currentLastLine = current[currentLastIndex]; + var commonRootMeetPoint = -1; -const MAX_MEM_SIZE = 5 * 1024 * 1024 // 5MB + for (var j = prev.length - 1; j >= 0; --j) { + if (prev[j] === currentLastLine) { + commonRootMeetPoint = j; + break; + } + } -function cacheKey (req) { - const parsed = url.parse(req.url) - return `make-fetch-happen:request-cache:${ - url.format({ - protocol: parsed.protocol, - slashes: parsed.slashes, - host: parsed.host, - hostname: parsed.hostname, - pathname: parsed.pathname - }) - }` + for (var j = commonRootMeetPoint; j >= 0; --j) { + var line = prev[j]; + if (current[currentLastIndex] === line) { + current.pop(); + currentLastIndex--; + } else { + break; + } + } + current = prev; + } } -// This is a cacache-based implementation of the Cache standard, -// using node-fetch. -// docs: https://developer.mozilla.org/en-US/docs/Web/API/Cache -// -module.exports = class Cache { - constructor (path, opts) { - this._path = path - this.Promise = (opts && opts.Promise) || Promise - } +function cleanStack(stack) { + var ret = []; + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + var isTraceLine = " (No stack trace)" === line || + stackFramePattern.test(line); + var isInternalFrame = isTraceLine && shouldIgnore(line); + if (isTraceLine && !isInternalFrame) { + if (indentStackFrames && line.charAt(0) !== " ") { + line = " " + line; + } + ret.push(line); + } + } + return ret; +} - // Returns a Promise that resolves to the response associated with the first - // matching request in the Cache object. - match (req, opts) { - opts = opts || {} - const key = cacheKey(req) - return cacache.get.info(this._path, key).then(info => { - return info && cacache.get.hasContent( - this._path, info.integrity, opts - ).then(exists => exists && info) - }).then(info => { - if (info && info.metadata && matchDetails(req, { - url: info.metadata.url, - reqHeaders: new fetch.Headers(info.metadata.reqHeaders), - resHeaders: new fetch.Headers(info.metadata.resHeaders), - cacheIntegrity: info.integrity, - integrity: opts && opts.integrity - })) { - const resHeaders = new fetch.Headers(info.metadata.resHeaders) - addCacheHeaders(resHeaders, this._path, key, info.integrity, info.time) - if (req.method === 'HEAD') { - return new fetch.Response(null, { - url: req.url, - headers: resHeaders, - status: 200 - }) +function stackFramesAsArray(error) { + var stack = error.stack.replace(/\s+$/g, "").split("\n"); + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + if (" (No stack trace)" === line || stackFramePattern.test(line)) { + break; } - let body - const cachePath = this._path - // avoid opening cache file handles until a user actually tries to - // read from it. - if (opts.memoize !== false && info.size > MAX_MEM_SIZE) { - body = new stream.PassThrough() - const realRead = body._read - body._read = function (size) { - body._read = realRead - pipe( - cacache.get.stream.byDigest(cachePath, info.integrity, { - memoize: opts.memoize - }), - body, - err => body.emit(err)) - return realRead.call(this, size) - } + } + if (i > 0 && error.name != "SyntaxError") { + stack = stack.slice(i); + } + return stack; +} + +function parseStackAndMessage(error) { + var stack = error.stack; + var message = error.toString(); + stack = typeof stack === "string" && stack.length > 0 + ? stackFramesAsArray(error) : [" (No stack trace)"]; + return { + message: message, + stack: error.name == "SyntaxError" ? stack : cleanStack(stack) + }; +} + +function formatAndLogError(error, title, isSoft) { + if (typeof console !== "undefined") { + var message; + if (util.isObject(error)) { + var stack = error.stack; + message = title + formatStack(stack, error); } else { - let readOnce = false - // cacache is much faster at bulk reads - body = new stream.Readable({ - read () { - if (readOnce) return this.push(null) - readOnce = true - cacache.get.byDigest(cachePath, info.integrity, { - memoize: opts.memoize - }).then(data => { - this.push(data) - this.push(null) - }, err => this.emit('error', err)) + message = title + String(error); + } + if (typeof printWarning === "function") { + printWarning(message, isSoft); + } else if (typeof console.log === "function" || + typeof console.log === "object") { + console.log(message); + } + } +} + +function fireRejectionEvent(name, localHandler, reason, promise) { + var localEventFired = false; + try { + if (typeof localHandler === "function") { + localEventFired = true; + if (name === "rejectionHandled") { + localHandler(promise); + } else { + localHandler(reason, promise); } - }) } - return this.Promise.resolve(new fetch.Response(body, { - url: req.url, - headers: resHeaders, - status: 200, - size: info.size - })) - } - }) - } + } catch (e) { + async.throwLater(e); + } - // Takes both a request and its response and adds it to the given cache. - put (req, response, opts) { - opts = opts || {} - const size = response.headers.get('content-length') - const fitInMemory = !!size && opts.memoize !== false && size < MAX_MEM_SIZE - const ckey = cacheKey(req) - const cacheOpts = { - algorithms: opts.algorithms, - metadata: { - url: req.url, - reqHeaders: req.headers.raw(), - resHeaders: response.headers.raw() - }, - size, - memoize: fitInMemory && opts.memoize - } - if (req.method === 'HEAD' || response.status === 304) { - // Update metadata without writing - return cacache.get.info(this._path, ckey).then(info => { - // Providing these will bypass content write - cacheOpts.integrity = info.integrity - addCacheHeaders( - response.headers, this._path, ckey, info.integrity, info.time - ) - return new this.Promise((resolve, reject) => { - pipe( - cacache.get.stream.byDigest(this._path, info.integrity, cacheOpts), - cacache.put.stream(this._path, cacheKey(req), cacheOpts), - err => err ? reject(err) : resolve(response) - ) - }) - }).then(() => response) - } - let buf = [] - let bufSize = 0 - let cacheTargetStream = false - const cachePath = this._path - let cacheStream = to((chunk, enc, cb) => { - if (!cacheTargetStream) { - if (fitInMemory) { - cacheTargetStream = - to({highWaterMark: MAX_MEM_SIZE}, (chunk, enc, cb) => { - buf.push(chunk) - bufSize += chunk.length - cb() - }, done => { - cacache.put( - cachePath, - cacheKey(req), - Buffer.concat(buf, bufSize), - cacheOpts - ).then( - () => done(), - done - ) - }) - } else { - cacheTargetStream = - cacache.put.stream(cachePath, cacheKey(req), cacheOpts) + if (name === "unhandledRejection") { + if (!activeFireEvent(name, reason, promise) && !localEventFired) { + formatAndLogError(reason, "Unhandled rejection "); } - } - cacheTargetStream.write(chunk, enc, cb) - }, done => { - cacheTargetStream ? cacheTargetStream.end(done) : done() - }) - const oldBody = response.body - const newBody = through({highWaterMark: MAX_MEM_SIZE}) - response.body = newBody - oldBody.once('error', err => newBody.emit('error', err)) - newBody.once('error', err => oldBody.emit('error', err)) - cacheStream.once('error', err => newBody.emit('error', err)) - pipe(oldBody, to((chunk, enc, cb) => { - cacheStream.write(chunk, enc, () => { - newBody.write(chunk, enc, cb) - }) - }, done => { - cacheStream.end(() => { - newBody.end(() => { - done() - }) - }) - }), err => err && newBody.emit('error', err)) - return response - } - - // Finds the Cache entry whose key is the request, and if found, deletes the - // Cache entry and returns a Promise that resolves to true. If no Cache entry - // is found, it returns false. - 'delete' (req, opts) { - opts = opts || {} - if (typeof opts.memoize === 'object') { - if (opts.memoize.reset) { - opts.memoize.reset() - } else if (opts.memoize.clear) { - opts.memoize.clear() - } else { - Object.keys(opts.memoize).forEach(k => { - opts.memoize[k] = null - }) - } + } else { + activeFireEvent(name, promise); } - return cacache.rm.entry( - this._path, - cacheKey(req) - // TODO - true/false - ).then(() => false) - } } -function matchDetails (req, cached) { - const reqUrl = url.parse(req.url) - const cacheUrl = url.parse(cached.url) - const vary = cached.resHeaders.get('Vary') - // https://tools.ietf.org/html/rfc7234#section-4.1 - if (vary) { - if (vary.match(/\*/)) { - return false +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; } else { - const fieldsMatch = vary.split(/\s*,\s*/).every(field => { - return cached.reqHeaders.get(field) === req.headers.get(field) - }) - if (!fieldsMatch) { - return false - } + str = obj && typeof obj.toString === "function" + ? obj.toString() : util.toString(obj); + var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; + if (ruselessToString.test(str)) { + try { + var newStr = JSON.stringify(obj); + str = newStr; + } + catch(e) { + + } + } + if (str.length === 0) { + str = "(empty array)"; + } } - } - if (cached.integrity) { - return ssri.parse(cached.integrity).match(cached.cacheIntegrity) - } - reqUrl.hash = null - cacheUrl.hash = null - return url.format(reqUrl) === url.format(cacheUrl) + return ("(<" + snip(str) + ">, no stack trace)"); } -function addCacheHeaders (resHeaders, path, key, hash, time) { - resHeaders.set('X-Local-Cache', encodeURIComponent(path)) - resHeaders.set('X-Local-Cache-Key', encodeURIComponent(key)) - resHeaders.set('X-Local-Cache-Hash', encodeURIComponent(hash)) - resHeaders.set('X-Local-Cache-Time', new Date(time).toUTCString()) +function snip(str) { + var maxChars = 41; + if (str.length < maxChars) { + return str; + } + return str.substr(0, maxChars - 3) + "..."; } +function longStackTracesIsSupported() { + return typeof captureStackTrace === "function"; +} -/***/ }), -/* 260 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - +var shouldIgnore = function() { return false; }; +var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; +function parseLineInfo(line) { + var matches = line.match(parseLineInfoRegex); + if (matches) { + return { + fileName: matches[1], + line: parseInt(matches[2], 10) + }; + } +} -exports = module.exports = lifecycle -exports.makeEnv = makeEnv -exports._incorrectWorkingDirectory = _incorrectWorkingDirectory +function setBounds(firstLineError, lastLineError) { + if (!longStackTracesIsSupported()) return; + var firstStackLines = (firstLineError.stack || "").split("\n"); + var lastStackLines = (lastLineError.stack || "").split("\n"); + var firstIndex = -1; + var lastIndex = -1; + var firstFileName; + var lastFileName; + for (var i = 0; i < firstStackLines.length; ++i) { + var result = parseLineInfo(firstStackLines[i]); + if (result) { + firstFileName = result.fileName; + firstIndex = result.line; + break; + } + } + for (var i = 0; i < lastStackLines.length; ++i) { + var result = parseLineInfo(lastStackLines[i]); + if (result) { + lastFileName = result.fileName; + lastIndex = result.line; + break; + } + } + if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || + firstFileName !== lastFileName || firstIndex >= lastIndex) { + return; + } -// for testing -const platform = process.env.__TESTING_FAKE_PLATFORM__ || process.platform -const isWindows = platform === 'win32' -const spawn = __webpack_require__(751) -const path = __webpack_require__(622) -const Stream = __webpack_require__(794).Stream -const fs = __webpack_require__(598) -const chain = __webpack_require__(404).chain -const uidNumber = __webpack_require__(798) -const umask = __webpack_require__(696) -const which = __webpack_require__(142) -const byline = __webpack_require__(861) -const resolveFrom = __webpack_require__(143) + shouldIgnore = function(line) { + if (bluebirdFramePattern.test(line)) return true; + var info = parseLineInfo(line); + if (info) { + if (info.fileName === firstFileName && + (firstIndex <= info.line && info.line <= lastIndex)) { + return true; + } + } + return false; + }; +} -const DEFAULT_NODE_GYP_PATH = /*require.resolve*/( 693) -const hookStatCache = new Map() +function CapturedTrace(parent) { + this._parent = parent; + this._promisesCreated = 0; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); +Context.CapturedTrace = CapturedTrace; -let PATH = isWindows ? 'Path' : 'PATH' -exports._pathEnvName = PATH -const delimiter = path.delimiter +CapturedTrace.prototype.uncycle = function() { + var length = this._length; + if (length < 2) return; + var nodes = []; + var stackToIndex = {}; -// windows calls its path 'Path' usually, but this is not guaranteed. -// merge them all together in the order they appear in the object. -const mergePath = env => - Object.keys(env).filter(p => /^path$/i.test(p) && env[p]) - .map(p => env[p].split(delimiter)) - .reduce((set, p) => set.concat(p.filter(p => !set.includes(p))), []) - .join(delimiter) -exports._mergePath = mergePath + for (var i = 0, node = this; node !== undefined; ++i) { + nodes.push(node); + node = node._parent; + } + length = this._length = i; + for (var i = length - 1; i >= 0; --i) { + var stack = nodes[i].stack; + if (stackToIndex[stack] === undefined) { + stackToIndex[stack] = i; + } + } + for (var i = 0; i < length; ++i) { + var currentStack = nodes[i].stack; + var index = stackToIndex[currentStack]; + if (index !== undefined && index !== i) { + if (index > 0) { + nodes[index - 1]._parent = undefined; + nodes[index - 1]._length = 1; + } + nodes[i]._parent = undefined; + nodes[i]._length = 1; + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; -const setPathEnv = (env, path) => { - // first ensure that the canonical value is set. - env[PATH] = path - // also set any other case values, because windows. - Object.keys(env) - .filter(p => p !== PATH && /^path$/i.test(p)) - .forEach(p => { env[p] = path }) -} -exports._setPathEnv = setPathEnv + if (index < length - 1) { + cycleEdgeNode._parent = nodes[index + 1]; + cycleEdgeNode._parent.uncycle(); + cycleEdgeNode._length = + cycleEdgeNode._parent._length + 1; + } else { + cycleEdgeNode._parent = undefined; + cycleEdgeNode._length = 1; + } + var currentChildLength = cycleEdgeNode._length + 1; + for (var j = i - 2; j >= 0; --j) { + nodes[j]._length = currentChildLength; + currentChildLength++; + } + return; + } + } +}; -function logid (pkg, stage) { - return pkg._id + '~' + stage + ':' -} +CapturedTrace.prototype.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = parseStackAndMessage(error); + var message = parsed.message; + var stacks = [parsed.stack]; -function hookStat (dir, stage, cb) { - const hook = path.join(dir, '.hooks', stage) - const cachedStatError = hookStatCache.get(hook) + var trace = this; + while (trace !== undefined) { + stacks.push(cleanStack(trace.stack.split("\n"))); + trace = trace._parent; + } + removeCommonRoots(stacks); + removeDuplicateOrEmptyJumps(stacks); + util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); + util.notEnumerableProp(error, "__stackCleaned__", true); +}; - if (cachedStatError === undefined) { - return fs.stat(hook, function (statError) { - hookStatCache.set(hook, statError) - cb(statError) - }) - } +var captureStackTrace = (function stackDetection() { + var v8stackFramePattern = /^\s*at\s*/; + var v8stackFormatter = function(stack, error) { + if (typeof stack === "string") return stack; - return setImmediate(() => cb(cachedStatError)) -} + if (error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; -function lifecycle (pkg, stage, wd, opts) { - return new Promise((resolve, reject) => { - while (pkg && pkg._data) pkg = pkg._data - if (!pkg) return reject(new Error('Invalid package data')) + if (typeof Error.stackTraceLimit === "number" && + typeof Error.captureStackTrace === "function") { + Error.stackTraceLimit += 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; - opts.log.info('lifecycle', logid(pkg, stage), pkg._id) - if (!pkg.scripts) pkg.scripts = {} + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit += 6; + captureStackTrace(receiver, ignoreUntil); + Error.stackTraceLimit -= 6; + }; + } + var err = new Error(); - if (stage === 'prepublish' && opts.ignorePrepublish) { - opts.log.info('lifecycle', logid(pkg, stage), 'ignored because ignore-prepublish is set to true', pkg._id) - delete pkg.scripts.prepublish + if (typeof err.stack === "string" && + err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { + stackFramePattern = /@/; + formatStack = v8stackFormatter; + indentStackFrames = true; + return function captureStackTrace(o) { + o.stack = new Error().stack; + }; } - hookStat(opts.dir, stage, function (statError) { - // makeEnv is a slow operation. This guard clause prevents makeEnv being called - // and avoids a ton of unnecessary work, and results in a major perf boost. - if (!pkg.scripts[stage] && statError) return resolve() + var hasStackAfterThrow; + try { throw new Error(); } + catch(e) { + hasStackAfterThrow = ("stack" in e); + } + if (!("stack" in err) && hasStackAfterThrow && + typeof Error.stackTraceLimit === "number") { + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + return function captureStackTrace(o) { + Error.stackTraceLimit += 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + Error.stackTraceLimit -= 6; + }; + } - validWd(wd || path.resolve(opts.dir, pkg.name), function (er, wd) { - if (er) return reject(er) + formatStack = function(stack, error) { + if (typeof stack === "string") return stack; - if ((wd.indexOf(opts.dir) !== 0 || _incorrectWorkingDirectory(wd, pkg)) && - !opts.unsafePerm && pkg.scripts[stage]) { - opts.log.warn('lifecycle', logid(pkg, stage), 'cannot run in wd', pkg._id, pkg.scripts[stage], `(wd=${wd})`) - return resolve() + if ((typeof error === "object" || + typeof error === "function") && + error.name !== undefined && + error.message !== undefined) { + return error.toString(); } + return formatNonError(error); + }; - // set the env variables, then run scripts as a child process. - var env = makeEnv(pkg, opts) - env.npm_lifecycle_event = stage - env.npm_node_execpath = env.NODE = env.NODE || process.execPath - env.npm_execpath = require.main.filename - env.INIT_CWD = process.cwd() - env.npm_config_node_gyp = env.npm_config_node_gyp || DEFAULT_NODE_GYP_PATH + return null; - // 'nobody' typically doesn't have permission to write to /tmp - // even if it's never used, sh freaks out. - if (!opts.unsafePerm) env.TMPDIR = wd +})([]); - lifecycle_(pkg, stage, wd, opts, env, (er) => { - if (er) return reject(er) - return resolve() - }) - }) - }) - }) +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + printWarning = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + printWarning = function(message, isSoft) { + var color = isSoft ? "\u001b[33m" : "\u001b[31m"; + console.warn(color + message + "\u001b[0m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + printWarning = function(message, isSoft) { + console.warn("%c" + message, + isSoft ? "color: darkorange" : "color: red"); + }; + } } -function _incorrectWorkingDirectory (wd, pkg) { - return wd.lastIndexOf(pkg.name) !== wd.length - pkg.name.length -} +var config = { + warnings: warnings, + longStackTraces: false, + cancellation: false, + monitoring: false, + asyncHooks: false +}; -function lifecycle_ (pkg, stage, wd, opts, env, cb) { - var pathArr = [] - var p = wd.split(/[\\/]node_modules[\\/]/) - var acc = path.resolve(p.shift()) +if (longStackTraces) Promise.longStackTraces(); - p.forEach(function (pp) { - pathArr.unshift(path.join(acc, 'node_modules', '.bin')) - acc = path.join(acc, 'node_modules', pp) - }) - pathArr.unshift(path.join(acc, 'node_modules', '.bin')) +return { + asyncHooks: function() { + return config.asyncHooks; + }, + longStackTraces: function() { + return config.longStackTraces; + }, + warnings: function() { + return config.warnings; + }, + cancellation: function() { + return config.cancellation; + }, + monitoring: function() { + return config.monitoring; + }, + propagateFromFunction: function() { + return propagateFromFunction; + }, + boundValueFunction: function() { + return boundValueFunction; + }, + checkForgottenReturns: checkForgottenReturns, + setBounds: setBounds, + warn: warn, + deprecated: deprecated, + CapturedTrace: CapturedTrace, + fireDomEvent: fireDomEvent, + fireGlobalEvent: fireGlobalEvent +}; +}; - // we also unshift the bundled node-gyp-bin folder so that - // the bundled one will be used for installing things. - pathArr.unshift(path.join(__dirname, 'node-gyp-bin')) - if (shouldPrependCurrentNodeDirToPATH(opts)) { - // prefer current node interpreter in child scripts - pathArr.push(path.dirname(process.execPath)) - } +/***/ }), +/* 273 */ +/***/ (function(module, exports, __webpack_require__) { - const existingPath = mergePath(env) - if (existingPath) pathArr.push(existingPath) - const envPath = pathArr.join(isWindows ? ';' : ':') - setPathEnv(env, envPath) - - var packageLifecycle = pkg.scripts && pkg.scripts.hasOwnProperty(stage) +"use strict"; - if (opts.ignoreScripts) { - opts.log.info('lifecycle', logid(pkg, stage), 'ignored because ignore-scripts is set to true', pkg._id) - packageLifecycle = false - } else if (packageLifecycle) { - // define this here so it's available to all scripts. - env.npm_lifecycle_script = pkg.scripts[stage] - } else { - opts.log.silly('lifecycle', logid(pkg, stage), 'no script for ' + stage + ', continuing') - } - function done (er) { - if (er) { - if (opts.force) { - opts.log.info('lifecycle', logid(pkg, stage), 'forced, continuing', er) - er = null - } else if (opts.failOk) { - opts.log.warn('lifecycle', logid(pkg, stage), 'continuing anyway', er.message) - er = null - } - } - cb(er) - } +const path = __webpack_require__(622) +const fs = __webpack_require__(598) +const chain = __webpack_require__(433).chain +const mkdir = __webpack_require__(836) +const rm = __webpack_require__(974) +const inferOwner = __webpack_require__(686) +const chown = __webpack_require__(358) - chain( - [ - packageLifecycle && [runPackageLifecycle, pkg, stage, env, wd, opts], - [runHookLifecycle, pkg, stage, env, wd, opts] - ], - done - ) +exports = module.exports = { + link: link, + linkIfExists: linkIfExists } -function shouldPrependCurrentNodeDirToPATH (opts) { - const cfgsetting = opts.scriptsPrependNodePath - if (cfgsetting === false) return false - if (cfgsetting === true) return true - - var isDifferentNodeInPath - - var foundExecPath - try { - foundExecPath = which.sync(path.basename(process.execPath), { pathExt: isWindows ? ';' : ':' }) - // Apply `fs.realpath()` here to avoid false positives when `node` is a symlinked executable. - isDifferentNodeInPath = fs.realpathSync(process.execPath).toUpperCase() !== - fs.realpathSync(foundExecPath).toUpperCase() - } catch (e) { - isDifferentNodeInPath = true - } - - if (cfgsetting === 'warn-only') { - if (isDifferentNodeInPath && !shouldPrependCurrentNodeDirToPATH.hasWarned) { - if (foundExecPath) { - opts.log.warn('lifecycle', 'The node binary used for scripts is', foundExecPath, 'but npm is using', process.execPath, 'itself. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.') - } else { - opts.log.warn('lifecycle', 'npm is using', process.execPath, 'but there is no node binary in the current PATH. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.') +function linkIfExists (from, to, opts, cb) { + opts.currentIsLink = false + opts.currentExists = false + fs.stat(from, function (er) { + if (er) return cb() + fs.readlink(to, function (er, fromOnDisk) { + if (!er || er.code !== 'ENOENT') { + opts.currentExists = true } - shouldPrependCurrentNodeDirToPATH.hasWarned = true - } - - return false - } + // if the link already exists and matches what we would do, + // we don't need to do anything + if (!er) { + opts.currentIsLink = true + var toDir = path.dirname(to) + var absoluteFrom = path.resolve(toDir, from) + var absoluteFromOnDisk = path.resolve(toDir, fromOnDisk) + opts.currentTarget = absoluteFromOnDisk + if (absoluteFrom === absoluteFromOnDisk) return cb() + } + link(from, to, opts, cb) + }) + }) +} - return isDifferentNodeInPath +function resolveIfSymlink (maybeSymlinkPath, cb) { + fs.lstat(maybeSymlinkPath, function (err, stat) { + if (err) return cb.apply(this, arguments) + if (!stat.isSymbolicLink()) return cb(null, maybeSymlinkPath) + fs.readlink(maybeSymlinkPath, cb) + }) } -function validWd (d, cb) { - fs.stat(d, function (er, st) { - if (er || !st.isDirectory()) { - var p = path.dirname(d) - if (p === d) { - return cb(new Error('Could not find suitable wd')) - } - return validWd(p, cb) +function ensureFromIsNotSource (from, to, cb) { + resolveIfSymlink(from, function (err, fromDestination) { + if (err) return cb.apply(this, arguments) + if (path.resolve(path.dirname(from), fromDestination) === path.resolve(to)) { + return cb(new Error('Link target resolves to the same directory as link source: ' + to)) } - return cb(null, d) + cb.apply(this, arguments) }) } -function runPackageLifecycle (pkg, stage, env, wd, opts, cb) { - // run package lifecycle scripts in the package root, or the nearest parent. - var cmd = env.npm_lifecycle_script +function link (from, to, opts, cb) { + to = path.resolve(to) + opts.base = path.dirname(to) + var absTarget = path.resolve(opts.base, from) + var relativeTarget = path.relative(opts.base, absTarget) + var target = opts.absolute ? absTarget : relativeTarget - var note = '\n> ' + pkg._id + ' ' + stage + ' ' + wd + - '\n> ' + cmd + '\n' - runCmd(note, cmd, pkg, env, stage, wd, opts, cb) -} + const tasks = [ + [ensureFromIsNotSource, absTarget, to], + [fs, 'stat', absTarget], + [clobberLinkGently, from, to, opts], + [mkdir, path.dirname(to)], + [fs, 'symlink', target, to, 'junction'] + ] -var running = false -var queue = [] -function dequeue () { - running = false - if (queue.length) { - var r = queue.shift() - runCmd.apply(null, r) + if (chown.selfOwner.uid !== 0) { + chain(tasks, cb) + } else { + inferOwner(to).then(owner => { + tasks.push([chown, to, owner.uid, owner.gid]) + chain(tasks, cb) + }) } } -function runCmd (note, cmd, pkg, env, stage, wd, opts, cb) { - if (running) { - queue.push([note, cmd, pkg, env, stage, wd, opts, cb]) - return +exports._clobberLinkGently = clobberLinkGently +function clobberLinkGently (from, to, opts, cb) { + if (opts.currentExists === false) { + // nothing to clobber! + opts.log.silly('gently link', 'link does not already exist', { + link: to, + target: from + }) + return cb() } - running = true - opts.log.pause() - var unsafe = opts.unsafePerm - var user = unsafe ? null : opts.user - var group = unsafe ? null : opts.group - - if (opts.log.level !== 'silent') { - opts.log.clearProgress() - console.log(note) - opts.log.showProgress() + if (!opts.clobberLinkGently || + opts.force === true || + !opts.gently || + typeof opts.gently !== 'string') { + opts.log.silly('gently link', 'deleting existing link forcefully', { + link: to, + target: from, + force: opts.force, + gently: opts.gently, + clobberLinkGently: opts.clobberLinkGently + }) + return rm(to, opts, cb) } - opts.log.verbose('lifecycle', logid(pkg, stage), 'unsafe-perm in lifecycle', unsafe) - if (isWindows) { - unsafe = true + if (!opts.currentIsLink) { + opts.log.verbose('gently link', 'cannot remove, not a link', to) + // don't delete. it'll fail with EEXIST when it tries to symlink. + return cb() } - if (unsafe) { - runCmd_(cmd, pkg, env, wd, opts, stage, unsafe, 0, 0, cb) + if (opts.currentTarget.indexOf(opts.gently) === 0) { + opts.log.silly('gently link', 'delete existing link', to) + return rm(to, opts, cb) } else { - uidNumber(user, group, function (er, uid, gid) { - if (er) { - er.code = 'EUIDLOOKUP' - opts.log.resume() - process.nextTick(dequeue) - return cb(er) - } - runCmd_(cmd, pkg, env, wd, opts, stage, unsafe, uid, gid, cb) + opts.log.verbose('gently link', 'refusing to delete existing link', { + link: to, + currentTarget: opts.currentTarget, + newTarget: from, + gently: opts.gently }) + return cb() } } -const getSpawnArgs = ({ cmd, wd, opts, uid, gid, unsafe, env }) => { - const conf = { - cwd: wd, - env: env, - stdio: opts.stdio || [ 0, 1, 2 ] - } - - if (!unsafe) { - conf.uid = uid ^ 0 - conf.gid = gid ^ 0 - } - - const customShell = opts.scriptShell - let sh = 'sh' - let shFlag = '-c' - if (customShell) { - sh = customShell - } else if (isWindows || opts._TESTING_FAKE_WINDOWS_) { - sh = process.env.comspec || 'cmd' - // '/d /s /c' is used only for cmd.exe. - if (/^(?:.*\\)?cmd(?:\.exe)?$/i.test(sh)) { - shFlag = '/d /s /c' - conf.windowsVerbatimArguments = true - } - } +/***/ }), +/* 274 */, +/* 275 */, +/* 276 */ +/***/ (function(__unusedmodule, exports) { - return [sh, [shFlag, cmd], conf] -} +"use strict"; -exports._getSpawnArgs = getSpawnArgs +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Logger.js.map -function runCmd_ (cmd, pkg, env, wd, opts, stage, unsafe, uid, gid, cb_) { - function cb (er) { - cb_.apply(null, arguments) - opts.log.resume() - process.nextTick(dequeue) - } +/***/ }), +/* 277 */, +/* 278 */ +/***/ (function(__unusedmodule, exports) { - const [sh, args, conf] = getSpawnArgs({ cmd, wd, opts, uid, gid, unsafe, env }) +"use strict"; - opts.log.verbose('lifecycle', logid(pkg, stage), 'PATH:', env[PATH]) - opts.log.verbose('lifecycle', logid(pkg, stage), 'CWD:', wd) - opts.log.silly('lifecycle', logid(pkg, stage), 'Args:', args) +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=CorrelationContext.js.map - var proc = spawn(sh, args, conf, opts.log) +/***/ }), +/* 279 */ +/***/ (function(module) { - proc.on('error', procError) - proc.on('close', function (code, signal) { - opts.log.silly('lifecycle', logid(pkg, stage), 'Returned: code:', code, ' signal:', signal) - if (signal) { - process.kill(process.pid, signal) - } else if (code) { - var er = new Error('Exit status ' + code) - er.errno = code - } - procError(er) - }) - byline(proc.stdout).on('data', function (data) { - opts.log.verbose('lifecycle', logid(pkg, stage), 'stdout', data.toString()) - }) - byline(proc.stderr).on('data', function (data) { - opts.log.verbose('lifecycle', logid(pkg, stage), 'stderr', data.toString()) - }) - process.once('SIGTERM', procKill) - process.once('SIGINT', procInterupt) +"use strict"; - function procError (er) { - if (er) { - opts.log.info('lifecycle', logid(pkg, stage), 'Failed to exec ' + stage + ' script') - er.message = pkg._id + ' ' + stage + ': `' + cmd + '`\n' + - er.message - if (er.code !== 'EPERM') { - er.code = 'ELIFECYCLE' - } - fs.stat(opts.dir, function (statError, d) { - if (statError && statError.code === 'ENOENT' && opts.dir.split(path.sep).slice(-1)[0] === 'node_modules') { - opts.log.warn('', 'Local package.json exists, but node_modules missing, did you mean to install?') - } - }) - er.pkgid = pkg._id - er.stage = stage - er.script = cmd - er.pkgname = pkg.name - } - process.removeListener('SIGTERM', procKill) - process.removeListener('SIGTERM', procInterupt) - process.removeListener('SIGINT', procKill) - process.removeListener('SIGINT', procInterupt) - return cb(er) - } - function procKill () { - proc.kill() - } - function procInterupt () { - proc.kill('SIGINT') - proc.on('exit', function () { - process.exit() - }) - process.once('SIGINT', procKill) - } -} -function runHookLifecycle (pkg, stage, env, wd, opts, cb) { - hookStat(opts.dir, stage, function (er) { - if (er) return cb() - var cmd = path.join(opts.dir, '.hooks', stage) - var note = '\n> ' + pkg._id + ' ' + stage + ' ' + wd + - '\n> ' + cmd - runCmd(note, cmd, pkg, env, stage, wd, opts, cb) - }) +module.exports = cacheKey +function cacheKey (type, identifier) { + return ['pacote', type, identifier].join(':') } -function makeEnv (data, opts, prefix, env) { - prefix = prefix || 'npm_package_' - if (!env) { - env = {} - for (var i in process.env) { - if (!i.match(/^npm_/)) { - env[i] = process.env[i] - } - } - // express and others respect the NODE_ENV value. - if (opts.production) env.NODE_ENV = 'production' - } else if (!data.hasOwnProperty('_lifecycleEnv')) { - Object.defineProperty(data, '_lifecycleEnv', - { - value: env, - enumerable: false - } - ) - } +/***/ }), +/* 280 */ +/***/ (function(module, exports) { - if (opts.nodeOptions) env.NODE_OPTIONS = opts.nodeOptions +exports = module.exports = SemVer - for (i in data) { - if (i.charAt(0) !== '_') { - var envKey = (prefix + i).replace(/[^a-zA-Z0-9_]/g, '_') - if (i === 'readme') { - continue - } - if (data[i] && typeof data[i] === 'object') { - try { - // quick and dirty detection for cyclical structures - JSON.stringify(data[i]) - makeEnv(data[i], opts, envKey + '_', env) - } catch (ex) { - // usually these are package objects. - // just get the path and basic details. - var d = data[i] - makeEnv( - { name: d.name, version: d.version, path: d.path }, - opts, - envKey + '_', - env - ) - } - } else { - env[envKey] = String(data[i]) - env[envKey] = env[envKey].indexOf('\n') !== -1 - ? JSON.stringify(env[envKey]) - : env[envKey] - } - } +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) } +} else { + debug = function () {} +} - if (prefix !== 'npm_package_') return env - - prefix = 'npm_config_' - var pkgConfig = {} - var pkgVerConfig = {} - var namePref = data.name + ':' - var verPref = data.name + '@' + data.version + ':' +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0' - Object.keys(opts.config).forEach(function (i) { - // in some rare cases (e.g. working with nerf darts), there are segmented - // "private" (underscore-prefixed) config names -- don't export - if ((i.charAt(0) === '_' && i.indexOf('_' + namePref) !== 0) || i.match(/:_/)) { - return - } - var value = opts.config[i] - if (value instanceof Stream || Array.isArray(value) || typeof value === 'function') return - if (i.match(/umask/)) value = umask.toString(value) +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 - if (!value) value = '' - else if (typeof value === 'number') value = '' + value - else if (typeof value !== 'string') value = JSON.stringify(value) +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 - if (typeof value !== 'string') { - return - } +// The actual regexps go on exports.re +var re = exports.re = [] +var src = exports.src = [] +var R = 0 - value = value.indexOf('\n') !== -1 - ? JSON.stringify(value) - : value - i = i.replace(/^_+/, '') - var k - if (i.indexOf(namePref) === 0) { - k = i.substr(namePref.length).replace(/[^a-zA-Z0-9_]/g, '_') - pkgConfig[k] = value - } else if (i.indexOf(verPref) === 0) { - k = i.substr(verPref.length).replace(/[^a-zA-Z0-9_]/g, '_') - pkgVerConfig[k] = value - } - var envKey = (prefix + i).replace(/[^a-zA-Z0-9_]/g, '_') - env[envKey] = value - }) +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. - prefix = 'npm_package_config_' - ;[pkgConfig, pkgVerConfig].forEach(function (conf) { - for (var i in conf) { - var envKey = (prefix + i) - env[envKey] = conf[i] - } - }) +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. - return env -} +var NUMERICIDENTIFIER = R++ +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' +var NUMERICIDENTIFIERLOOSE = R++ +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. -/***/ }), -/* 261 */, -/* 262 */ -/***/ (function(module) { +var NONNUMERICIDENTIFIER = R++ +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' -var toString = {}.toString; +// ## Main Version +// Three dot-separated numeric identifiers. -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; +var MAINVERSION = R++ +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')' +var MAINVERSIONLOOSE = R++ +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')' -/***/ }), -/* 263 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. -"use strict"; +var PRERELEASEIDENTIFIER = R++ +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')' +var PRERELEASEIDENTIFIERLOOSE = R++ +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')' -module.exports = __webpack_require__(282) +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. +var PRERELEASE = R++ +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' -/***/ }), -/* 264 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -exports.TrackerGroup = __webpack_require__(174) -exports.Tracker = __webpack_require__(623) -exports.TrackerStream = __webpack_require__(235) - +var PRERELEASELOOSE = R++ +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' -/***/ }), -/* 265 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. -"use strict"; +var BUILDIDENTIFIER = R++ +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.authenticate = exports.authWithToken = exports.authWithCredentials = void 0; -const core = __importStar(__webpack_require__(470)); -const cli = __importStar(__webpack_require__(986)); -/** - * Authenticate at Expo using `expo login`. - * This step is required for publishing and building new apps. - * It uses the `EXPO_CLI_PASSWORD` environment variable for improved security. - */ -function authWithCredentials(username, password) { - return __awaiter(this, void 0, void 0, function* () { - if (!username || !password) { - return core.info('Skipping authentication: `expo-username` and/or `expo-password` not set...'); - } - // github actions toolkit will handle commands with `.cmd` on windows, we need that - const bin = process.platform === 'win32' ? 'expo.cmd' : 'expo'; - yield cli.exec(bin, ['login', `--username=${username}`], { - env: Object.assign(Object.assign({}, process.env), { EXPO_CLI_PASSWORD: password }), - }); - }); -} -exports.authWithCredentials = authWithCredentials; -/** - * Authenticate with Expo using `EXPO_TOKEN`. - * This exports the EXPO_TOKEN environment variable for all future steps within the workflow. - * It also double-checks if this token is valid and for what user, by running `expo whoami`. - * - * @see https://github.com/actions/toolkit/blob/905b2c7b0681b11056141a60055f1ba77358b7e9/packages/core/src/core.ts#L39 - */ -function authWithToken(token) { - return __awaiter(this, void 0, void 0, function* () { - if (!token) { - return core.info('Skipping authentication: `expo-token` not set...'); - } - // github actions toolkit will handle commands with `.cmd` on windows, we need that - const bin = process.platform === 'win32' ? 'expo.cmd' : 'expo'; - yield cli.exec(bin, ['whoami'], { - env: Object.assign(Object.assign({}, process.env), { EXPO_TOKEN: token }), - }); - core.exportVariable('EXPO_TOKEN', token); - }); -} -exports.authWithToken = authWithToken; -/** - * Authenticate with Expo using either the token or username/password method. - * If both of them are set, token has priority. - */ -function authenticate(options) { - if (options.token) { - return authWithToken(options.token); - } - if (options.username || options.password) { - return authWithCredentials(options.username, options.password); - } - core.info('Skipping authentication: `expo-token`, `expo-username`, and/or `expo-password` not set...'); -} -exports.authenticate = authenticate; +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. +var BUILD = R++ +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' -/***/ }), -/* 266 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. -"use strict"; +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. -var os = __webpack_require__(87); +var FULL = R++ +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?' -function homedir() { - var env = process.env; - var home = env.HOME; - var user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME; +src[FULL] = '^' + FULLPLAIN + '$' - if (process.platform === 'win32') { - return env.USERPROFILE || env.HOMEDRIVE + env.HOMEPATH || home || null; - } +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?' - if (process.platform === 'darwin') { - return home || (user ? '/Users/' + user : null); - } +var LOOSE = R++ +src[LOOSE] = '^' + LOOSEPLAIN + '$' - if (process.platform === 'linux') { - return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null)); - } +var GTLT = R++ +src[GTLT] = '((?:<|>)?=?)' - return home || null; -} +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++ +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +var XRANGEIDENTIFIER = R++ +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' -module.exports = typeof os.homedir === 'function' ? os.homedir : homedir; +var XRANGEPLAIN = R++ +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?' +var XRANGEPLAINLOOSE = R++ +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?' -/***/ }), -/* 267 */, -/* 268 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +var XRANGE = R++ +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' +var XRANGELOOSE = R++ +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' -"use strict"; +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +var COERCE = R++ +src[COERCE] = '(?:^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++ +src[LONETILDE] = '(?:~>?)' -const assert = __webpack_require__(357) -const Buffer = __webpack_require__(293).Buffer -const realZlib = __webpack_require__(761) +var TILDETRIM = R++ +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') +var tildeTrimReplace = '$1~' -const constants = exports.constants = __webpack_require__(60) -const Minipass = __webpack_require__(720) +var TILDE = R++ +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' +var TILDELOOSE = R++ +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' -const OriginalBufferConcat = Buffer.concat +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++ +src[LONECARET] = '(?:\\^)' -class ZlibError extends Error { - constructor (err) { - super('zlib: ' + err.message) - this.code = err.code - this.errno = err.errno - /* istanbul ignore if */ - if (!this.code) - this.code = 'ZLIB_ERROR' +var CARETTRIM = R++ +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') +var caretTrimReplace = '$1^' - this.message = 'zlib: ' + err.message - Error.captureStackTrace(this, this.constructor) - } +var CARET = R++ +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' +var CARETLOOSE = R++ +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' - get name () { - return 'ZlibError' - } -} +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++ +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' +var COMPARATOR = R++ +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' -// the Zlib class they all inherit from -// This thing manages the queue of requests, and returns -// true or false if there is anything in the queue when -// you call the .write() method. -const _opts = Symbol('opts') -const _flushFlag = Symbol('flushFlag') -const _finishFlushFlag = Symbol('finishFlushFlag') -const _fullFlushFlag = Symbol('fullFlushFlag') -const _handle = Symbol('handle') -const _onError = Symbol('onError') -const _sawError = Symbol('sawError') -const _level = Symbol('level') -const _strategy = Symbol('strategy') -const _ended = Symbol('ended') -const _defaultFullFlush = Symbol('_defaultFullFlush') +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++ +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' -class ZlibBase extends Minipass { - constructor (opts, mode) { - if (!opts || typeof opts !== 'object') - throw new TypeError('invalid options for ZlibBase constructor') +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') +var comparatorTrimReplace = '$1$2$3' - super(opts) - this[_ended] = false - this[_opts] = opts +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++ +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$' - this[_flushFlag] = opts.flush - this[_finishFlushFlag] = opts.finishFlush - // this will throw if any options are invalid for the class selected - try { - this[_handle] = new realZlib[mode](opts) - } catch (er) { - // make sure that all errors get decorated properly - throw new ZlibError(er) - } +var HYPHENRANGELOOSE = R++ +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$' - this[_onError] = (err) => { - this[_sawError] = true - // there is no way to cleanly recover. - // continuing only obscures problems. - this.close() - this.emit('error', err) - } +// Star ranges basically just allow anything at all. +var STAR = R++ +src[STAR] = '(<|>)?=?\\s*\\*' - this[_handle].on('error', er => this[_onError](new ZlibError(er))) - this.once('end', () => this.close) +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]) + if (!re[i]) { + re[i] = new RegExp(src[i]) } +} - close () { - if (this[_handle]) { - this[_handle].close() - this[_handle] = null - this.emit('close') +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false } } - reset () { - if (!this[_sawError]) { - assert(this[_handle], 'zlib binding closed') - return this[_handle].reset() - } + if (version instanceof SemVer) { + return version } - flush (flushFlag) { - if (this.ended) - return + if (typeof version !== 'string') { + return null + } - if (typeof flushFlag !== 'number') - flushFlag = this[_fullFlushFlag] - this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag })) + if (version.length > MAX_LENGTH) { + return null } - end (chunk, encoding, cb) { - if (chunk) - this.write(chunk, encoding) - this.flush(this[_finishFlushFlag]) - this[_ended] = true - return super.end(null, null, cb) + var r = options.loose ? re[LOOSE] : re[FULL] + if (!r.test(version)) { + return null } - get ended () { - return this[_ended] + try { + return new SemVer(version, options) + } catch (er) { + return null } +} - write (chunk, encoding, cb) { - // process the chunk using the sync process - // then super.write() all the outputted chunks - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null +} - if (typeof chunk === 'string') - chunk = Buffer.from(chunk, encoding) +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} - if (this[_sawError]) - return - assert(this[_handle], 'zlib binding closed') +exports.SemVer = SemVer - // _processChunk tries to .close() the native handle after it's done, so we - // intercept that by temporarily making it a no-op. - const nativeHandle = this[_handle]._handle - const originalNativeClose = nativeHandle.close - nativeHandle.close = () => {} - const originalClose = this[_handle].close - this[_handle].close = () => {} - // It also calls `Buffer.concat()` at the end, which may be convenient - // for some, but which we are not interested in as it slows us down. - Buffer.concat = (args) => args - let result - try { - const flushFlag = typeof chunk[_flushFlag] === 'number' - ? chunk[_flushFlag] : this[_flushFlag] - result = this[_handle]._processChunk(chunk, flushFlag) - // if we don't throw, reset it back how it was - Buffer.concat = OriginalBufferConcat - } catch (err) { - // or if we do, put Buffer.concat() back before we emit error - // Error events call into user code, which may call Buffer.concat() - Buffer.concat = OriginalBufferConcat - this[_onError](new ZlibError(err)) - } finally { - if (this[_handle]) { - // Core zlib resets `_handle` to null after attempting to close the - // native handle. Our no-op handler prevented actual closure, but we - // need to restore the `._handle` property. - this[_handle]._handle = nativeHandle - nativeHandle.close = originalNativeClose - this[_handle].close = originalClose - // `_processChunk()` adds an 'error' listener. If we don't remove it - // after each call, these handlers start piling up. - this[_handle].removeAllListeners('error') - } +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false } - - let writeReturn - if (result) { - if (Array.isArray(result) && result.length > 0) { - // The first buffer is always `handle._outBuffer`, which would be - // re-used for later invocations; so, we always have to copy that one. - writeReturn = super.write(Buffer.from(result[0])) - for (let i = 1; i < result.length; i++) { - writeReturn = super.write(result[i]) - } - } else { - writeReturn = super.write(Buffer.from(result)) - } + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) + } - if (cb) - cb() - return writeReturn + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') } -} -class Zlib extends ZlibBase { - constructor (opts, mode) { - opts = opts || {} + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } - opts.flush = opts.flush || constants.Z_NO_FLUSH - opts.finishFlush = opts.finishFlush || constants.Z_FINISH - super(opts, mode) + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose - this[_fullFlushFlag] = constants.Z_FULL_FLUSH - this[_level] = opts.level - this[_strategy] = opts.strategy - } + var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) - params (level, strategy) { - if (this[_sawError]) - return + if (!m) { + throw new TypeError('Invalid Version: ' + version) + } - if (!this[_handle]) - throw new Error('cannot switch params when binding is closed') + this.raw = version - // no way to test this without also not supporting params at all - /* istanbul ignore if */ - if (!this[_handle].params) - throw new Error('not supported in this implementation') + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] - if (this[_level] !== level || this[_strategy] !== strategy) { - this.flush(constants.Z_SYNC_FLUSH) - assert(this[_handle], 'zlib binding closed') - // .params() calls .flush(), but the latter is always async in the - // core zlib. We override .flush() temporarily to intercept that and - // flush synchronously. - const origFlush = this[_handle].flush - this[_handle].flush = (flushFlag, cb) => { - this.flush(flushFlag) - cb() - } - try { - this[_handle].params(level, strategy) - } finally { - this[_handle].flush = origFlush - } - /* istanbul ignore else */ - if (this[_handle]) { - this[_level] = level - this[_strategy] = strategy - } - } + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') } -} -// minimal 2-byte header -class Deflate extends Zlib { - constructor (opts) { - super(opts, 'Deflate') + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') } -} -class Inflate extends Zlib { - constructor (opts) { - super(opts, 'Inflate') + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') } -} -// gzip - bigger header, same deflate compression -class Gzip extends Zlib { - constructor (opts) { - super(opts, 'Gzip') + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) } -} -class Gunzip extends Zlib { - constructor (opts) { - super(opts, 'Gunzip') - } + this.build = m[5] ? m[5].split('.') : [] + this.format() } -// raw - no header -class DeflateRaw extends Zlib { - constructor (opts) { - super(opts, 'DeflateRaw') +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') } + return this.version } -class InflateRaw extends Zlib { - constructor (opts) { - super(opts, 'InflateRaw') - } +SemVer.prototype.toString = function () { + return this.version } -// auto-detect header. -class Unzip extends Zlib { - constructor (opts) { - super(opts, 'Unzip') +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) } + + return this.compareMain(other) || this.comparePre(other) } -class Brotli extends ZlibBase { - constructor (opts, mode) { - opts = opts || {} +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } - opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS - opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) +} - super(opts, mode) +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } - this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 } + + var i = 0 + do { + var a = this.prerelease[i] + var b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) } -class BrotliCompress extends Brotli { - constructor (opts) { - super(opts, 'BrotliCompress') +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + var i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error('invalid increment argument: ' + release) } + this.format() + this.raw = this.version + return this } -class BrotliDecompress extends Brotli { - constructor (opts) { - super(opts, 'BrotliDecompress') +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined + } + + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null } } -exports.Deflate = Deflate -exports.Inflate = Inflate -exports.Gzip = Gzip -exports.Gunzip = Gunzip -exports.DeflateRaw = DeflateRaw -exports.InflateRaw = InflateRaw -exports.Unzip = Unzip -/* istanbul ignore else */ -if (typeof realZlib.BrotliCompress === 'function') { - exports.BrotliCompress = BrotliCompress - exports.BrotliDecompress = BrotliDecompress -} else { - exports.BrotliCompress = exports.BrotliDecompress = class { - constructor () { - throw new Error('Brotli is not supported in this version of Node.js') +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } } + return defaultResult // may be undefined } } +exports.compareIdentifiers = compareIdentifiers -/***/ }), -/* 269 */ -/***/ (function(module, exports, __webpack_require__) { +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) -"use strict"; + if (anum && bnum) { + a = +a + b = +b + } + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} -/** - * index.js - * - * a request API compatible with window.fetch - */ +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) +} -const url = __webpack_require__(835) -const http = __webpack_require__(605) -const https = __webpack_require__(211) -const zlib = __webpack_require__(761) -const PassThrough = __webpack_require__(794).PassThrough +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major +} -const Body = __webpack_require__(542) -const writeToStream = Body.writeToStream -const Response = __webpack_require__(901) -const Headers = __webpack_require__(68) -const Request = __webpack_require__(988) -const getNodeRequestOptions = Request.getNodeRequestOptions -const FetchError = __webpack_require__(888) -const isURL = /^https?:/ +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} -/** - * Fetch function - * - * @param Mixed url Absolute url or Request instance - * @param Object opts Fetch options - * @return Promise - */ -exports = module.exports = fetch -function fetch (uri, opts) { - // allow custom promise - if (!fetch.Promise) { - throw new Error('native promise missing, set fetch.Promise to your favorite alternative') - } +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch +} - Body.Promise = fetch.Promise +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) +} - // wrap http.request into fetch - return new fetch.Promise((resolve, reject) => { - // build request object - const request = new Request(uri, opts) - const options = getNodeRequestOptions(request) +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) +} - const send = (options.protocol === 'https:' ? https : http).request +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) +} - // http.request only support string as host header, this hack make custom host header possible - if (options.headers.host) { - options.headers.host = options.headers.host[0] - } +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compare(a, b, loose) + }) +} - // send request - const req = send(options) - let reqTimeout +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.rcompare(a, b, loose) + }) +} - if (request.timeout) { - req.once('socket', socket => { - reqTimeout = setTimeout(() => { - req.abort() - reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')) - }, request.timeout) - }) - } +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 0 +} - req.on('error', err => { - clearTimeout(reqTimeout) - reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)) - }) +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 +} - req.on('response', res => { - clearTimeout(reqTimeout) +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} - // handle redirect - if (fetch.isRedirect(res.statusCode) && request.redirect !== 'manual') { - if (request.redirect === 'error') { - reject(new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect')) - return - } +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 +} - if (request.counter >= request.follow) { - reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')) - return - } +exports.gte = gte +function gte (a, b, loose) { + return compare(a, b, loose) >= 0 +} - if (!res.headers.location) { - reject(new FetchError(`redirect location header missing at: ${request.url}`, 'invalid-redirect')) - return - } +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 +} - // Comment and logic below is used under the following license: - // Copyright (c) 2010-2012 Mikeal Rogers - // Licensed under the Apache License, Version 2.0 (the "License"); - // you may not use this file except in compliance with the License. - // You may obtain a copy of the License at - // http://www.apache.org/licenses/LICENSE-2.0 - // Unless required by applicable law or agreed to in writing, - // software distributed under the License is distributed on an "AS - // IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - // express or implied. See the License for the specific language - // governing permissions and limitations under the License. +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b - // Remove authorization if changing hostnames (but not if just - // changing ports or protocols). This matches the behavior of request: - // https://github.com/request/request/blob/b12a6245/lib/redirect.js#L134-L138 - const resolvedUrl = url.resolve(request.url, res.headers.location) - let redirectURL = '' - if (!isURL.test(res.headers.location)) { - redirectURL = url.parse(resolvedUrl) - } else { - redirectURL = url.parse(res.headers.location) - } - if (url.parse(request.url).hostname !== redirectURL.hostname) { - request.headers.delete('authorization') - } + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b - // per fetch spec, for POST request with 301/302 response, or any request with 303 response, use GET when following redirect - if (res.statusCode === 303 || - ((res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST')) { - request.method = 'GET' - request.body = null - request.headers.delete('content-length') - } + case '': + case '=': + case '==': + return eq(a, b, loose) - request.counter++ + case '!=': + return neq(a, b, loose) - resolve(fetch(resolvedUrl, request)) - return - } + case '>': + return gt(a, b, loose) - // normalize location header for manual redirect mode - const headers = new Headers() - for (const name of Object.keys(res.headers)) { - if (Array.isArray(res.headers[name])) { - for (const val of res.headers[name]) { - headers.append(name, val) - } - } else { - headers.append(name, res.headers[name]) - } - } - if (request.redirect === 'manual' && headers.has('location')) { - headers.set('location', url.resolve(request.url, headers.get('location'))) - } + case '>=': + return gte(a, b, loose) - // prepare response - let body = res.pipe(new PassThrough()) - const responseOptions = { - url: request.url, - status: res.statusCode, - statusText: res.statusMessage, - headers: headers, - size: request.size, - timeout: request.timeout - } + case '<': + return lt(a, b, loose) - // HTTP-network fetch step 16.1.2 - const codings = headers.get('Content-Encoding') + case '<=': + return lte(a, b, loose) - // HTTP-network fetch step 16.1.3: handle content codings + default: + throw new TypeError('Invalid operator: ' + op) + } +} - // in following scenarios we ignore compression support - // 1. compression support is disabled - // 2. HEAD request - // 3. no Content-Encoding header - // 4. no content response (204) - // 5. content not modified response (304) - if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { - resolve(new Response(body, responseOptions)) - return - } +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } - // Be less strict when decoding compressed responses, since sometimes - // servers send slightly invalid responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - const zlibOptions = { - flush: zlib.Z_SYNC_FLUSH, - finishFlush: zlib.Z_SYNC_FLUSH - } + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } - // for gzip - if (codings === 'gzip' || codings === 'x-gzip') { - body = body.pipe(zlib.createGunzip(zlibOptions)) - resolve(new Response(body, responseOptions)) - return - } + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } - // for deflate - if (codings === 'deflate' || codings === 'x-deflate') { - // handle the infamous raw deflate response from old servers - // a hack for old IIS and Apache servers - const raw = res.pipe(new PassThrough()) - raw.once('data', chunk => { - // see http://stackoverflow.com/questions/37519828 - if ((chunk[0] & 0x0F) === 0x08) { - body = body.pipe(zlib.createInflate(zlibOptions)) - } else { - body = body.pipe(zlib.createInflateRaw(zlibOptions)) - } - resolve(new Response(body, responseOptions)) - }) - return - } + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) - // otherwise, use response as-is - resolve(new Response(body, responseOptions)) - }) + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } - writeToStream(req, request) - }) -}; + debug('comp', this) +} -/** - * Redirect code matching - * - * @param Number code Status code - * @return Boolean - */ -fetch.isRedirect = code => code === 301 || code === 302 || code === 303 || code === 307 || code === 308 +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var m = comp.match(r) -// expose Promise -fetch.Promise = global.Promise -exports.Headers = Headers -exports.Request = Request -exports.Response = Response -exports.FetchError = FetchError + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } + this.operator = m[1] + if (this.operator === '=') { + this.operator = '' + } -/***/ }), -/* 270 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } +} -"use strict"; +Comparator.prototype.toString = function () { + return this.value +} +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) -module.exports = __webpack_require__(789) + if (this.semver === ANY) { + return true + } + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } -/***/ }), -/* 271 */, -/* 272 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + return cmp(version, this.operator, this.semver, this.options) +} -"use strict"; +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } -module.exports = function(Promise, Context, - enableAsyncHooks, disableAsyncHooks) { -var async = Promise._async; -var Warning = __webpack_require__(607).Warning; -var util = __webpack_require__(248); -var es5 = __webpack_require__(883); -var canAttachTrace = util.canAttachTrace; -var unhandledRejectionHandled; -var possiblyUnhandledRejection; -var bluebirdFramePattern = - /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; -var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; -var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; -var stackFramePattern = null; -var formatStack = null; -var indentStackFrames = false; -var printWarning; -var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && - ( false || - util.env("BLUEBIRD_DEBUG") || - util.env("NODE_ENV") === "development")); + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } -var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && - (debugging || util.env("BLUEBIRD_WARNINGS"))); + var rangeTmp -var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && - (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); + if (this.operator === '') { + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) + } -var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && - (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) -var deferUnhandledRejectionCheck; -(function() { - var promises = []; + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +} - function unhandledRejectionCheck() { - for (var i = 0; i < promises.length; ++i) { - promises[i]._notifyUnhandledRejection(); - } - unhandledRejectionClear(); +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false } + } - function unhandledRejectionClear() { - promises.length = 0; + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) } + } - deferUnhandledRejectionCheck = function(promise) { - promises.push(promise); - setTimeout(unhandledRejectionCheck, 1); - }; - - es5.defineProperty(Promise, "_unhandledRejectionCheck", { - value: unhandledRejectionCheck - }); - es5.defineProperty(Promise, "_unhandledRejectionClear", { - value: unhandledRejectionClear - }); -})(); + if (range instanceof Comparator) { + return new Range(range.value, options) + } -Promise.prototype.suppressUnhandledRejections = function() { - var target = this._target(); - target._bitField = ((target._bitField & (~1048576)) | - 524288); -}; + if (!(this instanceof Range)) { + return new Range(range, options) + } -Promise.prototype._ensurePossibleRejectionHandled = function () { - if ((this._bitField & 524288) !== 0) return; - this._setRejectionIsUnhandled(); - deferUnhandledRejectionCheck(this); -}; + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease -Promise.prototype._notifyUnhandledRejectionIsHandled = function () { - fireRejectionEvent("rejectionHandled", - unhandledRejectionHandled, undefined, this); -}; + // First, split based on boolean or || + this.raw = range + this.set = range.split(/\s*\|\|\s*/).map(function (range) { + return this.parseRange(range.trim()) + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length + }) -Promise.prototype._setReturnedNonUndefined = function() { - this._bitField = this._bitField | 268435456; -}; + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range) + } -Promise.prototype._returnedNonUndefined = function() { - return (this._bitField & 268435456) !== 0; -}; + this.format() +} -Promise.prototype._notifyUnhandledRejection = function () { - if (this._isRejectionUnhandled()) { - var reason = this._settledValue(); - this._setUnhandledRejectionIsNotified(); - fireRejectionEvent("unhandledRejection", - possiblyUnhandledRejection, reason, this); - } -}; +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} -Promise.prototype._setUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField | 262144; -}; +Range.prototype.toString = function () { + return this.range +} -Promise.prototype._unsetUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField & (~262144); -}; +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + range = range.trim() + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[COMPARATORTRIM]) -Promise.prototype._isUnhandledRejectionNotified = function () { - return (this._bitField & 262144) > 0; -}; + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace) -Promise.prototype._setRejectionIsUnhandled = function () { - this._bitField = this._bitField | 1048576; -}; + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace) -Promise.prototype._unsetRejectionIsUnhandled = function () { - this._bitField = this._bitField & (~1048576); - if (this._isUnhandledRejectionNotified()) { - this._unsetUnhandledRejectionIsNotified(); - this._notifyUnhandledRejectionIsHandled(); - } -}; + // normalize spaces + range = range.split(/\s+/).join(' ') -Promise.prototype._isRejectionUnhandled = function () { - return (this._bitField & 1048576) > 0; -}; + // At this point, the range is completely trimmed and + // ready to be split into comparators. -Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { - return warn(message, shouldUseOwnTrace, promise || this); -}; + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe) + }) + } + set = set.map(function (comp) { + return new Comparator(comp, this.options) + }, this) -Promise.onPossiblyUnhandledRejection = function (fn) { - var context = Promise._getContext(); - possiblyUnhandledRejection = util.contextBind(context, fn); -}; + return set +} -Promise.onUnhandledRejectionHandled = function (fn) { - var context = Promise._getContext(); - unhandledRejectionHandled = util.contextBind(context, fn); -}; +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } -var disableLongStackTraces = function() {}; -Promise.longStackTraces = function () { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (!config.longStackTraces && longStackTracesIsSupported()) { - var Promise_captureStackTrace = Promise.prototype._captureStackTrace; - var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; - var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace; - config.longStackTraces = true; - disableLongStackTraces = function() { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - Promise.prototype._captureStackTrace = Promise_captureStackTrace; - Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; - Promise.prototype._dereferenceTrace = Promise_dereferenceTrace; - Context.deactivateLongStackTraces(); - config.longStackTraces = false; - }; - Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; - Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; - Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace; - Context.activateLongStackTraces(); - } -}; + return this.set.some(function (thisComparators) { + return thisComparators.every(function (thisComparator) { + return range.set.some(function (rangeComparators) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + }) + }) +} -Promise.hasLongStackTraces = function () { - return config.longStackTraces && longStackTracesIsSupported(); -}; +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) +} +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator (comp, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} -var legacyHandlers = { - unhandledrejection: { - before: function() { - var ret = util.global.onunhandledrejection; - util.global.onunhandledrejection = null; - return ret; - }, - after: function(fn) { - util.global.onunhandledrejection = fn; - } - }, - rejectionhandled: { - before: function() { - var ret = util.global.onrejectionhandled; - util.global.onrejectionhandled = null; - return ret; - }, - after: function(fn) { - util.global.onrejectionhandled = fn; - } - } -}; +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' +} -var fireDomEvent = (function() { - var dispatch = function(legacy, e) { - if (legacy) { - var fn; - try { - fn = legacy.before(); - return !util.global.dispatchEvent(e); - } finally { - legacy.after(fn); - } - } else { - return !util.global.dispatchEvent(e); - } - }; - try { - if (typeof CustomEvent === "function") { - var event = new CustomEvent("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - name = name.toLowerCase(); - var eventData = { - detail: event, - cancelable: true - }; - var domEvent = new CustomEvent(name, eventData); - es5.defineProperty( - domEvent, "promise", {value: event.promise}); - es5.defineProperty( - domEvent, "reason", {value: event.reason}); +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') +} - return dispatch(legacyHandlers[name], domEvent); - }; - } else if (typeof Event === "function") { - var event = new Event("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - name = name.toLowerCase(); - var domEvent = new Event(name, { - cancelable: true - }); - domEvent.detail = event; - es5.defineProperty(domEvent, "promise", {value: event.promise}); - es5.defineProperty(domEvent, "reason", {value: event.reason}); - return dispatch(legacyHandlers[name], domEvent); - }; - } else { - var event = document.createEvent("CustomEvent"); - event.initCustomEvent("testingtheevent", false, true, {}); - util.global.dispatchEvent(event); - return function(name, event) { - name = name.toLowerCase(); - var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent(name, false, true, - event); - return dispatch(legacyHandlers[name], domEvent); - }; - } - } catch (e) {} - return function() { - return false; - }; -})(); +function replaceTilde (comp, options) { + var r = options.loose ? re[TILDELOOSE] : re[TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret -var fireGlobalEvent = (function() { - if (util.isNode) { - return function() { - return process.emit.apply(process, arguments); - }; + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else if (pr) { + debug('replaceTilde pr', pr) + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' } else { - if (!util.global) { - return function() { - return false; - }; - } - return function(name) { - var methodName = "on" + name.toLowerCase(); - var method = util.global[methodName]; - if (!method) return false; - method.apply(util.global, [].slice.call(arguments, 1)); - return true; - }; + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' } -})(); -function generatePromiseLifecycleEventObject(name, promise) { - return {promise: promise}; + debug('tilde return', ret) + return ret + }) } -var eventToObjectGenerator = { - promiseCreated: generatePromiseLifecycleEventObject, - promiseFulfilled: generatePromiseLifecycleEventObject, - promiseRejected: generatePromiseLifecycleEventObject, - promiseResolved: generatePromiseLifecycleEventObject, - promiseCancelled: generatePromiseLifecycleEventObject, - promiseChained: function(name, promise, child) { - return {promise: promise, child: child}; - }, - warning: function(name, warning) { - return {warning: warning}; - }, - unhandledRejection: function (name, reason, promise) { - return {reason: reason, promise: promise}; - }, - rejectionHandled: generatePromiseLifecycleEventObject -}; - -var activeFireEvent = function (name) { - var globalEventFired = false; - try { - globalEventFired = fireGlobalEvent.apply(null, arguments); - } catch (e) { - async.throwLater(e); - globalEventFired = true; - } - - var domEventFired = false; - try { - domEventFired = fireDomEvent(name, - eventToObjectGenerator[name].apply(null, arguments)); - } catch (e) { - async.throwLater(e); - domEventFired = true; - } - - return domEventFired || globalEventFired; -}; - -Promise.config = function(opts) { - opts = Object(opts); - if ("longStackTraces" in opts) { - if (opts.longStackTraces) { - Promise.longStackTraces(); - } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { - disableLongStackTraces(); - } - } - if ("warnings" in opts) { - var warningsOption = opts.warnings; - config.warnings = !!warningsOption; - wForgottenReturn = config.warnings; - - if (util.isObject(warningsOption)) { - if ("wForgottenReturn" in warningsOption) { - wForgottenReturn = !!warningsOption.wForgottenReturn; - } - } - } - if ("cancellation" in opts && opts.cancellation && !config.cancellation) { - if (async.haveItemsQueued()) { - throw new Error( - "cannot enable cancellation after promises are in use"); - } - Promise.prototype._clearCancellationData = - cancellationClearCancellationData; - Promise.prototype._propagateFrom = cancellationPropagateFrom; - Promise.prototype._onCancel = cancellationOnCancel; - Promise.prototype._setOnCancel = cancellationSetOnCancel; - Promise.prototype._attachCancellationCallback = - cancellationAttachCancellationCallback; - Promise.prototype._execute = cancellationExecute; - propagateFromFunction = cancellationPropagateFrom; - config.cancellation = true; - } - if ("monitoring" in opts) { - if (opts.monitoring && !config.monitoring) { - config.monitoring = true; - Promise.prototype._fireEvent = activeFireEvent; - } else if (!opts.monitoring && config.monitoring) { - config.monitoring = false; - Promise.prototype._fireEvent = defaultFireEvent; - } - } - if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) { - var prev = config.asyncHooks; - var cur = !!opts.asyncHooks; - if (prev !== cur) { - config.asyncHooks = cur; - if (cur) { - enableAsyncHooks(); - } else { - disableAsyncHooks(); - } - } - } - return Promise; -}; - -function defaultFireEvent() { return false; } - -Promise.prototype._fireEvent = defaultFireEvent; -Promise.prototype._execute = function(executor, resolve, reject) { - try { - executor(resolve, reject); - } catch (e) { - return e; - } -}; -Promise.prototype._onCancel = function () {}; -Promise.prototype._setOnCancel = function (handler) { ; }; -Promise.prototype._attachCancellationCallback = function(onCancel) { - ; -}; -Promise.prototype._captureStackTrace = function () {}; -Promise.prototype._attachExtraTrace = function () {}; -Promise.prototype._dereferenceTrace = function () {}; -Promise.prototype._clearCancellationData = function() {}; -Promise.prototype._propagateFrom = function (parent, flags) { - ; - ; -}; - -function cancellationExecute(executor, resolve, reject) { - var promise = this; - try { - executor(resolve, reject, function(onCancel) { - if (typeof onCancel !== "function") { - throw new TypeError("onCancel must be a function, got: " + - util.toString(onCancel)); - } - promise._attachCancellationCallback(onCancel); - }); - } catch (e) { - return e; - } +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') } -function cancellationAttachCancellationCallback(onCancel) { - if (!this._isCancellable()) return this; +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? re[CARETLOOSE] : re[CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret - var previousOnCancel = this._onCancel(); - if (previousOnCancel !== undefined) { - if (util.isArray(previousOnCancel)) { - previousOnCancel.push(onCancel); + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + m + '.' + (+p + 1) } else { - this._setOnCancel([previousOnCancel, onCancel]); + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + (+M + 1) + '.0.0' + } } else { - this._setOnCancel(onCancel); + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0' + } } -} -function cancellationOnCancel() { - return this._onCancelField; + debug('caret return', ret) + return ret + }) } -function cancellationSetOnCancel(onCancel) { - this._onCancelField = onCancel; +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') } -function cancellationClearCancellationData() { - this._cancellationParent = undefined; - this._onCancelField = undefined; -} +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + var xM = isX(M) + var xm = xM || isX(m) + var xp = xm || isX(p) + var anyX = xp -function cancellationPropagateFrom(parent, flags) { - if ((flags & 1) !== 0) { - this._cancellationParent = parent; - var branchesRemainingToCancel = parent._branchesRemainingToCancel; - if (branchesRemainingToCancel === undefined) { - branchesRemainingToCancel = 0; - } - parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; - } - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); + if (gtlt === '=' && anyX) { + gtlt = '' } -} -function bindingPropagateFrom(parent, flags) { - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} -var propagateFromFunction = bindingPropagateFrom; + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 -function boundValueFunction() { - var ret = this._boundTo; - if (ret !== undefined) { - if (ret instanceof Promise) { - if (ret.isFulfilled()) { - return ret.value(); - } else { - return undefined; - } + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 } + } + + ret = gtlt + M + '.' + m + '.' + p + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } - return ret; -} -function longStackTracesCaptureStackTrace() { - this._trace = new CapturedTrace(this._peekContext()); -} + debug('xRange return', ret) -function longStackTracesAttachExtraTrace(error, ignoreSelf) { - if (canAttachTrace(error)) { - var trace = this._trace; - if (trace !== undefined) { - if (ignoreSelf) trace = trace._parent; - } - if (trace !== undefined) { - trace.attachExtraTrace(error); - } else if (!error.__stackCleaned__) { - var parsed = parseStackAndMessage(error); - util.notEnumerableProp(error, "stack", - parsed.message + "\n" + parsed.stack.join("\n")); - util.notEnumerableProp(error, "__stackCleaned__", true); - } - } + return ret + }) } -function longStackTracesDereferenceTrace() { - this._trace = undefined; +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars (comp, options) { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], '') } -function checkForgottenReturns(returnValue, promiseCreated, name, promise, - parent) { - if (returnValue === undefined && promiseCreated !== null && - wForgottenReturn) { - if (parent !== undefined && parent._returnedNonUndefined()) return; - if ((promise._bitField & 65535) === 0) return; - - if (name) name = name + " "; - var handlerLine = ""; - var creatorLine = ""; - if (promiseCreated._trace) { - var traceLines = promiseCreated._trace.stack.split("\n"); - var stack = cleanStack(traceLines); - for (var i = stack.length - 1; i >= 0; --i) { - var line = stack[i]; - if (!nodeFramePattern.test(line)) { - var lineMatches = line.match(parseLinePattern); - if (lineMatches) { - handlerLine = "at " + lineMatches[1] + - ":" + lineMatches[2] + ":" + lineMatches[3] + " "; - } - break; - } - } - - if (stack.length > 0) { - var firstUserLine = stack[0]; - for (var i = 0; i < traceLines.length; ++i) { +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = '>=' + fM + '.0.0' + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0' + } else { + from = '>=' + from + } - if (traceLines[i] === firstUserLine) { - if (i > 0) { - creatorLine = "\n" + traceLines[i - 1]; - } - break; - } - } + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0' + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0' + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr + } else { + to = '<=' + to + } - } - } - var msg = "a promise was created in a " + name + - "handler " + handlerLine + "but was not returned from it, " + - "see http://goo.gl/rRqMUw" + - creatorLine; - promise._warn(msg, true, promiseCreated); - } + return (from + ' ' + to).trim() } -function deprecated(name, replacement) { - var message = name + - " is deprecated and will be removed in a future version."; - if (replacement) message += " Use " + replacement + " instead."; - return warn(message); -} +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function (version) { + if (!version) { + return false + } -function warn(message, shouldUseOwnTrace, promise) { - if (!config.warnings) return; - var warning = new Warning(message); - var ctx; - if (shouldUseOwnTrace) { - promise._attachExtraTrace(warning); - } else if (config.longStackTraces && (ctx = Promise._peekContext())) { - ctx.attachExtraTrace(warning); - } else { - var parsed = parseStackAndMessage(warning); - warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); - } + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } - if (!activeFireEvent("warning", warning)) { - formatAndLogError(warning, "", true); + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true } + } + return false } -function reconstructStack(message, stacks) { - for (var i = 0; i < stacks.length - 1; ++i) { - stacks[i].push("From previous event:"); - stacks[i] = stacks[i].join("\n"); - } - if (i < stacks.length) { - stacks[i] = stacks[i].join("\n"); +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false } - return message + "\n" + stacks.join("\n"); -} + } -function removeDuplicateOrEmptyJumps(stacks) { - for (var i = 0; i < stacks.length; ++i) { - if (stacks[i].length === 0 || - ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { - stacks.splice(i, 1); - i--; + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true } + } } -} -function removeCommonRoots(stacks) { - var current = stacks[0]; - for (var i = 1; i < stacks.length; ++i) { - var prev = stacks[i]; - var currentLastIndex = current.length - 1; - var currentLastLine = current[currentLastIndex]; - var commonRootMeetPoint = -1; + // Version has a -pre, but it's not one of the ones we like. + return false + } - for (var j = prev.length - 1; j >= 0; --j) { - if (prev[j] === currentLastLine) { - commonRootMeetPoint = j; - break; - } - } + return true +} - for (var j = commonRootMeetPoint; j >= 0; --j) { - var line = prev[j]; - if (current[currentLastIndex] === line) { - current.pop(); - currentLastIndex--; - } else { - break; - } - } - current = prev; - } +exports.satisfies = satisfies +function satisfies (version, range, options) { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) } -function cleanStack(stack) { - var ret = []; - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - var isTraceLine = " (No stack trace)" === line || - stackFramePattern.test(line); - var isInternalFrame = isTraceLine && shouldIgnore(line); - if (isTraceLine && !isInternalFrame) { - if (indentStackFrames && line.charAt(0) !== " ") { - line = " " + line; - } - ret.push(line); - } +exports.maxSatisfying = maxSatisfying +function maxSatisfying (versions, range, options) { + var max = null + var maxSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } } - return ret; + }) + return max } -function stackFramesAsArray(error) { - var stack = error.stack.replace(/\s+$/g, "").split("\n"); - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - if (" (No stack trace)" === line || stackFramePattern.test(line)) { - break; - } - } - if (i > 0 && error.name != "SyntaxError") { - stack = stack.slice(i); +exports.minSatisfying = minSatisfying +function minSatisfying (versions, range, options) { + var min = null + var minSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } } - return stack; -} - -function parseStackAndMessage(error) { - var stack = error.stack; - var message = error.toString(); - stack = typeof stack === "string" && stack.length > 0 - ? stackFramesAsArray(error) : [" (No stack trace)"]; - return { - message: message, - stack: error.name == "SyntaxError" ? stack : cleanStack(stack) - }; + }) + return min } -function formatAndLogError(error, title, isSoft) { - if (typeof console !== "undefined") { - var message; - if (util.isObject(error)) { - var stack = error.stack; - message = title + formatStack(stack, error); - } else { - message = title + String(error); - } - if (typeof printWarning === "function") { - printWarning(message, isSoft); - } else if (typeof console.log === "function" || - typeof console.log === "object") { - console.log(message); - } - } -} +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) -function fireRejectionEvent(name, localHandler, reason, promise) { - var localEventFired = false; - try { - if (typeof localHandler === "function") { - localEventFired = true; - if (name === "rejectionHandled") { - localHandler(promise); - } else { - localHandler(reason, promise); - } - } - } catch (e) { - async.throwLater(e); - } + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } - if (name === "unhandledRejection") { - if (!activeFireEvent(name, reason, promise) && !localEventFired) { - formatAndLogError(reason, "Unhandled rejection "); - } - } else { - activeFireEvent(name, promise); - } -} + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } -function formatNonError(obj) { - var str; - if (typeof obj === "function") { - str = "[function " + - (obj.name || "anonymous") + - "]"; - } else { - str = obj && typeof obj.toString === "function" - ? obj.toString() : util.toString(obj); - var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; - if (ruselessToString.test(str)) { - try { - var newStr = JSON.stringify(obj); - str = newStr; - } - catch(e) { + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] - } - } - if (str.length === 0) { - str = "(empty array)"; - } - } - return ("(<" + snip(str) + ">, no stack trace)"); -} + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) + } + }) + } -function snip(str) { - var maxChars = 41; - if (str.length < maxChars) { - return str; - } - return str.substr(0, maxChars - 3) + "..."; -} + if (minver && range.test(minver)) { + return minver + } -function longStackTracesIsSupported() { - return typeof captureStackTrace === "function"; + return null } -var shouldIgnore = function() { return false; }; -var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; -function parseLineInfo(line) { - var matches = line.match(parseLineInfoRegex); - if (matches) { - return { - fileName: matches[1], - line: parseInt(matches[2], 10) - }; - } +exports.validRange = validRange +function validRange (range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } } -function setBounds(firstLineError, lastLineError) { - if (!longStackTracesIsSupported()) return; - var firstStackLines = (firstLineError.stack || "").split("\n"); - var lastStackLines = (lastLineError.stack || "").split("\n"); - var firstIndex = -1; - var lastIndex = -1; - var firstFileName; - var lastFileName; - for (var i = 0; i < firstStackLines.length; ++i) { - var result = parseLineInfo(firstStackLines[i]); - if (result) { - firstFileName = result.fileName; - firstIndex = result.line; - break; - } - } - for (var i = 0; i < lastStackLines.length; ++i) { - var result = parseLineInfo(lastStackLines[i]); - if (result) { - lastFileName = result.fileName; - lastIndex = result.line; - break; - } - } - if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || - firstFileName !== lastFileName || firstIndex >= lastIndex) { - return; - } - - shouldIgnore = function(line) { - if (bluebirdFramePattern.test(line)) return true; - var info = parseLineInfo(line); - if (info) { - if (info.fileName === firstFileName && - (firstIndex <= info.line && info.line <= lastIndex)) { - return true; - } - } - return false; - }; +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr +function ltr (version, range, options) { + return outside(version, range, '<', options) } -function CapturedTrace(parent) { - this._parent = parent; - this._promisesCreated = 0; - var length = this._length = 1 + (parent === undefined ? 0 : parent._length); - captureStackTrace(this, CapturedTrace); - if (length > 32) this.uncycle(); +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr +function gtr (version, range, options) { + return outside(version, range, '>', options) } -util.inherits(CapturedTrace, Error); -Context.CapturedTrace = CapturedTrace; -CapturedTrace.prototype.uncycle = function() { - var length = this._length; - if (length < 2) return; - var nodes = []; - var stackToIndex = {}; - - for (var i = 0, node = this; node !== undefined; ++i) { - nodes.push(node); - node = node._parent; - } - length = this._length = i; - for (var i = length - 1; i >= 0; --i) { - var stack = nodes[i].stack; - if (stackToIndex[stack] === undefined) { - stackToIndex[stack] = i; - } - } - for (var i = 0; i < length; ++i) { - var currentStack = nodes[i].stack; - var index = stackToIndex[currentStack]; - if (index !== undefined && index !== i) { - if (index > 0) { - nodes[index - 1]._parent = undefined; - nodes[index - 1]._length = 1; - } - nodes[i]._parent = undefined; - nodes[i]._length = 1; - var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) - if (index < length - 1) { - cycleEdgeNode._parent = nodes[index + 1]; - cycleEdgeNode._parent.uncycle(); - cycleEdgeNode._length = - cycleEdgeNode._parent._length + 1; - } else { - cycleEdgeNode._parent = undefined; - cycleEdgeNode._length = 1; - } - var currentChildLength = cycleEdgeNode._length + 1; - for (var j = i - 2; j >= 0; --j) { - nodes[j]._length = currentChildLength; - currentChildLength++; - } - return; - } - } -}; + var gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } -CapturedTrace.prototype.attachExtraTrace = function(error) { - if (error.__stackCleaned__) return; - this.uncycle(); - var parsed = parseStackAndMessage(error); - var message = parsed.message; - var stacks = [parsed.stack]; + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } - var trace = this; - while (trace !== undefined) { - stacks.push(cleanStack(trace.stack.split("\n"))); - trace = trace._parent; - } - removeCommonRoots(stacks); - removeDuplicateOrEmptyJumps(stacks); - util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); - util.notEnumerableProp(error, "__stackCleaned__", true); -}; + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. -var captureStackTrace = (function stackDetection() { - var v8stackFramePattern = /^\s*at\s*/; - var v8stackFormatter = function(stack, error) { - if (typeof stack === "string") return stack; + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] - if (error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; + var high = null + var low = null - if (typeof Error.stackTraceLimit === "number" && - typeof Error.captureStackTrace === "function") { - Error.stackTraceLimit += 6; - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - var captureStackTrace = Error.captureStackTrace; + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) - shouldIgnore = function(line) { - return bluebirdFramePattern.test(line); - }; - return function(receiver, ignoreUntil) { - Error.stackTraceLimit += 6; - captureStackTrace(receiver, ignoreUntil); - Error.stackTraceLimit -= 6; - }; + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false } - var err = new Error(); - if (typeof err.stack === "string" && - err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { - stackFramePattern = /@/; - formatStack = v8stackFormatter; - indentStackFrames = true; - return function captureStackTrace(o) { - o.stack = new Error().stack; - }; + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false } + } + return true +} - var hasStackAfterThrow; - try { throw new Error(); } - catch(e) { - hasStackAfterThrow = ("stack" in e); - } - if (!("stack" in err) && hasStackAfterThrow && - typeof Error.stackTraceLimit === "number") { - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - return function captureStackTrace(o) { - Error.stackTraceLimit += 6; - try { throw new Error(); } - catch(e) { o.stack = e.stack; } - Error.stackTraceLimit -= 6; - }; - } +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} - if ((typeof error === "object" || - typeof error === "function") && - error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; +exports.coerce = coerce +function coerce (version) { + if (version instanceof SemVer) { + return version + } - return null; + if (typeof version !== 'string') { + return null + } -})([]); + var match = version.match(re[COERCE]) -if (typeof console !== "undefined" && typeof console.warn !== "undefined") { - printWarning = function (message) { - console.warn(message); - }; - if (util.isNode && process.stderr.isTTY) { - printWarning = function(message, isSoft) { - var color = isSoft ? "\u001b[33m" : "\u001b[31m"; - console.warn(color + message + "\u001b[0m\n"); - }; - } else if (!util.isNode && typeof (new Error().stack) === "string") { - printWarning = function(message, isSoft) { - console.warn("%c" + message, - isSoft ? "color: darkorange" : "color: red"); - }; - } + if (match == null) { + return null + } + + return parse(match[1] + + '.' + (match[2] || '0') + + '.' + (match[3] || '0')) } -var config = { - warnings: warnings, - longStackTraces: false, - cancellation: false, - monitoring: false, - asyncHooks: false -}; -if (longStackTraces) Promise.longStackTraces(); +/***/ }), +/* 281 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -return { - asyncHooks: function() { - return config.asyncHooks; - }, - longStackTraces: function() { - return config.longStackTraces; - }, - warnings: function() { - return config.warnings; - }, - cancellation: function() { - return config.cancellation; - }, - monitoring: function() { - return config.monitoring; - }, - propagateFromFunction: function() { - return propagateFromFunction; - }, - boundValueFunction: function() { - return boundValueFunction; - }, - checkForgottenReturns: checkForgottenReturns, - setBounds: setBounds, - warn: warn, - deprecated: deprecated, - CapturedTrace: CapturedTrace, - fireDomEvent: fireDomEvent, - fireGlobalEvent: fireGlobalEvent -}; -}; +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const internal_globber_1 = __webpack_require__(297); +/** + * Constructs a globber + * + * @param patterns Patterns separated by newlines + * @param options Glob options + */ +function create(patterns, options) { + return __awaiter(this, void 0, void 0, function* () { + return yield internal_globber_1.DefaultGlobber.create(patterns, options); + }); +} +exports.create = create; +//# sourceMappingURL=glob.js.map /***/ }), -/* 273 */, -/* 274 */, -/* 275 */, -/* 276 */, -/* 277 */, -/* 278 */ +/* 282 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -const url = __webpack_require__(835) +const figgyPudding = __webpack_require__(122) +const getStream = __webpack_require__(341) +const npmFetch = __webpack_require__(789) -function packageName (href) { - try { - let basePath = url.parse(href).pathname.substr(1) - if (!basePath.match(/^-/)) { - basePath = basePath.split('/') - var index = basePath.indexOf('_rewrite') - if (index === -1) { - index = basePath.length - 1 - } else { - index++ - } - return decodeURIComponent(basePath[index]) +const SearchOpts = figgyPudding({ + detailed: { default: false }, + limit: { default: 20 }, + from: { default: 0 }, + quality: { default: 0.65 }, + popularity: { default: 0.98 }, + maintenance: { default: 0.5 }, + sortBy: {} +}) + +module.exports = search +function search (query, opts) { + return getStream.array(search.stream(query, opts)) +} +search.stream = searchStream +function searchStream (query, opts) { + opts = SearchOpts(opts) + switch (opts.sortBy) { + case 'optimal': { + opts = opts.concat({ + quality: 0.65, + popularity: 0.98, + maintenance: 0.5 + }) + break + } + case 'quality': { + opts = opts.concat({ + quality: 1, + popularity: 0, + maintenance: 0 + }) + break + } + case 'popularity': { + opts = opts.concat({ + quality: 0, + popularity: 1, + maintenance: 0 + }) + break + } + case 'maintenance': { + opts = opts.concat({ + quality: 0, + popularity: 0, + maintenance: 1 + }) + break } - } catch (_) { - // this is ok } + return npmFetch.json.stream('/-/v1/search', 'objects.*', + opts.concat({ + query: { + text: Array.isArray(query) ? query.join(' ') : query, + size: opts.limit, + from: opts.from, + quality: opts.quality, + popularity: opts.popularity, + maintenance: opts.maintenance + }, + mapJson (obj) { + if (obj.package.date) { + obj.package.date = new Date(obj.package.date) + } + if (opts.detailed) { + return obj + } else { + return obj.package + } + } + }) + ) } -class HttpErrorBase extends Error { - constructor (method, res, body, spec) { - super() - this.headers = res.headers.raw() - this.statusCode = res.status - this.code = `E${res.status}` - this.method = method - this.uri = res.url - this.body = body - this.pkgid = spec ? spec.toString() : packageName(res.url) - } -} -module.exports.HttpErrorBase = HttpErrorBase -class HttpErrorGeneral extends HttpErrorBase { - constructor (method, res, body, spec) { - super(method, res, body, spec) - this.message = `${res.status} ${res.statusText} - ${ - this.method.toUpperCase() - } ${ - this.spec || this.uri - }${ - (body && body.error) ? ' - ' + body.error : '' - }` - Error.captureStackTrace(this, HttpErrorGeneral) - } -} -module.exports.HttpErrorGeneral = HttpErrorGeneral +/***/ }), +/* 283 */, +/* 284 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -class HttpErrorAuthOTP extends HttpErrorBase { - constructor (method, res, body, spec) { - super(method, res, body, spec) - this.message = 'OTP required for authentication' - this.code = 'EOTP' - Error.captureStackTrace(this, HttpErrorAuthOTP) - } +var once = __webpack_require__(49) +var eos = __webpack_require__(3) +var fs = __webpack_require__(747) // we only need fs to get the ReadStream and WriteStream prototypes + +var noop = function () {} +var ancient = /^v?\.0/.test(process.version) + +var isFn = function (fn) { + return typeof fn === 'function' } -module.exports.HttpErrorAuthOTP = HttpErrorAuthOTP -class HttpErrorAuthIPAddress extends HttpErrorBase { - constructor (method, res, body, spec) { - super(method, res, body, spec) - this.message = 'Login is not allowed from your IP address' - this.code = 'EAUTHIP' - Error.captureStackTrace(this, HttpErrorAuthIPAddress) - } +var isFS = function (stream) { + if (!ancient) return false // newer node version do not need to care about fs is a special way + if (!fs) return false // browser + return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) } -module.exports.HttpErrorAuthIPAddress = HttpErrorAuthIPAddress -class HttpErrorAuthUnknown extends HttpErrorBase { - constructor (method, res, body, spec) { - super(method, res, body, spec) - this.message = 'Unable to authenticate, need: ' + res.headers.get('www-authenticate') - Error.captureStackTrace(this, HttpErrorAuthUnknown) - } +var isRequest = function (stream) { + return stream.setHeader && isFn(stream.abort) } -module.exports.HttpErrorAuthUnknown = HttpErrorAuthUnknown +var destroyer = function (stream, reading, writing, callback) { + callback = once(callback) -/***/ }), -/* 279 */, -/* 280 */ -/***/ (function(module, exports) { + var closed = false + stream.on('close', function () { + closed = true + }) -exports = module.exports = SemVer + eos(stream, {readable: reading, writable: writing}, function (err) { + if (err) return callback(err) + closed = true + callback() + }) -var debug -/* istanbul ignore next */ -if (typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG)) { - debug = function () { - var args = Array.prototype.slice.call(arguments, 0) - args.unshift('SEMVER') - console.log.apply(console, args) + var destroyed = false + return function (err) { + if (closed) return + if (destroyed) return + destroyed = true + + if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks + if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want + + if (isFn(stream.destroy)) return stream.destroy() + + callback(err || new Error('stream was destroyed')) } -} else { - debug = function () {} } -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0' +var call = function (fn) { + fn() +} -var MAX_LENGTH = 256 -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 +var pipe = function (from, to) { + return from.pipe(to) +} -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16 +var pump = function () { + var streams = Array.prototype.slice.call(arguments) + var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop -// The actual regexps go on exports.re -var re = exports.re = [] -var src = exports.src = [] -var R = 0 + if (Array.isArray(streams[0])) streams = streams[0] + if (streams.length < 2) throw new Error('pump requires two streams per minimum') -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. + var error + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1 + var writing = i > 0 + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err + if (err) destroys.forEach(call) + if (reading) return + destroys.forEach(call) + callback(error) + }) + }) -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. + return streams.reduce(pipe) +} -var NUMERICIDENTIFIER = R++ -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' -var NUMERICIDENTIFIERLOOSE = R++ -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' +module.exports = pump -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. -var NONNUMERICIDENTIFIER = R++ -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' +/***/ }), +/* 285 */ +/***/ (function(module) { -// ## Main Version -// Three dot-separated numeric identifiers. +"use strict"; -var MAINVERSION = R++ -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')' -var MAINVERSIONLOOSE = R++ -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')' +function isArguments (thingy) { + return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee') +} -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. +var types = { + '*': {label: 'any', check: function () { return true }}, + A: {label: 'array', check: function (thingy) { return Array.isArray(thingy) || isArguments(thingy) }}, + S: {label: 'string', check: function (thingy) { return typeof thingy === 'string' }}, + N: {label: 'number', check: function (thingy) { return typeof thingy === 'number' }}, + F: {label: 'function', check: function (thingy) { return typeof thingy === 'function' }}, + O: {label: 'object', check: function (thingy) { return typeof thingy === 'object' && thingy != null && !types.A.check(thingy) && !types.E.check(thingy) }}, + B: {label: 'boolean', check: function (thingy) { return typeof thingy === 'boolean' }}, + E: {label: 'error', check: function (thingy) { return thingy instanceof Error }}, + Z: {label: 'null', check: function (thingy) { return thingy == null }} +} -var PRERELEASEIDENTIFIER = R++ -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')' +function addSchema (schema, arity) { + var group = arity[schema.length] = arity[schema.length] || [] + if (group.indexOf(schema) === -1) group.push(schema) +} -var PRERELEASEIDENTIFIERLOOSE = R++ -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')' +var validate = module.exports = function (rawSchemas, args) { + if (arguments.length !== 2) throw wrongNumberOfArgs(['SA'], arguments.length) + if (!rawSchemas) throw missingRequiredArg(0, 'rawSchemas') + if (!args) throw missingRequiredArg(1, 'args') + if (!types.S.check(rawSchemas)) throw invalidType(0, ['string'], rawSchemas) + if (!types.A.check(args)) throw invalidType(1, ['array'], args) + var schemas = rawSchemas.split('|') + var arity = {} -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. + schemas.forEach(function (schema) { + for (var ii = 0; ii < schema.length; ++ii) { + var type = schema[ii] + if (!types[type]) throw unknownType(ii, type) + } + if (/E.*E/.test(schema)) throw moreThanOneError(schema) + addSchema(schema, arity) + if (/E/.test(schema)) { + addSchema(schema.replace(/E.*$/, 'E'), arity) + addSchema(schema.replace(/E/, 'Z'), arity) + if (schema.length === 1) addSchema('', arity) + } + }) + var matching = arity[args.length] + if (!matching) { + throw wrongNumberOfArgs(Object.keys(arity), args.length) + } + for (var ii = 0; ii < args.length; ++ii) { + var newMatching = matching.filter(function (schema) { + var type = schema[ii] + var typeCheck = types[type].check + return typeCheck(args[ii]) + }) + if (!newMatching.length) { + var labels = matching.map(function (schema) { + return types[schema[ii]].label + }).filter(function (schema) { return schema != null }) + throw invalidType(ii, labels, args[ii]) + } + matching = newMatching + } +} -var PRERELEASE = R++ -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' +function missingRequiredArg (num) { + return newException('EMISSINGARG', 'Missing required argument #' + (num + 1)) +} -var PRERELEASELOOSE = R++ -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' +function unknownType (num, type) { + return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 1)) +} -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. +function invalidType (num, expectedTypes, value) { + var valueType + Object.keys(types).forEach(function (typeCode) { + if (types[typeCode].check(value)) valueType = types[typeCode].label + }) + return newException('EINVALIDTYPE', 'Argument #' + (num + 1) + ': Expected ' + + englishList(expectedTypes) + ' but got ' + valueType) +} -var BUILDIDENTIFIER = R++ -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' +function englishList (list) { + return list.join(', ').replace(/, ([^,]+)$/, ' or $1') +} -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. +function wrongNumberOfArgs (expected, got) { + var english = englishList(expected) + var args = expected.every(function (ex) { return ex.length === 1 }) + ? 'argument' + : 'arguments' + return newException('EWRONGARGCOUNT', 'Expected ' + english + ' ' + args + ' but got ' + got) +} -var BUILD = R++ -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' +function moreThanOneError (schema) { + return newException('ETOOMANYERRORTYPES', + 'Only one error type per argument signature is allowed, more than one found in "' + schema + '"') +} -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. +function newException (code, msg) { + var e = new Error(msg) + e.code = code + if (Error.captureStackTrace) Error.captureStackTrace(e, validate) + return e +} -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. -var FULL = R++ -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?' +/***/ }), +/* 286 */ +/***/ (function(__unusedmodule, exports) { -src[FULL] = '^' + FULLPLAIN + '$' +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?' +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. -var LOOSE = R++ -src[LOOSE] = '^' + LOOSEPLAIN + '$' +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; -var GTLT = R++ -src[GTLT] = '((?:<|>)?=?)' +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++ -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' -var XRANGEIDENTIFIER = R++ -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; -var XRANGEPLAIN = R++ -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?' +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; -var XRANGEPLAINLOOSE = R++ -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?' +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; -var XRANGE = R++ -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' -var XRANGELOOSE = R++ -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -var COERCE = R++ -src[COERCE] = '(?:^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])' +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++ -src[LONETILDE] = '(?:~>?)' +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; -var TILDETRIM = R++ -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') -var tildeTrimReplace = '$1~' +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; -var TILDE = R++ -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' -var TILDELOOSE = R++ -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++ -src[LONECARET] = '(?:\\^)' +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; -var CARETTRIM = R++ -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') -var caretTrimReplace = '$1^' +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; -var CARET = R++ -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' -var CARETLOOSE = R++ -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++ -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' -var COMPARATOR = R++ -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++ -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' +exports.isBuffer = Buffer.isBuffer; -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') -var comparatorTrimReplace = '$1$2$3' +function objectToString(o) { + return Object.prototype.toString.call(o); +} -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++ -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$' -var HYPHENRANGELOOSE = R++ -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$' +/***/ }), +/* 287 */, +/* 288 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -// Star ranges basically just allow anything at all. -var STAR = R++ -src[STAR] = '(<|>)?=?\\s*\\*' +"use strict"; -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]) - if (!re[i]) { - re[i] = new RegExp(src[i]) - } + +// Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. +var modules = [ + __webpack_require__(162), + __webpack_require__(640), + __webpack_require__(797), + __webpack_require__(645), + __webpack_require__(877), + __webpack_require__(762), + __webpack_require__(28), + __webpack_require__(189), + __webpack_require__(92), +]; + +// Put all encoding/alias/codec definitions to single object and export it. +for (var i = 0; i < modules.length; i++) { + var module = modules[i]; + for (var enc in module) + if (Object.prototype.hasOwnProperty.call(module, enc)) + exports[enc] = module[enc]; } -exports.parse = parse -function parse (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - if (version instanceof SemVer) { - return version - } +/***/ }), +/* 289 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (typeof version !== 'string') { - return null - } +"use strict"; - if (version.length > MAX_LENGTH) { - return null - } - var r = options.loose ? re[LOOSE] : re[FULL] - if (!r.test(version)) { - return null - } +// tar -x +const hlo = __webpack_require__(891) +const Unpack = __webpack_require__(63) +const fs = __webpack_require__(747) +const fsm = __webpack_require__(827) +const path = __webpack_require__(622) - try { - return new SemVer(version, options) - } catch (er) { - return null - } -} +const x = module.exports = (opt_, files, cb) => { + if (typeof opt_ === 'function') + cb = opt_, files = null, opt_ = {} + else if (Array.isArray(opt_)) + files = opt_, opt_ = {} -exports.valid = valid -function valid (version, options) { - var v = parse(version, options) - return v ? v.version : null -} + if (typeof files === 'function') + cb = files, files = null -exports.clean = clean -function clean (version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} + if (!files) + files = [] + else + files = Array.from(files) -exports.SemVer = SemVer + const opt = hlo(opt_) -function SemVer (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version - } else { - version = version.version - } - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version) - } + if (opt.sync && typeof cb === 'function') + throw new TypeError('callback not supported for sync tar functions') - if (version.length > MAX_LENGTH) { - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') - } + if (!opt.file && typeof cb === 'function') + throw new TypeError('callback only supported with file option') - if (!(this instanceof SemVer)) { - return new SemVer(version, options) - } + if (files.length) + filesFilter(opt, files) - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose + return opt.file && opt.sync ? extractFileSync(opt) + : opt.file ? extractFile(opt, cb) + : opt.sync ? extractSync(opt) + : extract(opt) +} - var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) +// construct a filter that limits the file entries listed +// include child entries if a dir is included +const filesFilter = (opt, files) => { + const map = new Map(files.map(f => [f.replace(/\/+$/, ''), true])) + const filter = opt.filter - if (!m) { - throw new TypeError('Invalid Version: ' + version) + const mapHas = (file, r) => { + const root = r || path.parse(file).root || '.' + const ret = file === root ? false + : map.has(file) ? map.get(file) + : mapHas(path.dirname(file), root) + + map.set(file, ret) + return ret } - this.raw = version + opt.filter = filter + ? (file, entry) => filter(file, entry) && mapHas(file.replace(/\/+$/, '')) + : file => mapHas(file.replace(/\/+$/, '')) +} - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] +const extractFileSync = opt => { + const u = new Unpack.Sync(opt) - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } + const file = opt.file + let threw = true + let fd + const stat = fs.statSync(file) + // This trades a zero-byte read() syscall for a stat + // However, it will usually result in less memory allocation + const readSize = opt.maxReadSize || 16*1024*1024 + const stream = new fsm.ReadStreamSync(file, { + readSize: readSize, + size: stat.size + }) + stream.pipe(u) +} - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } +const extractFile = (opt, cb) => { + const u = new Unpack(opt) + const readSize = opt.maxReadSize || 16*1024*1024 - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } + const file = opt.file + const p = new Promise((resolve, reject) => { + u.on('error', reject) + u.on('close', resolve) - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map(function (id) { - if (/^[0-9]+$/.test(id)) { - var num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } + // This trades a zero-byte read() syscall for a stat + // However, it will usually result in less memory allocation + fs.stat(file, (er, stat) => { + if (er) + reject(er) + else { + const stream = new fsm.ReadStream(file, { + readSize: readSize, + size: stat.size + }) + stream.on('error', reject) + stream.pipe(u) } - return id }) - } - - this.build = m[5] ? m[5].split('.') : [] - this.format() + }) + return cb ? p.then(cb, cb) : p } -SemVer.prototype.format = function () { - this.version = this.major + '.' + this.minor + '.' + this.patch - if (this.prerelease.length) { - this.version += '-' + this.prerelease.join('.') - } - return this.version +const extractSync = opt => { + return new Unpack.Sync(opt) } -SemVer.prototype.toString = function () { - return this.version +const extract = opt => { + return new Unpack(opt) } -SemVer.prototype.compare = function (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - return this.compareMain(other) || this.comparePre(other) -} -SemVer.prototype.compareMain = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } +/***/ }), +/* 290 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) -} +"use strict"; -SemVer.prototype.comparePre = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } +module.exports = __webpack_require__(305) - var i = 0 - do { - var a = this.prerelease[i] - var b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) -} -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier) - this.inc('pre', identifier) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier) - } - this.inc('pre', identifier) - break +/***/ }), +/* 291 */, +/* 292 */, +/* 293 */ +/***/ (function(module) { - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0] - } else { - var i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0] - } - } else { - this.prerelease = [identifier, 0] - } - } - break +module.exports = require("buffer"); - default: - throw new Error('invalid increment argument: ' + release) - } - this.format() - this.raw = this.version - return this -} +/***/ }), +/* 294 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -exports.inc = inc -function inc (version, release, loose, identifier) { - if (typeof (loose) === 'string') { - identifier = loose - loose = undefined - } +"use strict"; - try { - return new SemVer(version, loose).inc(release, identifier).version - } catch (er) { - return null - } -} +const fs = __webpack_require__(747); -exports.diff = diff -function diff (version1, version2) { - if (eq(version1, version2)) { - return null - } else { - var v1 = parse(version1) - var v2 = parse(version2) - var prefix = '' - if (v1.prerelease.length || v2.prerelease.length) { - prefix = 'pre' - var defaultResult = 'prerelease' - } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } - } - return defaultResult // may be undefined - } -} +module.exports = fp => new Promise(resolve => { + fs.access(fp, err => { + resolve(!err); + }); +}); -exports.compareIdentifiers = compareIdentifiers +module.exports.sync = fp => { + try { + fs.accessSync(fp); + return true; + } catch (err) { + return false; + } +}; -var numeric = /^[0-9]+$/ -function compareIdentifiers (a, b) { - var anum = numeric.test(a) - var bnum = numeric.test(b) - if (anum && bnum) { - a = +a - b = +b - } +/***/ }), +/* 295 */, +/* 296 */, +/* 297 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} +"use strict"; -exports.rcompareIdentifiers = rcompareIdentifiers -function rcompareIdentifiers (a, b) { - return compareIdentifiers(b, a) +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +}; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __webpack_require__(470); +const fs = __webpack_require__(747); +const globOptionsHelper = __webpack_require__(601); +const path = __webpack_require__(622); +const patternHelper = __webpack_require__(597); +const internal_match_kind_1 = __webpack_require__(327); +const internal_pattern_1 = __webpack_require__(923); +const internal_search_state_1 = __webpack_require__(728); +const IS_WINDOWS = process.platform === 'win32'; +class DefaultGlobber { + constructor(options) { + this.patterns = []; + this.searchPaths = []; + this.options = globOptionsHelper.getOptions(options); + } + getSearchPaths() { + // Return a copy + return this.searchPaths.slice(); + } + glob() { + var e_1, _a; + return __awaiter(this, void 0, void 0, function* () { + const result = []; + try { + for (var _b = __asyncValues(this.globGenerator()), _c; _c = yield _b.next(), !_c.done;) { + const itemPath = _c.value; + result.push(itemPath); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + return result; + }); + } + globGenerator() { + return __asyncGenerator(this, arguments, function* globGenerator_1() { + // Fill in defaults options + const options = globOptionsHelper.getOptions(this.options); + // Implicit descendants? + const patterns = []; + for (const pattern of this.patterns) { + patterns.push(pattern); + if (options.implicitDescendants && + (pattern.trailingSeparator || + pattern.segments[pattern.segments.length - 1] !== '**')) { + patterns.push(new internal_pattern_1.Pattern(pattern.negate, pattern.segments.concat('**'))); + } + } + // Push the search paths + const stack = []; + for (const searchPath of patternHelper.getSearchPaths(patterns)) { + core.debug(`Search path '${searchPath}'`); + // Exists? + try { + // Intentionally using lstat. Detection for broken symlink + // will be performed later (if following symlinks). + yield __await(fs.promises.lstat(searchPath)); + } + catch (err) { + if (err.code === 'ENOENT') { + continue; + } + throw err; + } + stack.unshift(new internal_search_state_1.SearchState(searchPath, 1)); + } + // Search + const traversalChain = []; // used to detect cycles + while (stack.length) { + // Pop + const item = stack.pop(); + // Match? + const match = patternHelper.match(patterns, item.path); + const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path); + if (!match && !partialMatch) { + continue; + } + // Stat + const stats = yield __await(DefaultGlobber.stat(item, options, traversalChain) + // Broken symlink, or symlink cycle detected, or no longer exists + ); + // Broken symlink, or symlink cycle detected, or no longer exists + if (!stats) { + continue; + } + // Directory + if (stats.isDirectory()) { + // Matched + if (match & internal_match_kind_1.MatchKind.Directory) { + yield yield __await(item.path); + } + // Descend? + else if (!partialMatch) { + continue; + } + // Push the child items in reverse + const childLevel = item.level + 1; + const childItems = (yield __await(fs.promises.readdir(item.path))).map(x => new internal_search_state_1.SearchState(path.join(item.path, x), childLevel)); + stack.push(...childItems.reverse()); + } + // File + else if (match & internal_match_kind_1.MatchKind.File) { + yield yield __await(item.path); + } + } + }); + } + /** + * Constructs a DefaultGlobber + */ + static create(patterns, options) { + return __awaiter(this, void 0, void 0, function* () { + const result = new DefaultGlobber(options); + if (IS_WINDOWS) { + patterns = patterns.replace(/\r\n/g, '\n'); + patterns = patterns.replace(/\r/g, '\n'); + } + const lines = patterns.split('\n').map(x => x.trim()); + for (const line of lines) { + // Empty or comment + if (!line || line.startsWith('#')) { + continue; + } + // Pattern + else { + result.patterns.push(new internal_pattern_1.Pattern(line)); + } + } + result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns)); + return result; + }); + } + static stat(item, options, traversalChain) { + return __awaiter(this, void 0, void 0, function* () { + // Note: + // `stat` returns info about the target of a symlink (or symlink chain) + // `lstat` returns info about a symlink itself + let stats; + if (options.followSymbolicLinks) { + try { + // Use `stat` (following symlinks) + stats = yield fs.promises.stat(item.path); + } + catch (err) { + if (err.code === 'ENOENT') { + if (options.omitBrokenSymbolicLinks) { + core.debug(`Broken symlink '${item.path}'`); + return undefined; + } + throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`); + } + throw err; + } + } + else { + // Use `lstat` (not following symlinks) + stats = yield fs.promises.lstat(item.path); + } + // Note, isDirectory() returns false for the lstat of a symlink + if (stats.isDirectory() && options.followSymbolicLinks) { + // Get the realpath + const realPath = yield fs.promises.realpath(item.path); + // Fixup the traversal chain to match the item level + while (traversalChain.length >= item.level) { + traversalChain.pop(); + } + // Test for a cycle + if (traversalChain.some((x) => x === realPath)) { + core.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`); + return undefined; + } + // Update the traversal chain + traversalChain.push(realPath); + } + return stats; + }); + } } +exports.DefaultGlobber = DefaultGlobber; +//# sourceMappingURL=internal-globber.js.map -exports.major = major -function major (a, loose) { - return new SemVer(a, loose).major -} +/***/ }), +/* 298 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -exports.minor = minor -function minor (a, loose) { - return new SemVer(a, loose).minor -} +"use strict"; -exports.patch = patch -function patch (a, loose) { - return new SemVer(a, loose).patch -} -exports.compare = compare -function compare (a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)) -} +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; -exports.compareLoose = compareLoose -function compareLoose (a, b) { - return compare(a, b, true) -} +var _v = _interopRequireDefault(__webpack_require__(241)); -exports.rcompare = rcompare -function rcompare (a, b, loose) { - return compare(b, a, loose) -} +var _md = _interopRequireDefault(__webpack_require__(245)); -exports.sort = sort -function sort (list, loose) { - return list.sort(function (a, b) { - return exports.compare(a, b, loose) - }) -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -exports.rsort = rsort -function rsort (list, loose) { - return list.sort(function (a, b) { - return exports.rcompare(a, b, loose) +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports.default = _default; + +/***/ }), +/* 299 */ +/***/ (function(module) { + +module.exports = function (blocking) { + [process.stdout, process.stderr].forEach(function (stream) { + if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === 'function') { + stream._handle.setBlocking(blocking) + } }) } -exports.gt = gt -function gt (a, b, loose) { - return compare(a, b, loose) > 0 -} -exports.lt = lt -function lt (a, b, loose) { - return compare(a, b, loose) < 0 -} +/***/ }), +/* 300 */ +/***/ (function(module) { -exports.eq = eq -function eq (a, b, loose) { - return compare(a, b, loose) === 0 -} +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLNodeList; -exports.neq = neq -function neq (a, b, loose) { - return compare(a, b, loose) !== 0 -} + module.exports = XMLNodeList = (function() { + function XMLNodeList(nodes) { + this.nodes = nodes; + } -exports.gte = gte -function gte (a, b, loose) { - return compare(a, b, loose) >= 0 -} + Object.defineProperty(XMLNodeList.prototype, 'length', { + get: function() { + return this.nodes.length || 0; + } + }); -exports.lte = lte -function lte (a, b, loose) { - return compare(a, b, loose) <= 0 -} + XMLNodeList.prototype.clone = function() { + return this.nodes = null; + }; -exports.cmp = cmp -function cmp (a, op, b, loose) { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a === b + XMLNodeList.prototype.item = function(index) { + return this.nodes[index] || null; + }; - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b + return XMLNodeList; - case '': - case '=': - case '==': - return eq(a, b, loose) + })(); - case '!=': - return neq(a, b, loose) +}).call(this); - case '>': - return gt(a, b, loose) - case '>=': - return gte(a, b, loose) +/***/ }), +/* 301 */, +/* 302 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - case '<': - return lt(a, b, loose) +module.exports = realpath +realpath.realpath = realpath +realpath.sync = realpathSync +realpath.realpathSync = realpathSync +realpath.monkeypatch = monkeypatch +realpath.unmonkeypatch = unmonkeypatch - case '<=': - return lte(a, b, loose) +var fs = __webpack_require__(747) +var origRealpath = fs.realpath +var origRealpathSync = fs.realpathSync - default: - throw new TypeError('Invalid operator: ' + op) - } +var version = process.version +var ok = /^v[0-5]\./.test(version) +var old = __webpack_require__(117) + +function newError (er) { + return er && er.syscall === 'realpath' && ( + er.code === 'ELOOP' || + er.code === 'ENOMEM' || + er.code === 'ENAMETOOLONG' + ) } -exports.Comparator = Comparator -function Comparator (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } +function realpath (p, cache, cb) { + if (ok) { + return origRealpath(p, cache, cb) } - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp + if (typeof cache === 'function') { + cb = cache + cache = null + } + origRealpath(p, cache, function (er, result) { + if (newError(er)) { + old.realpath(p, cache, cb) } else { - comp = comp.value + cb(er, result) } - } - - if (!(this instanceof Comparator)) { - return new Comparator(comp, options) - } - - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) - - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } - - debug('comp', this) + }) } -var ANY = {} -Comparator.prototype.parse = function (comp) { - var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var m = comp.match(r) - - if (!m) { - throw new TypeError('Invalid comparator: ' + comp) - } - - this.operator = m[1] - if (this.operator === '=') { - this.operator = '' +function realpathSync (p, cache) { + if (ok) { + return origRealpathSync(p, cache) } - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) + try { + return origRealpathSync(p, cache) + } catch (er) { + if (newError(er)) { + return old.realpathSync(p, cache) + } else { + throw er + } } } -Comparator.prototype.toString = function () { - return this.value +function monkeypatch () { + fs.realpath = realpath + fs.realpathSync = realpathSync } -Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.options.loose) - - if (this.semver === ANY) { - return true - } - - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } - - return cmp(version, this.operator, this.semver, this.options) +function unmonkeypatch () { + fs.realpath = origRealpath + fs.realpathSync = origRealpathSync } -Comparator.prototype.intersects = function (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - var rangeTmp +/***/ }), +/* 303 */ +/***/ (function(module) { - if (this.operator === '') { - rangeTmp = new Range(comp.value, options) - return satisfies(this.value, rangeTmp, options) - } else if (comp.operator === '') { - rangeTmp = new Range(this.value, options) - return satisfies(comp.semver, rangeTmp, options) - } +module.exports = require("async_hooks"); - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>') - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<') - var sameSemVer = this.semver.version === comp.semver.version - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<=') - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')) - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')) +/***/ }), +/* 304 */ +/***/ (function(module) { - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan -} +module.exports = require("string_decoder"); -exports.Range = Range -function Range (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } +/***/ }), +/* 305 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range - } else { - return new Range(range.raw, options) - } - } +"use strict"; - if (range instanceof Comparator) { - return new Range(range.value, options) - } - if (!(this instanceof Range)) { - return new Range(range, options) - } +const BB = __webpack_require__(489) - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease +const contentPath = __webpack_require__(969) +const figgyPudding = __webpack_require__(122) +const finished = BB.promisify(__webpack_require__(371).finished) +const fixOwner = __webpack_require__(133) +const fs = __webpack_require__(598) +const glob = BB.promisify(__webpack_require__(402)) +const index = __webpack_require__(407) +const path = __webpack_require__(622) +const rimraf = BB.promisify(__webpack_require__(503)) +const ssri = __webpack_require__(951) - // First, split based on boolean or || - this.raw = range - this.set = range.split(/\s*\|\|\s*/).map(function (range) { - return this.parseRange(range.trim()) - }, this).filter(function (c) { - // throw out any that are not relevant for whatever reason - return c.length - }) +BB.promisifyAll(fs) - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range) +const VerifyOpts = figgyPudding({ + concurrency: { + default: 20 + }, + filter: {}, + log: { + default: { silly () {} } } +}) - this.format() +module.exports = verify +function verify (cache, opts) { + opts = VerifyOpts(opts) + opts.log.silly('verify', 'verifying cache at', cache) + return BB.reduce([ + markStartTime, + fixPerms, + garbageCollect, + rebuildIndex, + cleanTmp, + writeVerifile, + markEndTime + ], (stats, step, i) => { + const label = step.name || `step #${i}` + const start = new Date() + return BB.resolve(step(cache, opts)).then(s => { + s && Object.keys(s).forEach(k => { + stats[k] = s[k] + }) + const end = new Date() + if (!stats.runTime) { stats.runTime = {} } + stats.runTime[label] = end - start + return stats + }) + }, {}).tap(stats => { + stats.runTime.total = stats.endTime - stats.startTime + opts.log.silly('verify', 'verification finished for', cache, 'in', `${stats.runTime.total}ms`) + }) } -Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim() - }).join('||').trim() - return this.range +function markStartTime (cache, opts) { + return { startTime: new Date() } } -Range.prototype.toString = function () { - return this.range +function markEndTime (cache, opts) { + return { endTime: new Date() } } -Range.prototype.parseRange = function (range) { - var loose = this.options.loose - range = range.trim() - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] - range = range.replace(hr, hyphenReplace) - debug('hyphen replace', range) - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[COMPARATORTRIM]) - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace) - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace) - - // normalize spaces - range = range.split(/\s+/).join(' ') - - // At this point, the range is completely trimmed and - // ready to be split into comparators. +function fixPerms (cache, opts) { + opts.log.silly('verify', 'fixing cache permissions') + return fixOwner.mkdirfix(cache, cache).then(() => { + // TODO - fix file permissions too + return fixOwner.chownr(cache, cache) + }).then(() => null) +} - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var set = range.split(' ').map(function (comp) { - return parseComparator(comp, this.options) - }, this).join(' ').split(/\s+/) - if (this.options.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function (comp) { - return !!comp.match(compRe) +// Implements a naive mark-and-sweep tracing garbage collector. +// +// The algorithm is basically as follows: +// 1. Read (and filter) all index entries ("pointers") +// 2. Mark each integrity value as "live" +// 3. Read entire filesystem tree in `content-vX/` dir +// 4. If content is live, verify its checksum and delete it if it fails +// 5. If content is not marked as live, rimraf it. +// +function garbageCollect (cache, opts) { + opts.log.silly('verify', 'garbage collecting content') + const indexStream = index.lsStream(cache) + const liveContent = new Set() + indexStream.on('data', entry => { + if (opts.filter && !opts.filter(entry)) { return } + liveContent.add(entry.integrity.toString()) + }) + return finished(indexStream).then(() => { + const contentDir = contentPath._contentDir(cache) + return glob(path.join(contentDir, '**'), { + follow: false, + nodir: true, + nosort: true + }).then(files => { + return BB.resolve({ + verifiedContent: 0, + reclaimedCount: 0, + reclaimedSize: 0, + badContentCount: 0, + keptSize: 0 + }).tap((stats) => BB.map(files, (f) => { + const split = f.split(/[/\\]/) + const digest = split.slice(split.length - 3).join('') + const algo = split[split.length - 4] + const integrity = ssri.fromHex(digest, algo) + if (liveContent.has(integrity.toString())) { + return verifyContent(f, integrity).then(info => { + if (!info.valid) { + stats.reclaimedCount++ + stats.badContentCount++ + stats.reclaimedSize += info.size + } else { + stats.verifiedContent++ + stats.keptSize += info.size + } + return stats + }) + } else { + // No entries refer to this content. We can delete. + stats.reclaimedCount++ + return fs.statAsync(f).then(s => { + return rimraf(f).then(() => { + stats.reclaimedSize += s.size + return stats + }) + }) + } + }, { concurrency: opts.concurrency })) }) - } - set = set.map(function (comp) { - return new Comparator(comp, this.options) - }, this) - - return set + }) } -Range.prototype.intersects = function (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } - - return this.set.some(function (thisComparators) { - return thisComparators.every(function (thisComparator) { - return range.set.some(function (rangeComparators) { - return rangeComparators.every(function (rangeComparator) { - return thisComparator.intersects(rangeComparator, options) - }) +function verifyContent (filepath, sri) { + return fs.statAsync(filepath).then(stat => { + const contentInfo = { + size: stat.size, + valid: true + } + return ssri.checkStream( + fs.createReadStream(filepath), + sri + ).catch(err => { + if (err.code !== 'EINTEGRITY') { throw err } + return rimraf(filepath).then(() => { + contentInfo.valid = false }) - }) + }).then(() => contentInfo) + }).catch({ code: 'ENOENT' }, () => ({ size: 0, valid: false })) +} + +function rebuildIndex (cache, opts) { + opts.log.silly('verify', 'rebuilding index') + return index.ls(cache).then(entries => { + const stats = { + missingContent: 0, + rejectedEntries: 0, + totalEntries: 0 + } + const buckets = {} + for (let k in entries) { + if (entries.hasOwnProperty(k)) { + const hashed = index._hashKey(k) + const entry = entries[k] + const excluded = opts.filter && !opts.filter(entry) + excluded && stats.rejectedEntries++ + if (buckets[hashed] && !excluded) { + buckets[hashed].push(entry) + } else if (buckets[hashed] && excluded) { + // skip + } else if (excluded) { + buckets[hashed] = [] + buckets[hashed]._path = index._bucketPath(cache, k) + } else { + buckets[hashed] = [entry] + buckets[hashed]._path = index._bucketPath(cache, k) + } + } + } + return BB.map(Object.keys(buckets), key => { + return rebuildBucket(cache, buckets[key], stats, opts) + }, { concurrency: opts.concurrency }).then(() => stats) }) } -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators -function toComparators (range, options) { - return new Range(range, options).set.map(function (comp) { - return comp.map(function (c) { - return c.value - }).join(' ').trim().split(' ') +function rebuildBucket (cache, bucket, stats, opts) { + return fs.truncateAsync(bucket._path).then(() => { + // This needs to be serialized because cacache explicitly + // lets very racy bucket conflicts clobber each other. + return BB.mapSeries(bucket, entry => { + const content = contentPath(cache, entry.integrity) + return fs.statAsync(content).then(() => { + return index.insert(cache, entry.key, entry.integrity, { + metadata: entry.metadata, + size: entry.size + }).then(() => { stats.totalEntries++ }) + }).catch({ code: 'ENOENT' }, () => { + stats.rejectedEntries++ + stats.missingContent++ + }) + }) }) } -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator (comp, options) { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp +function cleanTmp (cache, opts) { + opts.log.silly('verify', 'cleaning tmp directory') + return rimraf(path.join(cache, 'tmp')) } -function isX (id) { - return !id || id.toLowerCase() === 'x' || id === '*' +function writeVerifile (cache, opts) { + const verifile = path.join(cache, '_lastverified') + opts.log.silly('verify', 'writing verifile to ' + verifile) + try { + return fs.writeFileAsync(verifile, '' + (+(new Date()))) + } finally { + fixOwner.chownr.sync(cache, verifile) + } } -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceTilde(comp, options) - }).join(' ') +module.exports.lastRun = lastRun +function lastRun (cache) { + return fs.readFileAsync( + path.join(cache, '_lastverified'), 'utf8' + ).then(data => new Date(+data)) } -function replaceTilde (comp, options) { - var r = options.loose ? re[TILDELOOSE] : re[TILDE] - return comp.replace(r, function (_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr) - var ret - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else if (pr) { - debug('replaceTilde pr', pr) - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } else { - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } +/***/ }), +/* 306 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - debug('tilde return', ret) - return ret - }) -} +var concatMap = __webpack_require__(896); +var balanced = __webpack_require__(621); -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceCaret(comp, options) - }).join(' ') -} +module.exports = expandTop; -function replaceCaret (comp, options) { - debug('caret', comp, options) - var r = options.loose ? re[CARETLOOSE] : re[CARET] - return comp.replace(r, function (_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr) - var ret +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - if (M === '0') { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else { - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + (+M + 1) + '.0.0' - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0' - } - } +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} - debug('caret return', ret) - return ret - }) +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); } -function replaceXRanges (comp, options) { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map(function (comp) { - return replaceXRange(comp, options) - }).join(' ') +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); } -function replaceXRange (comp, options) { - comp = comp.trim() - var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] - return comp.replace(r, function (ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - var xM = isX(M) - var xm = xM || isX(m) - var xp = xm || isX(p) - var anyX = xp - if (gtlt === '=' && anyX) { - gtlt = '' - } +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 + var parts = []; + var m = balanced('{', '}', str); - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } + if (!m) + return str.split(','); - ret = gtlt + M + '.' + m + '.' + p - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); - debug('xRange return', ret) + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } - return ret - }) -} + parts.push.apply(parts, p); -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars (comp, options) { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], '') + return parts; } -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = '>=' + fM + '.0.0' - } else if (isX(fp)) { - from = '>=' + fM + '.' + fm + '.0' - } else { - from = '>=' + from - } +function expandTop(str) { + if (!str) + return []; - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = '<' + (+tM + 1) + '.0.0' - } else if (isX(tp)) { - to = '<' + tM + '.' + (+tm + 1) + '.0' - } else if (tpr) { - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr - } else { - to = '<=' + to + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); } - return (from + ' ' + to).trim() + return expand(escapeBraces(str), true).map(unescapeBraces); } -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function (version) { - if (!version) { - return false - } +function identity(e) { + return e; +} - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; } -function testSet (set, version, options) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } +function expand(str, isTop) { + var expansions = []; - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === ANY) { - continue - } + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true -} - -exports.satisfies = satisfies -function satisfies (version, range, options) { - try { - range = new Range(range, options) - } catch (er) { - return false + return [str]; } - return range.test(version) -} -exports.maxSatisfying = maxSatisfying -function maxSatisfying (versions, range, options) { - var max = null - var maxSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); } } - }) - return max -} - -exports.minSatisfying = minSatisfying -function minSatisfying (versions, range, options) { - var min = null - var minSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) - } - } - }) - return min -} -exports.minVersion = minVersion -function minVersion (range, loose) { - range = new Range(range, loose) + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. - var minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } + var N; - minver = null - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); - comparators.forEach(function (comparator) { - // Clone to avoid manipulating the comparator's semver object. - var compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!minver || gt(minver, compver)) { - minver = compver + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error('Unexpected operation: ' + comparator.operator) + } } - }) + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); } - if (minver && range.test(minver)) { - return minver + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } } - return null + return expansions; } -exports.validRange = validRange -function validRange (range, options) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null - } -} -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr -function ltr (version, range, options) { - return outside(version, range, '<', options) -} -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr -function gtr (version, range, options) { - return outside(version, range, '>', options) -} +/***/ }), +/* 307 */, +/* 308 */, +/* 309 */, +/* 310 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -exports.outside = outside -function outside (version, range, hilo, options) { - version = new SemVer(version, options) - range = new Range(range, options) +/** + * Module dependencies. + */ - var gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } +var tls; // lazy-loaded... +var url = __webpack_require__(835); +var dns = __webpack_require__(819); +var Agent = __webpack_require__(234); +var SocksClient = __webpack_require__(198).SocksClient; +var inherits = __webpack_require__(669).inherits; - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false - } +/** + * Module exports. + */ - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. +module.exports = SocksProxyAgent; - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] +/** + * The `SocksProxyAgent`. + * + * @api public + */ - var high = null - var low = null +function SocksProxyAgent(opts) { + if (!(this instanceof SocksProxyAgent)) return new SocksProxyAgent(opts); + if ('string' == typeof opts) opts = url.parse(opts); + if (!opts) + throw new Error( + 'a SOCKS proxy server `host` and `port` must be specified!' + ); + Agent.call(this, opts); - comparators.forEach(function (comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) + var proxy = Object.assign({}, opts); - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } + // prefer `hostname` over `host`, because of `url.parse()` + proxy.host = proxy.hostname || proxy.host; - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } + // SOCKS doesn't *technically* have a default port, but this is + // the same default that `curl(1)` uses + proxy.port = +proxy.port || 1080; + + if (proxy.host && proxy.path) { + // if both a `host` and `path` are specified then it's most likely the + // result of a `url.parse()` call... we need to remove the `path` portion so + // that `net.connect()` doesn't attempt to open that as a unix socket file. + delete proxy.path; + delete proxy.pathname; } - return true -} -exports.prerelease = prerelease -function prerelease (version, options) { - var parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} + // figure out if we want socks v4 or v5, based on the "protocol" used. + // Defaults to 5. + proxy.lookup = false; + switch (proxy.protocol) { + case 'socks4:': + proxy.lookup = true; + // pass through + case 'socks4a:': + proxy.version = 4; + break; + case 'socks5:': + proxy.lookup = true; + // pass through + case 'socks:': // no version specified, default to 5h + case 'socks5h:': + proxy.version = 5; + break; + default: + throw new TypeError( + 'A "socks" protocol must be specified! Got: ' + proxy.protocol + ); + } -exports.intersects = intersects -function intersects (r1, r2, options) { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) + if (proxy.auth) { + var auth = proxy.auth.split(':'); + proxy.authentication = { username: auth[0], password: auth[1] }; + proxy.userid = auth[0]; + } + this.proxy = proxy; } +inherits(SocksProxyAgent, Agent); -exports.coerce = coerce -function coerce (version) { - if (version instanceof SemVer) { - return version +/** + * Initiates a SOCKS connection to the specified SOCKS proxy server, + * which in turn connects to the specified remote host and port. + * + * @api public + */ + +SocksProxyAgent.prototype.callback = function connect(req, opts, fn) { + var proxy = this.proxy; + + // called once the SOCKS proxy has connected to the specified remote endpoint + function onhostconnect(err, result) { + if (err) return fn(err); + + var socket = result.socket; + + var s = socket; + if (opts.secureEndpoint) { + // since the proxy is connecting to an SSL server, we have + // to upgrade this socket connection to an SSL connection + if (!tls) tls = __webpack_require__(16); + opts.socket = socket; + opts.servername = opts.host; + opts.host = null; + opts.hostname = null; + opts.port = null; + s = tls.connect(opts); + } + + fn(null, s); } - if (typeof version !== 'string') { - return null + // called for the `dns.lookup()` callback + function onlookup(err, ip) { + if (err) return fn(err); + options.destination.host = ip; + SocksClient.createConnection(options, onhostconnect); } - var match = version.match(re[COERCE]) + var options = { + proxy: { + ipaddress: proxy.host, + port: +proxy.port, + type: proxy.version + }, + destination: { + port: +opts.port + }, + command: 'connect' + }; - if (match == null) { - return null + if (proxy.authentication) { + options.proxy.userId = proxy.userid; + options.proxy.password = proxy.authentication.password; } - return parse(match[1] + - '.' + (match[2] || '0') + - '.' + (match[3] || '0')) + if (proxy.lookup) { + // client-side DNS resolution for "4" and "5" socks proxy versions + dns.lookup(opts.host, onlookup); + } else { + // proxy hostname DNS resolution for "4a" and "5h" socks proxy servers + onlookup(null, opts.host); + } } /***/ }), -/* 281 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 311 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = __webpack_require__(446) +const rm = __webpack_require__(974) +const link = __webpack_require__(273) +const mkdir = __webpack_require__(836) +const binLink = __webpack_require__(834) + +exports = module.exports = { + rm: rm, + link: link.link, + linkIfExists: link.linkIfExists, + mkdir: mkdir, + binLink: binLink +} /***/ }), -/* 282 */ +/* 312 */ /***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, WriterState, XMLDOMImplementation, XMLDocument, XMLDocumentCB, XMLStreamWriter, XMLStringWriter, assign, isFunction, ref; + ref = __webpack_require__(582), assign = ref.assign, isFunction = ref.isFunction; -const figgyPudding = __webpack_require__(122) -const getStream = __webpack_require__(145) -const npmFetch = __webpack_require__(789) + XMLDOMImplementation = __webpack_require__(515); -const SearchOpts = figgyPudding({ - detailed: { default: false }, - limit: { default: 20 }, - from: { default: 0 }, - quality: { default: 0.65 }, - popularity: { default: 0.98 }, - maintenance: { default: 0.5 }, - sortBy: {} -}) + XMLDocument = __webpack_require__(559); -module.exports = search -function search (query, opts) { - return getStream.array(search.stream(query, opts)) -} -search.stream = searchStream -function searchStream (query, opts) { - opts = SearchOpts(opts) - switch (opts.sortBy) { - case 'optimal': { - opts = opts.concat({ - quality: 0.65, - popularity: 0.98, - maintenance: 0.5 - }) - break + XMLDocumentCB = __webpack_require__(768); + + XMLStringWriter = __webpack_require__(347); + + XMLStreamWriter = __webpack_require__(458); + + NodeType = __webpack_require__(683); + + WriterState = __webpack_require__(541); + + module.exports.create = function(name, xmldec, doctype, options) { + var doc, root; + if (name == null) { + throw new Error("Root element needs a name."); } - case 'quality': { - opts = opts.concat({ - quality: 1, - popularity: 0, - maintenance: 0 - }) - break + options = assign({}, xmldec, doctype, options); + doc = new XMLDocument(options); + root = doc.element(name); + if (!options.headless) { + doc.declaration(options); + if ((options.pubID != null) || (options.sysID != null)) { + doc.dtd(options); + } } - case 'popularity': { - opts = opts.concat({ - quality: 0, - popularity: 1, - maintenance: 0 - }) - break + return root; + }; + + module.exports.begin = function(options, onData, onEnd) { + var ref1; + if (isFunction(options)) { + ref1 = [options, onData], onData = ref1[0], onEnd = ref1[1]; + options = {}; } - case 'maintenance': { - opts = opts.concat({ - quality: 0, - popularity: 0, - maintenance: 1 - }) - break + if (onData) { + return new XMLDocumentCB(options, onData, onEnd); + } else { + return new XMLDocument(options); } - } - return npmFetch.json.stream('/-/v1/search', 'objects.*', - opts.concat({ - query: { - text: Array.isArray(query) ? query.join(' ') : query, - size: opts.limit, - from: opts.from, - quality: opts.quality, - popularity: opts.popularity, - maintenance: opts.maintenance - }, - mapJson (obj) { - if (obj.package.date) { - obj.package.date = new Date(obj.package.date) - } - if (opts.detailed) { - return obj - } else { - return obj.package - } - } - }) - ) -} + }; + + module.exports.stringWriter = function(options) { + return new XMLStringWriter(options); + }; + + module.exports.streamWriter = function(stream, options) { + return new XMLStreamWriter(stream, options); + }; + + module.exports.implementation = new XMLDOMImplementation(); + + module.exports.nodeType = NodeType; + + module.exports.writerState = WriterState; + +}).call(this); /***/ }), -/* 283 */, -/* 284 */ +/* 313 */ /***/ (function(module, __unusedexports, __webpack_require__) { -var once = __webpack_require__(49) -var eos = __webpack_require__(562) -var fs = __webpack_require__(747) // we only need fs to get the ReadStream and WriteStream prototypes - -var noop = function () {} -var ancient = /^v?\.0/.test(process.version) +"use strict"; -var isFn = function (fn) { - return typeof fn === 'function' -} -var isFS = function (stream) { - if (!ancient) return false // newer node version do not need to care about fs is a special way - if (!fs) return false // browser - return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) -} +var Buffer = __webpack_require__(215).Buffer; -var isRequest = function (stream) { - return stream.setHeader && isFn(stream.abort) -} +// NOTE: Due to 'stream' module being pretty large (~100Kb, significant in browser environments), +// we opt to dependency-inject it instead of creating a hard dependency. +module.exports = function(stream_module) { + var Transform = stream_module.Transform; -var destroyer = function (stream, reading, writing, callback) { - callback = once(callback) + // == Encoder stream ======================================================= - var closed = false - stream.on('close', function () { - closed = true - }) + function IconvLiteEncoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.decodeStrings = false; // We accept only strings, so we don't need to decode them. + Transform.call(this, options); + } - eos(stream, {readable: reading, writable: writing}, function (err) { - if (err) return callback(err) - closed = true - callback() - }) + IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } + }); - var destroyed = false - return function (err) { - if (closed) return - if (destroyed) return - destroyed = true + IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { + if (typeof chunk != 'string') + return done(new Error("Iconv encoding stream needs strings as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } + } - if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks - if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want + IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } + } - if (isFn(stream.destroy)) return stream.destroy() + IconvLiteEncoderStream.prototype.collect = function(cb) { + var chunks = []; + this.on('error', cb); + this.on('data', function(chunk) { chunks.push(chunk); }); + this.on('end', function() { + cb(null, Buffer.concat(chunks)); + }); + return this; + } - callback(err || new Error('stream was destroyed')) - } -} -var call = function (fn) { - fn() -} + // == Decoder stream ======================================================= -var pipe = function (from, to) { - return from.pipe(to) -} + function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + Transform.call(this, options); + } -var pump = function () { - var streams = Array.prototype.slice.call(arguments) - var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop + IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } + }); - if (Array.isArray(streams[0])) streams = streams[0] - if (streams.length < 2) throw new Error('pump requires two streams per minimum') + IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { + if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array)) + return done(new Error("Iconv decoding stream needs buffers as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } + } - var error - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1 - var writing = i > 0 - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err - if (err) destroys.forEach(call) - if (reading) return - destroys.forEach(call) - callback(error) - }) - }) + IconvLiteDecoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } + } - return streams.reduce(pipe) -} + IconvLiteDecoderStream.prototype.collect = function(cb) { + var res = ''; + this.on('error', cb); + this.on('data', function(chunk) { res += chunk; }); + this.on('end', function() { + cb(null, res); + }); + return this; + } -module.exports = pump + return { + IconvLiteEncoderStream: IconvLiteEncoderStream, + IconvLiteDecoderStream: IconvLiteDecoderStream, + }; +}; /***/ }), -/* 285 */ +/* 314 */, +/* 315 */ /***/ (function(module) { "use strict"; - -function isArguments (thingy) { - return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee') +module.exports = function(Promise) { +function returner() { + return this.value; } - -var types = { - '*': {label: 'any', check: function () { return true }}, - A: {label: 'array', check: function (thingy) { return Array.isArray(thingy) || isArguments(thingy) }}, - S: {label: 'string', check: function (thingy) { return typeof thingy === 'string' }}, - N: {label: 'number', check: function (thingy) { return typeof thingy === 'number' }}, - F: {label: 'function', check: function (thingy) { return typeof thingy === 'function' }}, - O: {label: 'object', check: function (thingy) { return typeof thingy === 'object' && thingy != null && !types.A.check(thingy) && !types.E.check(thingy) }}, - B: {label: 'boolean', check: function (thingy) { return typeof thingy === 'boolean' }}, - E: {label: 'error', check: function (thingy) { return thingy instanceof Error }}, - Z: {label: 'null', check: function (thingy) { return thingy == null }} +function thrower() { + throw this.reason; } -function addSchema (schema, arity) { - var group = arity[schema.length] = arity[schema.length] || [] - if (group.indexOf(schema) === -1) group.push(schema) -} +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + returner, undefined, undefined, {value: value}, undefined); +}; -var validate = module.exports = function (rawSchemas, args) { - if (arguments.length !== 2) throw wrongNumberOfArgs(['SA'], arguments.length) - if (!rawSchemas) throw missingRequiredArg(0, 'rawSchemas') - if (!args) throw missingRequiredArg(1, 'args') - if (!types.S.check(rawSchemas)) throw invalidType(0, ['string'], rawSchemas) - if (!types.A.check(args)) throw invalidType(1, ['array'], args) - var schemas = rawSchemas.split('|') - var arity = {} +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + return this._then( + thrower, undefined, undefined, {reason: reason}, undefined); +}; - schemas.forEach(function (schema) { - for (var ii = 0; ii < schema.length; ++ii) { - var type = schema[ii] - if (!types[type]) throw unknownType(ii, type) - } - if (/E.*E/.test(schema)) throw moreThanOneError(schema) - addSchema(schema, arity) - if (/E/.test(schema)) { - addSchema(schema.replace(/E.*$/, 'E'), arity) - addSchema(schema.replace(/E/, 'Z'), arity) - if (schema.length === 1) addSchema('', arity) - } - }) - var matching = arity[args.length] - if (!matching) { - throw wrongNumberOfArgs(Object.keys(arity), args.length) - } - for (var ii = 0; ii < args.length; ++ii) { - var newMatching = matching.filter(function (schema) { - var type = schema[ii] - var typeCheck = types[type].check - return typeCheck(args[ii]) - }) - if (!newMatching.length) { - var labels = matching.map(function (schema) { - return types[schema[ii]].label - }).filter(function (schema) { return schema != null }) - throw invalidType(ii, labels, args[ii]) +Promise.prototype.catchThrow = function (reason) { + if (arguments.length <= 1) { + return this._then( + undefined, thrower, undefined, {reason: reason}, undefined); + } else { + var _reason = arguments[1]; + var handler = function() {throw _reason;}; + return this.caught(reason, handler); } - matching = newMatching - } -} - -function missingRequiredArg (num) { - return newException('EMISSINGARG', 'Missing required argument #' + (num + 1)) -} - -function unknownType (num, type) { - return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 1)) -} - -function invalidType (num, expectedTypes, value) { - var valueType - Object.keys(types).forEach(function (typeCode) { - if (types[typeCode].check(value)) valueType = types[typeCode].label - }) - return newException('EINVALIDTYPE', 'Argument #' + (num + 1) + ': Expected ' + - englishList(expectedTypes) + ' but got ' + valueType) -} +}; -function englishList (list) { - return list.join(', ').replace(/, ([^,]+)$/, ' or $1') -} +Promise.prototype.catchReturn = function (value) { + if (arguments.length <= 1) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + undefined, returner, undefined, {value: value}, undefined); + } else { + var _value = arguments[1]; + if (_value instanceof Promise) _value.suppressUnhandledRejections(); + var handler = function() {return _value;}; + return this.caught(value, handler); + } +}; +}; -function wrongNumberOfArgs (expected, got) { - var english = englishList(expected) - var args = expected.every(function (ex) { return ex.length === 1 }) - ? 'argument' - : 'arguments' - return newException('EWRONGARGCOUNT', 'Expected ' + english + ' ' + args + ' but got ' + got) -} -function moreThanOneError (schema) { - return newException('ETOOMANYERRORTYPES', - 'Only one error type per argument signature is allowed, more than one found in "' + schema + '"') -} +/***/ }), +/* 316 */, +/* 317 */ +/***/ (function(__unusedmodule, exports) { -function newException (code, msg) { - var e = new Error(msg) - e.code = code - if (Error.captureStackTrace) Error.captureStackTrace(e, validate) - return e -} +var undefined = (void 0); // Paranoia +// Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to +// create, and consume so much memory, that the browser appears frozen. +var MAX_ARRAY_LENGTH = 1e5; -/***/ }), -/* 286 */ -/***/ (function(__unusedmodule, exports) { +// Approximations of internal ECMAScript conversion functions +var ECMAScript = (function() { + // Stash a copy in case other scripts modify these + var opts = Object.prototype.toString, + ophop = Object.prototype.hasOwnProperty; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + return { + // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues: + Class: function(v) { return opts.call(v).replace(/^\[object *|\]$/g, ''); }, + HasProperty: function(o, p) { return p in o; }, + HasOwnProperty: function(o, p) { return ophop.call(o, p); }, + IsCallable: function(o) { return typeof o === 'function'; }, + ToInt32: function(v) { return v >> 0; }, + ToUint32: function(v) { return v >>> 0; } + }; +}()); -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. +// Snapshot intrinsics +var LN2 = Math.LN2, + abs = Math.abs, + floor = Math.floor, + log = Math.log, + min = Math.min, + pow = Math.pow, + round = Math.round; -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); +// ES5: lock down object properties +function configureProperties(obj) { + if (getOwnPropNames && defineProp) { + var props = getOwnPropNames(obj), i; + for (i = 0; i < props.length; i += 1) { + defineProp(obj, props[i], { + value: obj[props[i]], + writable: false, + enumerable: false, + configurable: false + }); + } } - return objectToString(arg) === '[object Array]'; } -exports.isArray = isArray; -function isBoolean(arg) { - return typeof arg === 'boolean'; +// emulate ES5 getter/setter API using legacy APIs +// http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx +// (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but +// note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless) +var defineProp +if (Object.defineProperty && (function() { + try { + Object.defineProperty({}, 'x', {}); + return true; + } catch (e) { + return false; + } + })()) { + defineProp = Object.defineProperty; +} else { + defineProp = function(o, p, desc) { + if (!o === Object(o)) throw new TypeError("Object.defineProperty called on non-object"); + if (ECMAScript.HasProperty(desc, 'get') && Object.prototype.__defineGetter__) { Object.prototype.__defineGetter__.call(o, p, desc.get); } + if (ECMAScript.HasProperty(desc, 'set') && Object.prototype.__defineSetter__) { Object.prototype.__defineSetter__.call(o, p, desc.set); } + if (ECMAScript.HasProperty(desc, 'value')) { o[p] = desc.value; } + return o; + }; } -exports.isBoolean = isBoolean; -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; +var getOwnPropNames = Object.getOwnPropertyNames || function (o) { + if (o !== Object(o)) throw new TypeError("Object.getOwnPropertyNames called on non-object"); + var props = [], p; + for (p in o) { + if (ECMAScript.HasOwnProperty(o, p)) { + props.push(p); + } + } + return props; +}; -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; +// ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value) +// for index in 0 ... obj.length +function makeArrayAccessors(obj) { + if (!defineProp) { return; } -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; + if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill"); -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; + function makeArrayAccessor(index) { + defineProp(obj, index, { + 'get': function() { return obj._getter(index); }, + 'set': function(v) { obj._setter(index, v); }, + enumerable: true, + configurable: false + }); + } -function isSymbol(arg) { - return typeof arg === 'symbol'; + var i; + for (i = 0; i < obj.length; i += 1) { + makeArrayAccessor(i); + } } -exports.isSymbol = isSymbol; -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; +// Internal conversion functions: +// pack() - take a number (interpreted as Type), output a byte array +// unpack() - take a byte array, output a Type-like number -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; +function as_signed(value, bits) { var s = 32 - bits; return (value << s) >> s; } +function as_unsigned(value, bits) { var s = 32 - bits; return (value << s) >>> s; } -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; +function packI8(n) { return [n & 0xff]; } +function unpackI8(bytes) { return as_signed(bytes[0], 8); } -function isDate(d) { - return objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; +function packU8(n) { return [n & 0xff]; } +function unpackU8(bytes) { return as_unsigned(bytes[0], 8); } -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; +function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff]; } -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; +function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; } +function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 16); } -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; +function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; } +function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1], 16); } -exports.isBuffer = Buffer.isBuffer; +function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } +function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } -function objectToString(o) { - return Object.prototype.toString.call(o); -} +function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } +function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } +function packIEEE754(v, ebits, fbits) { -/***/ }), -/* 287 */, -/* 288 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { + var bias = (1 << (ebits - 1)) - 1, + s, e, f, ln, + i, bits, str, bytes; -"use strict"; + function roundToEven(n) { + var w = floor(n), f = n - w; + if (f < 0.5) + return w; + if (f > 0.5) + return w + 1; + return w % 2 ? w + 1 : w; + } + // Compute sign, exponent, fraction + if (v !== v) { + // NaN + // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping + e = (1 << ebits) - 1; f = pow(2, fbits - 1); s = 0; + } else if (v === Infinity || v === -Infinity) { + e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0; + } else if (v === 0) { + e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; + } else { + s = v < 0; + v = abs(v); -// Update this array if you add/rename/remove files in this directory. -// We support Browserify by skipping automatic module discovery and requiring modules directly. -var modules = [ - __webpack_require__(162), - __webpack_require__(640), - __webpack_require__(797), - __webpack_require__(645), - __webpack_require__(877), - __webpack_require__(23), - __webpack_require__(28), - __webpack_require__(189), - __webpack_require__(92), -]; + if (v >= pow(2, 1 - bias)) { + e = min(floor(log(v) / LN2), 1023); + f = roundToEven(v / pow(2, e) * pow(2, fbits)); + if (f / pow(2, fbits) >= 2) { + e = e + 1; + f = 1; + } + if (e > bias) { + // Overflow + e = (1 << ebits) - 1; + f = 0; + } else { + // Normalized + e = e + bias; + f = f - pow(2, fbits); + } + } else { + // Denormalized + e = 0; + f = roundToEven(v / pow(2, 1 - bias - fbits)); + } + } -// Put all encoding/alias/codec definitions to single object and export it. -for (var i = 0; i < modules.length; i++) { - var module = modules[i]; - for (var enc in module) - if (Object.prototype.hasOwnProperty.call(module, enc)) - exports[enc] = module[enc]; + // Pack sign, exponent, fraction + bits = []; + for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = floor(f / 2); } + for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = floor(e / 2); } + bits.push(s ? 1 : 0); + bits.reverse(); + str = bits.join(''); + + // Bits to bytes + bytes = []; + while (str.length) { + bytes.push(parseInt(str.substring(0, 8), 2)); + str = str.substring(8); + } + return bytes; } +function unpackIEEE754(bytes, ebits, fbits) { -/***/ }), -/* 289 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // Bytes to bits + var bits = [], i, j, b, str, + bias, s, e, f; -"use strict"; + for (i = bytes.length; i; i -= 1) { + b = bytes[i - 1]; + for (j = 8; j; j -= 1) { + bits.push(b % 2 ? 1 : 0); b = b >> 1; + } + } + bits.reverse(); + str = bits.join(''); + // Unpack sign, exponent, fraction + bias = (1 << (ebits - 1)) - 1; + s = parseInt(str.substring(0, 1), 2) ? -1 : 1; + e = parseInt(str.substring(1, 1 + ebits), 2); + f = parseInt(str.substring(1 + ebits), 2); -// tar -x -const hlo = __webpack_require__(29) -const Unpack = __webpack_require__(63) -const fs = __webpack_require__(747) -const fsm = __webpack_require__(827) -const path = __webpack_require__(622) + // Produce number + if (e === (1 << ebits) - 1) { + return f !== 0 ? NaN : s * Infinity; + } else if (e > 0) { + // Normalized + return s * pow(2, e - bias) * (1 + f / pow(2, fbits)); + } else if (f !== 0) { + // Denormalized + return s * pow(2, -(bias - 1)) * (f / pow(2, fbits)); + } else { + return s < 0 ? -0 : 0; + } +} -const x = module.exports = (opt_, files, cb) => { - if (typeof opt_ === 'function') - cb = opt_, files = null, opt_ = {} - else if (Array.isArray(opt_)) - files = opt_, opt_ = {} +function unpackF64(b) { return unpackIEEE754(b, 11, 52); } +function packF64(v) { return packIEEE754(v, 11, 52); } +function unpackF32(b) { return unpackIEEE754(b, 8, 23); } +function packF32(v) { return packIEEE754(v, 8, 23); } - if (typeof files === 'function') - cb = files, files = null - if (!files) - files = [] - else - files = Array.from(files) +// +// 3 The ArrayBuffer Type +// - const opt = hlo(opt_) +(function() { - if (opt.sync && typeof cb === 'function') - throw new TypeError('callback not supported for sync tar functions') + /** @constructor */ + var ArrayBuffer = function ArrayBuffer(length) { + length = ECMAScript.ToInt32(length); + if (length < 0) throw new RangeError('ArrayBuffer size is not a small enough positive integer'); - if (!opt.file && typeof cb === 'function') - throw new TypeError('callback only supported with file option') + this.byteLength = length; + this._bytes = []; + this._bytes.length = length; - if (files.length) - filesFilter(opt, files) + var i; + for (i = 0; i < this.byteLength; i += 1) { + this._bytes[i] = 0; + } - return opt.file && opt.sync ? extractFileSync(opt) - : opt.file ? extractFile(opt, cb) - : opt.sync ? extractSync(opt) - : extract(opt) -} + configureProperties(this); + }; -// construct a filter that limits the file entries listed -// include child entries if a dir is included -const filesFilter = (opt, files) => { - const map = new Map(files.map(f => [f.replace(/\/+$/, ''), true])) - const filter = opt.filter + exports.ArrayBuffer = exports.ArrayBuffer || ArrayBuffer; - const mapHas = (file, r) => { - const root = r || path.parse(file).root || '.' - const ret = file === root ? false - : map.has(file) ? map.get(file) - : mapHas(path.dirname(file), root) + // + // 4 The ArrayBufferView Type + // - map.set(file, ret) - return ret - } + // NOTE: this constructor is not exported + /** @constructor */ + var ArrayBufferView = function ArrayBufferView() { + //this.buffer = null; + //this.byteOffset = 0; + //this.byteLength = 0; + }; - opt.filter = filter - ? (file, entry) => filter(file, entry) && mapHas(file.replace(/\/+$/, '')) - : file => mapHas(file.replace(/\/+$/, '')) -} + // + // 5 The Typed Array View Types + // -const extractFileSync = opt => { - const u = new Unpack.Sync(opt) + function makeConstructor(bytesPerElement, pack, unpack) { + // Each TypedArray type requires a distinct constructor instance with + // identical logic, which this produces. - const file = opt.file - let threw = true - let fd - const stat = fs.statSync(file) - // This trades a zero-byte read() syscall for a stat - // However, it will usually result in less memory allocation - const readSize = opt.maxReadSize || 16*1024*1024 - const stream = new fsm.ReadStreamSync(file, { - readSize: readSize, - size: stat.size - }) - stream.pipe(u) -} + var ctor; + ctor = function(buffer, byteOffset, length) { + var array, sequence, i, s; -const extractFile = (opt, cb) => { - const u = new Unpack(opt) - const readSize = opt.maxReadSize || 16*1024*1024 + if (!arguments.length || typeof arguments[0] === 'number') { + // Constructor(unsigned long length) + this.length = ECMAScript.ToInt32(arguments[0]); + if (length < 0) throw new RangeError('ArrayBufferView size is not a small enough positive integer'); - const file = opt.file - const p = new Promise((resolve, reject) => { - u.on('error', reject) - u.on('close', resolve) + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer(this.byteLength); + this.byteOffset = 0; + } else if (typeof arguments[0] === 'object' && arguments[0].constructor === ctor) { + // Constructor(TypedArray array) + array = arguments[0]; - // This trades a zero-byte read() syscall for a stat - // However, it will usually result in less memory allocation - fs.stat(file, (er, stat) => { - if (er) - reject(er) - else { - const stream = new fsm.ReadStream(file, { - readSize: readSize, - size: stat.size - }) - stream.on('error', reject) - stream.pipe(u) - } - }) - }) - return cb ? p.then(cb, cb) : p -} + this.length = array.length; + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer(this.byteLength); + this.byteOffset = 0; -const extractSync = opt => { - return new Unpack.Sync(opt) -} + for (i = 0; i < this.length; i += 1) { + this._setter(i, array._getter(i)); + } + } else if (typeof arguments[0] === 'object' && + !(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { + // Constructor(sequence array) + sequence = arguments[0]; -const extract = opt => { - return new Unpack(opt) -} + this.length = ECMAScript.ToUint32(sequence.length); + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer(this.byteLength); + this.byteOffset = 0; + for (i = 0; i < this.length; i += 1) { + s = sequence[i]; + this._setter(i, Number(s)); + } + } else if (typeof arguments[0] === 'object' && + (arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { + // Constructor(ArrayBuffer buffer, + // optional unsigned long byteOffset, optional unsigned long length) + this.buffer = buffer; -/***/ }), -/* 290 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + this.byteOffset = ECMAScript.ToUint32(byteOffset); + if (this.byteOffset > this.buffer.byteLength) { + throw new RangeError("byteOffset out of range"); + } -"use strict"; + if (this.byteOffset % this.BYTES_PER_ELEMENT) { + // The given byteOffset must be a multiple of the element + // size of the specific type, otherwise an exception is raised. + throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size."); + } + if (arguments.length < 3) { + this.byteLength = this.buffer.byteLength - this.byteOffset; -module.exports = __webpack_require__(305) + if (this.byteLength % this.BYTES_PER_ELEMENT) { + throw new RangeError("length of buffer minus byteOffset not a multiple of the element size"); + } + this.length = this.byteLength / this.BYTES_PER_ELEMENT; + } else { + this.length = ECMAScript.ToUint32(length); + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + } + if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) { + throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); + } + } else { + throw new TypeError("Unexpected argument type(s)"); + } -/***/ }), -/* 291 */, -/* 292 */, -/* 293 */ -/***/ (function(module) { + this.constructor = ctor; -module.exports = require("buffer"); + configureProperties(this); + makeArrayAccessors(this); + }; -/***/ }), -/* 294 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + ctor.prototype = new ArrayBufferView(); + ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement; + ctor.prototype._pack = pack; + ctor.prototype._unpack = unpack; + ctor.BYTES_PER_ELEMENT = bytesPerElement; -"use strict"; + // getter type (unsigned long index); + ctor.prototype._getter = function(index) { + if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); -const fs = __webpack_require__(747); + index = ECMAScript.ToUint32(index); + if (index >= this.length) { + return undefined; + } -module.exports = fp => new Promise(resolve => { - fs.access(fp, err => { - resolve(!err); - }); -}); + var bytes = [], i, o; + for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; + i < this.BYTES_PER_ELEMENT; + i += 1, o += 1) { + bytes.push(this.buffer._bytes[o]); + } + return this._unpack(bytes); + }; -module.exports.sync = fp => { - try { - fs.accessSync(fp); - return true; - } catch (err) { - return false; - } -}; + // NONSTANDARD: convenience alias for getter: type get(unsigned long index); + ctor.prototype.get = ctor.prototype._getter; + // setter void (unsigned long index, type value); + ctor.prototype._setter = function(index, value) { + if (arguments.length < 2) throw new SyntaxError("Not enough arguments"); -/***/ }), -/* 295 */, -/* 296 */, -/* 297 */, -/* 298 */, -/* 299 */ -/***/ (function(module) { + index = ECMAScript.ToUint32(index); + if (index >= this.length) { + return undefined; + } -module.exports = function (blocking) { - [process.stdout, process.stderr].forEach(function (stream) { - if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === 'function') { - stream._handle.setBlocking(blocking) - } - }) -} + var bytes = this._pack(value), i, o; + for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; + i < this.BYTES_PER_ELEMENT; + i += 1, o += 1) { + this.buffer._bytes[o] = bytes[i]; + } + }; + // void set(TypedArray array, optional unsigned long offset); + // void set(sequence array, optional unsigned long offset); + ctor.prototype.set = function(index, value) { + if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); + var array, sequence, offset, len, + i, s, d, + byteOffset, byteLength, tmp; -/***/ }), -/* 300 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) { + // void set(TypedArray array, optional unsigned long offset); + array = arguments[0]; + offset = ECMAScript.ToUint32(arguments[1]); -"use strict"; + if (offset + array.length > this.length) { + throw new RangeError("Offset plus length of array is out of range"); + } -var consoleControl = __webpack_require__(920) -var ThemeSet = __webpack_require__(625) + byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT; + byteLength = array.length * this.BYTES_PER_ELEMENT; -var themes = module.exports = new ThemeSet() + if (array.buffer === this.buffer) { + tmp = []; + for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) { + tmp[i] = array.buffer._bytes[s]; + } + for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) { + this.buffer._bytes[d] = tmp[i]; + } + } else { + for (i = 0, s = array.byteOffset, d = byteOffset; + i < byteLength; i += 1, s += 1, d += 1) { + this.buffer._bytes[d] = array.buffer._bytes[s]; + } + } + } else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') { + // void set(sequence array, optional unsigned long offset); + sequence = arguments[0]; + len = ECMAScript.ToUint32(sequence.length); + offset = ECMAScript.ToUint32(arguments[1]); -themes.addTheme('ASCII', { - preProgressbar: '[', - postProgressbar: ']', - progressbarTheme: { - complete: '#', - remaining: '.' - }, - activityIndicatorTheme: '-\\|/', - preSubsection: '>' -}) + if (offset + len > this.length) { + throw new RangeError("Offset plus length of array is out of range"); + } -themes.addTheme('colorASCII', themes.getTheme('ASCII'), { - progressbarTheme: { - preComplete: consoleControl.color('inverse'), - complete: ' ', - postComplete: consoleControl.color('stopInverse'), - preRemaining: consoleControl.color('brightBlack'), - remaining: '.', - postRemaining: consoleControl.color('reset') - } -}) + for (i = 0; i < len; i += 1) { + s = sequence[i]; + this._setter(offset + i, Number(s)); + } + } else { + throw new TypeError("Unexpected argument type(s)"); + } + }; -themes.addTheme('brailleSpinner', { - preProgressbar: '⸨', - postProgressbar: '⸩', - progressbarTheme: { - complete: '░', - remaining: '⠂' - }, - activityIndicatorTheme: '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏', - preSubsection: '>' -}) + // TypedArray subarray(long begin, optional long end); + ctor.prototype.subarray = function(start, end) { + function clamp(v, min, max) { return v < min ? min : v > max ? max : v; } -themes.addTheme('colorBrailleSpinner', themes.getTheme('brailleSpinner'), { - progressbarTheme: { - preComplete: consoleControl.color('inverse'), - complete: ' ', - postComplete: consoleControl.color('stopInverse'), - preRemaining: consoleControl.color('brightBlack'), - remaining: '░', - postRemaining: consoleControl.color('reset') - } -}) + start = ECMAScript.ToInt32(start); + end = ECMAScript.ToInt32(end); -themes.setDefault({}, 'ASCII') -themes.setDefault({hasColor: true}, 'colorASCII') -themes.setDefault({platform: 'darwin', hasUnicode: true}, 'brailleSpinner') -themes.setDefault({platform: 'darwin', hasUnicode: true, hasColor: true}, 'colorBrailleSpinner') + if (arguments.length < 1) { start = 0; } + if (arguments.length < 2) { end = this.length; } + if (start < 0) { start = this.length + start; } + if (end < 0) { end = this.length + end; } -/***/ }), -/* 301 */, -/* 302 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + start = clamp(start, 0, this.length); + end = clamp(end, 0, this.length); -module.exports = realpath -realpath.realpath = realpath -realpath.sync = realpathSync -realpath.realpathSync = realpathSync -realpath.monkeypatch = monkeypatch -realpath.unmonkeypatch = unmonkeypatch + var len = end - start; + if (len < 0) { + len = 0; + } -var fs = __webpack_require__(747) -var origRealpath = fs.realpath -var origRealpathSync = fs.realpathSync + return new this.constructor( + this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len); + }; -var version = process.version -var ok = /^v[0-5]\./.test(version) -var old = __webpack_require__(117) + return ctor; + } -function newError (er) { - return er && er.syscall === 'realpath' && ( - er.code === 'ELOOP' || - er.code === 'ENOMEM' || - er.code === 'ENAMETOOLONG' - ) -} + var Int8Array = makeConstructor(1, packI8, unpackI8); + var Uint8Array = makeConstructor(1, packU8, unpackU8); + var Uint8ClampedArray = makeConstructor(1, packU8Clamped, unpackU8); + var Int16Array = makeConstructor(2, packI16, unpackI16); + var Uint16Array = makeConstructor(2, packU16, unpackU16); + var Int32Array = makeConstructor(4, packI32, unpackI32); + var Uint32Array = makeConstructor(4, packU32, unpackU32); + var Float32Array = makeConstructor(4, packF32, unpackF32); + var Float64Array = makeConstructor(8, packF64, unpackF64); -function realpath (p, cache, cb) { - if (ok) { - return origRealpath(p, cache, cb) - } + exports.Int8Array = exports.Int8Array || Int8Array; + exports.Uint8Array = exports.Uint8Array || Uint8Array; + exports.Uint8ClampedArray = exports.Uint8ClampedArray || Uint8ClampedArray; + exports.Int16Array = exports.Int16Array || Int16Array; + exports.Uint16Array = exports.Uint16Array || Uint16Array; + exports.Int32Array = exports.Int32Array || Int32Array; + exports.Uint32Array = exports.Uint32Array || Uint32Array; + exports.Float32Array = exports.Float32Array || Float32Array; + exports.Float64Array = exports.Float64Array || Float64Array; +}()); - if (typeof cache === 'function') { - cb = cache - cache = null +// +// 6 The DataView View Type +// + +(function() { + function r(array, index) { + return ECMAScript.IsCallable(array.get) ? array.get(index) : array[index]; } - origRealpath(p, cache, function (er, result) { - if (newError(er)) { - old.realpath(p, cache, cb) - } else { - cb(er, result) + + var IS_BIG_ENDIAN = (function() { + var u16array = new(exports.Uint16Array)([0x1234]), + u8array = new(exports.Uint8Array)(u16array.buffer); + return r(u8array, 0) === 0x12; + }()); + + // Constructor(ArrayBuffer buffer, + // optional unsigned long byteOffset, + // optional unsigned long byteLength) + /** @constructor */ + var DataView = function DataView(buffer, byteOffset, byteLength) { + if (arguments.length === 0) { + buffer = new exports.ArrayBuffer(0); + } else if (!(buffer instanceof exports.ArrayBuffer || ECMAScript.Class(buffer) === 'ArrayBuffer')) { + throw new TypeError("TypeError"); } - }) -} -function realpathSync (p, cache) { - if (ok) { - return origRealpathSync(p, cache) - } + this.buffer = buffer || new exports.ArrayBuffer(0); - try { - return origRealpathSync(p, cache) - } catch (er) { - if (newError(er)) { - return old.realpathSync(p, cache) + this.byteOffset = ECMAScript.ToUint32(byteOffset); + if (this.byteOffset > this.buffer.byteLength) { + throw new RangeError("byteOffset out of range"); + } + + if (arguments.length < 3) { + this.byteLength = this.buffer.byteLength - this.byteOffset; } else { - throw er + this.byteLength = ECMAScript.ToUint32(byteLength); + } + + if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) { + throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); } + + configureProperties(this); + }; + + function makeGetter(arrayType) { + return function(byteOffset, littleEndian) { + + byteOffset = ECMAScript.ToUint32(byteOffset); + + if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { + throw new RangeError("Array index out of range"); + } + byteOffset += this.byteOffset; + + var uint8Array = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT), + bytes = [], i; + for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { + bytes.push(r(uint8Array, i)); + } + + if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { + bytes.reverse(); + } + + return r(new arrayType(new exports.Uint8Array(bytes).buffer), 0); + }; } -} -function monkeypatch () { - fs.realpath = realpath - fs.realpathSync = realpathSync -} + DataView.prototype.getUint8 = makeGetter(exports.Uint8Array); + DataView.prototype.getInt8 = makeGetter(exports.Int8Array); + DataView.prototype.getUint16 = makeGetter(exports.Uint16Array); + DataView.prototype.getInt16 = makeGetter(exports.Int16Array); + DataView.prototype.getUint32 = makeGetter(exports.Uint32Array); + DataView.prototype.getInt32 = makeGetter(exports.Int32Array); + DataView.prototype.getFloat32 = makeGetter(exports.Float32Array); + DataView.prototype.getFloat64 = makeGetter(exports.Float64Array); -function unmonkeypatch () { - fs.realpath = origRealpath - fs.realpathSync = origRealpathSync -} + function makeSetter(arrayType) { + return function(byteOffset, value, littleEndian) { + byteOffset = ECMAScript.ToUint32(byteOffset); + if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { + throw new RangeError("Array index out of range"); + } -/***/ }), -/* 303 */ -/***/ (function(module) { + // Get bytes + var typeArray = new arrayType([value]), + byteArray = new exports.Uint8Array(typeArray.buffer), + bytes = [], i, byteView; -module.exports = require("async_hooks"); + for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { + bytes.push(r(byteArray, i)); + } -/***/ }), -/* 304 */ -/***/ (function(module) { + // Flip if necessary + if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { + bytes.reverse(); + } + + // Write them + byteView = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT); + byteView.set(bytes); + }; + } + + DataView.prototype.setUint8 = makeSetter(exports.Uint8Array); + DataView.prototype.setInt8 = makeSetter(exports.Int8Array); + DataView.prototype.setUint16 = makeSetter(exports.Uint16Array); + DataView.prototype.setInt16 = makeSetter(exports.Int16Array); + DataView.prototype.setUint32 = makeSetter(exports.Uint32Array); + DataView.prototype.setInt32 = makeSetter(exports.Int32Array); + DataView.prototype.setFloat32 = makeSetter(exports.Float32Array); + DataView.prototype.setFloat64 = makeSetter(exports.Float64Array); + + exports.DataView = exports.DataView || DataView; + +}()); -module.exports = require("string_decoder"); /***/ }), -/* 305 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 318 */ +/***/ (function(__unusedmodule, exports) { "use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=BatchObserverResult.js.map -const BB = __webpack_require__(440) - -const contentPath = __webpack_require__(969) -const figgyPudding = __webpack_require__(122) -const finished = BB.promisify(__webpack_require__(371).finished) -const fixOwner = __webpack_require__(133) -const fs = __webpack_require__(598) -const glob = BB.promisify(__webpack_require__(402)) -const index = __webpack_require__(407) -const path = __webpack_require__(622) -const rimraf = BB.promisify(__webpack_require__(503)) -const ssri = __webpack_require__(951) +/***/ }), +/* 319 */, +/* 320 */, +/* 321 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -BB.promisifyAll(fs) +"use strict"; -const VerifyOpts = figgyPudding({ - concurrency: { - default: 20 - }, - filter: {}, - log: { - default: { silly () {} } - } -}) +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = __webpack_require__(248); +var isObject = util.isObject; +var es5 = __webpack_require__(883); +var Es6Map; +if (typeof Map === "function") Es6Map = Map; -module.exports = verify -function verify (cache, opts) { - opts = VerifyOpts(opts) - opts.log.silly('verify', 'verifying cache at', cache) - return BB.reduce([ - markStartTime, - fixPerms, - garbageCollect, - rebuildIndex, - cleanTmp, - writeVerifile, - markEndTime - ], (stats, step, i) => { - const label = step.name || `step #${i}` - const start = new Date() - return BB.resolve(step(cache, opts)).then(s => { - s && Object.keys(s).forEach(k => { - stats[k] = s[k] - }) - const end = new Date() - if (!stats.runTime) { stats.runTime = {} } - stats.runTime[label] = end - start - return stats - }) - }, {}).tap(stats => { - stats.runTime.total = stats.endTime - stats.startTime - opts.log.silly('verify', 'verification finished for', cache, 'in', `${stats.runTime.total}ms`) - }) -} +var mapToEntries = (function() { + var index = 0; + var size = 0; -function markStartTime (cache, opts) { - return { startTime: new Date() } -} + function extractEntry(value, key) { + this[index] = value; + this[index + size] = key; + index++; + } -function markEndTime (cache, opts) { - return { endTime: new Date() } -} + return function mapToEntries(map) { + size = map.size; + index = 0; + var ret = new Array(map.size * 2); + map.forEach(extractEntry, ret); + return ret; + }; +})(); -function fixPerms (cache, opts) { - opts.log.silly('verify', 'fixing cache permissions') - return fixOwner.mkdirfix(cache, cache).then(() => { - // TODO - fix file permissions too - return fixOwner.chownr(cache, cache) - }).then(() => null) -} +var entriesToMap = function(entries) { + var ret = new Es6Map(); + var length = entries.length / 2 | 0; + for (var i = 0; i < length; ++i) { + var key = entries[length + i]; + var value = entries[i]; + ret.set(key, value); + } + return ret; +}; -// Implements a naive mark-and-sweep tracing garbage collector. -// -// The algorithm is basically as follows: -// 1. Read (and filter) all index entries ("pointers") -// 2. Mark each integrity value as "live" -// 3. Read entire filesystem tree in `content-vX/` dir -// 4. If content is live, verify its checksum and delete it if it fails -// 5. If content is not marked as live, rimraf it. -// -function garbageCollect (cache, opts) { - opts.log.silly('verify', 'garbage collecting content') - const indexStream = index.lsStream(cache) - const liveContent = new Set() - indexStream.on('data', entry => { - if (opts.filter && !opts.filter(entry)) { return } - liveContent.add(entry.integrity.toString()) - }) - return finished(indexStream).then(() => { - const contentDir = contentPath._contentDir(cache) - return glob(path.join(contentDir, '**'), { - follow: false, - nodir: true, - nosort: true - }).then(files => { - return BB.resolve({ - verifiedContent: 0, - reclaimedCount: 0, - reclaimedSize: 0, - badContentCount: 0, - keptSize: 0 - }).tap((stats) => BB.map(files, (f) => { - const split = f.split(/[/\\]/) - const digest = split.slice(split.length - 3).join('') - const algo = split[split.length - 4] - const integrity = ssri.fromHex(digest, algo) - if (liveContent.has(integrity.toString())) { - return verifyContent(f, integrity).then(info => { - if (!info.valid) { - stats.reclaimedCount++ - stats.badContentCount++ - stats.reclaimedSize += info.size - } else { - stats.verifiedContent++ - stats.keptSize += info.size - } - return stats - }) - } else { - // No entries refer to this content. We can delete. - stats.reclaimedCount++ - return fs.statAsync(f).then(s => { - return rimraf(f).then(() => { - stats.reclaimedSize += s.size - return stats - }) - }) +function PropertiesPromiseArray(obj) { + var isMap = false; + var entries; + if (Es6Map !== undefined && obj instanceof Es6Map) { + entries = mapToEntries(obj); + isMap = true; + } else { + var keys = es5.keys(obj); + var len = keys.length; + entries = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + entries[i] = obj[key]; + entries[i + len] = key; } - }, { concurrency: opts.concurrency })) - }) - }) -} - -function verifyContent (filepath, sri) { - return fs.statAsync(filepath).then(stat => { - const contentInfo = { - size: stat.size, - valid: true } - return ssri.checkStream( - fs.createReadStream(filepath), - sri - ).catch(err => { - if (err.code !== 'EINTEGRITY') { throw err } - return rimraf(filepath).then(() => { - contentInfo.valid = false - }) - }).then(() => contentInfo) - }).catch({ code: 'ENOENT' }, () => ({ size: 0, valid: false })) + this.constructor$(entries); + this._isMap = isMap; + this._init$(undefined, isMap ? -6 : -3); } +util.inherits(PropertiesPromiseArray, PromiseArray); -function rebuildIndex (cache, opts) { - opts.log.silly('verify', 'rebuilding index') - return index.ls(cache).then(entries => { - const stats = { - missingContent: 0, - rejectedEntries: 0, - totalEntries: 0 - } - const buckets = {} - for (let k in entries) { - if (entries.hasOwnProperty(k)) { - const hashed = index._hashKey(k) - const entry = entries[k] - const excluded = opts.filter && !opts.filter(entry) - excluded && stats.rejectedEntries++ - if (buckets[hashed] && !excluded) { - buckets[hashed].push(entry) - } else if (buckets[hashed] && excluded) { - // skip - } else if (excluded) { - buckets[hashed] = [] - buckets[hashed]._path = index._bucketPath(cache, k) +PropertiesPromiseArray.prototype._init = function () {}; + +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + var val; + if (this._isMap) { + val = entriesToMap(this._values); } else { - buckets[hashed] = [entry] - buckets[hashed]._path = index._bucketPath(cache, k) + val = {}; + var keyOffset = this.length(); + for (var i = 0, len = this.length(); i < len; ++i) { + val[this._values[i + keyOffset]] = this._values[i]; + } } - } + this._resolve(val); + return true; } - return BB.map(Object.keys(buckets), key => { - return rebuildBucket(cache, buckets[key], stats, opts) - }, { concurrency: opts.concurrency }).then(() => stats) - }) -} + return false; +}; -function rebuildBucket (cache, bucket, stats, opts) { - return fs.truncateAsync(bucket._path).then(() => { - // This needs to be serialized because cacache explicitly - // lets very racy bucket conflicts clobber each other. - return BB.mapSeries(bucket, entry => { - const content = contentPath(cache, entry.integrity) - return fs.statAsync(content).then(() => { - return index.insert(cache, entry.key, entry.integrity, { - metadata: entry.metadata, - size: entry.size - }).then(() => { stats.totalEntries++ }) - }).catch({ code: 'ENOENT' }, () => { - stats.rejectedEntries++ - stats.missingContent++ - }) - }) - }) -} +PropertiesPromiseArray.prototype.shouldCopyValues = function () { + return false; +}; -function cleanTmp (cache, opts) { - opts.log.silly('verify', 'cleaning tmp directory') - return rimraf(path.join(cache, 'tmp')) -} +PropertiesPromiseArray.prototype.getActualLength = function (len) { + return len >> 1; +}; -function writeVerifile (cache, opts) { - const verifile = path.join(cache, '_lastverified') - opts.log.silly('verify', 'writing verifile to ' + verifile) - try { - return fs.writeFileAsync(verifile, '' + (+(new Date()))) - } finally { - fixOwner.chownr.sync(cache, verifile) - } -} +function props(promises) { + var ret; + var castValue = tryConvertToPromise(promises); -module.exports.lastRun = lastRun -function lastRun (cache) { - return fs.readFileAsync( - path.join(cache, '_lastverified'), 'utf8' - ).then(data => new Date(+data)) + if (!isObject(castValue)) { + return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } else if (castValue instanceof Promise) { + ret = castValue._then( + Promise.props, undefined, undefined, undefined, undefined); + } else { + ret = new PropertiesPromiseArray(castValue).promise(); + } + + if (castValue instanceof Promise) { + ret._propagateFrom(castValue, 2); + } + return ret; } +Promise.prototype.props = function () { + return props(this); +}; + +Promise.props = function (promises) { + return props(promises); +}; +}; + /***/ }), -/* 306 */ +/* 322 */, +/* 323 */ /***/ (function(module, __unusedexports, __webpack_require__) { -var concatMap = __webpack_require__(896); -var balanced = __webpack_require__(621); - -module.exports = expandTop; +"use strict"; -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; - -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = __webpack_require__(248); +var RangeError = __webpack_require__(351).RangeError; +var AggregateError = __webpack_require__(351).AggregateError; +var isArray = util.isArray; +var CANCELLATION = {}; -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); +function SomePromiseArray(values) { + this.constructor$(values); + this._howMany = 0; + this._unwrap = false; + this._initialized = false; } +util.inherits(SomePromiseArray, PromiseArray); +SomePromiseArray.prototype._init = function () { + if (!this._initialized) { + return; + } + if (this._howMany === 0) { + this._resolve([]); + return; + } + this._init$(undefined, -5); + var isArrayResolved = isArray(this._values); + if (!this._isResolved() && + isArrayResolved && + this._howMany > this._canPossiblyFulfill()) { + this._reject(this._getRangeError(this.length())); + } +}; -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; - - var parts = []; - var m = balanced('{', '}', str); +SomePromiseArray.prototype.init = function () { + this._initialized = true; + this._init(); +}; - if (!m) - return str.split(','); +SomePromiseArray.prototype.setUnwrap = function () { + this._unwrap = true; +}; - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); +SomePromiseArray.prototype.howMany = function () { + return this._howMany; +}; - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); - } +SomePromiseArray.prototype.setHowMany = function (count) { + this._howMany = count; +}; - parts.push.apply(parts, p); +SomePromiseArray.prototype._promiseFulfilled = function (value) { + this._addFulfilled(value); + if (this._fulfilled() === this.howMany()) { + this._values.length = this.howMany(); + if (this.howMany() === 1 && this._unwrap) { + this._resolve(this._values[0]); + } else { + this._resolve(this._values); + } + return true; + } + return false; - return parts; -} +}; +SomePromiseArray.prototype._promiseRejected = function (reason) { + this._addRejected(reason); + return this._checkOutcome(); +}; -function expandTop(str) { - if (!str) - return []; +SomePromiseArray.prototype._promiseCancelled = function () { + if (this._values instanceof Promise || this._values == null) { + return this._cancel(); + } + this._addRejected(CANCELLATION); + return this._checkOutcome(); +}; - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); - } +SomePromiseArray.prototype._checkOutcome = function() { + if (this.howMany() > this._canPossiblyFulfill()) { + var e = new AggregateError(); + for (var i = this.length(); i < this._values.length; ++i) { + if (this._values[i] !== CANCELLATION) { + e.push(this._values[i]); + } + } + if (e.length > 0) { + this._reject(e); + } else { + this._cancel(); + } + return true; + } + return false; +}; - return expand(escapeBraces(str), true).map(unescapeBraces); -} +SomePromiseArray.prototype._fulfilled = function () { + return this._totalResolved; +}; -function identity(e) { - return e; -} +SomePromiseArray.prototype._rejected = function () { + return this._values.length - this.length(); +}; -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} +SomePromiseArray.prototype._addRejected = function (reason) { + this._values.push(reason); +}; -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} +SomePromiseArray.prototype._addFulfilled = function (value) { + this._values[this._totalResolved++] = value; +}; -function expand(str, isTop) { - var expansions = []; +SomePromiseArray.prototype._canPossiblyFulfill = function () { + return this.length() - this._rejected(); +}; - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; +SomePromiseArray.prototype._getRangeError = function (count) { + var message = "Input array must contain at least " + + this._howMany + " items but contains only " + count + " items"; + return new RangeError(message); +}; - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; - } +SomePromiseArray.prototype._resolveEmptyArray = function () { + this._reject(this._getRangeError(0)); +}; - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } +function some(promises, howMany) { + if ((howMany | 0) !== howMany || howMany < 0) { + return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } - } + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(howMany); + ret.init(); + return promise; +} - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. +Promise.some = function (promises, howMany) { + return some(promises, howMany); +}; - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; +Promise.prototype.some = function (howMany) { + return some(this, howMany); +}; - var N; +Promise._SomePromiseArray = SomePromiseArray; +}; - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); - N = []; +/***/ }), +/* 324 */, +/* 325 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } - } - N.push(c); - } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(__webpack_require__(470)); +const run_1 = __webpack_require__(180); +run_1.run().catch(core.setFailed); - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } - } - return expansions; -} +/***/ }), +/* 326 */ +/***/ (function(__unusedmodule, exports) { +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ObserverResult.js.map /***/ }), -/* 307 */, -/* 308 */, -/* 309 */, -/* 310 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 327 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); /** - * Module dependencies. + * Indicates whether a pattern matches a path */ +var MatchKind; +(function (MatchKind) { + /** Not matched */ + MatchKind[MatchKind["None"] = 0] = "None"; + /** Matched if the path is a directory */ + MatchKind[MatchKind["Directory"] = 1] = "Directory"; + /** Matched if the path is a regular file */ + MatchKind[MatchKind["File"] = 2] = "File"; + /** Matched */ + MatchKind[MatchKind["All"] = 3] = "All"; +})(MatchKind = exports.MatchKind || (exports.MatchKind = {})); +//# sourceMappingURL=internal-match-kind.js.map -var tls; // lazy-loaded... -var url = __webpack_require__(835); -var dns = __webpack_require__(881); -var Agent = __webpack_require__(234); -var SocksClient = __webpack_require__(198).SocksClient; -var inherits = __webpack_require__(669).inherits; +/***/ }), +/* 328 */, +/* 329 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -/** - * Module exports. - */ +"use strict"; -module.exports = SocksProxyAgent; +const stripAnsi = __webpack_require__(569); +const isFullwidthCodePoint = __webpack_require__(363); -/** - * The `SocksProxyAgent`. - * - * @api public - */ +module.exports = str => { + if (typeof str !== 'string' || str.length === 0) { + return 0; + } -function SocksProxyAgent(opts) { - if (!(this instanceof SocksProxyAgent)) return new SocksProxyAgent(opts); - if ('string' == typeof opts) opts = url.parse(opts); - if (!opts) - throw new Error( - 'a SOCKS proxy server `host` and `port` must be specified!' - ); - Agent.call(this, opts); + str = stripAnsi(str); - var proxy = Object.assign({}, opts); + let width = 0; - // prefer `hostname` over `host`, because of `url.parse()` - proxy.host = proxy.hostname || proxy.host; + for (let i = 0; i < str.length; i++) { + const code = str.codePointAt(i); - // SOCKS doesn't *technically* have a default port, but this is - // the same default that `curl(1)` uses - proxy.port = +proxy.port || 1080; + // Ignore control characters + if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { + continue; + } - if (proxy.host && proxy.path) { - // if both a `host` and `path` are specified then it's most likely the - // result of a `url.parse()` call... we need to remove the `path` portion so - // that `net.connect()` doesn't attempt to open that as a unix socket file. - delete proxy.path; - delete proxy.pathname; - } + // Ignore combining characters + if (code >= 0x300 && code <= 0x36F) { + continue; + } - // figure out if we want socks v4 or v5, based on the "protocol" used. - // Defaults to 5. - proxy.lookup = false; - switch (proxy.protocol) { - case 'socks4:': - proxy.lookup = true; - // pass through - case 'socks4a:': - proxy.version = 4; - break; - case 'socks5:': - proxy.lookup = true; - // pass through - case 'socks:': // no version specified, default to 5h - case 'socks5h:': - proxy.version = 5; - break; - default: - throw new TypeError( - 'A "socks" protocol must be specified! Got: ' + proxy.protocol - ); - } + // Surrogates + if (code > 0xFFFF) { + i++; + } - if (proxy.auth) { - var auth = proxy.auth.split(':'); - proxy.authentication = { username: auth[0], password: auth[1] }; - proxy.userid = auth[0]; - } - this.proxy = proxy; -} -inherits(SocksProxyAgent, Agent); + width += isFullwidthCodePoint(code) ? 2 : 1; + } -/** - * Initiates a SOCKS connection to the specified SOCKS proxy server, - * which in turn connects to the specified remote host and port. + return width; +}; + + +/***/ }), +/* 330 */, +/* 331 */, +/* 332 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. * - * @api public + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. */ -SocksProxyAgent.prototype.callback = function connect(req, opts, fn) { - var proxy = this.proxy; +const { fromCallback } = __webpack_require__(147); +const Store = __webpack_require__(338).Store; +const permuteDomain = __webpack_require__(89).permuteDomain; +const pathMatch = __webpack_require__(348).pathMatch; +const util = __webpack_require__(669); - // called once the SOCKS proxy has connected to the specified remote endpoint - function onhostconnect(err, result) { - if (err) return fn(err); +class MemoryCookieStore extends Store { + constructor() { + super(); + this.synchronous = true; + this.idx = {}; + if (util.inspect.custom) { + this[util.inspect.custom] = this.inspect; + } + } - var socket = result.socket; + inspect() { + return `{ idx: ${util.inspect(this.idx, false, 2)} }`; + } - var s = socket; - if (opts.secureEndpoint) { - // since the proxy is connecting to an SSL server, we have - // to upgrade this socket connection to an SSL connection - if (!tls) tls = __webpack_require__(16); - opts.socket = socket; - opts.servername = opts.host; - opts.host = null; - opts.hostname = null; - opts.port = null; - s = tls.connect(opts); + findCookie(domain, path, key, cb) { + if (!this.idx[domain]) { + return cb(null, undefined); + } + if (!this.idx[domain][path]) { + return cb(null, undefined); + } + return cb(null, this.idx[domain][path][key] || null); + } + findCookies(domain, path, allowSpecialUseDomain, cb) { + const results = []; + if (typeof allowSpecialUseDomain === "function") { + cb = allowSpecialUseDomain; + allowSpecialUseDomain = false; + } + if (!domain) { + return cb(null, []); } - fn(null, s); + let pathMatcher; + if (!path) { + // null means "all paths" + pathMatcher = function matchAll(domainIndex) { + for (const curPath in domainIndex) { + const pathIndex = domainIndex[curPath]; + for (const key in pathIndex) { + results.push(pathIndex[key]); + } + } + }; + } else { + pathMatcher = function matchRFC(domainIndex) { + //NOTE: we should use path-match algorithm from S5.1.4 here + //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299) + Object.keys(domainIndex).forEach(cookiePath => { + if (pathMatch(path, cookiePath)) { + const pathIndex = domainIndex[cookiePath]; + for (const key in pathIndex) { + results.push(pathIndex[key]); + } + } + }); + }; + } + + const domains = permuteDomain(domain, allowSpecialUseDomain) || [domain]; + const idx = this.idx; + domains.forEach(curDomain => { + const domainIndex = idx[curDomain]; + if (!domainIndex) { + return; + } + pathMatcher(domainIndex); + }); + + cb(null, results); } - // called for the `dns.lookup()` callback - function onlookup(err, ip) { - if (err) return fn(err); - options.destination.host = ip; - SocksClient.createConnection(options, onhostconnect); + putCookie(cookie, cb) { + if (!this.idx[cookie.domain]) { + this.idx[cookie.domain] = {}; + } + if (!this.idx[cookie.domain][cookie.path]) { + this.idx[cookie.domain][cookie.path] = {}; + } + this.idx[cookie.domain][cookie.path][cookie.key] = cookie; + cb(null); + } + updateCookie(oldCookie, newCookie, cb) { + // updateCookie() may avoid updating cookies that are identical. For example, + // lastAccessed may not be important to some stores and an equality + // comparison could exclude that field. + this.putCookie(newCookie, cb); + } + removeCookie(domain, path, key, cb) { + if ( + this.idx[domain] && + this.idx[domain][path] && + this.idx[domain][path][key] + ) { + delete this.idx[domain][path][key]; + } + cb(null); + } + removeCookies(domain, path, cb) { + if (this.idx[domain]) { + if (path) { + delete this.idx[domain][path]; + } else { + delete this.idx[domain]; + } + } + return cb(null); } + removeAllCookies(cb) { + this.idx = {}; + return cb(null); + } + getAllCookies(cb) { + const cookies = []; + const idx = this.idx; - var options = { - proxy: { - ipaddress: proxy.host, - port: +proxy.port, - type: proxy.version - }, - destination: { - port: +opts.port - }, - command: 'connect' - }; + const domains = Object.keys(idx); + domains.forEach(domain => { + const paths = Object.keys(idx[domain]); + paths.forEach(path => { + const keys = Object.keys(idx[domain][path]); + keys.forEach(key => { + if (key !== null) { + cookies.push(idx[domain][path][key]); + } + }); + }); + }); - if (proxy.authentication) { - options.proxy.userId = proxy.userid; - options.proxy.password = proxy.authentication.password; - } + // Sort by creationIndex so deserializing retains the creation order. + // When implementing your own store, this SHOULD retain the order too + cookies.sort((a, b) => { + return (a.creationIndex || 0) - (b.creationIndex || 0); + }); - if (proxy.lookup) { - // client-side DNS resolution for "4" and "5" socks proxy versions - dns.lookup(opts.host, onlookup); - } else { - // proxy hostname DNS resolution for "4a" and "5h" socks proxy servers - onlookup(null, opts.host); + cb(null, cookies); } } +[ + "findCookie", + "findCookies", + "putCookie", + "updateCookie", + "removeCookie", + "removeCookies", + "removeAllCookies", + "getAllCookies" +].forEach(name => { + MemoryCookieStore[name] = fromCallback(MemoryCookieStore.prototype[name]); +}); -/***/ }), -/* 311 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +exports.MemoryCookieStore = MemoryCookieStore; -const rm = __webpack_require__(570) -const link = __webpack_require__(21) -const mkdir = __webpack_require__(521) -const binLink = __webpack_require__(834) +/***/ }), +/* 333 */, +/* 334 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -exports = module.exports = { - rm: rm, - link: link.link, - linkIfExists: link.linkIfExists, - mkdir: mkdir, - binLink: binLink -} +module.exports = +{ + parallel : __webpack_require__(424), + serial : __webpack_require__(91), + serialOrdered : __webpack_require__(892) +}; /***/ }), -/* 312 */ +/* 335 */, +/* 336 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +var MurmurHash3 = __webpack_require__(188) -var errcode = __webpack_require__(120); -var retry = __webpack_require__(560); - -var hasOwn = Object.prototype.hasOwnProperty; - -function isRetryError(err) { - return err && err.code === 'EPROMISERETRY' && hasOwn.call(err, 'retried'); +module.exports = function (uniq) { + if (uniq) { + var hash = new MurmurHash3(uniq) + return ('00000000' + hash.result().toString(16)).substr(-8) + } else { + return (Math.random().toString(16) + '0000000').substr(2, 8) + } } -function promiseRetry(fn, options) { - var temp; - var operation; - if (typeof fn === 'object' && typeof options === 'function') { - // Swap options and fn when using alternate signature (options, fn) - temp = options; - options = fn; - fn = temp; - } +/***/ }), +/* 337 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - operation = retry.operation(options); +"use strict"; +/*! + * humanize-ms - index.js + * Copyright(c) 2014 dead_horse + * MIT Licensed + */ - return new Promise(function (resolve, reject) { - operation.attempt(function (number) { - Promise.resolve() - .then(function () { - return fn(function (err) { - if (isRetryError(err)) { - err = err.retried; - } - throw errcode('Retrying', 'EPROMISERETRY', { retried: err }); - }, number); - }) - .then(resolve, function (err) { - if (isRetryError(err)) { - err = err.retried; - if (operation.retry(err || new Error())) { - return; - } - } +/** + * Module dependencies. + */ - reject(err); - }); - }); - }); -} +var util = __webpack_require__(669); +var ms = __webpack_require__(527); -module.exports = promiseRetry; +module.exports = function (t) { + if (typeof t === 'number') return t; + var r = ms(t); + if (r === undefined) { + var err = new Error(util.format('humanize-ms(%j) result undefined', t)); + console.warn(err.stack); + } + return r; +}; /***/ }), -/* 313 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 338 */ +/***/ (function(__unusedmodule, exports) { "use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +/*jshint unused:false */ -var Buffer = __webpack_require__(215).Buffer; - -// NOTE: Due to 'stream' module being pretty large (~100Kb, significant in browser environments), -// we opt to dependency-inject it instead of creating a hard dependency. -module.exports = function(stream_module) { - var Transform = stream_module.Transform; - - // == Encoder stream ======================================================= - - function IconvLiteEncoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.decodeStrings = false; // We accept only strings, so we don't need to decode them. - Transform.call(this, options); - } +class Store { + constructor() { + this.synchronous = false; + } - IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteEncoderStream } - }); + findCookie(domain, path, key, cb) { + throw new Error("findCookie is not implemented"); + } - IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { - if (typeof chunk != 'string') - return done(new Error("Iconv encoding stream needs strings as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } - } + findCookies(domain, path, allowSpecialUseDomain, cb) { + throw new Error("findCookies is not implemented"); + } - IconvLiteEncoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } - } + putCookie(cookie, cb) { + throw new Error("putCookie is not implemented"); + } - IconvLiteEncoderStream.prototype.collect = function(cb) { - var chunks = []; - this.on('error', cb); - this.on('data', function(chunk) { chunks.push(chunk); }); - this.on('end', function() { - cb(null, Buffer.concat(chunks)); - }); - return this; - } + updateCookie(oldCookie, newCookie, cb) { + // recommended default implementation: + // return this.putCookie(newCookie, cb); + throw new Error("updateCookie is not implemented"); + } + removeCookie(domain, path, key, cb) { + throw new Error("removeCookie is not implemented"); + } - // == Decoder stream ======================================================= + removeCookies(domain, path, cb) { + throw new Error("removeCookies is not implemented"); + } - function IconvLiteDecoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.encoding = this.encoding = 'utf8'; // We output strings. - Transform.call(this, options); - } + removeAllCookies(cb) { + throw new Error("removeAllCookies is not implemented"); + } - IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteDecoderStream } - }); + getAllCookies(cb) { + throw new Error( + "getAllCookies is not implemented (therefore jar cannot be serialized)" + ); + } +} - IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { - if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array)) - return done(new Error("Iconv decoding stream needs buffers as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); - } - } +exports.Store = Store; - IconvLiteDecoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); - } - } - IconvLiteDecoderStream.prototype.collect = function(cb) { - var res = ''; - this.on('error', cb); - this.on('data', function(chunk) { res += chunk; }); - this.on('end', function() { - cb(null, res); - }); - return this; - } +/***/ }), +/* 339 */, +/* 340 */ +/***/ (function(__unusedmodule, exports) { - return { - IconvLiteEncoderStream: IconvLiteEncoderStream, - IconvLiteDecoderStream: IconvLiteDecoderStream, - }; -}; +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SamplingDecision = void 0; +/** + * A sampling decision that determines how a {@link Span} will be recorded + * and collected. + */ +var SamplingDecision; +(function (SamplingDecision) { + /** + * `Span.isRecording() === false`, span will not be recorded and all events + * and attributes will be dropped. + */ + SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; + /** + * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} + * MUST NOT be set. + */ + SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; + /** + * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} + * MUST be set. + */ + SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; +})(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {})); +//# sourceMappingURL=SamplingResult.js.map /***/ }), -/* 314 */, -/* 315 */ -/***/ (function(module) { +/* 341 */ +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -module.exports = function(Promise) { -function returner() { - return this.value; -} -function thrower() { - throw this.reason; +const pump = __webpack_require__(284); +const bufferStream = __webpack_require__(927); + +class MaxBufferError extends Error { + constructor() { + super('maxBuffer exceeded'); + this.name = 'MaxBufferError'; + } } -Promise.prototype["return"] = -Promise.prototype.thenReturn = function (value) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - returner, undefined, undefined, {value: value}, undefined); -}; +function getStream(inputStream, options) { + if (!inputStream) { + return Promise.reject(new Error('Expected a stream')); + } -Promise.prototype["throw"] = -Promise.prototype.thenThrow = function (reason) { - return this._then( - thrower, undefined, undefined, {reason: reason}, undefined); -}; + options = Object.assign({maxBuffer: Infinity}, options); -Promise.prototype.catchThrow = function (reason) { - if (arguments.length <= 1) { - return this._then( - undefined, thrower, undefined, {reason: reason}, undefined); - } else { - var _reason = arguments[1]; - var handler = function() {throw _reason;}; - return this.caught(reason, handler); - } -}; + const {maxBuffer} = options; -Promise.prototype.catchReturn = function (value) { - if (arguments.length <= 1) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - undefined, returner, undefined, {value: value}, undefined); - } else { - var _value = arguments[1]; - if (_value instanceof Promise) _value.suppressUnhandledRejections(); - var handler = function() {return _value;}; - return this.caught(value, handler); - } -}; -}; + let stream; + return new Promise((resolve, reject) => { + const rejectPromise = error => { + if (error) { // A null check + error.bufferedData = stream.getBufferedValue(); + } + reject(error); + }; + + stream = pump(inputStream, bufferStream(options), error => { + if (error) { + rejectPromise(error); + return; + } + + resolve(); + }); + + stream.on('data', () => { + if (stream.getBufferedLength() > maxBuffer) { + rejectPromise(new MaxBufferError()); + } + }); + }).then(() => stream.getBufferedValue()); +} + +module.exports = getStream; +module.exports.buffer = (stream, options) => getStream(stream, Object.assign({}, options, {encoding: 'buffer'})); +module.exports.array = (stream, options) => getStream(stream, Object.assign({}, options, {array: true})); +module.exports.MaxBufferError = MaxBufferError; /***/ }), -/* 316 */, -/* 317 */ -/***/ (function(__unusedmodule, exports) { +/* 342 */, +/* 343 */ +/***/ (function(module) { -var undefined = (void 0); // Paranoia +module.exports = require("timers"); -// Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to -// create, and consume so much memory, that the browser appears frozen. -var MAX_ARRAY_LENGTH = 1e5; +/***/ }), +/* 344 */, +/* 345 */, +/* 346 */, +/* 347 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -// Approximations of internal ECMAScript conversion functions -var ECMAScript = (function() { - // Stash a copy in case other scripts modify these - var opts = Object.prototype.toString, - ophop = Object.prototype.hasOwnProperty; +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLStringWriter, XMLWriterBase, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; - return { - // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues: - Class: function(v) { return opts.call(v).replace(/^\[object *|\]$/g, ''); }, - HasProperty: function(o, p) { return p in o; }, - HasOwnProperty: function(o, p) { return ophop.call(o, p); }, - IsCallable: function(o) { return typeof o === 'function'; }, - ToInt32: function(v) { return v >> 0; }, - ToUint32: function(v) { return v >>> 0; } - }; -}()); + XMLWriterBase = __webpack_require__(423); -// Snapshot intrinsics -var LN2 = Math.LN2, - abs = Math.abs, - floor = Math.floor, - log = Math.log, - min = Math.min, - pow = Math.pow, - round = Math.round; + module.exports = XMLStringWriter = (function(superClass) { + extend(XMLStringWriter, superClass); -// ES5: lock down object properties -function configureProperties(obj) { - if (getOwnPropNames && defineProp) { - var props = getOwnPropNames(obj), i; - for (i = 0; i < props.length; i += 1) { - defineProp(obj, props[i], { - value: obj[props[i]], - writable: false, - enumerable: false, - configurable: false - }); + function XMLStringWriter(options) { + XMLStringWriter.__super__.constructor.call(this, options); } - } -} -// emulate ES5 getter/setter API using legacy APIs -// http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx -// (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but -// note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless) -var defineProp -if (Object.defineProperty && (function() { - try { - Object.defineProperty({}, 'x', {}); - return true; - } catch (e) { - return false; + XMLStringWriter.prototype.document = function(doc, options) { + var child, i, len, r, ref; + options = this.filterOptions(options); + r = ''; + ref = doc.children; + for (i = 0, len = ref.length; i < len; i++) { + child = ref[i]; + r += this.writeChildNode(child, options, 0); } - })()) { - defineProp = Object.defineProperty; -} else { - defineProp = function(o, p, desc) { - if (!o === Object(o)) throw new TypeError("Object.defineProperty called on non-object"); - if (ECMAScript.HasProperty(desc, 'get') && Object.prototype.__defineGetter__) { Object.prototype.__defineGetter__.call(o, p, desc.get); } - if (ECMAScript.HasProperty(desc, 'set') && Object.prototype.__defineSetter__) { Object.prototype.__defineSetter__.call(o, p, desc.set); } - if (ECMAScript.HasProperty(desc, 'value')) { o[p] = desc.value; } - return o; - }; -} + if (options.pretty && r.slice(-options.newline.length) === options.newline) { + r = r.slice(0, -options.newline.length); + } + return r; + }; -var getOwnPropNames = Object.getOwnPropertyNames || function (o) { - if (o !== Object(o)) throw new TypeError("Object.getOwnPropertyNames called on non-object"); - var props = [], p; - for (p in o) { - if (ECMAScript.HasOwnProperty(o, p)) { - props.push(p); - } - } - return props; -}; + return XMLStringWriter; -// ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value) -// for index in 0 ... obj.length -function makeArrayAccessors(obj) { - if (!defineProp) { return; } + })(XMLWriterBase); - if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill"); +}).call(this); - function makeArrayAccessor(index) { - defineProp(obj, index, { - 'get': function() { return obj._getter(index); }, - 'set': function(v) { obj._setter(index, v); }, - enumerable: true, - configurable: false - }); + +/***/ }), +/* 348 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * "A request-path path-matches a given cookie-path if at least one of the + * following conditions holds:" + */ +function pathMatch(reqPath, cookiePath) { + // "o The cookie-path and the request-path are identical." + if (cookiePath === reqPath) { + return true; } - var i; - for (i = 0; i < obj.length; i += 1) { - makeArrayAccessor(i); + const idx = reqPath.indexOf(cookiePath); + if (idx === 0) { + // "o The cookie-path is a prefix of the request-path, and the last + // character of the cookie-path is %x2F ("/")." + if (cookiePath.substr(-1) === "/") { + return true; + } + + // " o The cookie-path is a prefix of the request-path, and the first + // character of the request-path that is not included in the cookie- path + // is a %x2F ("/") character." + if (reqPath.substr(cookiePath.length, 1) === "/") { + return true; + } } + + return false; } -// Internal conversion functions: -// pack() - take a number (interpreted as Type), output a byte array -// unpack() - take a byte array, output a Type-like number +exports.pathMatch = pathMatch; -function as_signed(value, bits) { var s = 32 - bits; return (value << s) >> s; } -function as_unsigned(value, bits) { var s = 32 - bits; return (value << s) >>> s; } -function packI8(n) { return [n & 0xff]; } -function unpackI8(bytes) { return as_signed(bytes[0], 8); } +/***/ }), +/* 349 */, +/* 350 */ +/***/ (function(__unusedmodule, exports) { -function packU8(n) { return [n & 0xff]; } -function unpackU8(bytes) { return as_unsigned(bytes[0], 8); } +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + var prefixMatch; -function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff]; } + prefixMatch = new RegExp(/(?!xmlns)^.*:/); -function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; } -function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 16); } + exports.normalize = function(str) { + return str.toLowerCase(); + }; -function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; } -function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1], 16); } + exports.firstCharLowerCase = function(str) { + return str.charAt(0).toLowerCase() + str.slice(1); + }; -function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } -function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } + exports.stripPrefix = function(str) { + return str.replace(prefixMatch, ''); + }; -function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } -function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } + exports.parseNumbers = function(str) { + if (!isNaN(str)) { + str = str % 1 === 0 ? parseInt(str, 10) : parseFloat(str); + } + return str; + }; -function packIEEE754(v, ebits, fbits) { + exports.parseBooleans = function(str) { + if (/^(?:true|false)$/i.test(str)) { + str = str.toLowerCase() === 'true'; + } + return str; + }; - var bias = (1 << (ebits - 1)) - 1, - s, e, f, ln, - i, bits, str, bytes; +}).call(this); - function roundToEven(n) { - var w = floor(n), f = n - w; - if (f < 0.5) - return w; - if (f > 0.5) - return w + 1; - return w % 2 ? w + 1 : w; - } - // Compute sign, exponent, fraction - if (v !== v) { - // NaN - // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping - e = (1 << ebits) - 1; f = pow(2, fbits - 1); s = 0; - } else if (v === Infinity || v === -Infinity) { - e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0; - } else if (v === 0) { - e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; - } else { - s = v < 0; - v = abs(v); +/***/ }), +/* 351 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (v >= pow(2, 1 - bias)) { - e = min(floor(log(v) / LN2), 1023); - f = roundToEven(v / pow(2, e) * pow(2, fbits)); - if (f / pow(2, fbits) >= 2) { - e = e + 1; - f = 1; - } - if (e > bias) { - // Overflow - e = (1 << ebits) - 1; - f = 0; - } else { - // Normalized - e = e + bias; - f = f - pow(2, fbits); - } - } else { - // Denormalized - e = 0; - f = roundToEven(v / pow(2, 1 - bias - fbits)); - } - } - - // Pack sign, exponent, fraction - bits = []; - for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = floor(f / 2); } - for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = floor(e / 2); } - bits.push(s ? 1 : 0); - bits.reverse(); - str = bits.join(''); - - // Bits to bytes - bytes = []; - while (str.length) { - bytes.push(parseInt(str.substring(0, 8), 2)); - str = str.substring(8); - } - return bytes; -} - -function unpackIEEE754(bytes, ebits, fbits) { +"use strict"; - // Bytes to bits - var bits = [], i, j, b, str, - bias, s, e, f; +var es5 = __webpack_require__(883); +var Objectfreeze = es5.freeze; +var util = __webpack_require__(248); +var inherits = util.inherits; +var notEnumerableProp = util.notEnumerableProp; - for (i = bytes.length; i; i -= 1) { - b = bytes[i - 1]; - for (j = 8; j; j -= 1) { - bits.push(b % 2 ? 1 : 0); b = b >> 1; +function subError(nameProperty, defaultMessage) { + function SubError(message) { + if (!(this instanceof SubError)) return new SubError(message); + notEnumerableProp(this, "message", + typeof message === "string" ? message : defaultMessage); + notEnumerableProp(this, "name", nameProperty); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + Error.call(this); + } } - } - bits.reverse(); - str = bits.join(''); - - // Unpack sign, exponent, fraction - bias = (1 << (ebits - 1)) - 1; - s = parseInt(str.substring(0, 1), 2) ? -1 : 1; - e = parseInt(str.substring(1, 1 + ebits), 2); - f = parseInt(str.substring(1 + ebits), 2); - - // Produce number - if (e === (1 << ebits) - 1) { - return f !== 0 ? NaN : s * Infinity; - } else if (e > 0) { - // Normalized - return s * pow(2, e - bias) * (1 + f / pow(2, fbits)); - } else if (f !== 0) { - // Denormalized - return s * pow(2, -(bias - 1)) * (f / pow(2, fbits)); - } else { - return s < 0 ? -0 : 0; - } + inherits(SubError, Error); + return SubError; } -function unpackF64(b) { return unpackIEEE754(b, 11, 52); } -function packF64(v) { return packIEEE754(v, 11, 52); } -function unpackF32(b) { return unpackIEEE754(b, 8, 23); } -function packF32(v) { return packIEEE754(v, 8, 23); } - - -// -// 3 The ArrayBuffer Type -// - -(function() { - - /** @constructor */ - var ArrayBuffer = function ArrayBuffer(length) { - length = ECMAScript.ToInt32(length); - if (length < 0) throw new RangeError('ArrayBuffer size is not a small enough positive integer'); +var _TypeError, _RangeError; +var Warning = subError("Warning", "warning"); +var CancellationError = subError("CancellationError", "cancellation error"); +var TimeoutError = subError("TimeoutError", "timeout error"); +var AggregateError = subError("AggregateError", "aggregate error"); +try { + _TypeError = TypeError; + _RangeError = RangeError; +} catch(e) { + _TypeError = subError("TypeError", "type error"); + _RangeError = subError("RangeError", "range error"); +} - this.byteLength = length; - this._bytes = []; - this._bytes.length = length; +var methods = ("join pop push shift unshift slice filter forEach some " + + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); - var i; - for (i = 0; i < this.byteLength; i += 1) { - this._bytes[i] = 0; +for (var i = 0; i < methods.length; ++i) { + if (typeof Array.prototype[methods[i]] === "function") { + AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; } +} - configureProperties(this); - }; - - exports.ArrayBuffer = exports.ArrayBuffer || ArrayBuffer; - - // - // 4 The ArrayBufferView Type - // - - // NOTE: this constructor is not exported - /** @constructor */ - var ArrayBufferView = function ArrayBufferView() { - //this.buffer = null; - //this.byteOffset = 0; - //this.byteLength = 0; - }; - - // - // 5 The Typed Array View Types - // - - function makeConstructor(bytesPerElement, pack, unpack) { - // Each TypedArray type requires a distinct constructor instance with - // identical logic, which this produces. - - var ctor; - ctor = function(buffer, byteOffset, length) { - var array, sequence, i, s; - - if (!arguments.length || typeof arguments[0] === 'number') { - // Constructor(unsigned long length) - this.length = ECMAScript.ToInt32(arguments[0]); - if (length < 0) throw new RangeError('ArrayBufferView size is not a small enough positive integer'); - - this.byteLength = this.length * this.BYTES_PER_ELEMENT; - this.buffer = new ArrayBuffer(this.byteLength); - this.byteOffset = 0; - } else if (typeof arguments[0] === 'object' && arguments[0].constructor === ctor) { - // Constructor(TypedArray array) - array = arguments[0]; - - this.length = array.length; - this.byteLength = this.length * this.BYTES_PER_ELEMENT; - this.buffer = new ArrayBuffer(this.byteLength); - this.byteOffset = 0; - - for (i = 0; i < this.length; i += 1) { - this._setter(i, array._getter(i)); - } - } else if (typeof arguments[0] === 'object' && - !(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { - // Constructor(sequence array) - sequence = arguments[0]; - - this.length = ECMAScript.ToUint32(sequence.length); - this.byteLength = this.length * this.BYTES_PER_ELEMENT; - this.buffer = new ArrayBuffer(this.byteLength); - this.byteOffset = 0; - - for (i = 0; i < this.length; i += 1) { - s = sequence[i]; - this._setter(i, Number(s)); - } - } else if (typeof arguments[0] === 'object' && - (arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { - // Constructor(ArrayBuffer buffer, - // optional unsigned long byteOffset, optional unsigned long length) - this.buffer = buffer; - - this.byteOffset = ECMAScript.ToUint32(byteOffset); - if (this.byteOffset > this.buffer.byteLength) { - throw new RangeError("byteOffset out of range"); +es5.defineProperty(AggregateError.prototype, "length", { + value: 0, + configurable: false, + writable: true, + enumerable: true +}); +AggregateError.prototype["isOperational"] = true; +var level = 0; +AggregateError.prototype.toString = function() { + var indent = Array(level * 4 + 1).join(" "); + var ret = "\n" + indent + "AggregateError of:" + "\n"; + level++; + indent = Array(level * 4 + 1).join(" "); + for (var i = 0; i < this.length; ++i) { + var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; + var lines = str.split("\n"); + for (var j = 0; j < lines.length; ++j) { + lines[j] = indent + lines[j]; } + str = lines.join("\n"); + ret += str + "\n"; + } + level--; + return ret; +}; - if (this.byteOffset % this.BYTES_PER_ELEMENT) { - // The given byteOffset must be a multiple of the element - // size of the specific type, otherwise an exception is raised. - throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size."); - } +function OperationalError(message) { + if (!(this instanceof OperationalError)) + return new OperationalError(message); + notEnumerableProp(this, "name", "OperationalError"); + notEnumerableProp(this, "message", message); + this.cause = message; + this["isOperational"] = true; - if (arguments.length < 3) { - this.byteLength = this.buffer.byteLength - this.byteOffset; + if (message instanceof Error) { + notEnumerableProp(this, "message", message.message); + notEnumerableProp(this, "stack", message.stack); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } - if (this.byteLength % this.BYTES_PER_ELEMENT) { - throw new RangeError("length of buffer minus byteOffset not a multiple of the element size"); - } - this.length = this.byteLength / this.BYTES_PER_ELEMENT; - } else { - this.length = ECMAScript.ToUint32(length); - this.byteLength = this.length * this.BYTES_PER_ELEMENT; - } +} +inherits(OperationalError, Error); - if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) { - throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); - } - } else { - throw new TypeError("Unexpected argument type(s)"); - } +var errorTypes = Error["__BluebirdErrorTypes__"]; +if (!errorTypes) { + errorTypes = Objectfreeze({ + CancellationError: CancellationError, + TimeoutError: TimeoutError, + OperationalError: OperationalError, + RejectionError: OperationalError, + AggregateError: AggregateError + }); + es5.defineProperty(Error, "__BluebirdErrorTypes__", { + value: errorTypes, + writable: false, + enumerable: false, + configurable: false + }); +} - this.constructor = ctor; +module.exports = { + Error: Error, + TypeError: _TypeError, + RangeError: _RangeError, + CancellationError: errorTypes.CancellationError, + OperationalError: errorTypes.OperationalError, + TimeoutError: errorTypes.TimeoutError, + AggregateError: errorTypes.AggregateError, + Warning: Warning +}; - configureProperties(this); - makeArrayAccessors(this); - }; - ctor.prototype = new ArrayBufferView(); - ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement; - ctor.prototype._pack = pack; - ctor.prototype._unpack = unpack; - ctor.BYTES_PER_ELEMENT = bytesPerElement; +/***/ }), +/* 352 */, +/* 353 */, +/* 354 */ +/***/ (function(module) { - // getter type (unsigned long index); - ctor.prototype._getter = function(index) { - if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); +"use strict"; - index = ECMAScript.ToUint32(index); - if (index >= this.length) { - return undefined; - } - var bytes = [], i, o; - for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; - i < this.BYTES_PER_ELEMENT; - i += 1, o += 1) { - bytes.push(this.buffer._bytes[o]); - } - return this._unpack(bytes); - }; +const LEVELS = [ + 'notice', + 'error', + 'warn', + 'info', + 'verbose', + 'http', + 'silly', + 'pause', + 'resume' +] - // NONSTANDARD: convenience alias for getter: type get(unsigned long index); - ctor.prototype.get = ctor.prototype._getter; +const logger = {} +for (const level of LEVELS) { + logger[level] = log(level) +} +module.exports = logger - // setter void (unsigned long index, type value); - ctor.prototype._setter = function(index, value) { - if (arguments.length < 2) throw new SyntaxError("Not enough arguments"); +function log (level) { + return (category, ...args) => process.emit('log', level, category, ...args) +} - index = ECMAScript.ToUint32(index); - if (index >= this.length) { - return undefined; - } - var bytes = this._pack(value), i, o; - for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; - i < this.BYTES_PER_ELEMENT; - i += 1, o += 1) { - this.buffer._bytes[o] = bytes[i]; - } - }; +/***/ }), +/* 355 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - // void set(TypedArray array, optional unsigned long offset); - // void set(sequence array, optional unsigned long offset); - ctor.prototype.set = function(index, value) { - if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); - var array, sequence, offset, len, - i, s, d, - byteOffset, byteLength, tmp; +module.exports = { + publish: __webpack_require__(395), + unpublish: __webpack_require__(368) +} - if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) { - // void set(TypedArray array, optional unsigned long offset); - array = arguments[0]; - offset = ECMAScript.ToUint32(arguments[1]); - if (offset + array.length > this.length) { - throw new RangeError("Offset plus length of array is out of range"); - } +/***/ }), +/* 356 */ +/***/ (function(module) { - byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT; - byteLength = array.length * this.BYTES_PER_ELEMENT; +"use strict"; - if (array.buffer === this.buffer) { - tmp = []; - for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) { - tmp[i] = array.buffer._bytes[s]; - } - for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) { - this.buffer._bytes[d] = tmp[i]; - } - } else { - for (i = 0, s = array.byteOffset, d = byteOffset; - i < byteLength; i += 1, s += 1, d += 1) { - this.buffer._bytes[d] = array.buffer._bytes[s]; - } - } - } else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') { - // void set(sequence array, optional unsigned long offset); - sequence = arguments[0]; - len = ECMAScript.ToUint32(sequence.length); - offset = ECMAScript.ToUint32(arguments[1]); +// this exists so we can replace it during testing +module.exports = process - if (offset + len > this.length) { - throw new RangeError("Offset plus length of array is out of range"); - } - for (i = 0; i < len; i += 1) { - s = sequence[i]; - this._setter(offset + i, Number(s)); - } - } else { - throw new TypeError("Unexpected argument type(s)"); - } - }; +/***/ }), +/* 357 */ +/***/ (function(module) { - // TypedArray subarray(long begin, optional long end); - ctor.prototype.subarray = function(start, end) { - function clamp(v, min, max) { return v < min ? min : v > max ? max : v; } +module.exports = require("assert"); - start = ECMAScript.ToInt32(start); - end = ECMAScript.ToInt32(end); +/***/ }), +/* 358 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (arguments.length < 1) { start = 0; } - if (arguments.length < 2) { end = this.length; } +"use strict"; - if (start < 0) { start = this.length + start; } - if (end < 0) { end = this.length + end; } - start = clamp(start, 0, this.length); - end = clamp(end, 0, this.length); +// A module for chowning things we just created, to preserve +// ownership of new links and directories. - var len = end - start; - if (len < 0) { - len = 0; - } +const chownr = __webpack_require__(941) - return new this.constructor( - this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len); - }; +const selfOwner = { + uid: process.getuid && process.getuid(), + gid: process.getgid && process.getgid() +} - return ctor; +module.exports = (path, uid, gid, cb) => { + if (selfOwner.uid !== 0 || + uid === undefined || gid === undefined || + (selfOwner.uid === uid && selfOwner.gid === gid)) { + // don't need to, or can't chown anyway, so just leave it. + // this also handles platforms where process.getuid is undefined + return cb() } + chownr(path, uid, gid, cb) +} - var Int8Array = makeConstructor(1, packI8, unpackI8); - var Uint8Array = makeConstructor(1, packU8, unpackU8); - var Uint8ClampedArray = makeConstructor(1, packU8Clamped, unpackU8); - var Int16Array = makeConstructor(2, packI16, unpackI16); - var Uint16Array = makeConstructor(2, packU16, unpackU16); - var Int32Array = makeConstructor(4, packI32, unpackI32); - var Uint32Array = makeConstructor(4, packU32, unpackU32); - var Float32Array = makeConstructor(4, packF32, unpackF32); - var Float64Array = makeConstructor(8, packF64, unpackF64); - - exports.Int8Array = exports.Int8Array || Int8Array; - exports.Uint8Array = exports.Uint8Array || Uint8Array; - exports.Uint8ClampedArray = exports.Uint8ClampedArray || Uint8ClampedArray; - exports.Int16Array = exports.Int16Array || Int16Array; - exports.Uint16Array = exports.Uint16Array || Uint16Array; - exports.Int32Array = exports.Int32Array || Int32Array; - exports.Uint32Array = exports.Uint32Array || Uint32Array; - exports.Float32Array = exports.Float32Array || Float32Array; - exports.Float64Array = exports.Float64Array || Float64Array; -}()); +module.exports.selfOwner = selfOwner -// -// 6 The DataView View Type -// -(function() { - function r(array, index) { - return ECMAScript.IsCallable(array.get) ? array.get(index) : array[index]; - } +/***/ }), +/* 359 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - var IS_BIG_ENDIAN = (function() { - var u16array = new(exports.Uint16Array)([0x1234]), - u8array = new(exports.Uint8Array)(u16array.buffer); - return r(u8array, 0) === 0x12; - }()); +"use strict"; - // Constructor(ArrayBuffer buffer, - // optional unsigned long byteOffset, - // optional unsigned long byteLength) - /** @constructor */ - var DataView = function DataView(buffer, byteOffset, byteLength) { - if (arguments.length === 0) { - buffer = new exports.ArrayBuffer(0); - } else if (!(buffer instanceof exports.ArrayBuffer || ECMAScript.Class(buffer) === 'ArrayBuffer')) { - throw new TypeError("TypeError"); +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const events_1 = __webpack_require__(614); +const net = __webpack_require__(631); +const ip = __webpack_require__(769); +const smart_buffer_1 = __webpack_require__(118); +const constants_1 = __webpack_require__(206); +const helpers_1 = __webpack_require__(372); +const receivebuffer_1 = __webpack_require__(806); +const util_1 = __webpack_require__(526); +class SocksClient extends events_1.EventEmitter { + constructor(options) { + super(); + this._options = Object.assign({}, options); + // Validate SocksClientOptions + helpers_1.validateSocksClientOptions(options); + // Default state + this.state = constants_1.SocksClientState.Created; } - - this.buffer = buffer || new exports.ArrayBuffer(0); - - this.byteOffset = ECMAScript.ToUint32(byteOffset); - if (this.byteOffset > this.buffer.byteLength) { - throw new RangeError("byteOffset out of range"); + /** + * Creates a new SOCKS connection. + * + * Note: Supports callbacks and promises. Only supports the connect command. + * @param options { SocksClientOptions } Options. + * @param callback { Function } An optional callback function. + * @returns { Promise } + */ + static createConnection(options, callback) { + // Validate SocksClientOptions + helpers_1.validateSocksClientOptions(options, ['connect']); + return new Promise((resolve, reject) => { + const client = new SocksClient(options); + client.connect(options.existing_socket); + client.once('established', (info) => { + client.removeAllListeners(); + if (typeof callback === 'function') { + callback(null, info); + resolve(); // Resolves pending promise (prevents memory leaks). + } + else { + resolve(info); + } + }); + // Error occurred, failed to establish connection. + client.once('error', (err) => { + client.removeAllListeners(); + if (typeof callback === 'function') { + callback(err); + resolve(); // Resolves pending promise (prevents memory leaks). + } + else { + reject(err); + } + }); + }); } - - if (arguments.length < 3) { - this.byteLength = this.buffer.byteLength - this.byteOffset; - } else { - this.byteLength = ECMAScript.ToUint32(byteLength); + /** + * Creates a new SOCKS connection chain to a destination host through 2 or more SOCKS proxies. + * + * Note: Supports callbacks and promises. Only supports the connect method. + * Note: Implemented via createConnection() factory function. + * @param options { SocksClientChainOptions } Options + * @param callback { Function } An optional callback function. + * @returns { Promise } + */ + static createConnectionChain(options, callback) { + // Validate SocksClientChainOptions + helpers_1.validateSocksClientChainOptions(options); + // Shuffle proxies + if (options.randomizeChain) { + util_1.shuffleArray(options.proxies); + } + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + let sock; + try { + for (let i = 0; i < options.proxies.length; i++) { + const nextProxy = options.proxies[i]; + // If we've reached the last proxy in the chain, the destination is the actual destination, otherwise it's the next proxy. + const nextDestination = i === options.proxies.length - 1 + ? options.destination + : { + host: options.proxies[i + 1].ipaddress, + port: options.proxies[i + 1].port + }; + // Creates the next connection in the chain. + const result = yield SocksClient.createConnection({ + command: 'connect', + proxy: nextProxy, + destination: nextDestination + // Initial connection ignores this as sock is undefined. Subsequent connections re-use the first proxy socket to form a chain. + }); + // If sock is undefined, assign it here. + if (!sock) { + sock = result.socket; + } + } + if (typeof callback === 'function') { + callback(null, { socket: sock }); + resolve(); // Resolves pending promise (prevents memory leaks). + } + else { + resolve({ socket: sock }); + } + } + catch (err) { + if (typeof callback === 'function') { + callback(err); + resolve(); // Resolves pending promise (prevents memory leaks). + } + else { + reject(err); + } + } + })); } - - if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) { - throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); + /** + * Creates a SOCKS UDP Frame. + * @param options + */ + static createUDPFrame(options) { + const buff = new smart_buffer_1.SmartBuffer(); + buff.writeUInt16BE(0); + buff.writeUInt8(options.frameNumber || 0); + // IPv4/IPv6/Hostname + if (net.isIPv4(options.remoteHost.host)) { + buff.writeUInt8(constants_1.Socks5HostType.IPv4); + buff.writeUInt32BE(ip.toLong(options.remoteHost.host)); + } + else if (net.isIPv6(options.remoteHost.host)) { + buff.writeUInt8(constants_1.Socks5HostType.IPv6); + buff.writeBuffer(ip.toBuffer(options.remoteHost.host)); + } + else { + buff.writeUInt8(constants_1.Socks5HostType.Hostname); + buff.writeUInt8(Buffer.byteLength(options.remoteHost.host)); + buff.writeString(options.remoteHost.host); + } + // Port + buff.writeUInt16BE(options.remoteHost.port); + // Data + buff.writeBuffer(options.data); + return buff.toBuffer(); } - - configureProperties(this); - }; - - function makeGetter(arrayType) { - return function(byteOffset, littleEndian) { - - byteOffset = ECMAScript.ToUint32(byteOffset); - - if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { - throw new RangeError("Array index out of range"); - } - byteOffset += this.byteOffset; - - var uint8Array = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT), - bytes = [], i; - for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { - bytes.push(r(uint8Array, i)); - } - - if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { - bytes.reverse(); - } - - return r(new arrayType(new exports.Uint8Array(bytes).buffer), 0); - }; - } - - DataView.prototype.getUint8 = makeGetter(exports.Uint8Array); - DataView.prototype.getInt8 = makeGetter(exports.Int8Array); - DataView.prototype.getUint16 = makeGetter(exports.Uint16Array); - DataView.prototype.getInt16 = makeGetter(exports.Int16Array); - DataView.prototype.getUint32 = makeGetter(exports.Uint32Array); - DataView.prototype.getInt32 = makeGetter(exports.Int32Array); - DataView.prototype.getFloat32 = makeGetter(exports.Float32Array); - DataView.prototype.getFloat64 = makeGetter(exports.Float64Array); - - function makeSetter(arrayType) { - return function(byteOffset, value, littleEndian) { - - byteOffset = ECMAScript.ToUint32(byteOffset); - if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { - throw new RangeError("Array index out of range"); - } - - // Get bytes - var typeArray = new arrayType([value]), - byteArray = new exports.Uint8Array(typeArray.buffer), - bytes = [], i, byteView; - - for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { - bytes.push(r(byteArray, i)); - } - - // Flip if necessary - if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { - bytes.reverse(); - } - - // Write them - byteView = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT); - byteView.set(bytes); - }; - } - - DataView.prototype.setUint8 = makeSetter(exports.Uint8Array); - DataView.prototype.setInt8 = makeSetter(exports.Int8Array); - DataView.prototype.setUint16 = makeSetter(exports.Uint16Array); - DataView.prototype.setInt16 = makeSetter(exports.Int16Array); - DataView.prototype.setUint32 = makeSetter(exports.Uint32Array); - DataView.prototype.setInt32 = makeSetter(exports.Int32Array); - DataView.prototype.setFloat32 = makeSetter(exports.Float32Array); - DataView.prototype.setFloat64 = makeSetter(exports.Float64Array); - - exports.DataView = exports.DataView || DataView; - -}()); - - -/***/ }), -/* 318 */, -/* 319 */, -/* 320 */, -/* 321 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -module.exports = function( - Promise, PromiseArray, tryConvertToPromise, apiRejection) { -var util = __webpack_require__(248); -var isObject = util.isObject; -var es5 = __webpack_require__(883); -var Es6Map; -if (typeof Map === "function") Es6Map = Map; - -var mapToEntries = (function() { - var index = 0; - var size = 0; - - function extractEntry(value, key) { - this[index] = value; - this[index + size] = key; - index++; + /** + * Parses a SOCKS UDP frame. + * @param data + */ + static parseUDPFrame(data) { + const buff = smart_buffer_1.SmartBuffer.fromBuffer(data); + buff.readOffset = 2; + const frameNumber = buff.readUInt8(); + const hostType = buff.readUInt8(); + let remoteHost; + if (hostType === constants_1.Socks5HostType.IPv4) { + remoteHost = ip.fromLong(buff.readUInt32BE()); + } + else if (hostType === constants_1.Socks5HostType.IPv6) { + remoteHost = ip.toString(buff.readBuffer(16)); + } + else { + remoteHost = buff.readString(buff.readUInt8()); + } + const remotePort = buff.readUInt16BE(); + return { + frameNumber, + remoteHost: { + host: remoteHost, + port: remotePort + }, + data: buff.readBuffer() + }; } - - return function mapToEntries(map) { - size = map.size; - index = 0; - var ret = new Array(map.size * 2); - map.forEach(extractEntry, ret); - return ret; - }; -})(); - -var entriesToMap = function(entries) { - var ret = new Es6Map(); - var length = entries.length / 2 | 0; - for (var i = 0; i < length; ++i) { - var key = entries[length + i]; - var value = entries[i]; - ret.set(key, value); + /** + * Gets the SocksClient internal state. + */ + get state() { + return this._state; } - return ret; -}; - -function PropertiesPromiseArray(obj) { - var isMap = false; - var entries; - if (Es6Map !== undefined && obj instanceof Es6Map) { - entries = mapToEntries(obj); - isMap = true; - } else { - var keys = es5.keys(obj); - var len = keys.length; - entries = new Array(len * 2); - for (var i = 0; i < len; ++i) { - var key = keys[i]; - entries[i] = obj[key]; - entries[i + len] = key; + /** + * Internal state setter. If the SocksClient is in an error state, it cannot be changed to a non error state. + */ + set state(newState) { + if (this._state !== constants_1.SocksClientState.Error) { + this._state = newState; } } - this.constructor$(entries); - this._isMap = isMap; - this._init$(undefined, isMap ? -6 : -3); -} -util.inherits(PropertiesPromiseArray, PromiseArray); - -PropertiesPromiseArray.prototype._init = function () {}; - -PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - var val; - if (this._isMap) { - val = entriesToMap(this._values); - } else { - val = {}; - var keyOffset = this.length(); - for (var i = 0, len = this.length(); i < len; ++i) { - val[this._values[i + keyOffset]] = this._values[i]; + /** + * Starts the connection establishment to the proxy and destination. + * @param existing_socket Connected socket to use instead of creating a new one (internal use). + */ + connect(existing_socket) { + this._onDataReceived = (data) => this.onDataReceived(data); + this._onClose = () => this.onClose(); + this._onError = (err) => this.onError(err); + this._onConnect = () => this.onConnect(); + // Start timeout timer (defaults to 30 seconds) + const timer = setTimeout(() => this.onEstablishedTimeout(), this._options.timeout || constants_1.DEFAULT_TIMEOUT); + // check whether unref is available as it differs from browser to NodeJS (#33) + if (timer.unref && typeof timer.unref === 'function') { + timer.unref(); + } + // If an existing socket is provided, use it to negotiate SOCKS handshake. Otherwise create a new Socket. + if (existing_socket) { + this._socket = existing_socket; + } + else { + this._socket = new net.Socket(); + } + // Attach Socket error handlers. + this._socket.once('close', this._onClose); + this._socket.once('error', this._onError); + this._socket.once('connect', this._onConnect); + this._socket.on('data', this._onDataReceived); + this.state = constants_1.SocksClientState.Connecting; + this._receiveBuffer = new receivebuffer_1.ReceiveBuffer(); + if (existing_socket) { + this._socket.emit('connect'); + } + else { + this._socket.connect(this.getSocketOptions()); + if (this._options.set_tcp_nodelay !== undefined && + this._options.set_tcp_nodelay !== null) { + this._socket.setNoDelay(!!this._options.set_tcp_nodelay); } } - this._resolve(val); - return true; - } - return false; -}; - -PropertiesPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -PropertiesPromiseArray.prototype.getActualLength = function (len) { - return len >> 1; -}; - -function props(promises) { - var ret; - var castValue = tryConvertToPromise(promises); - - if (!isObject(castValue)) { - return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } else if (castValue instanceof Promise) { - ret = castValue._then( - Promise.props, undefined, undefined, undefined, undefined); - } else { - ret = new PropertiesPromiseArray(castValue).promise(); - } - - if (castValue instanceof Promise) { - ret._propagateFrom(castValue, 2); - } - return ret; -} - -Promise.prototype.props = function () { - return props(this); -}; - -Promise.props = function (promises) { - return props(promises); -}; -}; - - -/***/ }), -/* 322 */, -/* 323 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -module.exports = -function(Promise, PromiseArray, apiRejection) { -var util = __webpack_require__(248); -var RangeError = __webpack_require__(607).RangeError; -var AggregateError = __webpack_require__(607).AggregateError; -var isArray = util.isArray; -var CANCELLATION = {}; - - -function SomePromiseArray(values) { - this.constructor$(values); - this._howMany = 0; - this._unwrap = false; - this._initialized = false; -} -util.inherits(SomePromiseArray, PromiseArray); - -SomePromiseArray.prototype._init = function () { - if (!this._initialized) { - return; + // Listen for established event so we can re-emit any excess data received during handshakes. + this.prependOnceListener('established', info => { + setImmediate(() => { + if (this._receiveBuffer.length > 0) { + const excessData = this._receiveBuffer.get(this._receiveBuffer.length); + info.socket.emit('data', excessData); + } + info.socket.resume(); + }); + }); } - if (this._howMany === 0) { - this._resolve([]); - return; + // Socket options (defaults host/port to options.proxy.host/options.proxy.port) + getSocketOptions() { + return Object.assign(Object.assign({}, this._options.socket_options), { host: this._options.proxy.host || this._options.proxy.ipaddress, port: this._options.proxy.port }); } - this._init$(undefined, -5); - var isArrayResolved = isArray(this._values); - if (!this._isResolved() && - isArrayResolved && - this._howMany > this._canPossiblyFulfill()) { - this._reject(this._getRangeError(this.length())); + /** + * Handles internal Socks timeout callback. + * Note: If the Socks client is not BoundWaitingForConnection or Established, the connection will be closed. + */ + onEstablishedTimeout() { + if (this.state !== constants_1.SocksClientState.Established && + this.state !== constants_1.SocksClientState.BoundWaitingForConnection) { + this._closeSocket(constants_1.ERRORS.ProxyConnectionTimedOut); + } } -}; - -SomePromiseArray.prototype.init = function () { - this._initialized = true; - this._init(); -}; - -SomePromiseArray.prototype.setUnwrap = function () { - this._unwrap = true; -}; - -SomePromiseArray.prototype.howMany = function () { - return this._howMany; -}; - -SomePromiseArray.prototype.setHowMany = function (count) { - this._howMany = count; -}; - -SomePromiseArray.prototype._promiseFulfilled = function (value) { - this._addFulfilled(value); - if (this._fulfilled() === this.howMany()) { - this._values.length = this.howMany(); - if (this.howMany() === 1 && this._unwrap) { - this._resolve(this._values[0]); - } else { - this._resolve(this._values); + /** + * Handles Socket connect event. + */ + onConnect() { + this.state = constants_1.SocksClientState.Connected; + // Send initial handshake. + if (this._options.proxy.type === 4) { + this.sendSocks4InitialHandshake(); } - return true; + else { + this.sendSocks5InitialHandshake(); + } + this.state = constants_1.SocksClientState.SentInitialHandshake; } - return false; - -}; -SomePromiseArray.prototype._promiseRejected = function (reason) { - this._addRejected(reason); - return this._checkOutcome(); -}; - -SomePromiseArray.prototype._promiseCancelled = function () { - if (this._values instanceof Promise || this._values == null) { - return this._cancel(); - } - this._addRejected(CANCELLATION); - return this._checkOutcome(); -}; - -SomePromiseArray.prototype._checkOutcome = function() { - if (this.howMany() > this._canPossiblyFulfill()) { - var e = new AggregateError(); - for (var i = this.length(); i < this._values.length; ++i) { - if (this._values[i] !== CANCELLATION) { - e.push(this._values[i]); - } - } - if (e.length > 0) { - this._reject(e); - } else { - this._cancel(); - } - return true; - } - return false; -}; - -SomePromiseArray.prototype._fulfilled = function () { - return this._totalResolved; -}; - -SomePromiseArray.prototype._rejected = function () { - return this._values.length - this.length(); -}; - -SomePromiseArray.prototype._addRejected = function (reason) { - this._values.push(reason); -}; - -SomePromiseArray.prototype._addFulfilled = function (value) { - this._values[this._totalResolved++] = value; -}; - -SomePromiseArray.prototype._canPossiblyFulfill = function () { - return this.length() - this._rejected(); -}; - -SomePromiseArray.prototype._getRangeError = function (count) { - var message = "Input array must contain at least " + - this._howMany + " items but contains only " + count + " items"; - return new RangeError(message); -}; - -SomePromiseArray.prototype._resolveEmptyArray = function () { - this._reject(this._getRangeError(0)); -}; - -function some(promises, howMany) { - if ((howMany | 0) !== howMany || howMany < 0) { - return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - ret.setHowMany(howMany); - ret.init(); - return promise; -} - -Promise.some = function (promises, howMany) { - return some(promises, howMany); -}; - -Promise.prototype.some = function (howMany) { - return some(this, howMany); -}; - -Promise._SomePromiseArray = SomePromiseArray; -}; - - -/***/ }), -/* 324 */, -/* 325 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); -const run_1 = __webpack_require__(180); -run_1.run().catch(core.setFailed); - - -/***/ }), -/* 326 */ -/***/ (function(module) { - -"use strict"; - - -module.exports = hashToSegments - -function hashToSegments (hash) { - return [ - hash.slice(0, 2), - hash.slice(2, 4), - hash.slice(4) - ] -} - - -/***/ }), -/* 327 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -Object.defineProperty(exports, "__esModule", { value: true }); -class PersonalAccessTokenCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; - options.headers['X-TFS-FedAuthRedirect'] = 'Suppress'; - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } -} -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; - - -/***/ }), -/* 328 */, -/* 329 */, -/* 330 */, -/* 331 */, -/* 332 */ -/***/ (function(module) { - -// Generated by CoffeeScript 1.7.1 -(function() { - var exports, iferr, printerr, throwerr, tiferr, - __slice = [].slice; - - iferr = function(fail, succ) { - return function() { - var a, err; - err = arguments[0], a = 2 <= arguments.length ? __slice.call(arguments, 1) : []; - if (err != null) { - return fail(err); - } else { - return typeof succ === "function" ? succ.apply(null, a) : void 0; - } - }; - }; - - tiferr = function(fail, succ) { - return iferr(fail, function() { - var a, err; - a = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - try { - return succ.apply(null, a); - } catch (_error) { - err = _error; - return fail(err); - } - }); - }; - - throwerr = iferr.bind(null, function(err) { - throw err; - }); - - printerr = iferr(function(err) { - return console.error(err.stack || err); - }); - - module.exports = exports = iferr; - - exports.iferr = iferr; - - exports.tiferr = tiferr; - - exports.throwerr = throwerr; - - exports.printerr = printerr; - -}).call(this); - - -/***/ }), -/* 333 */, -/* 334 */, -/* 335 */, -/* 336 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -var MurmurHash3 = __webpack_require__(188) - -module.exports = function (uniq) { - if (uniq) { - var hash = new MurmurHash3(uniq) - return ('00000000' + hash.result().toString(16)).substr(-8) - } else { - return (Math.random().toString(16) + '0000000').substr(2, 8) - } -} - - -/***/ }), -/* 337 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; -/*! - * humanize-ms - index.js - * Copyright(c) 2014 dead_horse - * MIT Licensed - */ - - - -/** - * Module dependencies. - */ - -var util = __webpack_require__(669); -var ms = __webpack_require__(186); - -module.exports = function (t) { - if (typeof t === 'number') return t; - var r = ms(t); - if (r === undefined) { - var err = new Error(util.format('humanize-ms(%j) result undefined', t)); - console.warn(err.stack); - } - return r; -}; - - -/***/ }), -/* 338 */, -/* 339 */, -/* 340 */, -/* 341 */, -/* 342 */, -/* 343 */, -/* 344 */ -/***/ (function(module) { - -module.exports = {"repositories":"'repositories' (plural) Not supported. Please pick one as the 'repository' field","missingRepository":"No repository field.","brokenGitUrl":"Probably broken git url: %s","nonObjectScripts":"scripts must be an object","nonStringScript":"script values must be string commands","nonArrayFiles":"Invalid 'files' member","invalidFilename":"Invalid filename in 'files' list: %s","nonArrayBundleDependencies":"Invalid 'bundleDependencies' list. Must be array of package names","nonStringBundleDependency":"Invalid bundleDependencies member: %s","nonDependencyBundleDependency":"Non-dependency in bundleDependencies: %s","nonObjectDependencies":"%s field must be an object","nonStringDependency":"Invalid dependency: %s %s","deprecatedArrayDependencies":"specifying %s as array is deprecated","deprecatedModules":"modules field is deprecated","nonArrayKeywords":"keywords should be an array of strings","nonStringKeyword":"keywords should be an array of strings","conflictingName":"%s is also the name of a node core module.","nonStringDescription":"'description' field should be a string","missingDescription":"No description","missingReadme":"No README data","missingLicense":"No license field.","nonEmailUrlBugsString":"Bug string field must be url, email, or {email,url}","nonUrlBugsUrlField":"bugs.url field must be a string url. Deleted.","nonEmailBugsEmailField":"bugs.email field must be a string email. Deleted.","emptyNormalizedBugs":"Normalized value of bugs field is an empty object. Deleted.","nonUrlHomepage":"homepage field must be a string url. Deleted.","invalidLicense":"license should be a valid SPDX license expression","typo":"%s should probably be %s."}; - -/***/ }), -/* 345 */, -/* 346 */, -/* 347 */ -/***/ (function(module) { - -/** - * 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[i] = (i + 0x100).toString(16).substr(1); -} - -function bytesToUuid(buf, offset) { - var i = offset || 0; - var bth = byteToHex; - // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 - return ([ - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]] - ]).join(''); -} - -module.exports = bytesToUuid; - - -/***/ }), -/* 348 */ -/***/ (function(module) { - -"use strict"; - -// this exists so we can replace it during testing -module.exports = process - - -/***/ }), -/* 349 */, -/* 350 */, -/* 351 */, -/* 352 */, -/* 353 */, -/* 354 */ -/***/ (function(module) { - -"use strict"; - - -const LEVELS = [ - 'notice', - 'error', - 'warn', - 'info', - 'verbose', - 'http', - 'silly', - 'pause', - 'resume' -] - -const logger = {} -for (const level of LEVELS) { - logger[level] = log(level) -} -module.exports = logger - -function log (level) { - return (category, ...args) => process.emit('log', level, category, ...args) -} - - -/***/ }), -/* 355 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = { - publish: __webpack_require__(500), - unpublish: __webpack_require__(368) -} - - -/***/ }), -/* 356 */, -/* 357 */ -/***/ (function(module) { - -module.exports = require("assert"); - -/***/ }), -/* 358 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -// A module for chowning things we just created, to preserve -// ownership of new links and directories. - -const chownr = __webpack_require__(427) - -const selfOwner = { - uid: process.getuid && process.getuid(), - gid: process.getgid && process.getgid() -} - -module.exports = (path, uid, gid, cb) => { - if (selfOwner.uid !== 0 || - uid === undefined || gid === undefined || - (selfOwner.uid === uid && selfOwner.gid === gid)) { - // don't need to, or can't chown anyway, so just leave it. - // this also handles platforms where process.getuid is undefined - return cb() - } - chownr(path, uid, gid, cb) -} - -module.exports.selfOwner = selfOwner - - -/***/ }), -/* 359 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const events_1 = __webpack_require__(614); -const net = __webpack_require__(631); -const ip = __webpack_require__(769); -const smart_buffer_1 = __webpack_require__(118); -const constants_1 = __webpack_require__(206); -const helpers_1 = __webpack_require__(372); -const receivebuffer_1 = __webpack_require__(806); -const util_1 = __webpack_require__(526); -class SocksClient extends events_1.EventEmitter { - constructor(options) { - super(); - this._options = Object.assign({}, options); - // Validate SocksClientOptions - helpers_1.validateSocksClientOptions(options); - // Default state - this.state = constants_1.SocksClientState.Created; + /** + * Handles Socket data event. + * @param data + */ + onDataReceived(data) { + /* + All received data is appended to a ReceiveBuffer. + This makes sure that all the data we need is received before we attempt to process it. + */ + this._receiveBuffer.append(data); + // Process data that we have. + this.processData(); } /** - * Creates a new SOCKS connection. - * - * Note: Supports callbacks and promises. Only supports the connect command. - * @param options { SocksClientOptions } Options. - * @param callback { Function } An optional callback function. - * @returns { Promise } + * Handles processing of the data we have received. */ - static createConnection(options, callback) { - // Validate SocksClientOptions - helpers_1.validateSocksClientOptions(options, ['connect']); - return new Promise((resolve, reject) => { - const client = new SocksClient(options); - client.connect(options.existing_socket); - client.once('established', (info) => { - client.removeAllListeners(); - if (typeof callback === 'function') { - callback(null, info); - resolve(); // Resolves pending promise (prevents memory leaks). + processData() { + // If we have enough data to process the next step in the SOCKS handshake, proceed. + if (this._receiveBuffer.length >= this._nextRequiredPacketBufferSize) { + // Sent initial handshake, waiting for response. + if (this.state === constants_1.SocksClientState.SentInitialHandshake) { + if (this._options.proxy.type === 4) { + // Socks v4 only has one handshake response. + this.handleSocks4FinalHandshakeResponse(); } else { - resolve(info); + // Socks v5 has two handshakes, handle initial one here. + this.handleInitialSocks5HandshakeResponse(); } - }); - // Error occurred, failed to establish connection. - client.once('error', (err) => { - client.removeAllListeners(); - if (typeof callback === 'function') { - callback(err); - resolve(); // Resolves pending promise (prevents memory leaks). + // Sent auth request for Socks v5, waiting for response. + } + else if (this.state === constants_1.SocksClientState.SentAuthentication) { + this.handleInitialSocks5AuthenticationHandshakeResponse(); + // Sent final Socks v5 handshake, waiting for final response. + } + else if (this.state === constants_1.SocksClientState.SentFinalHandshake) { + this.handleSocks5FinalHandshakeResponse(); + // Socks BIND established. Waiting for remote connection via proxy. + } + else if (this.state === constants_1.SocksClientState.BoundWaitingForConnection) { + if (this._options.proxy.type === 4) { + this.handleSocks4IncomingConnectionResponse(); } else { - reject(err); + this.handleSocks5IncomingConnectionResponse(); } - }); - }); + } + else if (this.state === constants_1.SocksClientState.Established) { + // do nothing (prevents closing of the socket) + } + else { + this._closeSocket(constants_1.ERRORS.InternalError); + } + } } /** - * Creates a new SOCKS connection chain to a destination host through 2 or more SOCKS proxies. - * - * Note: Supports callbacks and promises. Only supports the connect method. - * Note: Implemented via createConnection() factory function. - * @param options { SocksClientChainOptions } Options - * @param callback { Function } An optional callback function. - * @returns { Promise } - */ - static createConnectionChain(options, callback) { - // Validate SocksClientChainOptions - helpers_1.validateSocksClientChainOptions(options); - // Shuffle proxies - if (options.randomizeChain) { - util_1.shuffleArray(options.proxies); - } - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - let sock; - try { - for (let i = 0; i < options.proxies.length; i++) { - const nextProxy = options.proxies[i]; - // If we've reached the last proxy in the chain, the destination is the actual destination, otherwise it's the next proxy. - const nextDestination = i === options.proxies.length - 1 - ? options.destination - : { - host: options.proxies[i + 1].ipaddress, - port: options.proxies[i + 1].port - }; - // Creates the next connection in the chain. - const result = yield SocksClient.createConnection({ - command: 'connect', - proxy: nextProxy, - destination: nextDestination - // Initial connection ignores this as sock is undefined. Subsequent connections re-use the first proxy socket to form a chain. - }); - // If sock is undefined, assign it here. - if (!sock) { - sock = result.socket; - } - } - if (typeof callback === 'function') { - callback(null, { socket: sock }); - resolve(); // Resolves pending promise (prevents memory leaks). - } - else { - resolve({ socket: sock }); - } - } - catch (err) { - if (typeof callback === 'function') { - callback(err); - resolve(); // Resolves pending promise (prevents memory leaks). - } - else { - reject(err); - } - } - })); - } - /** - * Creates a SOCKS UDP Frame. - * @param options - */ - static createUDPFrame(options) { - const buff = new smart_buffer_1.SmartBuffer(); - buff.writeUInt16BE(0); - buff.writeUInt8(options.frameNumber || 0); - // IPv4/IPv6/Hostname - if (net.isIPv4(options.remoteHost.host)) { - buff.writeUInt8(constants_1.Socks5HostType.IPv4); - buff.writeUInt32BE(ip.toLong(options.remoteHost.host)); - } - else if (net.isIPv6(options.remoteHost.host)) { - buff.writeUInt8(constants_1.Socks5HostType.IPv6); - buff.writeBuffer(ip.toBuffer(options.remoteHost.host)); - } - else { - buff.writeUInt8(constants_1.Socks5HostType.Hostname); - buff.writeUInt8(Buffer.byteLength(options.remoteHost.host)); - buff.writeString(options.remoteHost.host); - } - // Port - buff.writeUInt16BE(options.remoteHost.port); - // Data - buff.writeBuffer(options.data); - return buff.toBuffer(); - } - /** - * Parses a SOCKS UDP frame. - * @param data - */ - static parseUDPFrame(data) { - const buff = smart_buffer_1.SmartBuffer.fromBuffer(data); - buff.readOffset = 2; - const frameNumber = buff.readUInt8(); - const hostType = buff.readUInt8(); - let remoteHost; - if (hostType === constants_1.Socks5HostType.IPv4) { - remoteHost = ip.fromLong(buff.readUInt32BE()); - } - else if (hostType === constants_1.Socks5HostType.IPv6) { - remoteHost = ip.toString(buff.readBuffer(16)); - } - else { - remoteHost = buff.readString(buff.readUInt8()); - } - const remotePort = buff.readUInt16BE(); - return { - frameNumber, - remoteHost: { - host: remoteHost, - port: remotePort - }, - data: buff.readBuffer() - }; - } - /** - * Gets the SocksClient internal state. - */ - get state() { - return this._state; - } - /** - * Internal state setter. If the SocksClient is in an error state, it cannot be changed to a non error state. - */ - set state(newState) { - if (this._state !== constants_1.SocksClientState.Error) { - this._state = newState; - } - } - /** - * Starts the connection establishment to the proxy and destination. - * @param existing_socket Connected socket to use instead of creating a new one (internal use). - */ - connect(existing_socket) { - this._onDataReceived = (data) => this.onDataReceived(data); - this._onClose = () => this.onClose(); - this._onError = (err) => this.onError(err); - this._onConnect = () => this.onConnect(); - // Start timeout timer (defaults to 30 seconds) - const timer = setTimeout(() => this.onEstablishedTimeout(), this._options.timeout || constants_1.DEFAULT_TIMEOUT); - // check whether unref is available as it differs from browser to NodeJS (#33) - if (timer.unref && typeof timer.unref === 'function') { - timer.unref(); - } - // If an existing socket is provided, use it to negotiate SOCKS handshake. Otherwise create a new Socket. - if (existing_socket) { - this._socket = existing_socket; - } - else { - this._socket = new net.Socket(); - } - // Attach Socket error handlers. - this._socket.once('close', this._onClose); - this._socket.once('error', this._onError); - this._socket.once('connect', this._onConnect); - this._socket.on('data', this._onDataReceived); - this.state = constants_1.SocksClientState.Connecting; - this._receiveBuffer = new receivebuffer_1.ReceiveBuffer(); - if (existing_socket) { - this._socket.emit('connect'); - } - else { - this._socket.connect(this.getSocketOptions()); - if (this._options.set_tcp_nodelay !== undefined && - this._options.set_tcp_nodelay !== null) { - this._socket.setNoDelay(!!this._options.set_tcp_nodelay); - } - } - // Listen for established event so we can re-emit any excess data received during handshakes. - this.prependOnceListener('established', info => { - setImmediate(() => { - if (this._receiveBuffer.length > 0) { - const excessData = this._receiveBuffer.get(this._receiveBuffer.length); - info.socket.emit('data', excessData); - } - info.socket.resume(); - }); - }); - } - // Socket options (defaults host/port to options.proxy.host/options.proxy.port) - getSocketOptions() { - return Object.assign(Object.assign({}, this._options.socket_options), { host: this._options.proxy.host || this._options.proxy.ipaddress, port: this._options.proxy.port }); - } - /** - * Handles internal Socks timeout callback. - * Note: If the Socks client is not BoundWaitingForConnection or Established, the connection will be closed. - */ - onEstablishedTimeout() { - if (this.state !== constants_1.SocksClientState.Established && - this.state !== constants_1.SocksClientState.BoundWaitingForConnection) { - this._closeSocket(constants_1.ERRORS.ProxyConnectionTimedOut); - } - } - /** - * Handles Socket connect event. - */ - onConnect() { - this.state = constants_1.SocksClientState.Connected; - // Send initial handshake. - if (this._options.proxy.type === 4) { - this.sendSocks4InitialHandshake(); - } - else { - this.sendSocks5InitialHandshake(); - } - this.state = constants_1.SocksClientState.SentInitialHandshake; - } - /** - * Handles Socket data event. - * @param data - */ - onDataReceived(data) { - /* - All received data is appended to a ReceiveBuffer. - This makes sure that all the data we need is received before we attempt to process it. - */ - this._receiveBuffer.append(data); - // Process data that we have. - this.processData(); - } - /** - * Handles processing of the data we have received. - */ - processData() { - // If we have enough data to process the next step in the SOCKS handshake, proceed. - if (this._receiveBuffer.length >= this._nextRequiredPacketBufferSize) { - // Sent initial handshake, waiting for response. - if (this.state === constants_1.SocksClientState.SentInitialHandshake) { - if (this._options.proxy.type === 4) { - // Socks v4 only has one handshake response. - this.handleSocks4FinalHandshakeResponse(); - } - else { - // Socks v5 has two handshakes, handle initial one here. - this.handleInitialSocks5HandshakeResponse(); - } - // Sent auth request for Socks v5, waiting for response. - } - else if (this.state === constants_1.SocksClientState.SentAuthentication) { - this.handleInitialSocks5AuthenticationHandshakeResponse(); - // Sent final Socks v5 handshake, waiting for final response. - } - else if (this.state === constants_1.SocksClientState.SentFinalHandshake) { - this.handleSocks5FinalHandshakeResponse(); - // Socks BIND established. Waiting for remote connection via proxy. - } - else if (this.state === constants_1.SocksClientState.BoundWaitingForConnection) { - if (this._options.proxy.type === 4) { - this.handleSocks4IncomingConnectionResponse(); - } - else { - this.handleSocks5IncomingConnectionResponse(); - } - } - else if (this.state === constants_1.SocksClientState.Established) { - // do nothing (prevents closing of the socket) - } - else { - this._closeSocket(constants_1.ERRORS.InternalError); - } - } - } - /** - * Handles Socket close event. - * @param had_error + * Handles Socket close event. + * @param had_error */ onClose() { this._closeSocket(constants_1.ERRORS.SocketClosed); @@ -27351,18429 +29905,57201 @@ class SocksClient extends events_1.EventEmitter { } } } - /** - * Sends Socks v5 user & password auth handshake. - * - * Note: No auth and user/pass are currently supported. - */ - sendSocks5UserPassAuthentication() { - const userId = this._options.proxy.userId || ''; - const password = this._options.proxy.password || ''; - const buff = new smart_buffer_1.SmartBuffer(); - buff.writeUInt8(0x01); - buff.writeUInt8(Buffer.byteLength(userId)); - buff.writeString(userId); - buff.writeUInt8(Buffer.byteLength(password)); - buff.writeString(password); - this._nextRequiredPacketBufferSize = - constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse; - this._socket.write(buff.toBuffer()); - this.state = constants_1.SocksClientState.SentAuthentication; + /** + * Sends Socks v5 user & password auth handshake. + * + * Note: No auth and user/pass are currently supported. + */ + sendSocks5UserPassAuthentication() { + const userId = this._options.proxy.userId || ''; + const password = this._options.proxy.password || ''; + const buff = new smart_buffer_1.SmartBuffer(); + buff.writeUInt8(0x01); + buff.writeUInt8(Buffer.byteLength(userId)); + buff.writeString(userId); + buff.writeUInt8(Buffer.byteLength(password)); + buff.writeString(password); + this._nextRequiredPacketBufferSize = + constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse; + this._socket.write(buff.toBuffer()); + this.state = constants_1.SocksClientState.SentAuthentication; + } + /** + * Handles Socks v5 auth handshake response. + * @param data + */ + handleInitialSocks5AuthenticationHandshakeResponse() { + this.state = constants_1.SocksClientState.ReceivedAuthenticationResponse; + const data = this._receiveBuffer.get(2); + if (data[1] !== 0x00) { + this._closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed); + } + else { + this.sendSocks5CommandRequest(); + } + } + /** + * Sends Socks v5 final handshake request. + */ + sendSocks5CommandRequest() { + const buff = new smart_buffer_1.SmartBuffer(); + buff.writeUInt8(0x05); + buff.writeUInt8(constants_1.SocksCommand[this._options.command]); + buff.writeUInt8(0x00); + // ipv4, ipv6, domain? + if (net.isIPv4(this._options.destination.host)) { + buff.writeUInt8(constants_1.Socks5HostType.IPv4); + buff.writeBuffer(ip.toBuffer(this._options.destination.host)); + } + else if (net.isIPv6(this._options.destination.host)) { + buff.writeUInt8(constants_1.Socks5HostType.IPv6); + buff.writeBuffer(ip.toBuffer(this._options.destination.host)); + } + else { + buff.writeUInt8(constants_1.Socks5HostType.Hostname); + buff.writeUInt8(this._options.destination.host.length); + buff.writeString(this._options.destination.host); + } + buff.writeUInt16BE(this._options.destination.port); + this._nextRequiredPacketBufferSize = + constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader; + this._socket.write(buff.toBuffer()); + this.state = constants_1.SocksClientState.SentFinalHandshake; + } + /** + * Handles Socks v5 final handshake response. + * @param data + */ + handleSocks5FinalHandshakeResponse() { + // Peek at available data (we need at least 5 bytes to get the hostname length) + const header = this._receiveBuffer.peek(5); + if (header[0] !== 0x05 || header[1] !== constants_1.Socks5Response.Granted) { + this._closeSocket(`${constants_1.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${constants_1.Socks5Response[header[1]]}`); + } + else { + // Read address type + const addressType = header[3]; + let remoteHost; + let buff; + // IPv4 + if (addressType === constants_1.Socks5HostType.IPv4) { + // Check if data is available. + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4; + if (this._receiveBuffer.length < dataNeeded) { + this._nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this._receiveBuffer.get(dataNeeded).slice(4)); + remoteHost = { + host: ip.fromLong(buff.readUInt32BE()), + port: buff.readUInt16BE() + }; + // If given host is 0.0.0.0, assume remote proxy ip instead. + if (remoteHost.host === '0.0.0.0') { + remoteHost.host = this._options.proxy.ipaddress; + } + // Hostname + } + else if (addressType === constants_1.Socks5HostType.Hostname) { + const hostLength = header[4]; + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); // header + host length + host + port + // Check if data is available. + if (this._receiveBuffer.length < dataNeeded) { + this._nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this._receiveBuffer.get(dataNeeded).slice(5) // Slice at 5 to skip host length + ); + remoteHost = { + host: buff.readString(hostLength), + port: buff.readUInt16BE() + }; + // IPv6 + } + else if (addressType === constants_1.Socks5HostType.IPv6) { + // Check if data is available. + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6; + if (this._receiveBuffer.length < dataNeeded) { + this._nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this._receiveBuffer.get(dataNeeded).slice(4)); + remoteHost = { + host: ip.toString(buff.readBuffer(16)), + port: buff.readUInt16BE() + }; + } + // We have everything we need + this.state = constants_1.SocksClientState.ReceivedFinalResponse; + // If using CONNECT, the client is now in the established state. + if (constants_1.SocksCommand[this._options.command] === constants_1.SocksCommand.connect) { + this.state = constants_1.SocksClientState.Established; + this.removeInternalSocketHandlers(); + this.emit('established', { socket: this._socket }); + } + else if (constants_1.SocksCommand[this._options.command] === constants_1.SocksCommand.bind) { + /* If using BIND, the Socks client is now in BoundWaitingForConnection state. + This means that the remote proxy server is waiting for a remote connection to the bound port. */ + this.state = constants_1.SocksClientState.BoundWaitingForConnection; + this._nextRequiredPacketBufferSize = + constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader; + this.emit('bound', { socket: this._socket, remoteHost }); + /* + If using Associate, the Socks client is now Established. And the proxy server is now accepting UDP packets at the + given bound port. This initial Socks TCP connection must remain open for the UDP relay to continue to work. + */ + } + else if (constants_1.SocksCommand[this._options.command] === constants_1.SocksCommand.associate) { + this.state = constants_1.SocksClientState.Established; + this.removeInternalSocketHandlers(); + this.emit('established', { socket: this._socket, remoteHost }); + } + } + } + /** + * Handles Socks v5 incoming connection request (BIND). + */ + handleSocks5IncomingConnectionResponse() { + // Peek at available data (we need at least 5 bytes to get the hostname length) + const header = this._receiveBuffer.peek(5); + if (header[0] !== 0x05 || header[1] !== constants_1.Socks5Response.Granted) { + this._closeSocket(`${constants_1.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${constants_1.Socks5Response[header[1]]}`); + } + else { + // Read address type + const addressType = header[3]; + let remoteHost; + let buff; + // IPv4 + if (addressType === constants_1.Socks5HostType.IPv4) { + // Check if data is available. + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4; + if (this._receiveBuffer.length < dataNeeded) { + this._nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this._receiveBuffer.get(dataNeeded).slice(4)); + remoteHost = { + host: ip.fromLong(buff.readUInt32BE()), + port: buff.readUInt16BE() + }; + // If given host is 0.0.0.0, assume remote proxy ip instead. + if (remoteHost.host === '0.0.0.0') { + remoteHost.host = this._options.proxy.ipaddress; + } + // Hostname + } + else if (addressType === constants_1.Socks5HostType.Hostname) { + const hostLength = header[4]; + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); // header + host length + port + // Check if data is available. + if (this._receiveBuffer.length < dataNeeded) { + this._nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this._receiveBuffer.get(dataNeeded).slice(5) // Slice at 5 to skip host length + ); + remoteHost = { + host: buff.readString(hostLength), + port: buff.readUInt16BE() + }; + // IPv6 + } + else if (addressType === constants_1.Socks5HostType.IPv6) { + // Check if data is available. + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6; + if (this._receiveBuffer.length < dataNeeded) { + this._nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this._receiveBuffer.get(dataNeeded).slice(4)); + remoteHost = { + host: ip.toString(buff.readBuffer(16)), + port: buff.readUInt16BE() + }; + } + this.state = constants_1.SocksClientState.Established; + this.removeInternalSocketHandlers(); + this.emit('established', { socket: this._socket, remoteHost }); + } + } + get socksClientOptions() { + return Object.assign({}, this._options); + } +} +exports.SocksClient = SocksClient; +//# sourceMappingURL=socksclient.js.map + +/***/ }), +/* 360 */, +/* 361 */, +/* 362 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +var util = __webpack_require__(669) +var messages = __webpack_require__(132) + +module.exports = function() { + var args = Array.prototype.slice.call(arguments, 0) + var warningName = args.shift() + if (warningName == "typo") { + return makeTypoWarning.apply(null,args) + } + else { + var msgTemplate = messages[warningName] ? messages[warningName] : warningName + ": '%s'" + args.unshift(msgTemplate) + return util.format.apply(null, args) + } +} + +function makeTypoWarning (providedName, probableName, field) { + if (field) { + providedName = field + "['" + providedName + "']" + probableName = field + "['" + probableName + "']" + } + return util.format(messages.typo, providedName, probableName) +} + + +/***/ }), +/* 363 */ +/***/ (function(module) { + +"use strict"; + +/* eslint-disable yoda */ +module.exports = x => { + if (Number.isNaN(x)) { + return false; + } + + // code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + x >= 0x1100 && ( + x <= 0x115f || // Hangul Jamo + x === 0x2329 || // LEFT-POINTING ANGLE BRACKET + x === 0x232a || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= x && x <= 0x4dbf) || + // CJK Unified Ideographs .. Yi Radicals + (0x4e00 <= x && x <= 0xa4c6) || + // Hangul Jamo Extended-A + (0xa960 <= x && x <= 0xa97c) || + // Hangul Syllables + (0xac00 <= x && x <= 0xd7a3) || + // CJK Compatibility Ideographs + (0xf900 <= x && x <= 0xfaff) || + // Vertical Forms + (0xfe10 <= x && x <= 0xfe19) || + // CJK Compatibility Forms .. Small Form Variants + (0xfe30 <= x && x <= 0xfe6b) || + // Halfwidth and Fullwidth Forms + (0xff01 <= x && x <= 0xff60) || + (0xffe0 <= x && x <= 0xffe6) || + // Kana Supplement + (0x1b000 <= x && x <= 0x1b001) || + // Enclosed Ideographic Supplement + (0x1f200 <= x && x <= 0x1f251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= x && x <= 0x3fffd) + ) + ) { + return true; + } + + return false; +}; + + +/***/ }), +/* 364 */ +/***/ (function(module) { + +"use strict"; + + +module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; + + +/***/ }), +/* 365 */, +/* 366 */ +/***/ (function(module) { + +var twoify = function (n) { + if (n && !(n & (n - 1))) return n + var p = 1 + while (p < n) p <<= 1 + return p +} + +var Cyclist = function (size) { + if (!(this instanceof Cyclist)) return new Cyclist(size) + size = twoify(size) + this.mask = size - 1 + this.size = size + this.values = new Array(size) +} + +Cyclist.prototype.put = function (index, val) { + var pos = index & this.mask + this.values[pos] = val + return pos +} + +Cyclist.prototype.get = function (index) { + return this.values[index & this.mask] +} + +Cyclist.prototype.del = function (index) { + var pos = index & this.mask + var val = this.values[pos] + this.values[pos] = undefined + return val +} + +module.exports = Cyclist + + +/***/ }), +/* 367 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +module.exports = __webpack_require__(100) + + +/***/ }), +/* 368 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const figgyPudding = __webpack_require__(122) +const npa = __webpack_require__(482) +const npmFetch = __webpack_require__(789) +const semver = __webpack_require__(280) +const url = __webpack_require__(835) + +const UnpublishConfig = figgyPudding({ + force: { default: false }, + Promise: { default: () => Promise } +}) + +module.exports = unpublish +function unpublish (spec, opts) { + opts = UnpublishConfig(opts) + return new opts.Promise(resolve => resolve()).then(() => { + spec = npa(spec) + // NOTE: spec is used to pick the appropriate registry/auth combo. + opts = opts.concat({ spec }) + const pkgUri = spec.escapedName + return npmFetch.json(pkgUri, opts.concat({ + query: { write: true } + })).then(pkg => { + if (!spec.rawSpec || spec.rawSpec === '*') { + return npmFetch(`${pkgUri}/-rev/${pkg._rev}`, opts.concat({ + method: 'DELETE', + ignoreBody: true + })) + } else { + const version = spec.rawSpec + const allVersions = pkg.versions || {} + const versionPublic = allVersions[version] + let dist + if (versionPublic) { + dist = allVersions[version].dist + } + delete allVersions[version] + // if it was the only version, then delete the whole package. + if (!Object.keys(allVersions).length) { + return npmFetch(`${pkgUri}/-rev/${pkg._rev}`, opts.concat({ + method: 'DELETE', + ignoreBody: true + })) + } else if (versionPublic) { + const latestVer = pkg['dist-tags'].latest + Object.keys(pkg['dist-tags']).forEach(tag => { + if (pkg['dist-tags'][tag] === version) { + delete pkg['dist-tags'][tag] + } + }) + + if (latestVer === version) { + pkg['dist-tags'].latest = Object.keys( + allVersions + ).sort(semver.compareLoose).pop() + } + + delete pkg._revisions + delete pkg._attachments + // Update packument with removed versions + return npmFetch(`${pkgUri}/-rev/${pkg._rev}`, opts.concat({ + method: 'PUT', + body: pkg, + ignoreBody: true + })).then(() => { + // Remove the tarball itself + return npmFetch.json(pkgUri, opts.concat({ + query: { write: true } + })).then(({ _rev, _id }) => { + const tarballUrl = url.parse(dist.tarball).pathname.substr(1) + return npmFetch(`${tarballUrl}/-rev/${_rev}`, opts.concat({ + method: 'DELETE', + ignoreBody: true + })) + }) + }) + } + } + }, err => { + if (err.code !== 'E404') { + throw err + } + }) + }).then(() => true) +} + + +/***/ }), +/* 369 */, +/* 370 */, +/* 371 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +module.exports.pipe = __webpack_require__(284) +module.exports.each = __webpack_require__(137) +module.exports.pipeline = __webpack_require__(746) +module.exports.duplex = __webpack_require__(394) +module.exports.through = __webpack_require__(576) +module.exports.concat = __webpack_require__(596) +module.exports.finished = __webpack_require__(3) +module.exports.from = __webpack_require__(868) +module.exports.to = __webpack_require__(6) +module.exports.parallel = __webpack_require__(565) + + +/***/ }), +/* 372 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = __webpack_require__(526); +const constants_1 = __webpack_require__(206); +const stream = __webpack_require__(794); +/** + * Validates the provided SocksClientOptions + * @param options { SocksClientOptions } + * @param acceptedCommands { string[] } A list of accepted SocksProxy commands. + */ +function validateSocksClientOptions(options, acceptedCommands = ['connect', 'bind', 'associate']) { + // Check SOCKs command option. + if (!constants_1.SocksCommand[options.command]) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommand, options); + } + // Check SocksCommand for acceptable command. + if (acceptedCommands.indexOf(options.command) === -1) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandForOperation, options); + } + // Check destination + if (!isValidSocksRemoteHost(options.destination)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options); + } + // Check SOCKS proxy to use + if (!isValidSocksProxy(options.proxy)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options); + } + // Check timeout + if (options.timeout && !isValidTimeoutValue(options.timeout)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options); + } + // Check existing_socket (if provided) + if (options.existing_socket && + !(options.existing_socket instanceof stream.Duplex)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsExistingSocket, options); + } +} +exports.validateSocksClientOptions = validateSocksClientOptions; +/** + * Validates the SocksClientChainOptions + * @param options { SocksClientChainOptions } + */ +function validateSocksClientChainOptions(options) { + // Only connect is supported when chaining. + if (options.command !== 'connect') { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandChain, options); + } + // Check destination + if (!isValidSocksRemoteHost(options.destination)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options); + } + // Validate proxies (length) + if (!(options.proxies && + Array.isArray(options.proxies) && + options.proxies.length >= 2)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxiesLength, options); + } + // Validate proxies + options.proxies.forEach((proxy) => { + if (!isValidSocksProxy(proxy)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options); + } + }); + // Check timeout + if (options.timeout && !isValidTimeoutValue(options.timeout)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options); + } +} +exports.validateSocksClientChainOptions = validateSocksClientChainOptions; +/** + * Validates a SocksRemoteHost + * @param remoteHost { SocksRemoteHost } + */ +function isValidSocksRemoteHost(remoteHost) { + return (remoteHost && + typeof remoteHost.host === 'string' && + typeof remoteHost.port === 'number' && + remoteHost.port >= 0 && + remoteHost.port <= 65535); +} +/** + * Validates a SocksProxy + * @param proxy { SocksProxy } + */ +function isValidSocksProxy(proxy) { + return (proxy && + (typeof proxy.host === 'string' || typeof proxy.ipaddress === 'string') && + typeof proxy.port === 'number' && + proxy.port >= 0 && + proxy.port <= 65535 && + (proxy.type === 4 || proxy.type === 5)); +} +/** + * Validates a timeout value. + * @param value { Number } + */ +function isValidTimeoutValue(value) { + return typeof value === 'number' && value > 0; +} +//# sourceMappingURL=helpers.js.map + +/***/ }), +/* 373 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, '__esModule', { value: true }); + +var coreHttp = __webpack_require__(999); +var tslib = __webpack_require__(815); +var api = __webpack_require__(440); +var logger$1 = __webpack_require__(492); +var abortController = __webpack_require__(106); +var os = __webpack_require__(87); +var stream = __webpack_require__(794); +__webpack_require__(242); +var crypto = __webpack_require__(417); +var coreLro = __webpack_require__(889); +var events = __webpack_require__(614); +var coreTracing = __webpack_require__(263); +var fs = __webpack_require__(747); +var util = __webpack_require__(669); + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ +var KeyInfo = { + serializedName: "KeyInfo", + type: { + name: "Composite", + className: "KeyInfo", + modelProperties: { + startsOn: { + xmlName: "Start", + required: true, + serializedName: "Start", + type: { + name: "String" + } + }, + expiresOn: { + xmlName: "Expiry", + required: true, + serializedName: "Expiry", + type: { + name: "String" + } + } + } + } +}; +var UserDelegationKey = { + serializedName: "UserDelegationKey", + type: { + name: "Composite", + className: "UserDelegationKey", + modelProperties: { + signedObjectId: { + xmlName: "SignedOid", + required: true, + serializedName: "SignedOid", + type: { + name: "String" + } + }, + signedTenantId: { + xmlName: "SignedTid", + required: true, + serializedName: "SignedTid", + type: { + name: "String" + } + }, + signedStartsOn: { + xmlName: "SignedStart", + required: true, + serializedName: "SignedStart", + type: { + name: "String" + } + }, + signedExpiresOn: { + xmlName: "SignedExpiry", + required: true, + serializedName: "SignedExpiry", + type: { + name: "String" + } + }, + signedService: { + xmlName: "SignedService", + required: true, + serializedName: "SignedService", + type: { + name: "String" + } + }, + signedVersion: { + xmlName: "SignedVersion", + required: true, + serializedName: "SignedVersion", + type: { + name: "String" + } + }, + value: { + xmlName: "Value", + required: true, + serializedName: "Value", + type: { + name: "String" + } + } + } + } +}; +var StorageError = { + serializedName: "StorageError", + type: { + name: "Composite", + className: "StorageError", + modelProperties: { + message: { + xmlName: "Message", + serializedName: "Message", + type: { + name: "String" + } + } + } + } +}; +var DataLakeStorageErrorError = { + serializedName: "DataLakeStorageError_error", + type: { + name: "Composite", + className: "DataLakeStorageErrorError", + modelProperties: { + code: { + xmlName: "Code", + serializedName: "Code", + type: { + name: "String" + } + }, + message: { + xmlName: "Message", + serializedName: "Message", + type: { + name: "String" + } + } + } + } +}; +var DataLakeStorageError = { + serializedName: "DataLakeStorageError", + type: { + name: "Composite", + className: "DataLakeStorageError", + modelProperties: { + dataLakeStorageErrorDetails: { + xmlName: "error", + serializedName: "error", + type: { + name: "Composite", + className: "DataLakeStorageErrorError" + } + } + } + } +}; +var AccessPolicy = { + serializedName: "AccessPolicy", + type: { + name: "Composite", + className: "AccessPolicy", + modelProperties: { + startsOn: { + xmlName: "Start", + serializedName: "Start", + type: { + name: "String" + } + }, + expiresOn: { + xmlName: "Expiry", + serializedName: "Expiry", + type: { + name: "String" + } + }, + permissions: { + xmlName: "Permission", + serializedName: "Permission", + type: { + name: "String" + } + } + } + } +}; +var BlobPropertiesInternal = { + xmlName: "Properties", + serializedName: "BlobPropertiesInternal", + type: { + name: "Composite", + className: "BlobPropertiesInternal", + modelProperties: { + createdOn: { + xmlName: "Creation-Time", + serializedName: "Creation-Time", + type: { + name: "DateTimeRfc1123" + } + }, + lastModified: { + xmlName: "Last-Modified", + required: true, + serializedName: "Last-Modified", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + xmlName: "Etag", + required: true, + serializedName: "Etag", + type: { + name: "String" + } + }, + contentLength: { + xmlName: "Content-Length", + serializedName: "Content-Length", + type: { + name: "Number" + } + }, + contentType: { + xmlName: "Content-Type", + serializedName: "Content-Type", + type: { + name: "String" + } + }, + contentEncoding: { + xmlName: "Content-Encoding", + serializedName: "Content-Encoding", + type: { + name: "String" + } + }, + contentLanguage: { + xmlName: "Content-Language", + serializedName: "Content-Language", + type: { + name: "String" + } + }, + contentMD5: { + xmlName: "Content-MD5", + serializedName: "Content-MD5", + type: { + name: "ByteArray" + } + }, + contentDisposition: { + xmlName: "Content-Disposition", + serializedName: "Content-Disposition", + type: { + name: "String" + } + }, + cacheControl: { + xmlName: "Cache-Control", + serializedName: "Cache-Control", + type: { + name: "String" + } + }, + blobSequenceNumber: { + xmlName: "x-ms-blob-sequence-number", + serializedName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + blobType: { + xmlName: "BlobType", + serializedName: "BlobType", + type: { + name: "Enum", + allowedValues: [ + "BlockBlob", + "PageBlob", + "AppendBlob" + ] + } + }, + leaseStatus: { + xmlName: "LeaseStatus", + serializedName: "LeaseStatus", + type: { + name: "Enum", + allowedValues: [ + "locked", + "unlocked" + ] + } + }, + leaseState: { + xmlName: "LeaseState", + serializedName: "LeaseState", + type: { + name: "Enum", + allowedValues: [ + "available", + "leased", + "expired", + "breaking", + "broken" + ] + } + }, + leaseDuration: { + xmlName: "LeaseDuration", + serializedName: "LeaseDuration", + type: { + name: "Enum", + allowedValues: [ + "infinite", + "fixed" + ] + } + }, + copyId: { + xmlName: "CopyId", + serializedName: "CopyId", + type: { + name: "String" + } + }, + copyStatus: { + xmlName: "CopyStatus", + serializedName: "CopyStatus", + type: { + name: "Enum", + allowedValues: [ + "pending", + "success", + "aborted", + "failed" + ] + } + }, + copySource: { + xmlName: "CopySource", + serializedName: "CopySource", + type: { + name: "String" + } + }, + copyProgress: { + xmlName: "CopyProgress", + serializedName: "CopyProgress", + type: { + name: "String" + } + }, + copyCompletedOn: { + xmlName: "CopyCompletionTime", + serializedName: "CopyCompletionTime", + type: { + name: "DateTimeRfc1123" + } + }, + copyStatusDescription: { + xmlName: "CopyStatusDescription", + serializedName: "CopyStatusDescription", + type: { + name: "String" + } + }, + serverEncrypted: { + xmlName: "ServerEncrypted", + serializedName: "ServerEncrypted", + type: { + name: "Boolean" + } + }, + incrementalCopy: { + xmlName: "IncrementalCopy", + serializedName: "IncrementalCopy", + type: { + name: "Boolean" + } + }, + destinationSnapshot: { + xmlName: "DestinationSnapshot", + serializedName: "DestinationSnapshot", + type: { + name: "String" + } + }, + deletedOn: { + xmlName: "DeletedTime", + serializedName: "DeletedTime", + type: { + name: "DateTimeRfc1123" + } + }, + remainingRetentionDays: { + xmlName: "RemainingRetentionDays", + serializedName: "RemainingRetentionDays", + type: { + name: "Number" + } + }, + accessTier: { + xmlName: "AccessTier", + serializedName: "AccessTier", + type: { + name: "String" + } + }, + accessTierInferred: { + xmlName: "AccessTierInferred", + serializedName: "AccessTierInferred", + type: { + name: "Boolean" + } + }, + archiveStatus: { + xmlName: "ArchiveStatus", + serializedName: "ArchiveStatus", + type: { + name: "String" + } + }, + customerProvidedKeySha256: { + xmlName: "CustomerProvidedKeySha256", + serializedName: "CustomerProvidedKeySha256", + type: { + name: "String" + } + }, + encryptionScope: { + xmlName: "EncryptionScope", + serializedName: "EncryptionScope", + type: { + name: "String" + } + }, + accessTierChangedOn: { + xmlName: "AccessTierChangeTime", + serializedName: "AccessTierChangeTime", + type: { + name: "DateTimeRfc1123" + } + }, + tagCount: { + xmlName: "TagCount", + serializedName: "TagCount", + type: { + name: "Number" + } + }, + expiresOn: { + xmlName: "Expiry-Time", + serializedName: "Expiry-Time", + type: { + name: "DateTimeRfc1123" + } + }, + isSealed: { + xmlName: "Sealed", + serializedName: "Sealed", + type: { + name: "Boolean" + } + }, + rehydratePriority: { + xmlName: "RehydratePriority", + serializedName: "RehydratePriority", + type: { + name: "String" + } + } + } + } +}; +var BlobTag = { + xmlName: "Tag", + serializedName: "BlobTag", + type: { + name: "Composite", + className: "BlobTag", + modelProperties: { + key: { + xmlName: "Key", + required: true, + serializedName: "Key", + type: { + name: "String" + } + }, + value: { + xmlName: "Value", + required: true, + serializedName: "Value", + type: { + name: "String" + } + } + } + } +}; +var BlobTags = { + xmlName: "Tags", + serializedName: "BlobTags", + type: { + name: "Composite", + className: "BlobTags", + modelProperties: { + blobTagSet: { + xmlIsWrapped: true, + xmlName: "TagSet", + xmlElementName: "Tag", + required: true, + serializedName: "BlobTagSet", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "BlobTag" + } + } + } + } + } + } +}; +var BlobItemInternal = { + xmlName: "Blob", + serializedName: "BlobItemInternal", + type: { + name: "Composite", + className: "BlobItemInternal", + modelProperties: { + name: { + xmlName: "Name", + required: true, + serializedName: "Name", + type: { + name: "String" + } + }, + deleted: { + xmlName: "Deleted", + required: true, + serializedName: "Deleted", + type: { + name: "Boolean" + } + }, + snapshot: { + xmlName: "Snapshot", + required: true, + serializedName: "Snapshot", + type: { + name: "String" + } + }, + versionId: { + xmlName: "VersionId", + serializedName: "VersionId", + type: { + name: "String" + } + }, + isCurrentVersion: { + xmlName: "IsCurrentVersion", + serializedName: "IsCurrentVersion", + type: { + name: "Boolean" + } + }, + properties: { + xmlName: "Properties", + required: true, + serializedName: "Properties", + type: { + name: "Composite", + className: "BlobPropertiesInternal" + } + }, + metadata: { + xmlName: "Metadata", + serializedName: "Metadata", + type: { + name: "Dictionary", + value: { + type: { + name: "String" + } + } + } + }, + blobTags: { + xmlName: "Tags", + serializedName: "BlobTags", + type: { + name: "Composite", + className: "BlobTags" + } + }, + objectReplicationMetadata: { + xmlName: "OrMetadata", + serializedName: "ObjectReplicationMetadata", + type: { + name: "Dictionary", + value: { + type: { + name: "String" + } + } + } + } + } + } +}; +var BlobFlatListSegment = { + xmlName: "Blobs", + serializedName: "BlobFlatListSegment", + type: { + name: "Composite", + className: "BlobFlatListSegment", + modelProperties: { + blobItems: { + xmlName: "BlobItems", + xmlElementName: "Blob", + required: true, + serializedName: "BlobItems", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "BlobItemInternal" + } + } + } + } + } + } +}; +var ListBlobsFlatSegmentResponse = { + xmlName: "EnumerationResults", + serializedName: "ListBlobsFlatSegmentResponse", + type: { + name: "Composite", + className: "ListBlobsFlatSegmentResponse", + modelProperties: { + serviceEndpoint: { + xmlIsAttribute: true, + xmlName: "ServiceEndpoint", + required: true, + serializedName: "ServiceEndpoint", + type: { + name: "String" + } + }, + containerName: { + xmlIsAttribute: true, + xmlName: "ContainerName", + required: true, + serializedName: "ContainerName", + type: { + name: "String" + } + }, + prefix: { + xmlName: "Prefix", + serializedName: "Prefix", + type: { + name: "String" + } + }, + marker: { + xmlName: "Marker", + serializedName: "Marker", + type: { + name: "String" + } + }, + maxPageSize: { + xmlName: "MaxResults", + serializedName: "MaxResults", + type: { + name: "Number" + } + }, + segment: { + xmlName: "Blobs", + required: true, + serializedName: "Segment", + type: { + name: "Composite", + className: "BlobFlatListSegment" + } + }, + continuationToken: { + xmlName: "NextMarker", + serializedName: "NextMarker", + type: { + name: "String" + } + } + } + } +}; +var BlobPrefix = { + serializedName: "BlobPrefix", + type: { + name: "Composite", + className: "BlobPrefix", + modelProperties: { + name: { + xmlName: "Name", + required: true, + serializedName: "Name", + type: { + name: "String" + } + } + } + } +}; +var BlobHierarchyListSegment = { + xmlName: "Blobs", + serializedName: "BlobHierarchyListSegment", + type: { + name: "Composite", + className: "BlobHierarchyListSegment", + modelProperties: { + blobPrefixes: { + xmlName: "BlobPrefixes", + xmlElementName: "BlobPrefix", + serializedName: "BlobPrefixes", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "BlobPrefix" + } + } + } + }, + blobItems: { + xmlName: "BlobItems", + xmlElementName: "Blob", + required: true, + serializedName: "BlobItems", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "BlobItemInternal" + } + } + } + } + } + } +}; +var ListBlobsHierarchySegmentResponse = { + xmlName: "EnumerationResults", + serializedName: "ListBlobsHierarchySegmentResponse", + type: { + name: "Composite", + className: "ListBlobsHierarchySegmentResponse", + modelProperties: { + serviceEndpoint: { + xmlIsAttribute: true, + xmlName: "ServiceEndpoint", + required: true, + serializedName: "ServiceEndpoint", + type: { + name: "String" + } + }, + containerName: { + xmlIsAttribute: true, + xmlName: "ContainerName", + required: true, + serializedName: "ContainerName", + type: { + name: "String" + } + }, + prefix: { + xmlName: "Prefix", + serializedName: "Prefix", + type: { + name: "String" + } + }, + marker: { + xmlName: "Marker", + serializedName: "Marker", + type: { + name: "String" + } + }, + maxPageSize: { + xmlName: "MaxResults", + serializedName: "MaxResults", + type: { + name: "Number" + } + }, + delimiter: { + xmlName: "Delimiter", + serializedName: "Delimiter", + type: { + name: "String" + } + }, + segment: { + xmlName: "Blobs", + required: true, + serializedName: "Segment", + type: { + name: "Composite", + className: "BlobHierarchyListSegment" + } + }, + continuationToken: { + xmlName: "NextMarker", + serializedName: "NextMarker", + type: { + name: "String" + } + } + } + } +}; +var Block = { + serializedName: "Block", + type: { + name: "Composite", + className: "Block", + modelProperties: { + name: { + xmlName: "Name", + required: true, + serializedName: "Name", + type: { + name: "String" + } + }, + size: { + xmlName: "Size", + required: true, + serializedName: "Size", + type: { + name: "Number" + } + } + } + } +}; +var BlockList = { + serializedName: "BlockList", + type: { + name: "Composite", + className: "BlockList", + modelProperties: { + committedBlocks: { + xmlIsWrapped: true, + xmlName: "CommittedBlocks", + xmlElementName: "Block", + serializedName: "CommittedBlocks", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "Block" + } + } + } + }, + uncommittedBlocks: { + xmlIsWrapped: true, + xmlName: "UncommittedBlocks", + xmlElementName: "Block", + serializedName: "UncommittedBlocks", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "Block" + } + } + } + } + } + } +}; +var BlockLookupList = { + xmlName: "BlockList", + serializedName: "BlockLookupList", + type: { + name: "Composite", + className: "BlockLookupList", + modelProperties: { + committed: { + xmlName: "Committed", + xmlElementName: "Committed", + serializedName: "Committed", + type: { + name: "Sequence", + element: { + type: { + name: "String" + } + } + } + }, + uncommitted: { + xmlName: "Uncommitted", + xmlElementName: "Uncommitted", + serializedName: "Uncommitted", + type: { + name: "Sequence", + element: { + type: { + name: "String" + } + } + } + }, + latest: { + xmlName: "Latest", + xmlElementName: "Latest", + serializedName: "Latest", + type: { + name: "Sequence", + element: { + type: { + name: "String" + } + } + } + } + } + } +}; +var ContainerProperties = { + serializedName: "ContainerProperties", + type: { + name: "Composite", + className: "ContainerProperties", + modelProperties: { + lastModified: { + xmlName: "Last-Modified", + required: true, + serializedName: "Last-Modified", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + xmlName: "Etag", + required: true, + serializedName: "Etag", + type: { + name: "String" + } + }, + leaseStatus: { + xmlName: "LeaseStatus", + serializedName: "LeaseStatus", + type: { + name: "Enum", + allowedValues: [ + "locked", + "unlocked" + ] + } + }, + leaseState: { + xmlName: "LeaseState", + serializedName: "LeaseState", + type: { + name: "Enum", + allowedValues: [ + "available", + "leased", + "expired", + "breaking", + "broken" + ] + } + }, + leaseDuration: { + xmlName: "LeaseDuration", + serializedName: "LeaseDuration", + type: { + name: "Enum", + allowedValues: [ + "infinite", + "fixed" + ] + } + }, + publicAccess: { + xmlName: "PublicAccess", + serializedName: "PublicAccess", + type: { + name: "String" + } + }, + hasImmutabilityPolicy: { + xmlName: "HasImmutabilityPolicy", + serializedName: "HasImmutabilityPolicy", + type: { + name: "Boolean" + } + }, + hasLegalHold: { + xmlName: "HasLegalHold", + serializedName: "HasLegalHold", + type: { + name: "Boolean" + } + }, + defaultEncryptionScope: { + xmlName: "DefaultEncryptionScope", + serializedName: "DefaultEncryptionScope", + type: { + name: "String" + } + }, + preventEncryptionScopeOverride: { + xmlName: "DenyEncryptionScopeOverride", + serializedName: "DenyEncryptionScopeOverride", + type: { + name: "Boolean" + } + }, + deletedOn: { + xmlName: "DeletedTime", + serializedName: "DeletedTime", + type: { + name: "DateTimeRfc1123" + } + }, + remainingRetentionDays: { + xmlName: "RemainingRetentionDays", + serializedName: "RemainingRetentionDays", + type: { + name: "Number" + } + } + } + } +}; +var ContainerItem = { + xmlName: "Container", + serializedName: "ContainerItem", + type: { + name: "Composite", + className: "ContainerItem", + modelProperties: { + name: { + xmlName: "Name", + required: true, + serializedName: "Name", + type: { + name: "String" + } + }, + deleted: { + xmlName: "Deleted", + serializedName: "Deleted", + type: { + name: "Boolean" + } + }, + version: { + xmlName: "Version", + serializedName: "Version", + type: { + name: "String" + } + }, + properties: { + xmlName: "Properties", + required: true, + serializedName: "Properties", + type: { + name: "Composite", + className: "ContainerProperties" + } + }, + metadata: { + xmlName: "Metadata", + serializedName: "Metadata", + type: { + name: "Dictionary", + value: { + type: { + name: "String" + } + } + } + } + } + } +}; +var DelimitedTextConfiguration = { + serializedName: "DelimitedTextConfiguration", + type: { + name: "Composite", + className: "DelimitedTextConfiguration", + modelProperties: { + columnSeparator: { + xmlName: "ColumnSeparator", + required: true, + serializedName: "ColumnSeparator", + type: { + name: "String" + } + }, + fieldQuote: { + xmlName: "FieldQuote", + required: true, + serializedName: "FieldQuote", + type: { + name: "String" + } + }, + recordSeparator: { + xmlName: "RecordSeparator", + required: true, + serializedName: "RecordSeparator", + type: { + name: "String" + } + }, + escapeChar: { + xmlName: "EscapeChar", + required: true, + serializedName: "EscapeChar", + type: { + name: "String" + } + }, + headersPresent: { + xmlName: "HasHeaders", + required: true, + serializedName: "HeadersPresent", + type: { + name: "Boolean" + } + } + } + } +}; +var JsonTextConfiguration = { + serializedName: "JsonTextConfiguration", + type: { + name: "Composite", + className: "JsonTextConfiguration", + modelProperties: { + recordSeparator: { + xmlName: "RecordSeparator", + required: true, + serializedName: "RecordSeparator", + type: { + name: "String" + } + } + } + } +}; +var ListContainersSegmentResponse = { + xmlName: "EnumerationResults", + serializedName: "ListContainersSegmentResponse", + type: { + name: "Composite", + className: "ListContainersSegmentResponse", + modelProperties: { + serviceEndpoint: { + xmlIsAttribute: true, + xmlName: "ServiceEndpoint", + required: true, + serializedName: "ServiceEndpoint", + type: { + name: "String" + } + }, + prefix: { + xmlName: "Prefix", + serializedName: "Prefix", + type: { + name: "String" + } + }, + marker: { + xmlName: "Marker", + serializedName: "Marker", + type: { + name: "String" + } + }, + maxPageSize: { + xmlName: "MaxResults", + serializedName: "MaxResults", + type: { + name: "Number" + } + }, + containerItems: { + xmlIsWrapped: true, + xmlName: "Containers", + xmlElementName: "Container", + required: true, + serializedName: "ContainerItems", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "ContainerItem" + } + } + } + }, + continuationToken: { + xmlName: "NextMarker", + serializedName: "NextMarker", + type: { + name: "String" + } + } + } + } +}; +var CorsRule = { + serializedName: "CorsRule", + type: { + name: "Composite", + className: "CorsRule", + modelProperties: { + allowedOrigins: { + xmlName: "AllowedOrigins", + required: true, + serializedName: "AllowedOrigins", + type: { + name: "String" + } + }, + allowedMethods: { + xmlName: "AllowedMethods", + required: true, + serializedName: "AllowedMethods", + type: { + name: "String" + } + }, + allowedHeaders: { + xmlName: "AllowedHeaders", + required: true, + serializedName: "AllowedHeaders", + type: { + name: "String" + } + }, + exposedHeaders: { + xmlName: "ExposedHeaders", + required: true, + serializedName: "ExposedHeaders", + type: { + name: "String" + } + }, + maxAgeInSeconds: { + xmlName: "MaxAgeInSeconds", + required: true, + serializedName: "MaxAgeInSeconds", + constraints: { + InclusiveMinimum: 0 + }, + type: { + name: "Number" + } + } + } + } +}; +var FilterBlobItem = { + xmlName: "Blob", + serializedName: "FilterBlobItem", + type: { + name: "Composite", + className: "FilterBlobItem", + modelProperties: { + name: { + xmlName: "Name", + required: true, + serializedName: "Name", + type: { + name: "String" + } + }, + containerName: { + xmlName: "ContainerName", + required: true, + serializedName: "ContainerName", + type: { + name: "String" + } + }, + tagValue: { + xmlName: "TagValue", + required: true, + serializedName: "TagValue", + type: { + name: "String" + } + } + } + } +}; +var FilterBlobSegment = { + xmlName: "EnumerationResults", + serializedName: "FilterBlobSegment", + type: { + name: "Composite", + className: "FilterBlobSegment", + modelProperties: { + serviceEndpoint: { + xmlIsAttribute: true, + xmlName: "ServiceEndpoint", + required: true, + serializedName: "ServiceEndpoint", + type: { + name: "String" + } + }, + where: { + xmlName: "Where", + required: true, + serializedName: "Where", + type: { + name: "String" + } + }, + blobs: { + xmlIsWrapped: true, + xmlName: "Blobs", + xmlElementName: "Blob", + required: true, + serializedName: "Blobs", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "FilterBlobItem" + } + } + } + }, + continuationToken: { + xmlName: "NextMarker", + serializedName: "NextMarker", + type: { + name: "String" + } + } + } + } +}; +var GeoReplication = { + serializedName: "GeoReplication", + type: { + name: "Composite", + className: "GeoReplication", + modelProperties: { + status: { + xmlName: "Status", + required: true, + serializedName: "Status", + type: { + name: "String" + } + }, + lastSyncOn: { + xmlName: "LastSyncTime", + required: true, + serializedName: "LastSyncTime", + type: { + name: "DateTimeRfc1123" + } + } + } + } +}; +var RetentionPolicy = { + serializedName: "RetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy", + modelProperties: { + enabled: { + xmlName: "Enabled", + required: true, + serializedName: "Enabled", + type: { + name: "Boolean" + } + }, + days: { + xmlName: "Days", + serializedName: "Days", + constraints: { + InclusiveMinimum: 1 + }, + type: { + name: "Number" + } + } + } + } +}; +var Logging = { + serializedName: "Logging", + type: { + name: "Composite", + className: "Logging", + modelProperties: { + version: { + xmlName: "Version", + required: true, + serializedName: "Version", + type: { + name: "String" + } + }, + deleteProperty: { + xmlName: "Delete", + required: true, + serializedName: "Delete", + type: { + name: "Boolean" + } + }, + read: { + xmlName: "Read", + required: true, + serializedName: "Read", + type: { + name: "Boolean" + } + }, + write: { + xmlName: "Write", + required: true, + serializedName: "Write", + type: { + name: "Boolean" + } + }, + retentionPolicy: { + xmlName: "RetentionPolicy", + required: true, + serializedName: "RetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy" + } + } + } + } +}; +var Metrics = { + serializedName: "Metrics", + type: { + name: "Composite", + className: "Metrics", + modelProperties: { + version: { + xmlName: "Version", + serializedName: "Version", + type: { + name: "String" + } + }, + enabled: { + xmlName: "Enabled", + required: true, + serializedName: "Enabled", + type: { + name: "Boolean" + } + }, + includeAPIs: { + xmlName: "IncludeAPIs", + serializedName: "IncludeAPIs", + type: { + name: "Boolean" + } + }, + retentionPolicy: { + xmlName: "RetentionPolicy", + serializedName: "RetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy" + } + } + } + } +}; +var PageRange = { + serializedName: "PageRange", + type: { + name: "Composite", + className: "PageRange", + modelProperties: { + start: { + xmlName: "Start", + required: true, + serializedName: "Start", + type: { + name: "Number" + } + }, + end: { + xmlName: "End", + required: true, + serializedName: "End", + type: { + name: "Number" + } + } + } + } +}; +var ClearRange = { + serializedName: "ClearRange", + type: { + name: "Composite", + className: "ClearRange", + modelProperties: { + start: { + xmlName: "Start", + required: true, + serializedName: "Start", + type: { + name: "Number" + } + }, + end: { + xmlName: "End", + required: true, + serializedName: "End", + type: { + name: "Number" + } + } + } + } +}; +var PageList = { + serializedName: "PageList", + type: { + name: "Composite", + className: "PageList", + modelProperties: { + pageRange: { + xmlName: "PageRange", + xmlElementName: "PageRange", + serializedName: "PageRange", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "PageRange" + } + } + } + }, + clearRange: { + xmlName: "ClearRange", + xmlElementName: "ClearRange", + serializedName: "ClearRange", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "ClearRange" + } + } + } + } + } + } +}; +var QueryFormat = { + serializedName: "QueryFormat", + type: { + name: "Composite", + className: "QueryFormat", + modelProperties: { + type: { + xmlName: "Type", + serializedName: "Type", + type: { + name: "Enum", + allowedValues: [ + "delimited", + "json" + ] + } + }, + delimitedTextConfiguration: { + xmlName: "DelimitedTextConfiguration", + serializedName: "DelimitedTextConfiguration", + type: { + name: "Composite", + className: "DelimitedTextConfiguration" + } + }, + jsonTextConfiguration: { + xmlName: "JsonTextConfiguration", + serializedName: "JsonTextConfiguration", + type: { + name: "Composite", + className: "JsonTextConfiguration" + } + } + } + } +}; +var QuerySerialization = { + serializedName: "QuerySerialization", + type: { + name: "Composite", + className: "QuerySerialization", + modelProperties: { + format: { + xmlName: "Format", + required: true, + serializedName: "Format", + type: { + name: "Composite", + className: "QueryFormat" + } + } + } + } +}; +var QueryRequest = { + serializedName: "QueryRequest", + type: { + name: "Composite", + className: "QueryRequest", + modelProperties: { + queryType: { + xmlName: "QueryType", + required: true, + isConstant: true, + serializedName: "QueryType", + defaultValue: 'SQL', + type: { + name: "String" + } + }, + expression: { + xmlName: "Expression", + required: true, + serializedName: "Expression", + type: { + name: "String" + } + }, + inputSerialization: { + xmlName: "InputSerialization", + serializedName: "InputSerialization", + type: { + name: "Composite", + className: "QuerySerialization" + } + }, + outputSerialization: { + xmlName: "OutputSerialization", + serializedName: "OutputSerialization", + type: { + name: "Composite", + className: "QuerySerialization" + } + } + } + } +}; +var SignedIdentifier = { + serializedName: "SignedIdentifier", + type: { + name: "Composite", + className: "SignedIdentifier", + modelProperties: { + id: { + xmlName: "Id", + required: true, + serializedName: "Id", + type: { + name: "String" + } + }, + accessPolicy: { + xmlName: "AccessPolicy", + required: true, + serializedName: "AccessPolicy", + type: { + name: "Composite", + className: "AccessPolicy" + } + } + } + } +}; +var StaticWebsite = { + serializedName: "StaticWebsite", + type: { + name: "Composite", + className: "StaticWebsite", + modelProperties: { + enabled: { + xmlName: "Enabled", + required: true, + serializedName: "Enabled", + type: { + name: "Boolean" + } + }, + indexDocument: { + xmlName: "IndexDocument", + serializedName: "IndexDocument", + type: { + name: "String" + } + }, + errorDocument404Path: { + xmlName: "ErrorDocument404Path", + serializedName: "ErrorDocument404Path", + type: { + name: "String" + } + }, + defaultIndexDocumentPath: { + xmlName: "DefaultIndexDocumentPath", + serializedName: "DefaultIndexDocumentPath", + type: { + name: "String" + } + } + } + } +}; +var BlobServiceProperties = { + xmlName: "StorageServiceProperties", + serializedName: "BlobServiceProperties", + type: { + name: "Composite", + className: "BlobServiceProperties", + modelProperties: { + blobAnalyticsLogging: { + xmlName: "Logging", + serializedName: "Logging", + type: { + name: "Composite", + className: "Logging" + } + }, + hourMetrics: { + xmlName: "HourMetrics", + serializedName: "HourMetrics", + type: { + name: "Composite", + className: "Metrics" + } + }, + minuteMetrics: { + xmlName: "MinuteMetrics", + serializedName: "MinuteMetrics", + type: { + name: "Composite", + className: "Metrics" + } + }, + cors: { + xmlIsWrapped: true, + xmlName: "Cors", + xmlElementName: "CorsRule", + serializedName: "Cors", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "CorsRule" + } + } + } + }, + defaultServiceVersion: { + xmlName: "DefaultServiceVersion", + serializedName: "DefaultServiceVersion", + type: { + name: "String" + } + }, + deleteRetentionPolicy: { + xmlName: "DeleteRetentionPolicy", + serializedName: "DeleteRetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy" + } + }, + staticWebsite: { + xmlName: "StaticWebsite", + serializedName: "StaticWebsite", + type: { + name: "Composite", + className: "StaticWebsite" + } + } + } + } +}; +var BlobServiceStatistics = { + xmlName: "StorageServiceStats", + serializedName: "BlobServiceStatistics", + type: { + name: "Composite", + className: "BlobServiceStatistics", + modelProperties: { + geoReplication: { + xmlName: "GeoReplication", + serializedName: "GeoReplication", + type: { + name: "Composite", + className: "GeoReplication" + } + } + } + } +}; +var ServiceSetPropertiesHeaders = { + serializedName: "service-setproperties-headers", + type: { + name: "Composite", + className: "ServiceSetPropertiesHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ServiceGetPropertiesHeaders = { + serializedName: "service-getproperties-headers", + type: { + name: "Composite", + className: "ServiceGetPropertiesHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ServiceGetStatisticsHeaders = { + serializedName: "service-getstatistics-headers", + type: { + name: "Composite", + className: "ServiceGetStatisticsHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ServiceListContainersSegmentHeaders = { + serializedName: "service-listcontainerssegment-headers", + type: { + name: "Composite", + className: "ServiceListContainersSegmentHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ServiceGetUserDelegationKeyHeaders = { + serializedName: "service-getuserdelegationkey-headers", + type: { + name: "Composite", + className: "ServiceGetUserDelegationKeyHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ServiceGetAccountInfoHeaders = { + serializedName: "service-getaccountinfo-headers", + type: { + name: "Composite", + className: "ServiceGetAccountInfoHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + skuName: { + serializedName: "x-ms-sku-name", + type: { + name: "Enum", + allowedValues: [ + "Standard_LRS", + "Standard_GRS", + "Standard_RAGRS", + "Standard_ZRS", + "Premium_LRS" + ] + } + }, + accountKind: { + serializedName: "x-ms-account-kind", + type: { + name: "Enum", + allowedValues: [ + "Storage", + "BlobStorage", + "StorageV2", + "FileStorage", + "BlockBlobStorage" + ] + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ServiceSubmitBatchHeaders = { + serializedName: "service-submitbatch-headers", + type: { + name: "Composite", + className: "ServiceSubmitBatchHeaders", + modelProperties: { + contentType: { + serializedName: "content-type", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ServiceFilterBlobsHeaders = { + serializedName: "service-filterblobs-headers", + type: { + name: "Composite", + className: "ServiceFilterBlobsHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ContainerCreateHeaders = { + serializedName: "container-create-headers", + type: { + name: "Composite", + className: "ContainerCreateHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ContainerGetPropertiesHeaders = { + serializedName: "container-getproperties-headers", + type: { + name: "Composite", + className: "ContainerGetPropertiesHeaders", + modelProperties: { + metadata: { + serializedName: "x-ms-meta", + type: { + name: "Dictionary", + value: { + type: { + name: "String" + } + } + }, + headerCollectionPrefix: "x-ms-meta-" + }, + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseDuration: { + serializedName: "x-ms-lease-duration", + type: { + name: "Enum", + allowedValues: [ + "infinite", + "fixed" + ] + } + }, + leaseState: { + serializedName: "x-ms-lease-state", + type: { + name: "Enum", + allowedValues: [ + "available", + "leased", + "expired", + "breaking", + "broken" + ] + } + }, + leaseStatus: { + serializedName: "x-ms-lease-status", + type: { + name: "Enum", + allowedValues: [ + "locked", + "unlocked" + ] + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + blobPublicAccess: { + serializedName: "x-ms-blob-public-access", + type: { + name: "String" + } + }, + hasImmutabilityPolicy: { + serializedName: "x-ms-has-immutability-policy", + type: { + name: "Boolean" + } + }, + hasLegalHold: { + serializedName: "x-ms-has-legal-hold", + type: { + name: "Boolean" + } + }, + defaultEncryptionScope: { + serializedName: "x-ms-default-encryption-scope", + type: { + name: "String" + } + }, + denyEncryptionScopeOverride: { + serializedName: "x-ms-deny-encryption-scope-override", + type: { + name: "Boolean" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ContainerDeleteHeaders = { + serializedName: "container-delete-headers", + type: { + name: "Composite", + className: "ContainerDeleteHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ContainerSetMetadataHeaders = { + serializedName: "container-setmetadata-headers", + type: { + name: "Composite", + className: "ContainerSetMetadataHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ContainerGetAccessPolicyHeaders = { + serializedName: "container-getaccesspolicy-headers", + type: { + name: "Composite", + className: "ContainerGetAccessPolicyHeaders", + modelProperties: { + blobPublicAccess: { + serializedName: "x-ms-blob-public-access", + type: { + name: "String" + } + }, + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ContainerSetAccessPolicyHeaders = { + serializedName: "container-setaccesspolicy-headers", + type: { + name: "Composite", + className: "ContainerSetAccessPolicyHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ContainerRestoreHeaders = { + serializedName: "container-restore-headers", + type: { + name: "Composite", + className: "ContainerRestoreHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ContainerAcquireLeaseHeaders = { + serializedName: "container-acquirelease-headers", + type: { + name: "Composite", + className: "ContainerAcquireLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseId: { + serializedName: "x-ms-lease-id", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ContainerReleaseLeaseHeaders = { + serializedName: "container-releaselease-headers", + type: { + name: "Composite", + className: "ContainerReleaseLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ContainerRenewLeaseHeaders = { + serializedName: "container-renewlease-headers", + type: { + name: "Composite", + className: "ContainerRenewLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseId: { + serializedName: "x-ms-lease-id", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ContainerBreakLeaseHeaders = { + serializedName: "container-breaklease-headers", + type: { + name: "Composite", + className: "ContainerBreakLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseTime: { + serializedName: "x-ms-lease-time", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ContainerChangeLeaseHeaders = { + serializedName: "container-changelease-headers", + type: { + name: "Composite", + className: "ContainerChangeLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseId: { + serializedName: "x-ms-lease-id", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ContainerListBlobFlatSegmentHeaders = { + serializedName: "container-listblobflatsegment-headers", + type: { + name: "Composite", + className: "ContainerListBlobFlatSegmentHeaders", + modelProperties: { + contentType: { + serializedName: "content-type", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ContainerListBlobHierarchySegmentHeaders = { + serializedName: "container-listblobhierarchysegment-headers", + type: { + name: "Composite", + className: "ContainerListBlobHierarchySegmentHeaders", + modelProperties: { + contentType: { + serializedName: "content-type", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var ContainerGetAccountInfoHeaders = { + serializedName: "container-getaccountinfo-headers", + type: { + name: "Composite", + className: "ContainerGetAccountInfoHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + skuName: { + serializedName: "x-ms-sku-name", + type: { + name: "Enum", + allowedValues: [ + "Standard_LRS", + "Standard_GRS", + "Standard_RAGRS", + "Standard_ZRS", + "Premium_LRS" + ] + } + }, + accountKind: { + serializedName: "x-ms-account-kind", + type: { + name: "Enum", + allowedValues: [ + "Storage", + "BlobStorage", + "StorageV2", + "FileStorage", + "BlockBlobStorage" + ] + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobDownloadHeaders = { + serializedName: "blob-download-headers", + type: { + name: "Composite", + className: "BlobDownloadHeaders", + modelProperties: { + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + metadata: { + serializedName: "x-ms-meta", + type: { + name: "Dictionary", + value: { + type: { + name: "String" + } + } + }, + headerCollectionPrefix: "x-ms-meta-" + }, + objectReplicationPolicyId: { + serializedName: "x-ms-or-policy-id", + type: { + name: "String" + } + }, + objectReplicationRules: { + serializedName: "x-ms-or", + type: { + name: "Dictionary", + value: { + type: { + name: "String" + } + } + }, + headerCollectionPrefix: "x-ms-or-" + }, + contentLength: { + serializedName: "content-length", + type: { + name: "Number" + } + }, + contentType: { + serializedName: "content-type", + type: { + name: "String" + } + }, + contentRange: { + serializedName: "content-range", + type: { + name: "String" + } + }, + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + contentEncoding: { + serializedName: "content-encoding", + type: { + name: "String" + } + }, + cacheControl: { + serializedName: "cache-control", + type: { + name: "String" + } + }, + contentDisposition: { + serializedName: "content-disposition", + type: { + name: "String" + } + }, + contentLanguage: { + serializedName: "content-language", + type: { + name: "String" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + blobType: { + serializedName: "x-ms-blob-type", + type: { + name: "Enum", + allowedValues: [ + "BlockBlob", + "PageBlob", + "AppendBlob" + ] + } + }, + copyCompletedOn: { + serializedName: "x-ms-copy-completion-time", + type: { + name: "DateTimeRfc1123" + } + }, + copyStatusDescription: { + serializedName: "x-ms-copy-status-description", + type: { + name: "String" + } + }, + copyId: { + serializedName: "x-ms-copy-id", + type: { + name: "String" + } + }, + copyProgress: { + serializedName: "x-ms-copy-progress", + type: { + name: "String" + } + }, + copySource: { + serializedName: "x-ms-copy-source", + type: { + name: "String" + } + }, + copyStatus: { + serializedName: "x-ms-copy-status", + type: { + name: "Enum", + allowedValues: [ + "pending", + "success", + "aborted", + "failed" + ] + } + }, + leaseDuration: { + serializedName: "x-ms-lease-duration", + type: { + name: "Enum", + allowedValues: [ + "infinite", + "fixed" + ] + } + }, + leaseState: { + serializedName: "x-ms-lease-state", + type: { + name: "Enum", + allowedValues: [ + "available", + "leased", + "expired", + "breaking", + "broken" + ] + } + }, + leaseStatus: { + serializedName: "x-ms-lease-status", + type: { + name: "Enum", + allowedValues: [ + "locked", + "unlocked" + ] + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + type: { + name: "String" + } + }, + acceptRanges: { + serializedName: "accept-ranges", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + blobCommittedBlockCount: { + serializedName: "x-ms-blob-committed-block-count", + type: { + name: "Number" + } + }, + isServerEncrypted: { + serializedName: "x-ms-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + blobContentMD5: { + serializedName: "x-ms-blob-content-md5", + type: { + name: "ByteArray" + } + }, + tagCount: { + serializedName: "x-ms-tag-count", + type: { + name: "Number" + } + }, + isSealed: { + serializedName: "x-ms-blob-sealed", + type: { + name: "Boolean" + } + }, + contentCrc64: { + serializedName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobGetPropertiesHeaders = { + serializedName: "blob-getproperties-headers", + type: { + name: "Composite", + className: "BlobGetPropertiesHeaders", + modelProperties: { + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + createdOn: { + serializedName: "x-ms-creation-time", + type: { + name: "DateTimeRfc1123" + } + }, + metadata: { + serializedName: "x-ms-meta", + type: { + name: "Dictionary", + value: { + type: { + name: "String" + } + } + }, + headerCollectionPrefix: "x-ms-meta-" + }, + objectReplicationPolicyId: { + serializedName: "x-ms-or-policy-id", + type: { + name: "String" + } + }, + objectReplicationRules: { + serializedName: "x-ms-or", + type: { + name: "Dictionary", + value: { + type: { + name: "String" + } + } + }, + headerCollectionPrefix: "x-ms-or-" + }, + blobType: { + serializedName: "x-ms-blob-type", + type: { + name: "Enum", + allowedValues: [ + "BlockBlob", + "PageBlob", + "AppendBlob" + ] + } + }, + copyCompletedOn: { + serializedName: "x-ms-copy-completion-time", + type: { + name: "DateTimeRfc1123" + } + }, + copyStatusDescription: { + serializedName: "x-ms-copy-status-description", + type: { + name: "String" + } + }, + copyId: { + serializedName: "x-ms-copy-id", + type: { + name: "String" + } + }, + copyProgress: { + serializedName: "x-ms-copy-progress", + type: { + name: "String" + } + }, + copySource: { + serializedName: "x-ms-copy-source", + type: { + name: "String" + } + }, + copyStatus: { + serializedName: "x-ms-copy-status", + type: { + name: "Enum", + allowedValues: [ + "pending", + "success", + "aborted", + "failed" + ] + } + }, + isIncrementalCopy: { + serializedName: "x-ms-incremental-copy", + type: { + name: "Boolean" + } + }, + destinationSnapshot: { + serializedName: "x-ms-copy-destination-snapshot", + type: { + name: "String" + } + }, + leaseDuration: { + serializedName: "x-ms-lease-duration", + type: { + name: "Enum", + allowedValues: [ + "infinite", + "fixed" + ] + } + }, + leaseState: { + serializedName: "x-ms-lease-state", + type: { + name: "Enum", + allowedValues: [ + "available", + "leased", + "expired", + "breaking", + "broken" + ] + } + }, + leaseStatus: { + serializedName: "x-ms-lease-status", + type: { + name: "Enum", + allowedValues: [ + "locked", + "unlocked" + ] + } + }, + contentLength: { + serializedName: "content-length", + type: { + name: "Number" + } + }, + contentType: { + serializedName: "content-type", + type: { + name: "String" + } + }, + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + contentEncoding: { + serializedName: "content-encoding", + type: { + name: "String" + } + }, + contentDisposition: { + serializedName: "content-disposition", + type: { + name: "String" + } + }, + contentLanguage: { + serializedName: "content-language", + type: { + name: "String" + } + }, + cacheControl: { + serializedName: "cache-control", + type: { + name: "String" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + acceptRanges: { + serializedName: "accept-ranges", + type: { + name: "String" + } + }, + blobCommittedBlockCount: { + serializedName: "x-ms-blob-committed-block-count", + type: { + name: "Number" + } + }, + isServerEncrypted: { + serializedName: "x-ms-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + accessTier: { + serializedName: "x-ms-access-tier", + type: { + name: "String" + } + }, + accessTierInferred: { + serializedName: "x-ms-access-tier-inferred", + type: { + name: "Boolean" + } + }, + archiveStatus: { + serializedName: "x-ms-archive-status", + type: { + name: "String" + } + }, + accessTierChangedOn: { + serializedName: "x-ms-access-tier-change-time", + type: { + name: "DateTimeRfc1123" + } + }, + versionId: { + serializedName: "x-ms-version-id", + type: { + name: "String" + } + }, + isCurrentVersion: { + serializedName: "x-ms-is-current-version", + type: { + name: "Boolean" + } + }, + tagCount: { + serializedName: "x-ms-tag-count", + type: { + name: "Number" + } + }, + expiresOn: { + serializedName: "x-ms-expiry-time", + type: { + name: "DateTimeRfc1123" + } + }, + isSealed: { + serializedName: "x-ms-blob-sealed", + type: { + name: "Boolean" + } + }, + rehydratePriority: { + serializedName: "x-ms-rehydrate-priority", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobDeleteHeaders = { + serializedName: "blob-delete-headers", + type: { + name: "Composite", + className: "BlobDeleteHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobSetAccessControlHeaders = { + serializedName: "blob-setaccesscontrol-headers", + type: { + name: "Composite", + className: "BlobSetAccessControlHeaders", + modelProperties: { + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + } + } + } +}; +var BlobGetAccessControlHeaders = { + serializedName: "blob-getaccesscontrol-headers", + type: { + name: "Composite", + className: "BlobGetAccessControlHeaders", + modelProperties: { + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + xMsOwner: { + serializedName: "x-ms-owner", + type: { + name: "String" + } + }, + xMsGroup: { + serializedName: "x-ms-group", + type: { + name: "String" + } + }, + xMsPermissions: { + serializedName: "x-ms-permissions", + type: { + name: "String" + } + }, + xMsAcl: { + serializedName: "x-ms-acl", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + } + } + } +}; +var BlobRenameHeaders = { + serializedName: "blob-rename-headers", + type: { + name: "Composite", + className: "BlobRenameHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + contentLength: { + serializedName: "content-length", + type: { + name: "Number" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } +}; +var PageBlobCreateHeaders = { + serializedName: "pageblob-create-headers", + type: { + name: "Composite", + className: "PageBlobCreateHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var AppendBlobCreateHeaders = { + serializedName: "appendblob-create-headers", + type: { + name: "Composite", + className: "AppendBlobCreateHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlockBlobUploadHeaders = { + serializedName: "blockblob-upload-headers", + type: { + name: "Composite", + className: "BlockBlobUploadHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobUndeleteHeaders = { + serializedName: "blob-undelete-headers", + type: { + name: "Composite", + className: "BlobUndeleteHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobSetExpiryHeaders = { + serializedName: "blob-setexpiry-headers", + type: { + name: "Composite", + className: "BlobSetExpiryHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobSetHTTPHeadersHeaders = { + serializedName: "blob-sethttpheaders-headers", + type: { + name: "Composite", + className: "BlobSetHTTPHeadersHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobSetMetadataHeaders = { + serializedName: "blob-setmetadata-headers", + type: { + name: "Composite", + className: "BlobSetMetadataHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobAcquireLeaseHeaders = { + serializedName: "blob-acquirelease-headers", + type: { + name: "Composite", + className: "BlobAcquireLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseId: { + serializedName: "x-ms-lease-id", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobReleaseLeaseHeaders = { + serializedName: "blob-releaselease-headers", + type: { + name: "Composite", + className: "BlobReleaseLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobRenewLeaseHeaders = { + serializedName: "blob-renewlease-headers", + type: { + name: "Composite", + className: "BlobRenewLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseId: { + serializedName: "x-ms-lease-id", + type: { + name: "String" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobChangeLeaseHeaders = { + serializedName: "blob-changelease-headers", + type: { + name: "Composite", + className: "BlobChangeLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + leaseId: { + serializedName: "x-ms-lease-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobBreakLeaseHeaders = { + serializedName: "blob-breaklease-headers", + type: { + name: "Composite", + className: "BlobBreakLeaseHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + leaseTime: { + serializedName: "x-ms-lease-time", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobCreateSnapshotHeaders = { + serializedName: "blob-createsnapshot-headers", + type: { + name: "Composite", + className: "BlobCreateSnapshotHeaders", + modelProperties: { + snapshot: { + serializedName: "x-ms-snapshot", + type: { + name: "String" + } + }, + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobStartCopyFromURLHeaders = { + serializedName: "blob-startcopyfromurl-headers", + type: { + name: "Composite", + className: "BlobStartCopyFromURLHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + copyId: { + serializedName: "x-ms-copy-id", + type: { + name: "String" + } + }, + copyStatus: { + serializedName: "x-ms-copy-status", + type: { + name: "Enum", + allowedValues: [ + "pending", + "success", + "aborted", + "failed" + ] + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobCopyFromURLHeaders = { + serializedName: "blob-copyfromurl-headers", + type: { + name: "Composite", + className: "BlobCopyFromURLHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + copyId: { + serializedName: "x-ms-copy-id", + type: { + name: "String" + } + }, + copyStatus: { + serializedName: "x-ms-copy-status", + type: { + name: "Enum", + allowedValues: [ + "success" + ] + } + }, + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobAbortCopyFromURLHeaders = { + serializedName: "blob-abortcopyfromurl-headers", + type: { + name: "Composite", + className: "BlobAbortCopyFromURLHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobSetTierHeaders = { + serializedName: "blob-settier-headers", + type: { + name: "Composite", + className: "BlobSetTierHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobGetAccountInfoHeaders = { + serializedName: "blob-getaccountinfo-headers", + type: { + name: "Composite", + className: "BlobGetAccountInfoHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + skuName: { + serializedName: "x-ms-sku-name", + type: { + name: "Enum", + allowedValues: [ + "Standard_LRS", + "Standard_GRS", + "Standard_RAGRS", + "Standard_ZRS", + "Premium_LRS" + ] + } + }, + accountKind: { + serializedName: "x-ms-account-kind", + type: { + name: "Enum", + allowedValues: [ + "Storage", + "BlobStorage", + "StorageV2", + "FileStorage", + "BlockBlobStorage" + ] + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlockBlobStageBlockHeaders = { + serializedName: "blockblob-stageblock-headers", + type: { + name: "Composite", + className: "BlockBlobStageBlockHeaders", + modelProperties: { + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlockBlobStageBlockFromURLHeaders = { + serializedName: "blockblob-stageblockfromurl-headers", + type: { + name: "Composite", + className: "BlockBlobStageBlockFromURLHeaders", + modelProperties: { + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlockBlobCommitBlockListHeaders = { + serializedName: "blockblob-commitblocklist-headers", + type: { + name: "Composite", + className: "BlockBlobCommitBlockListHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + versionId: { + serializedName: "x-ms-version-id", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlockBlobGetBlockListHeaders = { + serializedName: "blockblob-getblocklist-headers", + type: { + name: "Composite", + className: "BlockBlobGetBlockListHeaders", + modelProperties: { + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + contentType: { + serializedName: "content-type", + type: { + name: "String" + } + }, + blobContentLength: { + serializedName: "x-ms-blob-content-length", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var PageBlobUploadPagesHeaders = { + serializedName: "pageblob-uploadpages-headers", + type: { + name: "Composite", + className: "PageBlobUploadPagesHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var PageBlobClearPagesHeaders = { + serializedName: "pageblob-clearpages-headers", + type: { + name: "Composite", + className: "PageBlobClearPagesHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var PageBlobUploadPagesFromURLHeaders = { + serializedName: "pageblob-uploadpagesfromurl-headers", + type: { + name: "Composite", + className: "PageBlobUploadPagesFromURLHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var PageBlobGetPageRangesHeaders = { + serializedName: "pageblob-getpageranges-headers", + type: { + name: "Composite", + className: "PageBlobGetPageRangesHeaders", + modelProperties: { + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + blobContentLength: { + serializedName: "x-ms-blob-content-length", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var PageBlobGetPageRangesDiffHeaders = { + serializedName: "pageblob-getpagerangesdiff-headers", + type: { + name: "Composite", + className: "PageBlobGetPageRangesDiffHeaders", + modelProperties: { + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + blobContentLength: { + serializedName: "x-ms-blob-content-length", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var PageBlobResizeHeaders = { + serializedName: "pageblob-resize-headers", + type: { + name: "Composite", + className: "PageBlobResizeHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var PageBlobUpdateSequenceNumberHeaders = { + serializedName: "pageblob-updatesequencenumber-headers", + type: { + name: "Composite", + className: "PageBlobUpdateSequenceNumberHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var PageBlobCopyIncrementalHeaders = { + serializedName: "pageblob-copyincremental-headers", + type: { + name: "Composite", + className: "PageBlobCopyIncrementalHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + copyId: { + serializedName: "x-ms-copy-id", + type: { + name: "String" + } + }, + copyStatus: { + serializedName: "x-ms-copy-status", + type: { + name: "Enum", + allowedValues: [ + "pending", + "success", + "aborted", + "failed" + ] + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var AppendBlobAppendBlockHeaders = { + serializedName: "appendblob-appendblock-headers", + type: { + name: "Composite", + className: "AppendBlobAppendBlockHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + blobAppendOffset: { + serializedName: "x-ms-blob-append-offset", + type: { + name: "String" + } + }, + blobCommittedBlockCount: { + serializedName: "x-ms-blob-committed-block-count", + type: { + name: "Number" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var AppendBlobAppendBlockFromUrlHeaders = { + serializedName: "appendblob-appendblockfromurl-headers", + type: { + name: "Composite", + className: "AppendBlobAppendBlockFromUrlHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + xMsContentCrc64: { + serializedName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + blobAppendOffset: { + serializedName: "x-ms-blob-append-offset", + type: { + name: "String" + } + }, + blobCommittedBlockCount: { + serializedName: "x-ms-blob-committed-block-count", + type: { + name: "Number" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + isServerEncrypted: { + serializedName: "x-ms-request-server-encrypted", + type: { + name: "Boolean" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var AppendBlobSealHeaders = { + serializedName: "appendblob-seal-headers", + type: { + name: "Composite", + className: "AppendBlobSealHeaders", + modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + isSealed: { + serializedName: "x-ms-blob-sealed", + type: { + name: "Boolean" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobQueryHeaders = { + serializedName: "blob-query-headers", + type: { + name: "Composite", + className: "BlobQueryHeaders", + modelProperties: { + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, + metadata: { + serializedName: "x-ms-meta", + type: { + name: "Dictionary", + value: { + type: { + name: "String" + } + } + }, + headerCollectionPrefix: "x-ms-meta-" + }, + contentLength: { + serializedName: "content-length", + type: { + name: "Number" + } + }, + contentType: { + serializedName: "content-type", + type: { + name: "String" + } + }, + contentRange: { + serializedName: "content-range", + type: { + name: "String" + } + }, + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + contentMD5: { + serializedName: "content-md5", + type: { + name: "ByteArray" + } + }, + contentEncoding: { + serializedName: "content-encoding", + type: { + name: "String" + } + }, + cacheControl: { + serializedName: "cache-control", + type: { + name: "String" + } + }, + contentDisposition: { + serializedName: "content-disposition", + type: { + name: "String" + } + }, + contentLanguage: { + serializedName: "content-language", + type: { + name: "String" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + type: { + name: "Number" + } + }, + blobType: { + serializedName: "x-ms-blob-type", + type: { + name: "Enum", + allowedValues: [ + "BlockBlob", + "PageBlob", + "AppendBlob" + ] + } + }, + copyCompletionTime: { + serializedName: "x-ms-copy-completion-time", + type: { + name: "DateTimeRfc1123" + } + }, + copyStatusDescription: { + serializedName: "x-ms-copy-status-description", + type: { + name: "String" + } + }, + copyId: { + serializedName: "x-ms-copy-id", + type: { + name: "String" + } + }, + copyProgress: { + serializedName: "x-ms-copy-progress", + type: { + name: "String" + } + }, + copySource: { + serializedName: "x-ms-copy-source", + type: { + name: "String" + } + }, + copyStatus: { + serializedName: "x-ms-copy-status", + type: { + name: "Enum", + allowedValues: [ + "pending", + "success", + "aborted", + "failed" + ] + } + }, + leaseDuration: { + serializedName: "x-ms-lease-duration", + type: { + name: "Enum", + allowedValues: [ + "infinite", + "fixed" + ] + } + }, + leaseState: { + serializedName: "x-ms-lease-state", + type: { + name: "Enum", + allowedValues: [ + "available", + "leased", + "expired", + "breaking", + "broken" + ] + } + }, + leaseStatus: { + serializedName: "x-ms-lease-status", + type: { + name: "Enum", + allowedValues: [ + "locked", + "unlocked" + ] + } + }, + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + acceptRanges: { + serializedName: "accept-ranges", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + blobCommittedBlockCount: { + serializedName: "x-ms-blob-committed-block-count", + type: { + name: "Number" + } + }, + isServerEncrypted: { + serializedName: "x-ms-server-encrypted", + type: { + name: "Boolean" + } + }, + encryptionKeySha256: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + }, + encryptionScope: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + }, + blobContentMD5: { + serializedName: "x-ms-blob-content-md5", + type: { + name: "ByteArray" + } + }, + contentCrc64: { + serializedName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobGetTagsHeaders = { + serializedName: "blob-gettags-headers", + type: { + name: "Composite", + className: "BlobGetTagsHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +var BlobSetTagsHeaders = { + serializedName: "blob-settags-headers", + type: { + name: "Composite", + className: "BlobSetTagsHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + errorCode: { + serializedName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +var Mappers = /*#__PURE__*/Object.freeze({ + __proto__: null, + BlobServiceProperties: BlobServiceProperties, + BlobServiceStatistics: BlobServiceStatistics, + ContainerItem: ContainerItem, + ContainerProperties: ContainerProperties, + CorsRule: CorsRule, + FilterBlobItem: FilterBlobItem, + FilterBlobSegment: FilterBlobSegment, + GeoReplication: GeoReplication, + KeyInfo: KeyInfo, + ListContainersSegmentResponse: ListContainersSegmentResponse, + Logging: Logging, + Metrics: Metrics, + RetentionPolicy: RetentionPolicy, + ServiceFilterBlobsHeaders: ServiceFilterBlobsHeaders, + ServiceGetAccountInfoHeaders: ServiceGetAccountInfoHeaders, + ServiceGetPropertiesHeaders: ServiceGetPropertiesHeaders, + ServiceGetStatisticsHeaders: ServiceGetStatisticsHeaders, + ServiceGetUserDelegationKeyHeaders: ServiceGetUserDelegationKeyHeaders, + ServiceListContainersSegmentHeaders: ServiceListContainersSegmentHeaders, + ServiceSetPropertiesHeaders: ServiceSetPropertiesHeaders, + ServiceSubmitBatchHeaders: ServiceSubmitBatchHeaders, + StaticWebsite: StaticWebsite, + StorageError: StorageError, + UserDelegationKey: UserDelegationKey +}); + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ +var access = { + parameterPath: [ + "options", + "access" + ], + mapper: { + serializedName: "x-ms-blob-public-access", + type: { + name: "String" + } + } +}; +var action0 = { + parameterPath: "action", + mapper: { + required: true, + isConstant: true, + serializedName: "x-ms-lease-action", + defaultValue: 'acquire', + type: { + name: "String" + } + } +}; +var action1 = { + parameterPath: "action", + mapper: { + required: true, + isConstant: true, + serializedName: "x-ms-lease-action", + defaultValue: 'release', + type: { + name: "String" + } + } +}; +var action2 = { + parameterPath: "action", + mapper: { + required: true, + isConstant: true, + serializedName: "x-ms-lease-action", + defaultValue: 'renew', + type: { + name: "String" + } + } +}; +var action3 = { + parameterPath: "action", + mapper: { + required: true, + isConstant: true, + serializedName: "x-ms-lease-action", + defaultValue: 'break', + type: { + name: "String" + } + } +}; +var action4 = { + parameterPath: "action", + mapper: { + required: true, + isConstant: true, + serializedName: "x-ms-lease-action", + defaultValue: 'change', + type: { + name: "String" + } + } +}; +var action5 = { + parameterPath: "action", + mapper: { + required: true, + isConstant: true, + serializedName: "action", + defaultValue: 'setAccessControl', + type: { + name: "String" + } + } +}; +var action6 = { + parameterPath: "action", + mapper: { + required: true, + isConstant: true, + serializedName: "action", + defaultValue: 'getAccessControl', + type: { + name: "String" + } + } +}; +var appendPosition = { + parameterPath: [ + "options", + "appendPositionAccessConditions", + "appendPosition" + ], + mapper: { + serializedName: "x-ms-blob-condition-appendpos", + type: { + name: "Number" + } + } +}; +var blobCacheControl = { + parameterPath: [ + "options", + "blobHTTPHeaders", + "blobCacheControl" + ], + mapper: { + serializedName: "x-ms-blob-cache-control", + type: { + name: "String" + } + } +}; +var blobContentDisposition = { + parameterPath: [ + "options", + "blobHTTPHeaders", + "blobContentDisposition" + ], + mapper: { + serializedName: "x-ms-blob-content-disposition", + type: { + name: "String" + } + } +}; +var blobContentEncoding = { + parameterPath: [ + "options", + "blobHTTPHeaders", + "blobContentEncoding" + ], + mapper: { + serializedName: "x-ms-blob-content-encoding", + type: { + name: "String" + } + } +}; +var blobContentLanguage = { + parameterPath: [ + "options", + "blobHTTPHeaders", + "blobContentLanguage" + ], + mapper: { + serializedName: "x-ms-blob-content-language", + type: { + name: "String" + } + } +}; +var blobContentLength = { + parameterPath: "blobContentLength", + mapper: { + required: true, + serializedName: "x-ms-blob-content-length", + type: { + name: "Number" + } + } +}; +var blobContentMD5 = { + parameterPath: [ + "options", + "blobHTTPHeaders", + "blobContentMD5" + ], + mapper: { + serializedName: "x-ms-blob-content-md5", + type: { + name: "ByteArray" + } + } +}; +var blobContentType = { + parameterPath: [ + "options", + "blobHTTPHeaders", + "blobContentType" + ], + mapper: { + serializedName: "x-ms-blob-content-type", + type: { + name: "String" + } + } +}; +var blobSequenceNumber = { + parameterPath: [ + "options", + "blobSequenceNumber" + ], + mapper: { + serializedName: "x-ms-blob-sequence-number", + defaultValue: 0, + type: { + name: "Number" + } + } +}; +var blobTagsString = { + parameterPath: [ + "options", + "blobTagsString" + ], + mapper: { + serializedName: "x-ms-tags", + type: { + name: "String" + } + } +}; +var blobType0 = { + parameterPath: "blobType", + mapper: { + required: true, + isConstant: true, + serializedName: "x-ms-blob-type", + defaultValue: 'PageBlob', + type: { + name: "String" + } + } +}; +var blobType1 = { + parameterPath: "blobType", + mapper: { + required: true, + isConstant: true, + serializedName: "x-ms-blob-type", + defaultValue: 'AppendBlob', + type: { + name: "String" + } + } +}; +var blobType2 = { + parameterPath: "blobType", + mapper: { + required: true, + isConstant: true, + serializedName: "x-ms-blob-type", + defaultValue: 'BlockBlob', + type: { + name: "String" + } + } +}; +var blockId = { + parameterPath: "blockId", + mapper: { + required: true, + serializedName: "blockid", + type: { + name: "String" + } + } +}; +var breakPeriod = { + parameterPath: [ + "options", + "breakPeriod" + ], + mapper: { + serializedName: "x-ms-lease-break-period", + type: { + name: "Number" + } + } +}; +var cacheControl = { + parameterPath: [ + "options", + "directoryHttpHeaders", + "cacheControl" + ], + mapper: { + serializedName: "x-ms-cache-control", + type: { + name: "String" + } + } +}; +var comp0 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'properties', + type: { + name: "String" + } + } +}; +var comp1 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'stats', + type: { + name: "String" + } + } +}; +var comp10 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'expiry', + type: { + name: "String" + } + } +}; +var comp11 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'snapshot', + type: { + name: "String" + } + } +}; +var comp12 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'copy', + type: { + name: "String" + } + } +}; +var comp13 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'tier', + type: { + name: "String" + } + } +}; +var comp14 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'query', + type: { + name: "String" + } + } +}; +var comp15 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'tags', + type: { + name: "String" + } + } +}; +var comp16 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'page', + type: { + name: "String" + } + } +}; +var comp17 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'pagelist', + type: { + name: "String" + } + } +}; +var comp18 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'incrementalcopy', + type: { + name: "String" + } + } +}; +var comp19 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'appendblock', + type: { + name: "String" + } + } +}; +var comp2 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'list', + type: { + name: "String" + } + } +}; +var comp20 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'seal', + type: { + name: "String" + } + } +}; +var comp21 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'block', + type: { + name: "String" + } + } +}; +var comp22 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'blocklist', + type: { + name: "String" + } + } +}; +var comp3 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'userdelegationkey', + type: { + name: "String" + } + } +}; +var comp4 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'batch', + type: { + name: "String" + } + } +}; +var comp5 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'blobs', + type: { + name: "String" + } + } +}; +var comp6 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'metadata', + type: { + name: "String" + } + } +}; +var comp7 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'acl', + type: { + name: "String" + } + } +}; +var comp8 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'undelete', + type: { + name: "String" + } + } +}; +var comp9 = { + parameterPath: "comp", + mapper: { + required: true, + isConstant: true, + serializedName: "comp", + defaultValue: 'lease', + type: { + name: "String" + } + } +}; +var contentDisposition = { + parameterPath: [ + "options", + "directoryHttpHeaders", + "contentDisposition" + ], + mapper: { + serializedName: "x-ms-content-disposition", + type: { + name: "String" + } + } +}; +var contentEncoding = { + parameterPath: [ + "options", + "directoryHttpHeaders", + "contentEncoding" + ], + mapper: { + serializedName: "x-ms-content-encoding", + type: { + name: "String" + } + } +}; +var contentLanguage = { + parameterPath: [ + "options", + "directoryHttpHeaders", + "contentLanguage" + ], + mapper: { + serializedName: "x-ms-content-language", + type: { + name: "String" + } + } +}; +var contentLength = { + parameterPath: "contentLength", + mapper: { + required: true, + serializedName: "Content-Length", + type: { + name: "Number" + } + } +}; +var contentType = { + parameterPath: [ + "options", + "directoryHttpHeaders", + "contentType" + ], + mapper: { + serializedName: "x-ms-content-type", + type: { + name: "String" + } + } +}; +var copyActionAbortConstant = { + parameterPath: "copyActionAbortConstant", + mapper: { + required: true, + isConstant: true, + serializedName: "x-ms-copy-action", + defaultValue: 'abort', + type: { + name: "String" + } + } +}; +var copyId = { + parameterPath: "copyId", + mapper: { + required: true, + serializedName: "copyid", + type: { + name: "String" + } + } +}; +var copySource = { + parameterPath: "copySource", + mapper: { + required: true, + serializedName: "x-ms-copy-source", + type: { + name: "String" + } + } +}; +var defaultEncryptionScope = { + parameterPath: [ + "options", + "containerEncryptionScope", + "defaultEncryptionScope" + ], + mapper: { + serializedName: "x-ms-default-encryption-scope", + type: { + name: "String" + } + } +}; +var deletedContainerName = { + parameterPath: [ + "options", + "deletedContainerName" + ], + mapper: { + serializedName: "x-ms-deleted-container-name", + type: { + name: "String" + } + } +}; +var deletedContainerVersion = { + parameterPath: [ + "options", + "deletedContainerVersion" + ], + mapper: { + serializedName: "x-ms-deleted-container-version", + type: { + name: "String" + } + } +}; +var deleteSnapshots = { + parameterPath: [ + "options", + "deleteSnapshots" + ], + mapper: { + serializedName: "x-ms-delete-snapshots", + type: { + name: "Enum", + allowedValues: [ + "include", + "only" + ] + } + } +}; +var delimiter = { + parameterPath: "delimiter", + mapper: { + required: true, + serializedName: "delimiter", + type: { + name: "String" + } + } +}; +var directoryProperties = { + parameterPath: [ + "options", + "directoryProperties" + ], + mapper: { + serializedName: "x-ms-properties", + type: { + name: "String" + } + } +}; +var duration = { + parameterPath: [ + "options", + "duration" + ], + mapper: { + serializedName: "x-ms-lease-duration", + type: { + name: "Number" + } + } +}; +var encryptionAlgorithm = { + parameterPath: [ + "options", + "cpkInfo", + "encryptionAlgorithm" + ], + mapper: { + serializedName: "x-ms-encryption-algorithm", + type: { + name: "Enum", + allowedValues: [ + "AES256" + ] + } + } +}; +var encryptionKey = { + parameterPath: [ + "options", + "cpkInfo", + "encryptionKey" + ], + mapper: { + serializedName: "x-ms-encryption-key", + type: { + name: "String" + } + } +}; +var encryptionKeySha256 = { + parameterPath: [ + "options", + "cpkInfo", + "encryptionKeySha256" + ], + mapper: { + serializedName: "x-ms-encryption-key-sha256", + type: { + name: "String" + } + } +}; +var encryptionScope = { + parameterPath: [ + "options", + "encryptionScope" + ], + mapper: { + serializedName: "x-ms-encryption-scope", + type: { + name: "String" + } + } +}; +var expiresOn = { + parameterPath: [ + "options", + "expiresOn" + ], + mapper: { + serializedName: "x-ms-expiry-time", + type: { + name: "String" + } + } +}; +var expiryOptions = { + parameterPath: "expiryOptions", + mapper: { + required: true, + serializedName: "x-ms-expiry-option", + type: { + name: "String" + } + } +}; +var group = { + parameterPath: [ + "options", + "group" + ], + mapper: { + serializedName: "x-ms-group", + type: { + name: "String" + } + } +}; +var ifMatch = { + parameterPath: [ + "options", + "modifiedAccessConditions", + "ifMatch" + ], + mapper: { + serializedName: "If-Match", + type: { + name: "String" + } + } +}; +var ifModifiedSince = { + parameterPath: [ + "options", + "modifiedAccessConditions", + "ifModifiedSince" + ], + mapper: { + serializedName: "If-Modified-Since", + type: { + name: "DateTimeRfc1123" + } + } +}; +var ifNoneMatch = { + parameterPath: [ + "options", + "modifiedAccessConditions", + "ifNoneMatch" + ], + mapper: { + serializedName: "If-None-Match", + type: { + name: "String" + } + } +}; +var ifSequenceNumberEqualTo = { + parameterPath: [ + "options", + "sequenceNumberAccessConditions", + "ifSequenceNumberEqualTo" + ], + mapper: { + serializedName: "x-ms-if-sequence-number-eq", + type: { + name: "Number" + } + } +}; +var ifSequenceNumberLessThan = { + parameterPath: [ + "options", + "sequenceNumberAccessConditions", + "ifSequenceNumberLessThan" + ], + mapper: { + serializedName: "x-ms-if-sequence-number-lt", + type: { + name: "Number" + } + } +}; +var ifSequenceNumberLessThanOrEqualTo = { + parameterPath: [ + "options", + "sequenceNumberAccessConditions", + "ifSequenceNumberLessThanOrEqualTo" + ], + mapper: { + serializedName: "x-ms-if-sequence-number-le", + type: { + name: "Number" + } + } +}; +var ifTags = { + parameterPath: [ + "options", + "modifiedAccessConditions", + "ifTags" + ], + mapper: { + serializedName: "x-ms-if-tags", + type: { + name: "String" + } + } +}; +var ifUnmodifiedSince = { + parameterPath: [ + "options", + "modifiedAccessConditions", + "ifUnmodifiedSince" + ], + mapper: { + serializedName: "If-Unmodified-Since", + type: { + name: "DateTimeRfc1123" + } + } +}; +var include0 = { + parameterPath: [ + "options", + "include" + ], + mapper: { + serializedName: "include", + type: { + name: "Sequence", + element: { + type: { + name: "Enum", + allowedValues: [ + "metadata", + "deleted" + ] + } + } + } + }, + collectionFormat: coreHttp.QueryCollectionFormat.Csv +}; +var include1 = { + parameterPath: [ + "options", + "include" + ], + mapper: { + serializedName: "include", + type: { + name: "Sequence", + element: { + type: { + name: "Enum", + allowedValues: [ + "copy", + "deleted", + "metadata", + "snapshots", + "uncommittedblobs", + "versions", + "tags" + ] + } + } + } + }, + collectionFormat: coreHttp.QueryCollectionFormat.Csv +}; +var leaseId0 = { + parameterPath: [ + "options", + "leaseAccessConditions", + "leaseId" + ], + mapper: { + serializedName: "x-ms-lease-id", + type: { + name: "String" + } + } +}; +var leaseId1 = { + parameterPath: "leaseId", + mapper: { + required: true, + serializedName: "x-ms-lease-id", + type: { + name: "String" + } + } +}; +var listType = { + parameterPath: "listType", + mapper: { + required: true, + serializedName: "blocklisttype", + defaultValue: 'committed', + type: { + name: "Enum", + allowedValues: [ + "committed", + "uncommitted", + "all" + ] + } + } +}; +var marker0 = { + parameterPath: [ + "options", + "marker" + ], + mapper: { + serializedName: "marker", + type: { + name: "String" + } + } +}; +var maxPageSize = { + parameterPath: [ + "options", + "maxPageSize" + ], + mapper: { + serializedName: "maxresults", + constraints: { + InclusiveMinimum: 1 + }, + type: { + name: "Number" + } + } +}; +var maxSize = { + parameterPath: [ + "options", + "appendPositionAccessConditions", + "maxSize" + ], + mapper: { + serializedName: "x-ms-blob-condition-maxsize", + type: { + name: "Number" + } + } +}; +var metadata = { + parameterPath: [ + "options", + "metadata" + ], + mapper: { + serializedName: "x-ms-meta", + type: { + name: "Dictionary", + value: { + type: { + name: "String" + } + } + }, + headerCollectionPrefix: "x-ms-meta-" + } +}; +var multipartContentType = { + parameterPath: "multipartContentType", + mapper: { + required: true, + serializedName: "Content-Type", + type: { + name: "String" + } + } +}; +var owner = { + parameterPath: [ + "options", + "owner" + ], + mapper: { + serializedName: "x-ms-owner", + type: { + name: "String" + } + } +}; +var pageWrite0 = { + parameterPath: "pageWrite", + mapper: { + required: true, + isConstant: true, + serializedName: "x-ms-page-write", + defaultValue: 'update', + type: { + name: "String" + } + } +}; +var pageWrite1 = { + parameterPath: "pageWrite", + mapper: { + required: true, + isConstant: true, + serializedName: "x-ms-page-write", + defaultValue: 'clear', + type: { + name: "String" + } + } +}; +var pathRenameMode = { + parameterPath: [ + "options", + "pathRenameMode" + ], + mapper: { + serializedName: "mode", + type: { + name: "Enum", + allowedValues: [ + "legacy", + "posix" + ] + } + } +}; +var posixAcl = { + parameterPath: [ + "options", + "posixAcl" + ], + mapper: { + serializedName: "x-ms-acl", + type: { + name: "String" + } + } +}; +var posixPermissions = { + parameterPath: [ + "options", + "posixPermissions" + ], + mapper: { + serializedName: "x-ms-permissions", + type: { + name: "String" + } + } +}; +var posixUmask = { + parameterPath: [ + "options", + "posixUmask" + ], + mapper: { + serializedName: "x-ms-umask", + type: { + name: "String" + } + } +}; +var prefix = { + parameterPath: [ + "options", + "prefix" + ], + mapper: { + serializedName: "prefix", + type: { + name: "String" + } + } +}; +var preventEncryptionScopeOverride = { + parameterPath: [ + "options", + "containerEncryptionScope", + "preventEncryptionScopeOverride" + ], + mapper: { + serializedName: "x-ms-deny-encryption-scope-override", + type: { + name: "Boolean" + } + } +}; +var prevsnapshot = { + parameterPath: [ + "options", + "prevsnapshot" + ], + mapper: { + serializedName: "prevsnapshot", + type: { + name: "String" + } + } +}; +var prevSnapshotUrl = { + parameterPath: [ + "options", + "prevSnapshotUrl" + ], + mapper: { + serializedName: "x-ms-previous-snapshot-url", + type: { + name: "String" + } + } +}; +var proposedLeaseId0 = { + parameterPath: [ + "options", + "proposedLeaseId" + ], + mapper: { + serializedName: "x-ms-proposed-lease-id", + type: { + name: "String" + } + } +}; +var proposedLeaseId1 = { + parameterPath: "proposedLeaseId", + mapper: { + required: true, + serializedName: "x-ms-proposed-lease-id", + type: { + name: "String" + } + } +}; +var range0 = { + parameterPath: [ + "options", + "range" + ], + mapper: { + serializedName: "x-ms-range", + type: { + name: "String" + } + } +}; +var range1 = { + parameterPath: "range", + mapper: { + required: true, + serializedName: "x-ms-range", + type: { + name: "String" + } + } +}; +var rangeGetContentCRC64 = { + parameterPath: [ + "options", + "rangeGetContentCRC64" + ], + mapper: { + serializedName: "x-ms-range-get-content-crc64", + type: { + name: "Boolean" + } + } +}; +var rangeGetContentMD5 = { + parameterPath: [ + "options", + "rangeGetContentMD5" + ], + mapper: { + serializedName: "x-ms-range-get-content-md5", + type: { + name: "Boolean" + } + } +}; +var rehydratePriority = { + parameterPath: [ + "options", + "rehydratePriority" + ], + mapper: { + serializedName: "x-ms-rehydrate-priority", + type: { + name: "String" + } + } +}; +var renameSource = { + parameterPath: "renameSource", + mapper: { + required: true, + serializedName: "x-ms-rename-source", + type: { + name: "String" + } + } +}; +var requestId = { + parameterPath: [ + "options", + "requestId" + ], + mapper: { + serializedName: "x-ms-client-request-id", + type: { + name: "String" + } + } +}; +var restype0 = { + parameterPath: "restype", + mapper: { + required: true, + isConstant: true, + serializedName: "restype", + defaultValue: 'service', + type: { + name: "String" + } + } +}; +var restype1 = { + parameterPath: "restype", + mapper: { + required: true, + isConstant: true, + serializedName: "restype", + defaultValue: 'account', + type: { + name: "String" + } + } +}; +var restype2 = { + parameterPath: "restype", + mapper: { + required: true, + isConstant: true, + serializedName: "restype", + defaultValue: 'container', + type: { + name: "String" + } + } +}; +var sealBlob = { + parameterPath: [ + "options", + "sealBlob" + ], + mapper: { + serializedName: "x-ms-seal-blob", + type: { + name: "Boolean" + } + } +}; +var sequenceNumberAction = { + parameterPath: "sequenceNumberAction", + mapper: { + required: true, + serializedName: "x-ms-sequence-number-action", + type: { + name: "Enum", + allowedValues: [ + "max", + "update", + "increment" + ] + } + } +}; +var snapshot = { + parameterPath: [ + "options", + "snapshot" + ], + mapper: { + serializedName: "snapshot", + type: { + name: "String" + } + } +}; +var sourceContentCrc64 = { + parameterPath: [ + "options", + "sourceContentCrc64" + ], + mapper: { + serializedName: "x-ms-source-content-crc64", + type: { + name: "ByteArray" + } + } +}; +var sourceContentMD5 = { + parameterPath: [ + "options", + "sourceContentMD5" + ], + mapper: { + serializedName: "x-ms-source-content-md5", + type: { + name: "ByteArray" + } + } +}; +var sourceIfMatch = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfMatch" + ], + mapper: { + serializedName: "x-ms-source-if-match", + type: { + name: "String" + } + } +}; +var sourceIfModifiedSince = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfModifiedSince" + ], + mapper: { + serializedName: "x-ms-source-if-modified-since", + type: { + name: "DateTimeRfc1123" + } + } +}; +var sourceIfNoneMatch = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfNoneMatch" + ], + mapper: { + serializedName: "x-ms-source-if-none-match", + type: { + name: "String" + } + } +}; +var sourceIfTags = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfTags" + ], + mapper: { + serializedName: "x-ms-source-if-tags", + type: { + name: "String" + } + } +}; +var sourceIfUnmodifiedSince = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfUnmodifiedSince" + ], + mapper: { + serializedName: "x-ms-source-if-unmodified-since", + type: { + name: "DateTimeRfc1123" + } + } +}; +var sourceLeaseId = { + parameterPath: [ + "options", + "sourceLeaseId" + ], + mapper: { + serializedName: "x-ms-source-lease-id", + type: { + name: "String" + } + } +}; +var sourceRange0 = { + parameterPath: "sourceRange", + mapper: { + required: true, + serializedName: "x-ms-source-range", + type: { + name: "String" + } + } +}; +var sourceRange1 = { + parameterPath: [ + "options", + "sourceRange" + ], + mapper: { + serializedName: "x-ms-source-range", + type: { + name: "String" + } + } +}; +var sourceUrl = { + parameterPath: "sourceUrl", + mapper: { + required: true, + serializedName: "x-ms-copy-source", + type: { + name: "String" + } + } +}; +var tier0 = { + parameterPath: [ + "options", + "tier" + ], + mapper: { + serializedName: "x-ms-access-tier", + type: { + name: "String" + } + } +}; +var tier1 = { + parameterPath: "tier", + mapper: { + required: true, + serializedName: "x-ms-access-tier", + type: { + name: "String" + } + } +}; +var timeoutInSeconds = { + parameterPath: [ + "options", + "timeoutInSeconds" + ], + mapper: { + serializedName: "timeout", + constraints: { + InclusiveMinimum: 0 + }, + type: { + name: "Number" + } + } +}; +var transactionalContentCrc64 = { + parameterPath: [ + "options", + "transactionalContentCrc64" + ], + mapper: { + serializedName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } + } +}; +var transactionalContentMD5 = { + parameterPath: [ + "options", + "transactionalContentMD5" + ], + mapper: { + serializedName: "Content-MD5", + type: { + name: "ByteArray" + } + } +}; +var upn = { + parameterPath: [ + "options", + "upn" + ], + mapper: { + serializedName: "upn", + type: { + name: "Boolean" + } + } +}; +var url = { + parameterPath: "url", + mapper: { + required: true, + serializedName: "url", + defaultValue: '', + type: { + name: "String" + } + }, + skipEncoding: true +}; +var version = { + parameterPath: "version", + mapper: { + required: true, + isConstant: true, + serializedName: "x-ms-version", + defaultValue: '2019-12-12', + type: { + name: "String" + } + } +}; +var versionId = { + parameterPath: [ + "options", + "versionId" + ], + mapper: { + serializedName: "versionid", + type: { + name: "String" + } + } +}; +var where = { + parameterPath: [ + "options", + "where" + ], + mapper: { + serializedName: "where", + type: { + name: "String" + } + } +}; +var xMsRequiresSync = { + parameterPath: "xMsRequiresSync", + mapper: { + required: true, + isConstant: true, + serializedName: "x-ms-requires-sync", + defaultValue: 'true', + type: { + name: "String" + } + } +}; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ +/** Class representing a Service. */ +var Service = /** @class */ (function () { + /** + * Create a Service. + * @param {StorageClientContext} client Reference to the service client. + */ + function Service(client) { + this.client = client; + } + Service.prototype.setProperties = function (blobServiceProperties, options, callback) { + return this.client.sendOperationRequest({ + blobServiceProperties: blobServiceProperties, + options: options + }, setPropertiesOperationSpec, callback); + }; + Service.prototype.getProperties = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, getPropertiesOperationSpec, callback); + }; + Service.prototype.getStatistics = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, getStatisticsOperationSpec, callback); + }; + Service.prototype.listContainersSegment = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, listContainersSegmentOperationSpec, callback); + }; + Service.prototype.getUserDelegationKey = function (keyInfo, options, callback) { + return this.client.sendOperationRequest({ + keyInfo: keyInfo, + options: options + }, getUserDelegationKeyOperationSpec, callback); + }; + Service.prototype.getAccountInfo = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, getAccountInfoOperationSpec, callback); + }; + Service.prototype.submitBatch = function (body, contentLength, multipartContentType, options, callback) { + return this.client.sendOperationRequest({ + body: body, + contentLength: contentLength, + multipartContentType: multipartContentType, + options: options + }, submitBatchOperationSpec, callback); + }; + Service.prototype.filterBlobs = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, filterBlobsOperationSpec, callback); + }; + return Service; +}()); +// Operation Specifications +var serializer = new coreHttp.Serializer(Mappers, true); +var setPropertiesOperationSpec = { + httpMethod: "PUT", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + restype0, + comp0 + ], + headerParameters: [ + version, + requestId + ], + requestBody: { + parameterPath: "blobServiceProperties", + mapper: tslib.__assign(tslib.__assign({}, BlobServiceProperties), { required: true }) + }, + contentType: "application/xml; charset=utf-8", + responses: { + 202: { + headersMapper: ServiceSetPropertiesHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ServiceSetPropertiesHeaders + } + }, + isXML: true, + serializer: serializer +}; +var getPropertiesOperationSpec = { + httpMethod: "GET", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + restype0, + comp0 + ], + headerParameters: [ + version, + requestId + ], + responses: { + 200: { + bodyMapper: BlobServiceProperties, + headersMapper: ServiceGetPropertiesHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ServiceGetPropertiesHeaders + } + }, + isXML: true, + serializer: serializer +}; +var getStatisticsOperationSpec = { + httpMethod: "GET", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + restype0, + comp1 + ], + headerParameters: [ + version, + requestId + ], + responses: { + 200: { + bodyMapper: BlobServiceStatistics, + headersMapper: ServiceGetStatisticsHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ServiceGetStatisticsHeaders + } + }, + isXML: true, + serializer: serializer +}; +var listContainersSegmentOperationSpec = { + httpMethod: "GET", + urlParameters: [ + url + ], + queryParameters: [ + prefix, + marker0, + maxPageSize, + include0, + timeoutInSeconds, + comp2 + ], + headerParameters: [ + version, + requestId + ], + responses: { + 200: { + bodyMapper: ListContainersSegmentResponse, + headersMapper: ServiceListContainersSegmentHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ServiceListContainersSegmentHeaders + } + }, + isXML: true, + serializer: serializer +}; +var getUserDelegationKeyOperationSpec = { + httpMethod: "POST", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + restype0, + comp3 + ], + headerParameters: [ + version, + requestId + ], + requestBody: { + parameterPath: "keyInfo", + mapper: tslib.__assign(tslib.__assign({}, KeyInfo), { required: true }) + }, + contentType: "application/xml; charset=utf-8", + responses: { + 200: { + bodyMapper: UserDelegationKey, + headersMapper: ServiceGetUserDelegationKeyHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ServiceGetUserDelegationKeyHeaders + } + }, + isXML: true, + serializer: serializer +}; +var getAccountInfoOperationSpec = { + httpMethod: "GET", + urlParameters: [ + url + ], + queryParameters: [ + restype1, + comp0 + ], + headerParameters: [ + version + ], + responses: { + 200: { + headersMapper: ServiceGetAccountInfoHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ServiceGetAccountInfoHeaders + } + }, + isXML: true, + serializer: serializer +}; +var submitBatchOperationSpec = { + httpMethod: "POST", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp4 + ], + headerParameters: [ + contentLength, + multipartContentType, + version, + requestId + ], + requestBody: { + parameterPath: "body", + mapper: { + required: true, + serializedName: "body", + type: { + name: "Stream" + } + } + }, + contentType: "application/xml; charset=utf-8", + responses: { + 202: { + bodyMapper: { + serializedName: "parsedResponse", + type: { + name: "Stream" + } + }, + headersMapper: ServiceSubmitBatchHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ServiceSubmitBatchHeaders + } + }, + isXML: true, + serializer: serializer +}; +var filterBlobsOperationSpec = { + httpMethod: "GET", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + where, + marker0, + maxPageSize, + comp5 + ], + headerParameters: [ + version, + requestId + ], + responses: { + 200: { + bodyMapper: FilterBlobSegment, + headersMapper: ServiceFilterBlobsHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ServiceFilterBlobsHeaders + } + }, + isXML: true, + serializer: serializer +}; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +var Mappers$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + AccessPolicy: AccessPolicy, + BlobFlatListSegment: BlobFlatListSegment, + BlobHierarchyListSegment: BlobHierarchyListSegment, + BlobItemInternal: BlobItemInternal, + BlobPrefix: BlobPrefix, + BlobPropertiesInternal: BlobPropertiesInternal, + BlobTag: BlobTag, + BlobTags: BlobTags, + ContainerAcquireLeaseHeaders: ContainerAcquireLeaseHeaders, + ContainerBreakLeaseHeaders: ContainerBreakLeaseHeaders, + ContainerChangeLeaseHeaders: ContainerChangeLeaseHeaders, + ContainerCreateHeaders: ContainerCreateHeaders, + ContainerDeleteHeaders: ContainerDeleteHeaders, + ContainerGetAccessPolicyHeaders: ContainerGetAccessPolicyHeaders, + ContainerGetAccountInfoHeaders: ContainerGetAccountInfoHeaders, + ContainerGetPropertiesHeaders: ContainerGetPropertiesHeaders, + ContainerListBlobFlatSegmentHeaders: ContainerListBlobFlatSegmentHeaders, + ContainerListBlobHierarchySegmentHeaders: ContainerListBlobHierarchySegmentHeaders, + ContainerReleaseLeaseHeaders: ContainerReleaseLeaseHeaders, + ContainerRenewLeaseHeaders: ContainerRenewLeaseHeaders, + ContainerRestoreHeaders: ContainerRestoreHeaders, + ContainerSetAccessPolicyHeaders: ContainerSetAccessPolicyHeaders, + ContainerSetMetadataHeaders: ContainerSetMetadataHeaders, + ListBlobsFlatSegmentResponse: ListBlobsFlatSegmentResponse, + ListBlobsHierarchySegmentResponse: ListBlobsHierarchySegmentResponse, + SignedIdentifier: SignedIdentifier, + StorageError: StorageError +}); + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ +/** Class representing a Container. */ +var Container = /** @class */ (function () { + /** + * Create a Container. + * @param {StorageClientContext} client Reference to the service client. + */ + function Container(client) { + this.client = client; + } + Container.prototype.create = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, createOperationSpec, callback); + }; + Container.prototype.getProperties = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, getPropertiesOperationSpec$1, callback); + }; + Container.prototype.deleteMethod = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, deleteMethodOperationSpec, callback); + }; + Container.prototype.setMetadata = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, setMetadataOperationSpec, callback); + }; + Container.prototype.getAccessPolicy = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, getAccessPolicyOperationSpec, callback); + }; + Container.prototype.setAccessPolicy = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, setAccessPolicyOperationSpec, callback); + }; + Container.prototype.restore = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, restoreOperationSpec, callback); + }; + Container.prototype.acquireLease = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, acquireLeaseOperationSpec, callback); + }; + Container.prototype.releaseLease = function (leaseId, options, callback) { + return this.client.sendOperationRequest({ + leaseId: leaseId, + options: options + }, releaseLeaseOperationSpec, callback); + }; + Container.prototype.renewLease = function (leaseId, options, callback) { + return this.client.sendOperationRequest({ + leaseId: leaseId, + options: options + }, renewLeaseOperationSpec, callback); + }; + Container.prototype.breakLease = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, breakLeaseOperationSpec, callback); + }; + Container.prototype.changeLease = function (leaseId, proposedLeaseId, options, callback) { + return this.client.sendOperationRequest({ + leaseId: leaseId, + proposedLeaseId: proposedLeaseId, + options: options + }, changeLeaseOperationSpec, callback); + }; + Container.prototype.listBlobFlatSegment = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, listBlobFlatSegmentOperationSpec, callback); + }; + Container.prototype.listBlobHierarchySegment = function (delimiter, options, callback) { + return this.client.sendOperationRequest({ + delimiter: delimiter, + options: options + }, listBlobHierarchySegmentOperationSpec, callback); + }; + Container.prototype.getAccountInfo = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, getAccountInfoOperationSpec$1, callback); + }; + return Container; +}()); +// Operation Specifications +var serializer$1 = new coreHttp.Serializer(Mappers$1, true); +var createOperationSpec = { + httpMethod: "PUT", + path: "{containerName}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + restype2 + ], + headerParameters: [ + metadata, + access, + version, + requestId, + defaultEncryptionScope, + preventEncryptionScopeOverride + ], + responses: { + 201: { + headersMapper: ContainerCreateHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerCreateHeaders + } + }, + isXML: true, + serializer: serializer$1 +}; +var getPropertiesOperationSpec$1 = { + httpMethod: "GET", + path: "{containerName}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + restype2 + ], + headerParameters: [ + version, + requestId, + leaseId0 + ], + responses: { + 200: { + headersMapper: ContainerGetPropertiesHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerGetPropertiesHeaders + } + }, + isXML: true, + serializer: serializer$1 +}; +var deleteMethodOperationSpec = { + httpMethod: "DELETE", + path: "{containerName}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + restype2 + ], + headerParameters: [ + version, + requestId, + leaseId0, + ifModifiedSince, + ifUnmodifiedSince + ], + responses: { + 202: { + headersMapper: ContainerDeleteHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerDeleteHeaders + } + }, + isXML: true, + serializer: serializer$1 +}; +var setMetadataOperationSpec = { + httpMethod: "PUT", + path: "{containerName}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + restype2, + comp6 + ], + headerParameters: [ + metadata, + version, + requestId, + leaseId0, + ifModifiedSince + ], + responses: { + 200: { + headersMapper: ContainerSetMetadataHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerSetMetadataHeaders + } + }, + isXML: true, + serializer: serializer$1 +}; +var getAccessPolicyOperationSpec = { + httpMethod: "GET", + path: "{containerName}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + restype2, + comp7 + ], + headerParameters: [ + version, + requestId, + leaseId0 + ], + responses: { + 200: { + bodyMapper: { + xmlElementName: "SignedIdentifier", + serializedName: "parsedResponse", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "SignedIdentifier" + } + } + } + }, + headersMapper: ContainerGetAccessPolicyHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerGetAccessPolicyHeaders + } + }, + isXML: true, + serializer: serializer$1 +}; +var setAccessPolicyOperationSpec = { + httpMethod: "PUT", + path: "{containerName}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + restype2, + comp7 + ], + headerParameters: [ + access, + version, + requestId, + leaseId0, + ifModifiedSince, + ifUnmodifiedSince + ], + requestBody: { + parameterPath: [ + "options", + "containerAcl" + ], + mapper: { + xmlName: "SignedIdentifiers", + xmlElementName: "SignedIdentifier", + serializedName: "containerAcl", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "SignedIdentifier" + } + } + } + } + }, + contentType: "application/xml; charset=utf-8", + responses: { + 200: { + headersMapper: ContainerSetAccessPolicyHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerSetAccessPolicyHeaders + } + }, + isXML: true, + serializer: serializer$1 +}; +var restoreOperationSpec = { + httpMethod: "PUT", + path: "{containerName}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + restype2, + comp8 + ], + headerParameters: [ + version, + requestId, + deletedContainerName, + deletedContainerVersion + ], + responses: { + 201: { + headersMapper: ContainerRestoreHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerRestoreHeaders + } + }, + isXML: true, + serializer: serializer$1 +}; +var acquireLeaseOperationSpec = { + httpMethod: "PUT", + path: "{containerName}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp9, + restype2 + ], + headerParameters: [ + duration, + proposedLeaseId0, + version, + requestId, + action0, + ifModifiedSince, + ifUnmodifiedSince + ], + responses: { + 201: { + headersMapper: ContainerAcquireLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerAcquireLeaseHeaders + } + }, + isXML: true, + serializer: serializer$1 +}; +var releaseLeaseOperationSpec = { + httpMethod: "PUT", + path: "{containerName}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp9, + restype2 + ], + headerParameters: [ + leaseId1, + version, + requestId, + action1, + ifModifiedSince, + ifUnmodifiedSince + ], + responses: { + 200: { + headersMapper: ContainerReleaseLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerReleaseLeaseHeaders + } + }, + isXML: true, + serializer: serializer$1 +}; +var renewLeaseOperationSpec = { + httpMethod: "PUT", + path: "{containerName}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp9, + restype2 + ], + headerParameters: [ + leaseId1, + version, + requestId, + action2, + ifModifiedSince, + ifUnmodifiedSince + ], + responses: { + 200: { + headersMapper: ContainerRenewLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerRenewLeaseHeaders + } + }, + isXML: true, + serializer: serializer$1 +}; +var breakLeaseOperationSpec = { + httpMethod: "PUT", + path: "{containerName}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp9, + restype2 + ], + headerParameters: [ + breakPeriod, + version, + requestId, + action3, + ifModifiedSince, + ifUnmodifiedSince + ], + responses: { + 202: { + headersMapper: ContainerBreakLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerBreakLeaseHeaders + } + }, + isXML: true, + serializer: serializer$1 +}; +var changeLeaseOperationSpec = { + httpMethod: "PUT", + path: "{containerName}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp9, + restype2 + ], + headerParameters: [ + leaseId1, + proposedLeaseId1, + version, + requestId, + action4, + ifModifiedSince, + ifUnmodifiedSince + ], + responses: { + 200: { + headersMapper: ContainerChangeLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerChangeLeaseHeaders + } + }, + isXML: true, + serializer: serializer$1 +}; +var listBlobFlatSegmentOperationSpec = { + httpMethod: "GET", + path: "{containerName}", + urlParameters: [ + url + ], + queryParameters: [ + prefix, + marker0, + maxPageSize, + include1, + timeoutInSeconds, + restype2, + comp2 + ], + headerParameters: [ + version, + requestId + ], + responses: { + 200: { + bodyMapper: ListBlobsFlatSegmentResponse, + headersMapper: ContainerListBlobFlatSegmentHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerListBlobFlatSegmentHeaders + } + }, + isXML: true, + serializer: serializer$1 +}; +var listBlobHierarchySegmentOperationSpec = { + httpMethod: "GET", + path: "{containerName}", + urlParameters: [ + url + ], + queryParameters: [ + prefix, + delimiter, + marker0, + maxPageSize, + include1, + timeoutInSeconds, + restype2, + comp2 + ], + headerParameters: [ + version, + requestId + ], + responses: { + 200: { + bodyMapper: ListBlobsHierarchySegmentResponse, + headersMapper: ContainerListBlobHierarchySegmentHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerListBlobHierarchySegmentHeaders + } + }, + isXML: true, + serializer: serializer$1 +}; +var getAccountInfoOperationSpec$1 = { + httpMethod: "GET", + path: "{containerName}", + urlParameters: [ + url + ], + queryParameters: [ + restype1, + comp0 + ], + headerParameters: [ + version + ], + responses: { + 200: { + headersMapper: ContainerGetAccountInfoHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: ContainerGetAccountInfoHeaders + } + }, + isXML: true, + serializer: serializer$1 +}; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +var Mappers$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + BlobAbortCopyFromURLHeaders: BlobAbortCopyFromURLHeaders, + BlobAcquireLeaseHeaders: BlobAcquireLeaseHeaders, + BlobBreakLeaseHeaders: BlobBreakLeaseHeaders, + BlobChangeLeaseHeaders: BlobChangeLeaseHeaders, + BlobCopyFromURLHeaders: BlobCopyFromURLHeaders, + BlobCreateSnapshotHeaders: BlobCreateSnapshotHeaders, + BlobDeleteHeaders: BlobDeleteHeaders, + BlobDownloadHeaders: BlobDownloadHeaders, + BlobGetAccessControlHeaders: BlobGetAccessControlHeaders, + BlobGetAccountInfoHeaders: BlobGetAccountInfoHeaders, + BlobGetPropertiesHeaders: BlobGetPropertiesHeaders, + BlobGetTagsHeaders: BlobGetTagsHeaders, + BlobQueryHeaders: BlobQueryHeaders, + BlobReleaseLeaseHeaders: BlobReleaseLeaseHeaders, + BlobRenameHeaders: BlobRenameHeaders, + BlobRenewLeaseHeaders: BlobRenewLeaseHeaders, + BlobSetAccessControlHeaders: BlobSetAccessControlHeaders, + BlobSetExpiryHeaders: BlobSetExpiryHeaders, + BlobSetHTTPHeadersHeaders: BlobSetHTTPHeadersHeaders, + BlobSetMetadataHeaders: BlobSetMetadataHeaders, + BlobSetTagsHeaders: BlobSetTagsHeaders, + BlobSetTierHeaders: BlobSetTierHeaders, + BlobStartCopyFromURLHeaders: BlobStartCopyFromURLHeaders, + BlobTag: BlobTag, + BlobTags: BlobTags, + BlobUndeleteHeaders: BlobUndeleteHeaders, + DataLakeStorageError: DataLakeStorageError, + DataLakeStorageErrorError: DataLakeStorageErrorError, + DelimitedTextConfiguration: DelimitedTextConfiguration, + JsonTextConfiguration: JsonTextConfiguration, + QueryFormat: QueryFormat, + QueryRequest: QueryRequest, + QuerySerialization: QuerySerialization, + StorageError: StorageError +}); + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ +/** Class representing a Blob. */ +var Blob$1 = /** @class */ (function () { + /** + * Create a Blob. + * @param {StorageClientContext} client Reference to the service client. + */ + function Blob(client) { + this.client = client; + } + Blob.prototype.download = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, downloadOperationSpec, callback); + }; + Blob.prototype.getProperties = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, getPropertiesOperationSpec$2, callback); + }; + Blob.prototype.deleteMethod = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, deleteMethodOperationSpec$1, callback); + }; + Blob.prototype.setAccessControl = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, setAccessControlOperationSpec, callback); + }; + Blob.prototype.getAccessControl = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, getAccessControlOperationSpec, callback); + }; + Blob.prototype.rename = function (renameSource, options, callback) { + return this.client.sendOperationRequest({ + renameSource: renameSource, + options: options + }, renameOperationSpec, callback); + }; + Blob.prototype.undelete = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, undeleteOperationSpec, callback); + }; + Blob.prototype.setExpiry = function (expiryOptions, options, callback) { + return this.client.sendOperationRequest({ + expiryOptions: expiryOptions, + options: options + }, setExpiryOperationSpec, callback); + }; + Blob.prototype.setHTTPHeaders = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, setHTTPHeadersOperationSpec, callback); + }; + Blob.prototype.setMetadata = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, setMetadataOperationSpec$1, callback); + }; + Blob.prototype.acquireLease = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, acquireLeaseOperationSpec$1, callback); + }; + Blob.prototype.releaseLease = function (leaseId, options, callback) { + return this.client.sendOperationRequest({ + leaseId: leaseId, + options: options + }, releaseLeaseOperationSpec$1, callback); + }; + Blob.prototype.renewLease = function (leaseId, options, callback) { + return this.client.sendOperationRequest({ + leaseId: leaseId, + options: options + }, renewLeaseOperationSpec$1, callback); + }; + Blob.prototype.changeLease = function (leaseId, proposedLeaseId, options, callback) { + return this.client.sendOperationRequest({ + leaseId: leaseId, + proposedLeaseId: proposedLeaseId, + options: options + }, changeLeaseOperationSpec$1, callback); + }; + Blob.prototype.breakLease = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, breakLeaseOperationSpec$1, callback); + }; + Blob.prototype.createSnapshot = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, createSnapshotOperationSpec, callback); + }; + Blob.prototype.startCopyFromURL = function (copySource, options, callback) { + return this.client.sendOperationRequest({ + copySource: copySource, + options: options + }, startCopyFromURLOperationSpec, callback); + }; + Blob.prototype.copyFromURL = function (copySource, options, callback) { + return this.client.sendOperationRequest({ + copySource: copySource, + options: options + }, copyFromURLOperationSpec, callback); + }; + Blob.prototype.abortCopyFromURL = function (copyId, options, callback) { + return this.client.sendOperationRequest({ + copyId: copyId, + options: options + }, abortCopyFromURLOperationSpec, callback); + }; + Blob.prototype.setTier = function (tier, options, callback) { + return this.client.sendOperationRequest({ + tier: tier, + options: options + }, setTierOperationSpec, callback); + }; + Blob.prototype.getAccountInfo = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, getAccountInfoOperationSpec$2, callback); + }; + Blob.prototype.query = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, queryOperationSpec, callback); + }; + Blob.prototype.getTags = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, getTagsOperationSpec, callback); + }; + Blob.prototype.setTags = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, setTagsOperationSpec, callback); + }; + return Blob; +}()); +// Operation Specifications +var serializer$2 = new coreHttp.Serializer(Mappers$2, true); +var downloadOperationSpec = { + httpMethod: "GET", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + snapshot, + versionId, + timeoutInSeconds + ], + headerParameters: [ + range0, + rangeGetContentMD5, + rangeGetContentCRC64, + version, + requestId, + leaseId0, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 200: { + bodyMapper: { + serializedName: "parsedResponse", + type: { + name: "Stream" + } + }, + headersMapper: BlobDownloadHeaders + }, + 206: { + bodyMapper: { + serializedName: "parsedResponse", + type: { + name: "Stream" + } + }, + headersMapper: BlobDownloadHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobDownloadHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var getPropertiesOperationSpec$2 = { + httpMethod: "HEAD", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + snapshot, + versionId, + timeoutInSeconds + ], + headerParameters: [ + version, + requestId, + leaseId0, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 200: { + headersMapper: BlobGetPropertiesHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobGetPropertiesHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var deleteMethodOperationSpec$1 = { + httpMethod: "DELETE", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + snapshot, + versionId, + timeoutInSeconds + ], + headerParameters: [ + deleteSnapshots, + version, + requestId, + leaseId0, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 202: { + headersMapper: BlobDeleteHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobDeleteHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var setAccessControlOperationSpec = { + httpMethod: "PATCH", + path: "{filesystem}/{path}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + action5 + ], + headerParameters: [ + owner, + group, + posixPermissions, + posixAcl, + requestId, + version, + leaseId0, + ifMatch, + ifNoneMatch, + ifModifiedSince, + ifUnmodifiedSince + ], + responses: { + 200: { + headersMapper: BlobSetAccessControlHeaders + }, + default: { + bodyMapper: DataLakeStorageError, + headersMapper: BlobSetAccessControlHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var getAccessControlOperationSpec = { + httpMethod: "HEAD", + path: "{filesystem}/{path}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + upn, + action6 + ], + headerParameters: [ + requestId, + version, + leaseId0, + ifMatch, + ifNoneMatch, + ifModifiedSince, + ifUnmodifiedSince + ], + responses: { + 200: { + headersMapper: BlobGetAccessControlHeaders + }, + default: { + bodyMapper: DataLakeStorageError, + headersMapper: BlobGetAccessControlHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var renameOperationSpec = { + httpMethod: "PUT", + path: "{filesystem}/{path}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + pathRenameMode + ], + headerParameters: [ + renameSource, + directoryProperties, + posixPermissions, + posixUmask, + sourceLeaseId, + version, + requestId, + cacheControl, + contentType, + contentEncoding, + contentLanguage, + contentDisposition, + leaseId0, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch + ], + responses: { + 201: { + headersMapper: BlobRenameHeaders + }, + default: { + bodyMapper: DataLakeStorageError, + headersMapper: BlobRenameHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var undeleteOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp8 + ], + headerParameters: [ + version, + requestId + ], + responses: { + 200: { + headersMapper: BlobUndeleteHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobUndeleteHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var setExpiryOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp10 + ], + headerParameters: [ + version, + requestId, + expiryOptions, + expiresOn + ], + responses: { + 200: { + headersMapper: BlobSetExpiryHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobSetExpiryHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var setHTTPHeadersOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp0 + ], + headerParameters: [ + version, + requestId, + blobCacheControl, + blobContentType, + blobContentMD5, + blobContentEncoding, + blobContentLanguage, + blobContentDisposition, + leaseId0, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 200: { + headersMapper: BlobSetHTTPHeadersHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobSetHTTPHeadersHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var setMetadataOperationSpec$1 = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp6 + ], + headerParameters: [ + metadata, + encryptionScope, + version, + requestId, + leaseId0, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 200: { + headersMapper: BlobSetMetadataHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobSetMetadataHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var acquireLeaseOperationSpec$1 = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp9 + ], + headerParameters: [ + duration, + proposedLeaseId0, + version, + requestId, + action0, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 201: { + headersMapper: BlobAcquireLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobAcquireLeaseHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var releaseLeaseOperationSpec$1 = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp9 + ], + headerParameters: [ + leaseId1, + version, + requestId, + action1, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 200: { + headersMapper: BlobReleaseLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobReleaseLeaseHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var renewLeaseOperationSpec$1 = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp9 + ], + headerParameters: [ + leaseId1, + version, + requestId, + action2, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 200: { + headersMapper: BlobRenewLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobRenewLeaseHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var changeLeaseOperationSpec$1 = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp9 + ], + headerParameters: [ + leaseId1, + proposedLeaseId1, + version, + requestId, + action4, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 200: { + headersMapper: BlobChangeLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobChangeLeaseHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var breakLeaseOperationSpec$1 = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp9 + ], + headerParameters: [ + breakPeriod, + version, + requestId, + action3, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 202: { + headersMapper: BlobBreakLeaseHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobBreakLeaseHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var createSnapshotOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp11 + ], + headerParameters: [ + metadata, + encryptionScope, + version, + requestId, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags, + leaseId0 + ], + responses: { + 201: { + headersMapper: BlobCreateSnapshotHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobCreateSnapshotHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var startCopyFromURLOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds + ], + headerParameters: [ + metadata, + tier0, + rehydratePriority, + copySource, + version, + requestId, + blobTagsString, + sealBlob, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch, + sourceIfTags, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags, + leaseId0 + ], + responses: { + 202: { + headersMapper: BlobStartCopyFromURLHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobStartCopyFromURLHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var copyFromURLOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds + ], + headerParameters: [ + metadata, + tier0, + copySource, + version, + requestId, + sourceContentMD5, + blobTagsString, + xMsRequiresSync, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags, + leaseId0 + ], + responses: { + 202: { + headersMapper: BlobCopyFromURLHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobCopyFromURLHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var abortCopyFromURLOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + copyId, + timeoutInSeconds, + comp12 + ], + headerParameters: [ + version, + requestId, + copyActionAbortConstant, + leaseId0 + ], + responses: { + 204: { + headersMapper: BlobAbortCopyFromURLHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobAbortCopyFromURLHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var setTierOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + snapshot, + versionId, + timeoutInSeconds, + comp13 + ], + headerParameters: [ + tier1, + rehydratePriority, + version, + requestId, + leaseId0, + ifTags + ], + responses: { + 200: { + headersMapper: BlobSetTierHeaders + }, + 202: { + headersMapper: BlobSetTierHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobSetTierHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var getAccountInfoOperationSpec$2 = { + httpMethod: "GET", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + restype1, + comp0 + ], + headerParameters: [ + version + ], + responses: { + 200: { + headersMapper: BlobGetAccountInfoHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobGetAccountInfoHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var queryOperationSpec = { + httpMethod: "POST", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + snapshot, + timeoutInSeconds, + comp14 + ], + headerParameters: [ + version, + requestId, + leaseId0, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + requestBody: { + parameterPath: [ + "options", + "queryRequest" + ], + mapper: QueryRequest + }, + contentType: "application/xml; charset=utf-8", + responses: { + 200: { + bodyMapper: { + serializedName: "parsedResponse", + type: { + name: "Stream" + } + }, + headersMapper: BlobQueryHeaders + }, + 206: { + bodyMapper: { + serializedName: "parsedResponse", + type: { + name: "Stream" + } + }, + headersMapper: BlobQueryHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobQueryHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var getTagsOperationSpec = { + httpMethod: "GET", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + snapshot, + versionId, + comp15 + ], + headerParameters: [ + version, + requestId, + ifTags + ], + responses: { + 200: { + bodyMapper: BlobTags, + headersMapper: BlobGetTagsHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobGetTagsHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; +var setTagsOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + versionId, + comp15 + ], + headerParameters: [ + version, + transactionalContentMD5, + transactionalContentCrc64, + requestId, + ifTags + ], + requestBody: { + parameterPath: [ + "options", + "tags" + ], + mapper: BlobTags + }, + contentType: "application/xml; charset=utf-8", + responses: { + 204: { + headersMapper: BlobSetTagsHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobSetTagsHeaders + } + }, + isXML: true, + serializer: serializer$2 +}; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +var Mappers$3 = /*#__PURE__*/Object.freeze({ + __proto__: null, + ClearRange: ClearRange, + PageBlobClearPagesHeaders: PageBlobClearPagesHeaders, + PageBlobCopyIncrementalHeaders: PageBlobCopyIncrementalHeaders, + PageBlobCreateHeaders: PageBlobCreateHeaders, + PageBlobGetPageRangesDiffHeaders: PageBlobGetPageRangesDiffHeaders, + PageBlobGetPageRangesHeaders: PageBlobGetPageRangesHeaders, + PageBlobResizeHeaders: PageBlobResizeHeaders, + PageBlobUpdateSequenceNumberHeaders: PageBlobUpdateSequenceNumberHeaders, + PageBlobUploadPagesFromURLHeaders: PageBlobUploadPagesFromURLHeaders, + PageBlobUploadPagesHeaders: PageBlobUploadPagesHeaders, + PageList: PageList, + PageRange: PageRange, + StorageError: StorageError +}); + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ +/** Class representing a PageBlob. */ +var PageBlob = /** @class */ (function () { + /** + * Create a PageBlob. + * @param {StorageClientContext} client Reference to the service client. + */ + function PageBlob(client) { + this.client = client; + } + PageBlob.prototype.create = function (contentLength, blobContentLength, options, callback) { + return this.client.sendOperationRequest({ + contentLength: contentLength, + blobContentLength: blobContentLength, + options: options + }, createOperationSpec$1, callback); + }; + PageBlob.prototype.uploadPages = function (body, contentLength, options, callback) { + return this.client.sendOperationRequest({ + body: body, + contentLength: contentLength, + options: options + }, uploadPagesOperationSpec, callback); + }; + PageBlob.prototype.clearPages = function (contentLength, options, callback) { + return this.client.sendOperationRequest({ + contentLength: contentLength, + options: options + }, clearPagesOperationSpec, callback); + }; + PageBlob.prototype.uploadPagesFromURL = function (sourceUrl, sourceRange, contentLength, range, options, callback) { + return this.client.sendOperationRequest({ + sourceUrl: sourceUrl, + sourceRange: sourceRange, + contentLength: contentLength, + range: range, + options: options + }, uploadPagesFromURLOperationSpec, callback); + }; + PageBlob.prototype.getPageRanges = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, getPageRangesOperationSpec, callback); + }; + PageBlob.prototype.getPageRangesDiff = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, getPageRangesDiffOperationSpec, callback); + }; + PageBlob.prototype.resize = function (blobContentLength, options, callback) { + return this.client.sendOperationRequest({ + blobContentLength: blobContentLength, + options: options + }, resizeOperationSpec, callback); + }; + PageBlob.prototype.updateSequenceNumber = function (sequenceNumberAction, options, callback) { + return this.client.sendOperationRequest({ + sequenceNumberAction: sequenceNumberAction, + options: options + }, updateSequenceNumberOperationSpec, callback); + }; + PageBlob.prototype.copyIncremental = function (copySource, options, callback) { + return this.client.sendOperationRequest({ + copySource: copySource, + options: options + }, copyIncrementalOperationSpec, callback); + }; + return PageBlob; +}()); +// Operation Specifications +var serializer$3 = new coreHttp.Serializer(Mappers$3, true); +var createOperationSpec$1 = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds + ], + headerParameters: [ + contentLength, + tier0, + metadata, + encryptionScope, + blobContentLength, + blobSequenceNumber, + version, + requestId, + blobTagsString, + blobType0, + blobContentType, + blobContentEncoding, + blobContentLanguage, + blobContentMD5, + blobCacheControl, + blobContentDisposition, + leaseId0, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 201: { + headersMapper: PageBlobCreateHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobCreateHeaders + } + }, + isXML: true, + serializer: serializer$3 +}; +var uploadPagesOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp16 + ], + headerParameters: [ + contentLength, + transactionalContentMD5, + transactionalContentCrc64, + range0, + encryptionScope, + version, + requestId, + pageWrite0, + leaseId0, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifSequenceNumberLessThanOrEqualTo, + ifSequenceNumberLessThan, + ifSequenceNumberEqualTo, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + requestBody: { + parameterPath: "body", + mapper: { + required: true, + serializedName: "body", + type: { + name: "Stream" + } + } + }, + contentType: "application/octet-stream", + responses: { + 201: { + headersMapper: PageBlobUploadPagesHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobUploadPagesHeaders + } + }, + isXML: true, + serializer: serializer$3 +}; +var clearPagesOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp16 + ], + headerParameters: [ + contentLength, + range0, + encryptionScope, + version, + requestId, + pageWrite1, + leaseId0, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifSequenceNumberLessThanOrEqualTo, + ifSequenceNumberLessThan, + ifSequenceNumberEqualTo, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 201: { + headersMapper: PageBlobClearPagesHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobClearPagesHeaders + } + }, + isXML: true, + serializer: serializer$3 +}; +var uploadPagesFromURLOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp16 + ], + headerParameters: [ + sourceUrl, + sourceRange0, + sourceContentMD5, + sourceContentCrc64, + contentLength, + range1, + encryptionScope, + version, + requestId, + pageWrite0, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + leaseId0, + ifSequenceNumberLessThanOrEqualTo, + ifSequenceNumberLessThan, + ifSequenceNumberEqualTo, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch + ], + responses: { + 201: { + headersMapper: PageBlobUploadPagesFromURLHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobUploadPagesFromURLHeaders + } + }, + isXML: true, + serializer: serializer$3 +}; +var getPageRangesOperationSpec = { + httpMethod: "GET", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + snapshot, + timeoutInSeconds, + comp17 + ], + headerParameters: [ + range0, + version, + requestId, + leaseId0, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 200: { + bodyMapper: PageList, + headersMapper: PageBlobGetPageRangesHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobGetPageRangesHeaders + } + }, + isXML: true, + serializer: serializer$3 +}; +var getPageRangesDiffOperationSpec = { + httpMethod: "GET", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + snapshot, + timeoutInSeconds, + prevsnapshot, + comp17 + ], + headerParameters: [ + prevSnapshotUrl, + range0, + version, + requestId, + leaseId0, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 200: { + bodyMapper: PageList, + headersMapper: PageBlobGetPageRangesDiffHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobGetPageRangesDiffHeaders + } + }, + isXML: true, + serializer: serializer$3 +}; +var resizeOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp0 + ], + headerParameters: [ + encryptionScope, + blobContentLength, + version, + requestId, + leaseId0, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 200: { + headersMapper: PageBlobResizeHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobResizeHeaders + } + }, + isXML: true, + serializer: serializer$3 +}; +var updateSequenceNumberOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp0 + ], + headerParameters: [ + sequenceNumberAction, + blobSequenceNumber, + version, + requestId, + leaseId0, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 200: { + headersMapper: PageBlobUpdateSequenceNumberHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobUpdateSequenceNumberHeaders + } + }, + isXML: true, + serializer: serializer$3 +}; +var copyIncrementalOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp18 + ], + headerParameters: [ + copySource, + version, + requestId, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 202: { + headersMapper: PageBlobCopyIncrementalHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: PageBlobCopyIncrementalHeaders + } + }, + isXML: true, + serializer: serializer$3 +}; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +var Mappers$4 = /*#__PURE__*/Object.freeze({ + __proto__: null, + AppendBlobAppendBlockFromUrlHeaders: AppendBlobAppendBlockFromUrlHeaders, + AppendBlobAppendBlockHeaders: AppendBlobAppendBlockHeaders, + AppendBlobCreateHeaders: AppendBlobCreateHeaders, + AppendBlobSealHeaders: AppendBlobSealHeaders, + StorageError: StorageError +}); + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ +/** Class representing a AppendBlob. */ +var AppendBlob = /** @class */ (function () { + /** + * Create a AppendBlob. + * @param {StorageClientContext} client Reference to the service client. + */ + function AppendBlob(client) { + this.client = client; + } + AppendBlob.prototype.create = function (contentLength, options, callback) { + return this.client.sendOperationRequest({ + contentLength: contentLength, + options: options + }, createOperationSpec$2, callback); + }; + AppendBlob.prototype.appendBlock = function (body, contentLength, options, callback) { + return this.client.sendOperationRequest({ + body: body, + contentLength: contentLength, + options: options + }, appendBlockOperationSpec, callback); + }; + AppendBlob.prototype.appendBlockFromUrl = function (sourceUrl, contentLength, options, callback) { + return this.client.sendOperationRequest({ + sourceUrl: sourceUrl, + contentLength: contentLength, + options: options + }, appendBlockFromUrlOperationSpec, callback); + }; + AppendBlob.prototype.seal = function (options, callback) { + return this.client.sendOperationRequest({ + options: options + }, sealOperationSpec, callback); + }; + return AppendBlob; +}()); +// Operation Specifications +var serializer$4 = new coreHttp.Serializer(Mappers$4, true); +var createOperationSpec$2 = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds + ], + headerParameters: [ + contentLength, + metadata, + encryptionScope, + version, + requestId, + blobTagsString, + blobType1, + blobContentType, + blobContentEncoding, + blobContentLanguage, + blobContentMD5, + blobCacheControl, + blobContentDisposition, + leaseId0, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + responses: { + 201: { + headersMapper: AppendBlobCreateHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: AppendBlobCreateHeaders + } + }, + isXML: true, + serializer: serializer$4 +}; +var appendBlockOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp19 + ], + headerParameters: [ + contentLength, + transactionalContentMD5, + transactionalContentCrc64, + encryptionScope, + version, + requestId, + leaseId0, + maxSize, + appendPosition, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + requestBody: { + parameterPath: "body", + mapper: { + required: true, + serializedName: "body", + type: { + name: "Stream" + } + } + }, + contentType: "application/octet-stream", + responses: { + 201: { + headersMapper: AppendBlobAppendBlockHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: AppendBlobAppendBlockHeaders + } + }, + isXML: true, + serializer: serializer$4 +}; +var appendBlockFromUrlOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp19 + ], + headerParameters: [ + sourceUrl, + sourceRange1, + sourceContentMD5, + sourceContentCrc64, + contentLength, + transactionalContentMD5, + encryptionScope, + version, + requestId, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + leaseId0, + maxSize, + appendPosition, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch + ], + responses: { + 201: { + headersMapper: AppendBlobAppendBlockFromUrlHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: AppendBlobAppendBlockFromUrlHeaders + } + }, + isXML: true, + serializer: serializer$4 +}; +var sealOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp20 + ], + headerParameters: [ + version, + requestId, + leaseId0, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + appendPosition + ], + responses: { + 200: { + headersMapper: AppendBlobSealHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: AppendBlobSealHeaders + } + }, + isXML: true, + serializer: serializer$4 +}; + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +var Mappers$5 = /*#__PURE__*/Object.freeze({ + __proto__: null, + Block: Block, + BlockBlobCommitBlockListHeaders: BlockBlobCommitBlockListHeaders, + BlockBlobGetBlockListHeaders: BlockBlobGetBlockListHeaders, + BlockBlobStageBlockFromURLHeaders: BlockBlobStageBlockFromURLHeaders, + BlockBlobStageBlockHeaders: BlockBlobStageBlockHeaders, + BlockBlobUploadHeaders: BlockBlobUploadHeaders, + BlockList: BlockList, + BlockLookupList: BlockLookupList, + StorageError: StorageError +}); + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ +/** Class representing a BlockBlob. */ +var BlockBlob = /** @class */ (function () { + /** + * Create a BlockBlob. + * @param {StorageClientContext} client Reference to the service client. + */ + function BlockBlob(client) { + this.client = client; + } + BlockBlob.prototype.upload = function (body, contentLength, options, callback) { + return this.client.sendOperationRequest({ + body: body, + contentLength: contentLength, + options: options + }, uploadOperationSpec, callback); + }; + BlockBlob.prototype.stageBlock = function (blockId, contentLength, body, options, callback) { + return this.client.sendOperationRequest({ + blockId: blockId, + contentLength: contentLength, + body: body, + options: options + }, stageBlockOperationSpec, callback); + }; + BlockBlob.prototype.stageBlockFromURL = function (blockId, contentLength, sourceUrl, options, callback) { + return this.client.sendOperationRequest({ + blockId: blockId, + contentLength: contentLength, + sourceUrl: sourceUrl, + options: options + }, stageBlockFromURLOperationSpec, callback); + }; + BlockBlob.prototype.commitBlockList = function (blocks, options, callback) { + return this.client.sendOperationRequest({ + blocks: blocks, + options: options + }, commitBlockListOperationSpec, callback); + }; + BlockBlob.prototype.getBlockList = function (listType, options, callback) { + return this.client.sendOperationRequest({ + listType: listType, + options: options + }, getBlockListOperationSpec, callback); + }; + return BlockBlob; +}()); +// Operation Specifications +var serializer$5 = new coreHttp.Serializer(Mappers$5, true); +var uploadOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds + ], + headerParameters: [ + transactionalContentMD5, + contentLength, + metadata, + encryptionScope, + tier0, + version, + requestId, + blobTagsString, + blobType2, + blobContentType, + blobContentEncoding, + blobContentLanguage, + blobContentMD5, + blobCacheControl, + blobContentDisposition, + leaseId0, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + requestBody: { + parameterPath: "body", + mapper: { + required: true, + serializedName: "body", + type: { + name: "Stream" + } + } + }, + contentType: "application/octet-stream", + responses: { + 201: { + headersMapper: BlockBlobUploadHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlockBlobUploadHeaders + } + }, + isXML: true, + serializer: serializer$5 +}; +var stageBlockOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + blockId, + timeoutInSeconds, + comp21 + ], + headerParameters: [ + contentLength, + transactionalContentMD5, + transactionalContentCrc64, + encryptionScope, + version, + requestId, + leaseId0, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm + ], + requestBody: { + parameterPath: "body", + mapper: { + required: true, + serializedName: "body", + type: { + name: "Stream" + } + } + }, + contentType: "application/octet-stream", + responses: { + 201: { + headersMapper: BlockBlobStageBlockHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlockBlobStageBlockHeaders + } + }, + isXML: true, + serializer: serializer$5 +}; +var stageBlockFromURLOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + blockId, + timeoutInSeconds, + comp21 + ], + headerParameters: [ + contentLength, + sourceUrl, + sourceRange1, + sourceContentMD5, + sourceContentCrc64, + encryptionScope, + version, + requestId, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + leaseId0, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch + ], + responses: { + 201: { + headersMapper: BlockBlobStageBlockFromURLHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlockBlobStageBlockFromURLHeaders + } + }, + isXML: true, + serializer: serializer$5 +}; +var commitBlockListOperationSpec = { + httpMethod: "PUT", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + timeoutInSeconds, + comp22 + ], + headerParameters: [ + transactionalContentMD5, + transactionalContentCrc64, + metadata, + encryptionScope, + tier0, + version, + requestId, + blobTagsString, + blobCacheControl, + blobContentType, + blobContentEncoding, + blobContentLanguage, + blobContentMD5, + blobContentDisposition, + leaseId0, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, + ifModifiedSince, + ifUnmodifiedSince, + ifMatch, + ifNoneMatch, + ifTags + ], + requestBody: { + parameterPath: "blocks", + mapper: tslib.__assign(tslib.__assign({}, BlockLookupList), { required: true }) + }, + contentType: "application/xml; charset=utf-8", + responses: { + 201: { + headersMapper: BlockBlobCommitBlockListHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlockBlobCommitBlockListHeaders + } + }, + isXML: true, + serializer: serializer$5 +}; +var getBlockListOperationSpec = { + httpMethod: "GET", + path: "{containerName}/{blob}", + urlParameters: [ + url + ], + queryParameters: [ + snapshot, + listType, + timeoutInSeconds, + comp22 + ], + headerParameters: [ + version, + requestId, + leaseId0, + ifTags + ], + responses: { + 200: { + bodyMapper: BlockList, + headersMapper: BlockBlobGetBlockListHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlockBlobGetBlockListHeaders + } + }, + isXML: true, + serializer: serializer$5 +}; + +// Copyright (c) Microsoft Corporation. +/** + * The @azure/logger configuration for this package. + */ +var logger = logger$1.createClientLogger("storage-blob"); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +var SDK_VERSION = "12.2.1"; +var SERVICE_VERSION = "2019-12-12"; +var BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; // 256MB +var BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4000 * 1024 * 1024; // 4000MB +var BLOCK_BLOB_MAX_BLOCKS = 50000; +var DEFAULT_BLOCK_BUFFER_SIZE_BYTES = 8 * 1024 * 1024; // 8MB +var DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES = 4 * 1024 * 1024; // 4MB +var DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS = 5; +/** + * The OAuth scope to use with Azure Storage. + */ +var StorageOAuthScopes = "https://storage.azure.com/.default"; +var URLConstants = { + Parameters: { + FORCE_BROWSER_NO_CACHE: "_", + SIGNATURE: "sig", + SNAPSHOT: "snapshot", + VERSIONID: "versionid", + TIMEOUT: "timeout" + } +}; +var HTTPURLConnection = { + HTTP_ACCEPTED: 202, + HTTP_CONFLICT: 409, + HTTP_NOT_FOUND: 404, + HTTP_PRECON_FAILED: 412, + HTTP_RANGE_NOT_SATISFIABLE: 416 +}; +var HeaderConstants = { + AUTHORIZATION: "Authorization", + AUTHORIZATION_SCHEME: "Bearer", + CONTENT_ENCODING: "Content-Encoding", + CONTENT_ID: "Content-ID", + CONTENT_LANGUAGE: "Content-Language", + CONTENT_LENGTH: "Content-Length", + CONTENT_MD5: "Content-Md5", + CONTENT_TRANSFER_ENCODING: "Content-Transfer-Encoding", + CONTENT_TYPE: "Content-Type", + COOKIE: "Cookie", + DATE: "date", + IF_MATCH: "if-match", + IF_MODIFIED_SINCE: "if-modified-since", + IF_NONE_MATCH: "if-none-match", + IF_UNMODIFIED_SINCE: "if-unmodified-since", + PREFIX_FOR_STORAGE: "x-ms-", + RANGE: "Range", + USER_AGENT: "User-Agent", + X_MS_CLIENT_REQUEST_ID: "x-ms-client-request-id", + X_MS_COPY_SOURCE: "x-ms-copy-source", + X_MS_DATE: "x-ms-date", + X_MS_ERROR_CODE: "x-ms-error-code", + X_MS_VERSION: "x-ms-version" +}; +var ETagNone = ""; +var ETagAny = "*"; +var SIZE_1_MB = 1 * 1024 * 1024; +var BATCH_MAX_REQUEST = 256; +var BATCH_MAX_PAYLOAD_IN_BYTES = 4 * SIZE_1_MB; +var HTTP_LINE_ENDING = "\r\n"; +var HTTP_VERSION_1_1 = "HTTP/1.1"; +var EncryptionAlgorithmAES25 = "AES256"; +var DevelopmentConnectionString = "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;"; +var StorageBlobLoggingAllowedHeaderNames = [ + "Access-Control-Allow-Origin", + "Cache-Control", + "Content-Length", + "Content-Type", + "Date", + "Request-Id", + "traceparent", + "Transfer-Encoding", + "User-Agent", + "x-ms-client-request-id", + "x-ms-date", + "x-ms-error-code", + "x-ms-request-id", + "x-ms-return-client-request-id", + "x-ms-version", + "Accept-Ranges", + "Content-Disposition", + "Content-Encoding", + "Content-Language", + "Content-MD5", + "Content-Range", + "ETag", + "Last-Modified", + "Server", + "Vary", + "x-ms-content-crc64", + "x-ms-copy-action", + "x-ms-copy-completion-time", + "x-ms-copy-id", + "x-ms-copy-progress", + "x-ms-copy-status", + "x-ms-has-immutability-policy", + "x-ms-has-legal-hold", + "x-ms-lease-state", + "x-ms-lease-status", + "x-ms-range", + "x-ms-request-server-encrypted", + "x-ms-server-encrypted", + "x-ms-snapshot", + "x-ms-source-range", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "x-ms-access-tier", + "x-ms-access-tier-change-time", + "x-ms-access-tier-inferred", + "x-ms-account-kind", + "x-ms-archive-status", + "x-ms-blob-append-offset", + "x-ms-blob-cache-control", + "x-ms-blob-committed-block-count", + "x-ms-blob-condition-appendpos", + "x-ms-blob-condition-maxsize", + "x-ms-blob-content-disposition", + "x-ms-blob-content-encoding", + "x-ms-blob-content-language", + "x-ms-blob-content-length", + "x-ms-blob-content-md5", + "x-ms-blob-content-type", + "x-ms-blob-public-access", + "x-ms-blob-sequence-number", + "x-ms-blob-type", + "x-ms-copy-destination-snapshot", + "x-ms-creation-time", + "x-ms-default-encryption-scope", + "x-ms-delete-snapshots", + "x-ms-delete-type-permanent", + "x-ms-deny-encryption-scope-override", + "x-ms-encryption-algorithm", + "x-ms-if-sequence-number-eq", + "x-ms-if-sequence-number-le", + "x-ms-if-sequence-number-lt", + "x-ms-incremental-copy", + "x-ms-lease-action", + "x-ms-lease-break-period", + "x-ms-lease-duration", + "x-ms-lease-id", + "x-ms-lease-time", + "x-ms-page-write", + "x-ms-proposed-lease-id", + "x-ms-range-get-content-md5", + "x-ms-rehydrate-priority", + "x-ms-sequence-number-action", + "x-ms-sku-name", + "x-ms-source-content-md5", + "x-ms-source-if-match", + "x-ms-source-if-modified-since", + "x-ms-source-if-none-match", + "x-ms-source-if-unmodified-since", + "x-ms-tag-count", + "x-ms-encryption-key-sha256", + "x-ms-if-tags", + "x-ms-source-if-tags" +]; +var StorageBlobLoggingAllowedQueryParameters = [ + "comp", + "maxresults", + "rscc", + "rscd", + "rsce", + "rscl", + "rsct", + "se", + "si", + "sip", + "sp", + "spr", + "sr", + "srt", + "ss", + "st", + "sv", + "include", + "marker", + "prefix", + "copyid", + "restype", + "blockid", + "blocklisttype", + "delimiter", + "prevsnapshot", + "ske", + "skoid", + "sks", + "skt", + "sktid", + "skv", + "snapshot" +]; + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * Reserved URL characters must be properly escaped for Storage services like Blob or File. + * + * ## URL encode and escape strategy for JS SDKs + * + * When customers pass a URL string into XxxClient classes constructor, the URL string may already be URL encoded or not. + * But before sending to Azure Storage server, the URL must be encoded. However, it's hard for a SDK to guess whether the URL + * string has been encoded or not. We have 2 potential strategies, and chose strategy two for the XxxClient constructors. + * + * ### Strategy One: Assume the customer URL string is not encoded, and always encode URL string in SDK. + * + * This is what legacy V2 SDK does, simple and works for most of the cases. + * - When customer URL string is "http://account.blob.core.windows.net/con/b:", + * SDK will encode it to "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created. + * - When customer URL string is "http://account.blob.core.windows.net/con/b%3A", + * SDK will encode it to "http://account.blob.core.windows.net/con/b%253A" and send to server. A blob named "b%3A" will be created. + * + * But this strategy will make it not possible to create a blob with "?" in it's name. Because when customer URL string is + * "http://account.blob.core.windows.net/con/blob?name", the "?name" will be treated as URL paramter instead of blob name. + * If customer URL string is "http://account.blob.core.windows.net/con/blob%3Fname", a blob named "blob%3Fname" will be created. + * V2 SDK doesn't have this issue because it doesn't allow customer pass in a full URL, it accepts a separate blob name and encodeURIComponent for it. + * We cannot accept a SDK cannot create a blob name with "?". So we implement strategy two: + * + * ### Strategy Two: SDK doesn't assume the URL has been encoded or not. It will just escape the special characters. + * + * This is what V10 Blob Go SDK does. It accepts a URL type in Go, and call url.EscapedPath() to escape the special chars unescaped. + * - When customer URL string is "http://account.blob.core.windows.net/con/b:", + * SDK will escape ":" like "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created. + * - When customer URL string is "http://account.blob.core.windows.net/con/b%3A", + * There is no special characters, so send "http://account.blob.core.windows.net/con/b%3A" to server. A blob named "b:" will be created. + * - When customer URL string is "http://account.blob.core.windows.net/con/b%253A", + * There is no special characters, so send "http://account.blob.core.windows.net/con/b%253A" to server. A blob named "b%3A" will be created. + * + * This strategy gives us flexibility to create with any special characters. But "%" will be treated as a special characters, if the URL string + * is not encoded, there shouldn't a "%" in the URL string, otherwise the URL is not a valid URL. + * If customer needs to create a blob with "%" in it's blob name, use "%25" instead of "%". Just like above 3rd sample. + * And following URL strings are invalid: + * - "http://account.blob.core.windows.net/con/b%" + * - "http://account.blob.core.windows.net/con/b%2" + * - "http://account.blob.core.windows.net/con/b%G" + * + * Another special character is "?", use "%2F" to represent a blob name with "?" in a URL string. + * + * ### Strategy for containerName, blobName or other specific XXXName parameters in methods such as `containerClient.getBlobClient(blobName)` + * + * We will apply strategy one, and call encodeURIComponent for these parameters like blobName. Because what customers passes in is a plain name instead of a URL. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-shares--directories--files--and-metadata + * + * @export + * @param {string} url + * @returns {string} + */ +function escapeURLPath(url) { + var urlParsed = coreHttp.URLBuilder.parse(url); + var path = urlParsed.getPath(); + path = path || "/"; + path = escape(path); + urlParsed.setPath(path); + return urlParsed.toString(); +} +function getProxyUriFromDevConnString(connectionString) { + // Development Connection String + // https://docs.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string#connect-to-the-emulator-account-using-the-well-known-account-name-and-key + var proxyUri = ""; + if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) { + // CONNECTION_STRING=UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://myProxyUri + var matchCredentials = connectionString.split(";"); + for (var _i = 0, matchCredentials_1 = matchCredentials; _i < matchCredentials_1.length; _i++) { + var element = matchCredentials_1[_i]; + if (element.trim().startsWith("DevelopmentStorageProxyUri=")) { + proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1]; + } + } + } + return proxyUri; +} +function getValueInConnString(connectionString, argument) { + var elements = connectionString.split(";"); + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var element = elements_1[_i]; + if (element.trim().startsWith(argument)) { + return element.trim().match(argument + "=(.*)")[1]; + } + } + return ""; +} +/** + * Extracts the parts of an Azure Storage account connection string. + * + * @export + * @param {string} connectionString Connection string. + * @returns {ConnectionString} String key value pairs of the storage account's url and credentials. + */ +function extractConnectionStringParts(connectionString) { + var proxyUri = ""; + if (connectionString.startsWith("UseDevelopmentStorage=true")) { + // Development connection string + proxyUri = getProxyUriFromDevConnString(connectionString); + connectionString = DevelopmentConnectionString; + } + // Matching BlobEndpoint in the Account connection string + var blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint"); + // Slicing off '/' at the end if exists + // (The methods that use `extractConnectionStringParts` expect the url to not have `/` at the end) + blobEndpoint = blobEndpoint.endsWith("/") ? blobEndpoint.slice(0, -1) : blobEndpoint; + if (connectionString.search("DefaultEndpointsProtocol=") !== -1 && + connectionString.search("AccountKey=") !== -1) { + // Account connection string + var defaultEndpointsProtocol = ""; + var accountName = ""; + var accountKey = Buffer.from("accountKey", "base64"); + var endpointSuffix = ""; + // Get account name and key + accountName = getValueInConnString(connectionString, "AccountName"); + accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64"); + if (!blobEndpoint) { + // BlobEndpoint is not present in the Account connection string + // Can be obtained from `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}` + defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol"); + var protocol = defaultEndpointsProtocol.toLowerCase(); + if (protocol !== "https" && protocol !== "http") { + throw new Error("Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'"); + } + endpointSuffix = getValueInConnString(connectionString, "EndpointSuffix"); + if (!endpointSuffix) { + throw new Error("Invalid EndpointSuffix in the provided Connection String"); + } + blobEndpoint = defaultEndpointsProtocol + "://" + accountName + ".blob." + endpointSuffix; + } + if (!accountName) { + throw new Error("Invalid AccountName in the provided Connection String"); + } + else if (accountKey.length === 0) { + throw new Error("Invalid AccountKey in the provided Connection String"); + } + return { + kind: "AccountConnString", + url: blobEndpoint, + accountName: accountName, + accountKey: accountKey, + proxyUri: proxyUri + }; + } + else { + // SAS connection string + var accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); + var accountName = getAccountNameFromUrl(blobEndpoint); + if (!blobEndpoint) { + throw new Error("Invalid BlobEndpoint in the provided SAS Connection String"); + } + else if (!accountSas) { + throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String"); + } + return { kind: "SASConnString", url: blobEndpoint, accountName: accountName, accountSas: accountSas }; + } +} +/** + * Internal escape method implemented Strategy Two mentioned in escapeURL() description. + * + * @param {string} text + * @returns {string} + */ +function escape(text) { + return encodeURIComponent(text) + .replace(/%2F/g, "/") // Don't escape for "/" + .replace(/'/g, "%27") // Escape for "'" + .replace(/\+/g, "%20") + .replace(/%25/g, "%"); // Revert encoded "%" +} +/** + * Append a string to URL path. Will remove duplicated "/" in front of the string + * when URL path ends with a "/". + * + * @export + * @param {string} url Source URL string + * @param {string} name String to be appended to URL + * @returns {string} An updated URL string + */ +function appendToURLPath(url, name) { + var urlParsed = coreHttp.URLBuilder.parse(url); + var path = urlParsed.getPath(); + path = path ? (path.endsWith("/") ? "" + path + name : path + "/" + name) : name; + urlParsed.setPath(path); + return urlParsed.toString(); +} +/** + * Set URL parameter name and value. If name exists in URL parameters, old value + * will be replaced by name key. If not provide value, the parameter will be deleted. + * + * @export + * @param {string} url Source URL string + * @param {string} name Parameter name + * @param {string} [value] Parameter value + * @returns {string} An updated URL string + */ +function setURLParameter(url, name, value) { + var urlParsed = coreHttp.URLBuilder.parse(url); + urlParsed.setQueryParameter(name, value); + return urlParsed.toString(); +} +/** + * Set URL host. + * + * @export + * @param {string} url Source URL string + * @param {string} host New host string + * @returns An updated URL string + */ +function setURLHost(url, host) { + var urlParsed = coreHttp.URLBuilder.parse(url); + urlParsed.setHost(host); + return urlParsed.toString(); +} +/** + * Get URL path from an URL string. + * + * @export + * @param {string} url Source URL string + * @returns {(string | undefined)} + */ +function getURLPath(url) { + var urlParsed = coreHttp.URLBuilder.parse(url); + return urlParsed.getPath(); +} +/** + * Get URL scheme from an URL string. + * + * @export + * @param {string} url Source URL string + * @returns {(string | undefined)} + */ +function getURLScheme(url) { + var urlParsed = coreHttp.URLBuilder.parse(url); + return urlParsed.getScheme(); +} +/** + * Get URL path and query from an URL string. + * + * @export + * @param {string} url Source URL string + * @returns {(string | undefined)} + */ +function getURLPathAndQuery(url) { + var urlParsed = coreHttp.URLBuilder.parse(url); + var pathString = urlParsed.getPath(); + if (!pathString) { + throw new RangeError("Invalid url without valid path."); + } + var queryString = urlParsed.getQuery() || ""; + queryString = queryString.trim(); + if (queryString != "") { + queryString = queryString.startsWith("?") ? queryString : "?" + queryString; // Ensure query string start with '?' + } + return "" + pathString + queryString; +} +/** + * Get URL query key value pairs from an URL string. + * + * @export + * @param {string} url + * @returns {{[key: string]: string}} + */ +function getURLQueries(url) { + var queryString = coreHttp.URLBuilder.parse(url).getQuery(); + if (!queryString) { + return {}; + } + queryString = queryString.trim(); + queryString = queryString.startsWith("?") ? queryString.substr(1) : queryString; + var querySubStrings = queryString.split("&"); + querySubStrings = querySubStrings.filter(function (value) { + var indexOfEqual = value.indexOf("="); + var lastIndexOfEqual = value.lastIndexOf("="); + return (indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1); + }); + var queries = {}; + for (var _i = 0, querySubStrings_1 = querySubStrings; _i < querySubStrings_1.length; _i++) { + var querySubString = querySubStrings_1[_i]; + var splitResults = querySubString.split("="); + var key = splitResults[0]; + var value = splitResults[1]; + queries[key] = value; + } + return queries; +} +/** + * Rounds a date off to seconds. + * + * @export + * @param {Date} date + * @param {boolean} [withMilliseconds=true] If true, YYYY-MM-DDThh:mm:ss.fffffffZ will be returned; + * If false, YYYY-MM-DDThh:mm:ssZ will be returned. + * @returns {string} Date string in ISO8061 format, with or without 7 milliseconds component + */ +function truncatedISO8061Date(date, withMilliseconds) { + if (withMilliseconds === void 0) { withMilliseconds = true; } + // Date.toISOString() will return like "2018-10-29T06:34:36.139Z" + var dateString = date.toISOString(); + return withMilliseconds + ? dateString.substring(0, dateString.length - 1) + "0000" + "Z" + : dateString.substring(0, dateString.length - 5) + "Z"; +} +/** + * Base64 encode. + * + * @export + * @param {string} content + * @returns {string} + */ +function base64encode(content) { + return !coreHttp.isNode ? btoa(content) : Buffer.from(content).toString("base64"); +} +/** + * Generate a 64 bytes base64 block ID string. + * + * @export + * @param {number} blockIndex + * @returns {string} + */ +function generateBlockID(blockIDPrefix, blockIndex) { + // To generate a 64 bytes base64 string, source string should be 48 + var maxSourceStringLength = 48; + // A blob can have a maximum of 100,000 uncommitted blocks at any given time + var maxBlockIndexLength = 6; + var maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; + if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) { + blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength); + } + var res = blockIDPrefix + + padStart(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0"); + return base64encode(res); +} +/** + * Delay specified time interval. + * + * @export + * @param {number} timeInMs + * @param {AbortSignalLike} [aborter] + * @param {Error} [abortError] + */ +function delay(timeInMs, aborter, abortError) { + return tslib.__awaiter(this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + return [2 /*return*/, new Promise(function (resolve, reject) { + var timeout; + var abortHandler = function () { + if (timeout !== undefined) { + clearTimeout(timeout); + } + reject(abortError); + }; + var resolveHandler = function () { + if (aborter !== undefined) { + aborter.removeEventListener("abort", abortHandler); + } + resolve(); + }; + timeout = setTimeout(resolveHandler, timeInMs); + if (aborter !== undefined) { + aborter.addEventListener("abort", abortHandler); + } + })]; + }); + }); +} +/** + * String.prototype.padStart() + * + * @export + * @param {string} currentString + * @param {number} targetLength + * @param {string} [padString=" "] + * @returns {string} + */ +function padStart(currentString, targetLength, padString) { + if (padString === void 0) { padString = " "; } + // TS doesn't know this code needs to run downlevel sometimes. + // @ts-expect-error + if (String.prototype.padStart) { + return currentString.padStart(targetLength, padString); + } + padString = padString || " "; + if (currentString.length > targetLength) { + return currentString; + } + else { + targetLength = targetLength - currentString.length; + if (targetLength > padString.length) { + padString += padString.repeat(targetLength / padString.length); + } + return padString.slice(0, targetLength) + currentString; + } +} +/** + * If two strings are equal when compared case insensitive. + * + * @export + * @param {string} str1 + * @param {string} str2 + * @returns {boolean} + */ +function iEqual(str1, str2) { + return str1.toLocaleLowerCase() === str2.toLocaleLowerCase(); +} +/** + * Extracts account name from the url + * @param {string} url url to extract the account name from + * @returns {string} with the account name + */ +function getAccountNameFromUrl(url) { + var parsedUrl = coreHttp.URLBuilder.parse(url); + var accountName; + try { + if (parsedUrl.getHost().split(".")[1] === "blob") { + // `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; + accountName = parsedUrl.getHost().split(".")[0]; + } + else if (isIpEndpointStyle(parsedUrl)) { + // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/ + // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/ + // .getPath() -> /devstoreaccount1/ + accountName = parsedUrl.getPath().split("/")[1]; + } + else { + // Custom domain case: "https://customdomain.com/containername/blob". + accountName = ""; + } + return accountName; + } + catch (error) { + throw new Error("Unable to extract accountName with provided information."); + } +} +function isIpEndpointStyle(parsedUrl) { + if (parsedUrl.getHost() == undefined) { + return false; + } + var host = parsedUrl.getHost() + (parsedUrl.getPort() == undefined ? "" : ":" + parsedUrl.getPort()); + // Case 1: Ipv6, use a broad regex to find out candidates whose host contains two ':'. + // Case 2: localhost(:port), use broad regex to match port part. + // Case 3: Ipv4, use broad regex which just check if host contains Ipv4. + // For valid host please refer to https://man7.org/linux/man-pages/man7/hostname.7.html. + return /^.*:.*:.*$|^localhost(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test(host); +} +/** + * Convert Tags to encoded string. + * + * @export + * @param {Tags} tags + * @returns {string | undefined} + */ +function toBlobTagsString(tags) { + if (tags === undefined) { + return undefined; + } + var tagPairs = []; + for (var key in tags) { + if (tags.hasOwnProperty(key)) { + var value = tags[key]; + tagPairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(value)); + } + } + return tagPairs.join("&"); +} +/** + * Convert Tags type to BlobTags. + * + * @export + * @param {Tags} [tags] + * @returns {(BlobTags | undefined)} + */ +function toBlobTags(tags) { + if (tags === undefined) { + return undefined; + } + var res = { + blobTagSet: [] + }; + for (var key in tags) { + if (tags.hasOwnProperty(key)) { + var value = tags[key]; + res.blobTagSet.push({ + key: key, + value: value + }); + } + } + return res; +} +/** + * Covert BlobTags to Tags type. + * + * @export + * @param {BlobTags} [tags] + * @returns {(Tags | undefined)} + */ +function toTags(tags) { + if (tags === undefined) { + return undefined; + } + var res = {}; + for (var _i = 0, _a = tags.blobTagSet; _i < _a.length; _i++) { + var blobTag = _a[_i]; + res[blobTag.key] = blobTag.value; + } + return res; +} +/** + * Convert BlobQueryTextConfiguration to QuerySerialization type. + * + * @export + * @param {(BlobQueryJsonTextConfiguration | BlobQueryCsvTextConfiguration)} [textConfiguration] + * @returns {(QuerySerialization | undefined)} + */ +function toQuerySerialization(textConfiguration) { + if (textConfiguration === undefined) { + return undefined; + } + switch (textConfiguration.kind) { + case "csv": + return { + format: { + type: "delimited", + delimitedTextConfiguration: { + columnSeparator: textConfiguration.columnSeparator || ",", + fieldQuote: textConfiguration.fieldQuote || "", + recordSeparator: textConfiguration.recordSeparator, + escapeChar: textConfiguration.escapeCharacter || "", + headersPresent: textConfiguration.hasHeaders || false + } + } + }; + case "json": + return { + format: { + type: "json", + jsonTextConfiguration: { + recordSeparator: textConfiguration.recordSeparator + } + } + }; + default: + throw Error("Invalid BlobQueryTextConfiguration."); + } +} +function parseObjectReplicationRecord(objectReplicationRecord) { + if (!objectReplicationRecord) { + return undefined; + } + if ("policy-id" in objectReplicationRecord) { + // If the dictionary contains a key with policy id, we are not required to do any parsing since + // the policy id should already be stored in the ObjectReplicationDestinationPolicyId. + return undefined; + } + var orProperties = []; + var _loop_1 = function (key) { + var ids = key.split("_"); + var policyPrefix = "or-"; + if (ids[0].startsWith(policyPrefix)) { + ids[0] = ids[0].substring(policyPrefix.length); + } + var rule = { + ruleId: ids[1], + replicationStatus: objectReplicationRecord[key] + }; + var policyIndex = orProperties.findIndex(function (policy) { return policy.policyId === ids[0]; }); + if (policyIndex > -1) { + orProperties[policyIndex].rules.push(rule); + } + else { + orProperties.push({ + policyId: ids[0], + rules: [rule] + }); + } + }; + for (var key in objectReplicationRecord) { + _loop_1(key); + } + return orProperties; +} + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * StorageBrowserPolicy will handle differences between Node.js and browser runtime, including: + * + * 1. Browsers cache GET/HEAD requests by adding conditional headers such as 'IF_MODIFIED_SINCE'. + * StorageBrowserPolicy is a policy used to add a timestamp query to GET/HEAD request URL + * thus avoid the browser cache. + * + * 2. Remove cookie header for security + * + * 3. Remove content-length header to avoid browsers warning + * + * @class StorageBrowserPolicy + * @extends {BaseRequestPolicy} + */ +var StorageBrowserPolicy = /** @class */ (function (_super) { + tslib.__extends(StorageBrowserPolicy, _super); + /** + * Creates an instance of StorageBrowserPolicy. + * @param {RequestPolicy} nextPolicy + * @param {RequestPolicyOptions} options + * @memberof StorageBrowserPolicy + */ + function StorageBrowserPolicy(nextPolicy, options) { + return _super.call(this, nextPolicy, options) || this; + } + /** + * Sends out request. + * + * @param {WebResource} request + * @returns {Promise} + * @memberof StorageBrowserPolicy + */ + StorageBrowserPolicy.prototype.sendRequest = function (request) { + return tslib.__awaiter(this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + { + return [2 /*return*/, this._nextPolicy.sendRequest(request)]; + } + }); + }); + }; + return StorageBrowserPolicy; +}(coreHttp.BaseRequestPolicy)); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * StorageBrowserPolicyFactory is a factory class helping generating StorageBrowserPolicy objects. + * + * @export + * @class StorageBrowserPolicyFactory + * @implements {RequestPolicyFactory} + */ +var StorageBrowserPolicyFactory = /** @class */ (function () { + function StorageBrowserPolicyFactory() { + } + /** + * Creates a StorageBrowserPolicyFactory object. + * + * @param {RequestPolicy} nextPolicy + * @param {RequestPolicyOptions} options + * @returns {StorageBrowserPolicy} + * @memberof StorageBrowserPolicyFactory + */ + StorageBrowserPolicyFactory.prototype.create = function (nextPolicy, options) { + return new StorageBrowserPolicy(nextPolicy, options); + }; + return StorageBrowserPolicyFactory; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +(function (StorageRetryPolicyType) { + /** + * Exponential retry. Retry time delay grows exponentially. + */ + StorageRetryPolicyType[StorageRetryPolicyType["EXPONENTIAL"] = 0] = "EXPONENTIAL"; + /** + * Linear retry. Retry time delay grows linearly. + */ + StorageRetryPolicyType[StorageRetryPolicyType["FIXED"] = 1] = "FIXED"; +})(exports.StorageRetryPolicyType || (exports.StorageRetryPolicyType = {})); +// Default values of StorageRetryOptions +var DEFAULT_RETRY_OPTIONS = { + maxRetryDelayInMs: 120 * 1000, + maxTries: 4, + retryDelayInMs: 4 * 1000, + retryPolicyType: exports.StorageRetryPolicyType.EXPONENTIAL, + secondaryHost: "", + tryTimeoutInMs: undefined // Use server side default timeout strategy +}; +var RETRY_ABORT_ERROR = new abortController.AbortError("The operation was aborted."); +/** + * Retry policy with exponential retry and linear retry implemented. + * + * @class RetryPolicy + * @extends {BaseRequestPolicy} + */ +var StorageRetryPolicy = /** @class */ (function (_super) { + tslib.__extends(StorageRetryPolicy, _super); + /** + * Creates an instance of RetryPolicy. + * + * @param {RequestPolicy} nextPolicy + * @param {RequestPolicyOptions} options + * @param {StorageRetryOptions} [retryOptions=DEFAULT_RETRY_OPTIONS] + * @memberof StorageRetryPolicy + */ + function StorageRetryPolicy(nextPolicy, options, retryOptions) { + if (retryOptions === void 0) { retryOptions = DEFAULT_RETRY_OPTIONS; } + var _this = _super.call(this, nextPolicy, options) || this; + // Initialize retry options + _this.retryOptions = { + retryPolicyType: retryOptions.retryPolicyType + ? retryOptions.retryPolicyType + : DEFAULT_RETRY_OPTIONS.retryPolicyType, + maxTries: retryOptions.maxTries && retryOptions.maxTries >= 1 + ? Math.floor(retryOptions.maxTries) + : DEFAULT_RETRY_OPTIONS.maxTries, + tryTimeoutInMs: retryOptions.tryTimeoutInMs && retryOptions.tryTimeoutInMs >= 0 + ? retryOptions.tryTimeoutInMs + : DEFAULT_RETRY_OPTIONS.tryTimeoutInMs, + retryDelayInMs: retryOptions.retryDelayInMs && retryOptions.retryDelayInMs >= 0 + ? Math.min(retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs + ? retryOptions.maxRetryDelayInMs + : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs) + : DEFAULT_RETRY_OPTIONS.retryDelayInMs, + maxRetryDelayInMs: retryOptions.maxRetryDelayInMs && retryOptions.maxRetryDelayInMs >= 0 + ? retryOptions.maxRetryDelayInMs + : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs, + secondaryHost: retryOptions.secondaryHost + ? retryOptions.secondaryHost + : DEFAULT_RETRY_OPTIONS.secondaryHost + }; + return _this; + } + /** + * Sends request. + * + * @param {WebResource} request + * @returns {Promise} + * @memberof StorageRetryPolicy + */ + StorageRetryPolicy.prototype.sendRequest = function (request) { + return tslib.__awaiter(this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + return [2 /*return*/, this.attemptSendRequest(request, false, 1)]; + }); + }); + }; + /** + * Decide and perform next retry. Won't mutate request parameter. + * + * @protected + * @param {WebResource} request + * @param {boolean} secondaryHas404 If attempt was against the secondary & it returned a StatusNotFound (404), then + * the resource was not found. This may be due to replication delay. So, in this + * case, we'll never try the secondary again for this operation. + * @param {number} attempt How many retries has been attempted to performed, starting from 1, which includes + * the attempt will be performed by this method call. + * @returns {Promise} + * @memberof StorageRetryPolicy + */ + StorageRetryPolicy.prototype.attemptSendRequest = function (request, secondaryHas404, attempt) { + return tslib.__awaiter(this, void 0, void 0, function () { + var newRequest, isPrimaryRetry, response, err_1; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + newRequest = request.clone(); + isPrimaryRetry = secondaryHas404 || + !this.retryOptions.secondaryHost || + !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") || + attempt % 2 === 1; + if (!isPrimaryRetry) { + newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost); + } + // Set the server-side timeout query parameter "timeout=[seconds]" + if (this.retryOptions.tryTimeoutInMs) { + newRequest.url = setURLParameter(newRequest.url, URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1000).toString()); + } + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + logger.info("RetryPolicy: =====> Try=" + attempt + " " + (isPrimaryRetry ? "Primary" : "Secondary")); + return [4 /*yield*/, this._nextPolicy.sendRequest(newRequest)]; + case 2: + response = _a.sent(); + if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { + return [2 /*return*/, response]; + } + secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404); + return [3 /*break*/, 4]; + case 3: + err_1 = _a.sent(); + logger.error("RetryPolicy: Caught error, message: " + err_1.message + ", code: " + err_1.code); + if (!this.shouldRetry(isPrimaryRetry, attempt, response, err_1)) { + throw err_1; + } + return [3 /*break*/, 4]; + case 4: return [4 /*yield*/, this.delay(isPrimaryRetry, attempt, request.abortSignal)]; + case 5: + _a.sent(); + return [4 /*yield*/, this.attemptSendRequest(request, secondaryHas404, ++attempt)]; + case 6: return [2 /*return*/, _a.sent()]; + } + }); + }); + }; + /** + * Decide whether to retry according to last HTTP response and retry counters. + * + * @protected + * @param {boolean} isPrimaryRetry + * @param {number} attempt + * @param {HttpOperationResponse} [response] + * @param {RestError} [err] + * @returns {boolean} + * @memberof StorageRetryPolicy + */ + StorageRetryPolicy.prototype.shouldRetry = function (isPrimaryRetry, attempt, response, err) { + if (attempt >= this.retryOptions.maxTries) { + logger.info("RetryPolicy: Attempt(s) " + attempt + " >= maxTries " + this.retryOptions + .maxTries + ", no further try."); + return false; + } + // Handle network failures, you may need to customize the list when you implement + // your own http client + var retriableErrors = [ + "ETIMEDOUT", + "ESOCKETTIMEDOUT", + "ECONNREFUSED", + "ECONNRESET", + "ENOENT", + "ENOTFOUND", + "TIMEOUT", + "EPIPE", + "REQUEST_SEND_ERROR" // For default xhr based http client provided in ms-rest-js + ]; + if (err) { + for (var _i = 0, retriableErrors_1 = retriableErrors; _i < retriableErrors_1.length; _i++) { + var retriableError = retriableErrors_1[_i]; + if (err.name.toUpperCase().includes(retriableError) || + err.message.toUpperCase().includes(retriableError) || + (err.code && + err.code + .toString() + .toUpperCase() + .includes(retriableError))) { + logger.info("RetryPolicy: Network error " + retriableError + " found, will retry."); + return true; + } + } + } + // If attempt was against the secondary & it returned a StatusNotFound (404), then + // the resource was not found. This may be due to replication delay. So, in this + // case, we'll never try the secondary again for this operation. + if (response || err) { + var statusCode = response ? response.status : err ? err.statusCode : 0; + if (!isPrimaryRetry && statusCode === 404) { + logger.info("RetryPolicy: Secondary access with 404, will retry."); + return true; + } + // Server internal error or server timeout + if (statusCode === 503 || statusCode === 500) { + logger.info("RetryPolicy: Will retry for status code " + statusCode + "."); + return true; + } + } + return false; + }; + /** + * Delay a calculated time between retries. + * + * @private + * @param {boolean} isPrimaryRetry + * @param {number} attempt + * @param {AbortSignalLike} [abortSignal] + * @memberof StorageRetryPolicy + */ + StorageRetryPolicy.prototype.delay = function (isPrimaryRetry, attempt, abortSignal) { + return tslib.__awaiter(this, void 0, void 0, function () { + var delayTimeInMs; + return tslib.__generator(this, function (_a) { + delayTimeInMs = 0; + if (isPrimaryRetry) { + switch (this.retryOptions.retryPolicyType) { + case exports.StorageRetryPolicyType.EXPONENTIAL: + delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs); + break; + case exports.StorageRetryPolicyType.FIXED: + delayTimeInMs = this.retryOptions.retryDelayInMs; + break; + } + } + else { + delayTimeInMs = Math.random() * 1000; + } + logger.info("RetryPolicy: Delay for " + delayTimeInMs + "ms"); + return [2 /*return*/, delay(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR)]; + }); + }); + }; + return StorageRetryPolicy; +}(coreHttp.BaseRequestPolicy)); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * StorageRetryPolicyFactory is a factory class helping generating {@link StorageRetryPolicy} objects. + * + * @export + * @class StorageRetryPolicyFactory + * @implements {RequestPolicyFactory} + */ +var StorageRetryPolicyFactory = /** @class */ (function () { + /** + * Creates an instance of StorageRetryPolicyFactory. + * @param {StorageRetryOptions} [retryOptions] + * @memberof StorageRetryPolicyFactory + */ + function StorageRetryPolicyFactory(retryOptions) { + this.retryOptions = retryOptions; + } + /** + * Creates a StorageRetryPolicy object. + * + * @param {RequestPolicy} nextPolicy + * @param {RequestPolicyOptions} options + * @returns {StorageRetryPolicy} + * @memberof StorageRetryPolicyFactory + */ + StorageRetryPolicyFactory.prototype.create = function (nextPolicy, options) { + return new StorageRetryPolicy(nextPolicy, options, this.retryOptions); + }; + return StorageRetryPolicyFactory; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * Credential policy used to sign HTTP(S) requests before sending. This is an + * abstract class. + * + * @export + * @abstract + * @class CredentialPolicy + * @extends {BaseRequestPolicy} + */ +var CredentialPolicy = /** @class */ (function (_super) { + tslib.__extends(CredentialPolicy, _super); + function CredentialPolicy() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + * Sends out request. + * + * @param {WebResource} request + * @returns {Promise} + * @memberof CredentialPolicy + */ + CredentialPolicy.prototype.sendRequest = function (request) { + return this._nextPolicy.sendRequest(this.signRequest(request)); + }; + /** + * Child classes must implement this method with request signing. This method + * will be executed in {@link sendRequest}. + * + * @protected + * @abstract + * @param {WebResource} request + * @returns {WebResource} + * @memberof CredentialPolicy + */ + CredentialPolicy.prototype.signRequest = function (request) { + // Child classes must override this method with request signing. This method + // will be executed in sendRequest(). + return request; + }; + return CredentialPolicy; +}(coreHttp.BaseRequestPolicy)); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * AnonymousCredentialPolicy is used with HTTP(S) requests that read public resources + * or for use with Shared Access Signatures (SAS). + * + * @export + * @class AnonymousCredentialPolicy + * @extends {CredentialPolicy} + */ +var AnonymousCredentialPolicy = /** @class */ (function (_super) { + tslib.__extends(AnonymousCredentialPolicy, _super); + /** + * Creates an instance of AnonymousCredentialPolicy. + * @param {RequestPolicy} nextPolicy + * @param {RequestPolicyOptions} options + * @memberof AnonymousCredentialPolicy + */ + function AnonymousCredentialPolicy(nextPolicy, options) { + return _super.call(this, nextPolicy, options) || this; + } + return AnonymousCredentialPolicy; +}(CredentialPolicy)); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * Credential is an abstract class for Azure Storage HTTP requests signing. This + * class will host an credentialPolicyCreator factory which generates CredentialPolicy. + * + * @export + * @abstract + * @class Credential + */ +var Credential = /** @class */ (function () { + function Credential() { + } + /** + * Creates a RequestPolicy object. + * + * @param {RequestPolicy} _nextPolicy + * @param {RequestPolicyOptions} _options + * @returns {RequestPolicy} + * @memberof Credential + */ + Credential.prototype.create = function ( + // tslint:disable-next-line:variable-name + _nextPolicy, + // tslint:disable-next-line:variable-name + _options) { + throw new Error("Method should be implemented in children classes."); + }; + return Credential; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * AnonymousCredential provides a credentialPolicyCreator member used to create + * AnonymousCredentialPolicy objects. AnonymousCredentialPolicy is used with + * HTTP(S) requests that read public resources or for use with Shared Access + * Signatures (SAS). + * + * @export + * @class AnonymousCredential + * @extends {Credential} + */ +var AnonymousCredential = /** @class */ (function (_super) { + tslib.__extends(AnonymousCredential, _super); + function AnonymousCredential() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + * Creates an {@link AnonymousCredentialPolicy} object. + * + * @param {RequestPolicy} nextPolicy + * @param {RequestPolicyOptions} options + * @returns {AnonymousCredentialPolicy} + * @memberof AnonymousCredential + */ + AnonymousCredential.prototype.create = function (nextPolicy, options) { + return new AnonymousCredentialPolicy(nextPolicy, options); + }; + return AnonymousCredential; +}(Credential)); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * TelemetryPolicy is a policy used to tag user-agent header for every requests. + * + * @class TelemetryPolicy + * @extends {BaseRequestPolicy} + */ +var TelemetryPolicy = /** @class */ (function (_super) { + tslib.__extends(TelemetryPolicy, _super); + /** + * Creates an instance of TelemetryPolicy. + * @param {RequestPolicy} nextPolicy + * @param {RequestPolicyOptions} options + * @param {string} telemetry + * @memberof TelemetryPolicy + */ + function TelemetryPolicy(nextPolicy, options, telemetry) { + var _this = _super.call(this, nextPolicy, options) || this; + _this.telemetry = telemetry; + return _this; + } + /** + * Sends out request. + * + * @param {WebResource} request + * @returns {Promise} + * @memberof TelemetryPolicy + */ + TelemetryPolicy.prototype.sendRequest = function (request) { + return tslib.__awaiter(this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + { + if (!request.headers) { + request.headers = new coreHttp.HttpHeaders(); + } + if (!request.headers.get(HeaderConstants.USER_AGENT)) { + request.headers.set(HeaderConstants.USER_AGENT, this.telemetry); + } + } + return [2 /*return*/, this._nextPolicy.sendRequest(request)]; + }); + }); + }; + return TelemetryPolicy; +}(coreHttp.BaseRequestPolicy)); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * TelemetryPolicyFactory is a factory class helping generating {@link TelemetryPolicy} objects. + * + * @export + * @class TelemetryPolicyFactory + * @implements {RequestPolicyFactory} + */ +var TelemetryPolicyFactory = /** @class */ (function () { + /** + * Creates an instance of TelemetryPolicyFactory. + * @param {UserAgentOptions} [telemetry] + * @memberof TelemetryPolicyFactory + */ + function TelemetryPolicyFactory(telemetry) { + var userAgentInfo = []; + { + if (telemetry) { + // FIXME: replace() only replaces the first space. And we have no idea why we need to replace spaces in the first place. + // But fixing this would be a breaking change. Logged an issue here: https://github.com/Azure/azure-sdk-for-js/issues/10793 + var telemetryString = (telemetry.userAgentPrefix || "").replace(" ", ""); + if (telemetryString.length > 0 && userAgentInfo.indexOf(telemetryString) === -1) { + userAgentInfo.push(telemetryString); + } + } + // e.g. azsdk-js-storageblob/10.0.0 + var libInfo = "azsdk-js-storageblob/" + SDK_VERSION; + if (userAgentInfo.indexOf(libInfo) === -1) { + userAgentInfo.push(libInfo); + } + // e.g. (NODE-VERSION 4.9.1; Windows_NT 10.0.16299) + var runtimeInfo = "(NODE-VERSION " + process.version + "; " + os.type() + " " + os.release() + ")"; + if (userAgentInfo.indexOf(runtimeInfo) === -1) { + userAgentInfo.push(runtimeInfo); + } + } + this.telemetryString = userAgentInfo.join(" "); + } + /** + * Creates a TelemetryPolicy object. + * + * @param {RequestPolicy} nextPolicy + * @param {RequestPolicyOptions} options + * @returns {TelemetryPolicy} + * @memberof TelemetryPolicyFactory + */ + TelemetryPolicyFactory.prototype.create = function (nextPolicy, options) { + return new TelemetryPolicy(nextPolicy, options, this.telemetryString); + }; + return TelemetryPolicyFactory; +}()); + +// Copyright (c) Microsoft Corporation. +var _defaultHttpClient = new coreHttp.DefaultHttpClient(); +function getCachedDefaultHttpClient() { + return _defaultHttpClient; +} + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * A Pipeline class containing HTTP request policies. + * You can create a default Pipeline by calling {@link newPipeline}. + * Or you can create a Pipeline with your own policies by the constructor of Pipeline. + * + * Refer to {@link newPipeline} and provided policies before implementing your + * customized Pipeline. + * + * @export + * @class Pipeline + */ +var Pipeline = /** @class */ (function () { + /** + * Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface. + * + * @param {RequestPolicyFactory[]} factories + * @param {PipelineOptions} [options={}] + * @memberof Pipeline + */ + function Pipeline(factories, options) { + if (options === void 0) { options = {}; } + this.factories = factories; + // when options.httpClient is not specified, passing in a DefaultHttpClient instance to + // avoid each client creating its own http client. + this.options = tslib.__assign(tslib.__assign({}, options), { httpClient: options.httpClient || getCachedDefaultHttpClient() }); + } + /** + * Transfer Pipeline object to ServiceClientOptions object which is required by + * ServiceClient constructor. + * + * @returns {ServiceClientOptions} The ServiceClientOptions object from this Pipeline. + * @memberof Pipeline + */ + Pipeline.prototype.toServiceClientOptions = function () { + return { + httpClient: this.options.httpClient, + requestPolicyFactories: this.factories + }; + }; + return Pipeline; +}()); +/** + * Creates a new Pipeline object with Credential provided. + * + * @export + * @param {StorageSharedKeyCredential | AnonymousCredential | TokenCredential} credential Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the @azure/identity package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. + * @param {StoragePipelineOptions} [pipelineOptions] Optional. Options. + * @returns {Pipeline} A new Pipeline object. + */ +function newPipeline(credential, pipelineOptions) { + if (pipelineOptions === void 0) { pipelineOptions = {}; } + if (credential === undefined) { + credential = new AnonymousCredential(); + } + // Order is important. Closer to the API at the top & closer to the network at the bottom. + // The credential's policy factory must appear close to the wire so it can sign any + // changes made by other factories (like UniqueRequestIDPolicyFactory) + var telemetryPolicy = new TelemetryPolicyFactory(pipelineOptions.userAgentOptions); + var factories = [ + coreHttp.tracingPolicy({ userAgent: telemetryPolicy.telemetryString }), + coreHttp.keepAlivePolicy(pipelineOptions.keepAliveOptions), + telemetryPolicy, + coreHttp.generateClientRequestIdPolicy(), + new StorageBrowserPolicyFactory(), + coreHttp.deserializationPolicy(), + new StorageRetryPolicyFactory(pipelineOptions.retryOptions), + coreHttp.logPolicy({ + logger: logger.info, + allowedHeaderNames: StorageBlobLoggingAllowedHeaderNames, + allowedQueryParameters: StorageBlobLoggingAllowedQueryParameters + }) + ]; + { + // policies only available in Node.js runtime, not in browsers + factories.push(coreHttp.proxyPolicy(pipelineOptions.proxyOptions)); + factories.push(coreHttp.disableResponseDecompressionPolicy()); + } + factories.push(coreHttp.isTokenCredential(credential) + ? coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes) + : credential); + return new Pipeline(factories, pipelineOptions); +} + +// Copyright (c) Microsoft Corporation. All rights reserved. +var ABORT_ERROR = new abortController.AbortError("The operation was aborted."); +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * A Node.js ReadableStream will internally retry when internal ReadableStream unexpected ends. + * + * @class RetriableReadableStream + * @extends {Readable} + */ +var RetriableReadableStream = /** @class */ (function (_super) { + tslib.__extends(RetriableReadableStream, _super); + /** + * Creates an instance of RetriableReadableStream. + * + * @param {NodeJS.ReadableStream} source The current ReadableStream returned from getter + * @param {ReadableStreamGetter} getter A method calling downloading request returning + * a new ReadableStream from specified offset + * @param {number} offset Offset position in original data source to read + * @param {number} count How much data in original data source to read + * @param {RetriableReadableStreamOptions} [options={}] + * @memberof RetriableReadableStream + */ + function RetriableReadableStream(source, getter, offset, count, options) { + if (options === void 0) { options = {}; } + var _this = _super.call(this) || this; + _this.retries = 0; + _this.abortHandler = function () { + _this.source.pause(); + _this.emit("error", ABORT_ERROR); + }; + _this.aborter = options.abortSignal || abortController.AbortSignal.none; + _this.getter = getter; + _this.source = source; + _this.start = offset; + _this.offset = offset; + _this.end = offset + count - 1; + _this.maxRetryRequests = + options.maxRetryRequests && options.maxRetryRequests >= 0 ? options.maxRetryRequests : 0; + _this.onProgress = options.onProgress; + _this.options = options; + _this.aborter.addEventListener("abort", _this.abortHandler); + _this.setSourceDataHandler(); + _this.setSourceEndHandler(); + _this.setSourceErrorHandler(); + return _this; + } + RetriableReadableStream.prototype._read = function () { + if (!this.aborter.aborted) { + this.source.resume(); + } + }; + RetriableReadableStream.prototype.setSourceDataHandler = function () { + var _this = this; + this.source.on("data", function (data) { + if (_this.options.doInjectErrorOnce) { + _this.options.doInjectErrorOnce = undefined; + _this.source.pause(); + _this.source.removeAllListeners("data"); + _this.source.emit("end"); + return; + } + // console.log( + // `Offset: ${this.offset}, Received ${data.length} from internal stream` + // ); + _this.offset += data.length; + if (_this.onProgress) { + _this.onProgress({ loadedBytes: _this.offset - _this.start }); + } + if (!_this.push(data)) { + _this.source.pause(); + } + }); + }; + RetriableReadableStream.prototype.setSourceEndHandler = function () { + var _this = this; + this.source.on("end", function () { + // console.log( + // `Source stream emits end, offset: ${ + // this.offset + // }, dest end : ${this.end}` + // ); + if (_this.offset - 1 === _this.end) { + _this.aborter.removeEventListener("abort", _this.abortHandler); + _this.push(null); + } + else if (_this.offset <= _this.end) { + // console.log( + // `retries: ${this.retries}, max retries: ${this.maxRetries}` + // ); + if (_this.retries < _this.maxRetryRequests) { + _this.retries += 1; + _this.getter(_this.offset) + .then(function (newSource) { + _this.source = newSource; + _this.setSourceDataHandler(); + _this.setSourceEndHandler(); + _this.setSourceErrorHandler(); + }) + .catch(function (error) { + _this.emit("error", error); + }); + } + else { + _this.emit("error", new Error( + // tslint:disable-next-line:max-line-length + "Data corruption failure: received less data than required and reached maxRetires limitation. Received data offset: " + (_this + .offset - 1) + ", data needed offset: " + _this.end + ", retries: " + _this.retries + ", max retries: " + _this.maxRetryRequests)); + } + } + else { + _this.emit("error", new Error("Data corruption failure: Received more data than original request, data needed offset is " + _this.end + ", received offset: " + (_this.offset - 1))); + } + }); + }; + RetriableReadableStream.prototype.setSourceErrorHandler = function () { + var _this = this; + this.source.on("error", function (error) { + _this.emit("error", error); + }); + }; + return RetriableReadableStream; +}(stream.Readable)); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * BlobDownloadResponse implements BlobDownloadResponseParsed interface, and in Node.js runtime it will + * automatically retry when internal read stream unexpected ends. (This kind of unexpected ends cannot + * trigger retries defined in pipeline retry policy.) + * + * The {@link readableStreamBody} stream will retry underlayer, you can just use it as a normal Node.js + * Readable stream. + * + * @export + * @class BlobDownloadResponse + * @implements {BlobDownloadResponseParsed} + */ +var BlobDownloadResponse = /** @class */ (function () { + /** + * Creates an instance of BlobDownloadResponse. + * + * @param {BlobDownloadResponseParsed} originalResponse + * @param {ReadableStreamGetter} getter + * @param {number} offset + * @param {number} count + * @param {RetriableReadableStreamOptions} [options={}] + * @memberof BlobDownloadResponse + */ + function BlobDownloadResponse(originalResponse, getter, offset, count, options) { + if (options === void 0) { options = {}; } + this.originalResponse = originalResponse; + this.blobDownloadStream = new RetriableReadableStream(this.originalResponse.readableStreamBody, getter, offset, count, options); + } + Object.defineProperty(BlobDownloadResponse.prototype, "acceptRanges", { + /** + * Indicates that the service supports + * requests for partial file content. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.acceptRanges; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "cacheControl", { + /** + * Returns if it was previously specified + * for the file. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.cacheControl; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "contentDisposition", { + /** + * Returns the value that was specified + * for the 'x-ms-content-disposition' header and specifies how to process the + * response. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.contentDisposition; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "contentEncoding", { + /** + * Returns the value that was specified + * for the Content-Encoding request header. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.contentEncoding; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "contentLanguage", { + /** + * Returns the value that was specified + * for the Content-Language request header. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.contentLanguage; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "blobSequenceNumber", { + /** + * The current sequence number for a + * page blob. This header is not returned for block blobs or append blobs. + * + * @readonly + * @type {(number | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.blobSequenceNumber; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "blobType", { + /** + * The blob's type. Possible values include: + * 'BlockBlob', 'PageBlob', 'AppendBlob'. + * + * @readonly + * @type {(BlobType | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.blobType; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "contentLength", { + /** + * The number of bytes present in the + * response body. + * + * @readonly + * @type {(number | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.contentLength; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "contentMD5", { + /** + * If the file has an MD5 hash and the + * request is to read the full file, this response header is returned so that + * the client can check for message content integrity. If the request is to + * read a specified range and the 'x-ms-range-get-content-md5' is set to + * true, then the request returns an MD5 hash for the range, as long as the + * range size is less than or equal to 4 MB. If neither of these sets of + * conditions is true, then no value is returned for the 'Content-MD5' + * header. + * + * @readonly + * @type {(Uint8Array | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.contentMD5; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "contentRange", { + /** + * Indicates the range of bytes returned if + * the client requested a subset of the file by setting the Range request + * header. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.contentRange; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "contentType", { + /** + * The content type specified for the file. + * The default content type is 'application/octet-stream' + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.contentType; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "copyCompletedOn", { + /** + * Conclusion time of the last attempted + * Copy File operation where this file was the destination file. This value + * can specify the time of a completed, aborted, or failed copy attempt. + * + * @readonly + * @type {(Date | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.copyCompletedOn; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "copyId", { + /** + * String identifier for the last attempted Copy + * File operation where this file was the destination file. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.copyId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "copyProgress", { + /** + * Contains the number of bytes copied and + * the total bytes in the source in the last attempted Copy File operation + * where this file was the destination file. Can show between 0 and + * Content-Length bytes copied. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.copyProgress; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "copySource", { + /** + * URL up to 2KB in length that specifies the + * source file used in the last attempted Copy File operation where this file + * was the destination file. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.copySource; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "copyStatus", { + /** + * State of the copy operation + * identified by 'x-ms-copy-id'. Possible values include: 'pending', + * 'success', 'aborted', 'failed' + * + * @readonly + * @type {(CopyStatusType | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.copyStatus; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "copyStatusDescription", { + /** + * Only appears when + * x-ms-copy-status is failed or pending. Describes cause of fatal or + * non-fatal copy operation failure. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.copyStatusDescription; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "leaseDuration", { + /** + * When a blob is leased, + * specifies whether the lease is of infinite or fixed duration. Possible + * values include: 'infinite', 'fixed'. + * + * @readonly + * @type {(LeaseDurationType | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.leaseDuration; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "leaseState", { + /** + * Lease state of the blob. Possible + * values include: 'available', 'leased', 'expired', 'breaking', 'broken'. + * + * @readonly + * @type {(LeaseStateType | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.leaseState; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "leaseStatus", { + /** + * The current lease status of the + * blob. Possible values include: 'locked', 'unlocked'. + * + * @readonly + * @type {(LeaseStatusType | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.leaseStatus; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "date", { + /** + * A UTC date/time value generated by the service that + * indicates the time at which the response was initiated. + * + * @readonly + * @type {(Date | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.date; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "blobCommittedBlockCount", { + /** + * The number of committed blocks + * present in the blob. This header is returned only for append blobs. + * + * @readonly + * @type {(number | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.blobCommittedBlockCount; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "etag", { + /** + * The ETag contains a value that you can use to + * perform operations conditionally, in quotes. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.etag; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "tagCount", { + /** + * The number of tags associated with the blob + * + * @readonly + * @type {(number | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.tagCount; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "errorCode", { + /** + * The error code. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.errorCode; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "isServerEncrypted", { + /** + * The value of this header is set to + * true if the file data and application metadata are completely encrypted + * using the specified algorithm. Otherwise, the value is set to false (when + * the file is unencrypted, or if only parts of the file/application metadata + * are encrypted). + * + * @readonly + * @type {(boolean | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.isServerEncrypted; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "blobContentMD5", { + /** + * If the blob has a MD5 hash, and if + * request contains range header (Range or x-ms-range), this response header + * is returned with the value of the whole blob's MD5 value. This value may + * or may not be equal to the value returned in Content-MD5 header, with the + * latter calculated from the requested range. + * + * @readonly + * @type {(Uint8Array | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.blobContentMD5; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "lastModified", { + /** + * Returns the date and time the file was last + * modified. Any operation that modifies the file or its properties updates + * the last modified time. + * + * @readonly + * @type {(Date | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.lastModified; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "metadata", { + /** + * A name-value pair + * to associate with a file storage object. + * + * @readonly + * @type {(Metadata | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.metadata; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "requestId", { + /** + * This header uniquely identifies the request + * that was made and can be used for troubleshooting the request. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.requestId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "clientRequestId", { + /** + * If a client request id header is sent in the request, this header will be present in the + * response with the same value. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.clientRequestId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "version", { + /** + * Indicates the version of the Blob service used + * to execute the request. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.version; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "versionId", { + /** + * Indicates the versionId of the downloaded blob version. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.versionId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "encryptionKeySha256", { + /** + * The SHA-256 hash of the encryption key used to encrypt the blob. This value is only returned + * when the blob was encrypted with a customer-provided key. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.encryptionKeySha256; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "contentCrc64", { + /** + * If the request is to read a specified range and the x-ms-range-get-content-crc64 is set to + * true, then the request returns a crc64 for the range, as long as the range size is less than + * or equal to 4 MB. If both x-ms-range-get-content-crc64 & x-ms-range-get-content-md5 is + * specified in the same request, it will fail with 400(Bad Request) + * + * @type {(Uint8Array | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.contentCrc64; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "objectReplicationDestinationPolicyId", { + /** + * Object Replication Policy Id of the destination blob. + * + * @readonly + * @type {(string| undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.objectReplicationDestinationPolicyId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "objectReplicationSourceProperties", { + /** + * Parsed Object Replication Policy Id, Rule Id(s) and status of the source blob. + * + * @readonly + * @type {(ObjectReplicationPolicy[] | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.objectReplicationSourceProperties; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "isSealed", { + /** + * If this blob has been sealed. + * + * @readonly + * @type {(boolean | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.isSealed; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "contentAsBlob", { + /** + * The response body as a browser Blob. + * Always undefined in node.js. + * + * @readonly + * @type {(Promise | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse.blobBody; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "readableStreamBody", { + /** + * The response body as a node.js Readable stream. + * Always undefined in the browser. + * + * It will automatically retry when internal read stream unexpected ends. + * + * @readonly + * @type {(NodeJS.ReadableStream | undefined)} + * @memberof BlobDownloadResponse + */ + get: function () { + return coreHttp.isNode ? this.blobDownloadStream : undefined; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobDownloadResponse.prototype, "_response", { + /** + * The HTTP response. + * + * @type {HttpResponse} + * @memberof BlobDownloadResponse + */ + get: function () { + return this.originalResponse._response; + }, + enumerable: false, + configurable: true + }); + return BlobDownloadResponse; +}()); + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +var AVRO_SYNC_MARKER_SIZE = 16; +var AVRO_INIT_BYTES = new Uint8Array([79, 98, 106, 1]); +var AVRO_CODEC_KEY = "avro.codec"; +var AVRO_SCHEMA_KEY = "avro.schema"; + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +function arraysEqual(a, b) { + if (a === b) + return true; + if (a == null || b == null) + return false; + if (a.length != b.length) + return false; + for (var i = 0; i < a.length; ++i) { + if (a[i] !== b[i]) + return false; + } + return true; +} + +// Copyright (c) Microsoft Corporation. +var AvroParser = /** @class */ (function () { + function AvroParser() { + } + /** + * Reads a fixed number of bytes from the stream. + * + * @static + * @param {AvroReadable} [stream] + * @param {number} [length] + * @param {AvroParserReadOptions} [options={}] + * @returns {Promise} + * @memberof AvroParser + */ + AvroParser.readFixedBytes = function (stream, length, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var bytes; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, stream.read(length, { abortSignal: options.abortSignal })]; + case 1: + bytes = _a.sent(); + if (bytes.length != length) { + throw new Error("Hit stream end."); + } + return [2 /*return*/, bytes]; + } + }); + }); + }; + /** + * Reads a single byte from the stream. + * + * @static + * @param {AvroReadable} [stream] + * @param {AvroParserReadOptions} [options={}] + * @returns {Promise} + * @memberof AvroParser + */ + AvroParser.readByte = function (stream, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var buf; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, AvroParser.readFixedBytes(stream, 1, options)]; + case 1: + buf = _a.sent(); + return [2 /*return*/, buf[0]]; + } + }); + }); + }; + // int and long are stored in variable-length zig-zag coding. + // variable-length: https://lucene.apache.org/core/3_5_0/fileformats.html#VInt + // zig-zag: https://developers.google.com/protocol-buffers/docs/encoding?csw=1#types + AvroParser.readZigZagLong = function (stream, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var zigZagEncoded, significanceInBit, byte, haveMoreByte, significanceInFloat, res; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + zigZagEncoded = 0; + significanceInBit = 0; + _a.label = 1; + case 1: return [4 /*yield*/, AvroParser.readByte(stream, options)]; + case 2: + byte = _a.sent(); + haveMoreByte = byte & 0x80; + zigZagEncoded |= (byte & 0x7f) << significanceInBit; + significanceInBit += 7; + _a.label = 3; + case 3: + if (haveMoreByte && significanceInBit < 28) return [3 /*break*/, 1]; + _a.label = 4; + case 4: + if (!haveMoreByte) return [3 /*break*/, 9]; + // Switch to float arithmetic + zigZagEncoded = zigZagEncoded; + significanceInFloat = 268435456; // 2 ** 28. + _a.label = 5; + case 5: return [4 /*yield*/, AvroParser.readByte(stream, options)]; + case 6: + byte = _a.sent(); + zigZagEncoded += (byte & 0x7f) * significanceInFloat; + significanceInFloat *= 128; // 2 ** 7 + _a.label = 7; + case 7: + if (byte & 0x80) return [3 /*break*/, 5]; + _a.label = 8; + case 8: + res = (zigZagEncoded % 2 ? -(zigZagEncoded + 1) : zigZagEncoded) / 2; + if (res < Number.MIN_SAFE_INTEGER || res > Number.MAX_SAFE_INTEGER) { + throw new Error("Integer overflow."); + } + return [2 /*return*/, res]; + case 9: return [2 /*return*/, (zigZagEncoded >> 1) ^ -(zigZagEncoded & 1)]; + } + }); + }); + }; + AvroParser.readLong = function (stream, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + return [2 /*return*/, AvroParser.readZigZagLong(stream, options)]; + }); + }); + }; + AvroParser.readInt = function (stream, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + return [2 /*return*/, AvroParser.readZigZagLong(stream, options)]; + }); + }); + }; + AvroParser.readNull = function () { + return tslib.__awaiter(this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + return [2 /*return*/, null]; + }); + }); + }; + AvroParser.readBoolean = function (stream, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var b; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, AvroParser.readByte(stream, options)]; + case 1: + b = _a.sent(); + if (b == 1) { + return [2 /*return*/, true]; + } + else if (b == 0) { + return [2 /*return*/, false]; + } + else { + throw new Error("Byte was not a boolean."); + } + } + }); + }); + }; + AvroParser.readFloat = function (stream, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var u8arr, view; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, AvroParser.readFixedBytes(stream, 4, options)]; + case 1: + u8arr = _a.sent(); + view = new DataView(u8arr.buffer, u8arr.byteOffset, u8arr.byteLength); + return [2 /*return*/, view.getFloat32(0, true)]; // littleEndian = true + } + }); + }); + }; + AvroParser.readDouble = function (stream, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var u8arr, view; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, AvroParser.readFixedBytes(stream, 8, options)]; + case 1: + u8arr = _a.sent(); + view = new DataView(u8arr.buffer, u8arr.byteOffset, u8arr.byteLength); + return [2 /*return*/, view.getFloat64(0, true)]; // littleEndian = true + } + }); + }); + }; + AvroParser.readBytes = function (stream, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var size; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, AvroParser.readLong(stream, options)]; + case 1: + size = _a.sent(); + if (size < 0) { + throw new Error("Bytes size was negative."); + } + return [4 /*yield*/, stream.read(size, { abortSignal: options.abortSignal })]; + case 2: return [2 /*return*/, _a.sent()]; + } + }); + }); + }; + AvroParser.readString = function (stream, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var u8arr, utf8decoder; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, AvroParser.readBytes(stream, options)]; + case 1: + u8arr = _a.sent(); + // polyfill TextDecoder to be backward compatible with older + // nodejs that doesn't expose TextDecoder as a global variable + if (typeof TextDecoder === "undefined" && "function" !== "undefined") { + global.TextDecoder = __webpack_require__(669).TextDecoder; + } + utf8decoder = new TextDecoder(); + return [2 /*return*/, utf8decoder.decode(u8arr)]; + } + }); + }); + }; + AvroParser.readMapPair = function (stream, readItemMethod, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var key, value; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, AvroParser.readString(stream, options)]; + case 1: + key = _a.sent(); + return [4 /*yield*/, readItemMethod(stream, options)]; + case 2: + value = _a.sent(); + return [2 /*return*/, { key: key, value: value }]; + } + }); + }); + }; + AvroParser.readMap = function (stream, readItemMethod, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var readPairMethod, pairs, dict, _i, pairs_1, pair; + var _this = this; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + readPairMethod = function (stream, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(_this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, AvroParser.readMapPair(stream, readItemMethod, options)]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); + }; + return [4 /*yield*/, AvroParser.readArray(stream, readPairMethod, options)]; + case 1: + pairs = _a.sent(); + dict = {}; + for (_i = 0, pairs_1 = pairs; _i < pairs_1.length; _i++) { + pair = pairs_1[_i]; + dict[pair.key] = pair.value; + } + return [2 /*return*/, dict]; + } + }); + }); + }; + AvroParser.readArray = function (stream, readItemMethod, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var items, count, item; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + items = []; + return [4 /*yield*/, AvroParser.readLong(stream, options)]; + case 1: + count = _a.sent(); + _a.label = 2; + case 2: + if (!(count != 0)) return [3 /*break*/, 8]; + if (!(count < 0)) return [3 /*break*/, 4]; + // Ignore block sizes + return [4 /*yield*/, AvroParser.readLong(stream, options)]; + case 3: + // Ignore block sizes + _a.sent(); + count = -count; + _a.label = 4; + case 4: + if (!count--) return [3 /*break*/, 6]; + return [4 /*yield*/, readItemMethod(stream, options)]; + case 5: + item = _a.sent(); + items.push(item); + return [3 /*break*/, 4]; + case 6: return [4 /*yield*/, AvroParser.readLong(stream, options)]; + case 7: + count = _a.sent(); + return [3 /*break*/, 2]; + case 8: return [2 /*return*/, items]; + } + }); + }); + }; + return AvroParser; +}()); +var AvroComplex; +(function (AvroComplex) { + AvroComplex["RECORD"] = "record"; + AvroComplex["ENUM"] = "enum"; + AvroComplex["ARRAY"] = "array"; + AvroComplex["MAP"] = "map"; + AvroComplex["UNION"] = "union"; + AvroComplex["FIXED"] = "fixed"; +})(AvroComplex || (AvroComplex = {})); +var AvroType = /** @class */ (function () { + function AvroType() { + } + /** + * Determines the AvroType from the Avro Schema. + */ + AvroType.fromSchema = function (schema) { + if (typeof schema == "string") { + return AvroType.fromStringSchema(schema); + } + else if (Array.isArray(schema)) { + return AvroType.fromArraySchema(schema); + } + else { + return AvroType.fromObjectSchema(schema); + } + }; + AvroType.fromStringSchema = function (schema) { + switch (schema) { + case AvroPrimitive.NULL: + case AvroPrimitive.BOOLEAN: + case AvroPrimitive.INT: + case AvroPrimitive.LONG: + case AvroPrimitive.FLOAT: + case AvroPrimitive.DOUBLE: + case AvroPrimitive.BYTES: + case AvroPrimitive.STRING: + return new AvroPrimitiveType(schema); + default: + throw new Error("Unexpected Avro type " + schema); + } + }; + AvroType.fromArraySchema = function (schema) { + return new AvroUnionType(schema.map(AvroType.fromSchema)); + }; + AvroType.fromObjectSchema = function (schema) { + var type = schema.type; + // Primitives can be defined as strings or objects + try { + return AvroType.fromStringSchema(type); + } + catch (err) { } + switch (type) { + case AvroComplex.RECORD: + if (schema.aliases) { + throw new Error("aliases currently is not supported, schema: " + schema); + } + if (!schema.name) { + throw new Error("Required attribute 'name' doesn't exist on schema: " + schema); + } + var fields = {}; + if (!schema.fields) { + throw new Error("Required attribute 'fields' doesn't exist on schema: " + schema); + } + for (var _i = 0, _a = schema.fields; _i < _a.length; _i++) { + var field = _a[_i]; + fields[field.name] = AvroType.fromSchema(field.type); + } + return new AvroRecordType(fields, schema.name); + case AvroComplex.ENUM: + if (schema.aliases) { + throw new Error("aliases currently is not supported, schema: " + schema); + } + if (!schema.symbols) { + throw new Error("Required attribute 'symbols' doesn't exist on schema: " + schema); + } + return new AvroEnumType(schema.symbols); + case AvroComplex.MAP: + if (!schema.values) { + throw new Error("Required attribute 'values' doesn't exist on schema: " + schema); + } + return new AvroMapType(AvroType.fromSchema(schema.values)); + case AvroComplex.ARRAY: // Unused today + case AvroComplex.FIXED: // Unused today + default: + throw new Error("Unexpected Avro type " + type + " in " + schema); + } + }; + return AvroType; +}()); +var AvroPrimitive; +(function (AvroPrimitive) { + AvroPrimitive["NULL"] = "null"; + AvroPrimitive["BOOLEAN"] = "boolean"; + AvroPrimitive["INT"] = "int"; + AvroPrimitive["LONG"] = "long"; + AvroPrimitive["FLOAT"] = "float"; + AvroPrimitive["DOUBLE"] = "double"; + AvroPrimitive["BYTES"] = "bytes"; + AvroPrimitive["STRING"] = "string"; +})(AvroPrimitive || (AvroPrimitive = {})); +var AvroPrimitiveType = /** @class */ (function (_super) { + tslib.__extends(AvroPrimitiveType, _super); + function AvroPrimitiveType(primitive) { + var _this = _super.call(this) || this; + _this._primitive = primitive; + return _this; + } + AvroPrimitiveType.prototype.read = function (stream, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = this._primitive; + switch (_a) { + case AvroPrimitive.NULL: return [3 /*break*/, 1]; + case AvroPrimitive.BOOLEAN: return [3 /*break*/, 3]; + case AvroPrimitive.INT: return [3 /*break*/, 5]; + case AvroPrimitive.LONG: return [3 /*break*/, 7]; + case AvroPrimitive.FLOAT: return [3 /*break*/, 9]; + case AvroPrimitive.DOUBLE: return [3 /*break*/, 11]; + case AvroPrimitive.BYTES: return [3 /*break*/, 13]; + case AvroPrimitive.STRING: return [3 /*break*/, 15]; + } + return [3 /*break*/, 17]; + case 1: return [4 /*yield*/, AvroParser.readNull()]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: return [4 /*yield*/, AvroParser.readBoolean(stream, options)]; + case 4: return [2 /*return*/, _b.sent()]; + case 5: return [4 /*yield*/, AvroParser.readInt(stream, options)]; + case 6: return [2 /*return*/, _b.sent()]; + case 7: return [4 /*yield*/, AvroParser.readLong(stream, options)]; + case 8: return [2 /*return*/, _b.sent()]; + case 9: return [4 /*yield*/, AvroParser.readFloat(stream, options)]; + case 10: return [2 /*return*/, _b.sent()]; + case 11: return [4 /*yield*/, AvroParser.readDouble(stream, options)]; + case 12: return [2 /*return*/, _b.sent()]; + case 13: return [4 /*yield*/, AvroParser.readBytes(stream, options)]; + case 14: return [2 /*return*/, _b.sent()]; + case 15: return [4 /*yield*/, AvroParser.readString(stream, options)]; + case 16: return [2 /*return*/, _b.sent()]; + case 17: throw new Error("Unknown Avro Primitive"); + } + }); + }); + }; + return AvroPrimitiveType; +}(AvroType)); +var AvroEnumType = /** @class */ (function (_super) { + tslib.__extends(AvroEnumType, _super); + function AvroEnumType(symbols) { + var _this = _super.call(this) || this; + _this._symbols = symbols; + return _this; + } + AvroEnumType.prototype.read = function (stream, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var value; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, AvroParser.readInt(stream, options)]; + case 1: + value = _a.sent(); + return [2 /*return*/, this._symbols[value]]; + } + }); + }); + }; + return AvroEnumType; +}(AvroType)); +var AvroUnionType = /** @class */ (function (_super) { + tslib.__extends(AvroUnionType, _super); + function AvroUnionType(types) { + var _this = _super.call(this) || this; + _this._types = types; + return _this; + } + AvroUnionType.prototype.read = function (stream, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var typeIndex; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, AvroParser.readInt(stream, options)]; + case 1: + typeIndex = _a.sent(); + return [4 /*yield*/, this._types[typeIndex].read(stream, options)]; + case 2: return [2 /*return*/, _a.sent()]; + } + }); + }); + }; + return AvroUnionType; +}(AvroType)); +var AvroMapType = /** @class */ (function (_super) { + tslib.__extends(AvroMapType, _super); + function AvroMapType(itemType) { + var _this = _super.call(this) || this; + _this._itemType = itemType; + return _this; + } + AvroMapType.prototype.read = function (stream, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var readItemMethod; + var _this = this; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + readItemMethod = function (s, options) { return tslib.__awaiter(_this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this._itemType.read(s, options)]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); }; + return [4 /*yield*/, AvroParser.readMap(stream, readItemMethod, options)]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); + }; + return AvroMapType; +}(AvroType)); +var AvroRecordType = /** @class */ (function (_super) { + tslib.__extends(AvroRecordType, _super); + function AvroRecordType(fields, name) { + var _this = _super.call(this) || this; + _this._fields = fields; + _this._name = name; + return _this; + } + AvroRecordType.prototype.read = function (stream, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var record, _a, _b, _i, key, _c, _d; + return tslib.__generator(this, function (_e) { + switch (_e.label) { + case 0: + record = {}; + record["$schema"] = this._name; + _a = []; + for (_b in this._fields) + _a.push(_b); + _i = 0; + _e.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 4]; + key = _a[_i]; + if (!this._fields.hasOwnProperty(key)) return [3 /*break*/, 3]; + _c = record; + _d = key; + return [4 /*yield*/, this._fields[key].read(stream, options)]; + case 2: + _c[_d] = _e.sent(); + _e.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/, record]; + } + }); + }); + }; + return AvroRecordType; +}(AvroType)); + +// Copyright (c) Microsoft Corporation. +var AvroReader = /** @class */ (function () { + function AvroReader(dataStream, headerStream, currentBlockOffset, indexWithinCurrentBlock) { + this._dataStream = dataStream; + this._headerStream = headerStream || dataStream; + this._initialized = false; + this._blockOffset = currentBlockOffset || 0; + this._objectIndex = indexWithinCurrentBlock || 0; + this._initialBlockOffset = currentBlockOffset || 0; + } + Object.defineProperty(AvroReader.prototype, "blockOffset", { + get: function () { + return this._blockOffset; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AvroReader.prototype, "objectIndex", { + get: function () { + return this._objectIndex; + }, + enumerable: false, + configurable: true + }); + AvroReader.prototype.initialize = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var header, _a, codec, _b, schema, _c, i; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: return [4 /*yield*/, AvroParser.readFixedBytes(this._headerStream, AVRO_INIT_BYTES.length, { + abortSignal: options.abortSignal + })]; + case 1: + header = _d.sent(); + if (!arraysEqual(header, AVRO_INIT_BYTES)) { + throw new Error("Stream is not an Avro file."); + } + // File metadata is written as if defined by the following map schema: + // { "type": "map", "values": "bytes"} + _a = this; + return [4 /*yield*/, AvroParser.readMap(this._headerStream, AvroParser.readString, { + abortSignal: options.abortSignal + })]; + case 2: + // File metadata is written as if defined by the following map schema: + // { "type": "map", "values": "bytes"} + _a._metadata = _d.sent(); + codec = this._metadata[AVRO_CODEC_KEY]; + if (!(codec == undefined || codec == "null")) { + throw new Error("Codecs are not supported"); + } + // The 16-byte, randomly-generated sync marker for this file. + _b = this; + return [4 /*yield*/, AvroParser.readFixedBytes(this._headerStream, AVRO_SYNC_MARKER_SIZE, { + abortSignal: options.abortSignal + })]; + case 3: + // The 16-byte, randomly-generated sync marker for this file. + _b._syncMarker = _d.sent(); + schema = JSON.parse(this._metadata[AVRO_SCHEMA_KEY]); + this._itemType = AvroType.fromSchema(schema); + if (this._blockOffset == 0) { + this._blockOffset = this._initialBlockOffset + this._dataStream.position; + } + _c = this; + return [4 /*yield*/, AvroParser.readLong(this._dataStream, { + abortSignal: options.abortSignal + })]; + case 4: + _c._itemsRemainingInBlock = _d.sent(); + // skip block length + return [4 /*yield*/, AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal })]; + case 5: + // skip block length + _d.sent(); + this._initialized = true; + if (!(this._objectIndex && this._objectIndex > 0)) return [3 /*break*/, 9]; + i = 0; + _d.label = 6; + case 6: + if (!(i < this._objectIndex)) return [3 /*break*/, 9]; + return [4 /*yield*/, this._itemType.read(this._dataStream, { abortSignal: options.abortSignal })]; + case 7: + _d.sent(); + this._itemsRemainingInBlock--; + _d.label = 8; + case 8: + i++; + return [3 /*break*/, 6]; + case 9: return [2 /*return*/]; + } + }); + }); + }; + AvroReader.prototype.hasNext = function () { + return !this._initialized || this._itemsRemainingInBlock > 0; + }; + AvroReader.prototype.parseObjects = function (options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function parseObjects_1() { + var result, marker, _a, err_1; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!!this._initialized) return [3 /*break*/, 2]; + return [4 /*yield*/, tslib.__await(this.initialize(options))]; + case 1: + _b.sent(); + _b.label = 2; + case 2: + if (!this.hasNext()) return [3 /*break*/, 13]; + return [4 /*yield*/, tslib.__await(this._itemType.read(this._dataStream, { + abortSignal: options.abortSignal + }))]; + case 3: + result = _b.sent(); + this._itemsRemainingInBlock--; + this._objectIndex++; + if (!(this._itemsRemainingInBlock == 0)) return [3 /*break*/, 10]; + return [4 /*yield*/, tslib.__await(AvroParser.readFixedBytes(this._dataStream, AVRO_SYNC_MARKER_SIZE, { + abortSignal: options.abortSignal + }))]; + case 4: + marker = _b.sent(); + this._blockOffset = this._initialBlockOffset + this._dataStream.position; + this._objectIndex = 0; + if (!arraysEqual(this._syncMarker, marker)) { + throw new Error("Stream is not a valid Avro file."); + } + _b.label = 5; + case 5: + _b.trys.push([5, 7, , 8]); + _a = this; + return [4 /*yield*/, tslib.__await(AvroParser.readLong(this._dataStream, { + abortSignal: options.abortSignal + }))]; + case 6: + _a._itemsRemainingInBlock = _b.sent(); + return [3 /*break*/, 8]; + case 7: + err_1 = _b.sent(); + // We hit the end of the stream. + this._itemsRemainingInBlock = 0; + return [3 /*break*/, 8]; + case 8: + if (!(this._itemsRemainingInBlock > 0)) return [3 /*break*/, 10]; + // Ignore block size + return [4 /*yield*/, tslib.__await(AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal }))]; + case 9: + // Ignore block size + _b.sent(); + _b.label = 10; + case 10: return [4 /*yield*/, tslib.__await(result)]; + case 11: return [4 /*yield*/, _b.sent()]; + case 12: + _b.sent(); + return [3 /*break*/, 2]; + case 13: return [2 /*return*/]; + } + }); + }); + }; + return AvroReader; +}()); + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +var AvroReadable = /** @class */ (function () { + function AvroReadable() { + } + return AvroReadable; +}()); + +// Copyright (c) Microsoft Corporation. +var ABORT_ERROR$1 = new abortController.AbortError("Reading from the avro stream was aborted."); +var AvroReadableFromStream = /** @class */ (function (_super) { + tslib.__extends(AvroReadableFromStream, _super); + function AvroReadableFromStream(readable) { + var _this = _super.call(this) || this; + _this._readable = readable; + _this._position = 0; + return _this; + } + AvroReadableFromStream.prototype.toUint8Array = function (data) { + if (typeof data === "string") { + return Buffer.from(data); + } + return data; + }; + Object.defineProperty(AvroReadableFromStream.prototype, "position", { + get: function () { + return this._position; + }, + enumerable: false, + configurable: true + }); + AvroReadableFromStream.prototype.read = function (size, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var chunk; + var _this = this; + return tslib.__generator(this, function (_b) { + if ((_a = options.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { + throw ABORT_ERROR$1; + } + if (size < 0) { + throw new Error("size parameter should be positive: " + size); + } + if (size === 0) { + return [2 /*return*/, new Uint8Array()]; + } + if (!this._readable.readable) { + throw new Error("Stream no longer readable."); + } + chunk = this._readable.read(size); + if (chunk) { + this._position += chunk.length; + // chunk.length maybe less than desired size if the stream ends. + return [2 /*return*/, this.toUint8Array(chunk)]; + } + else { + // register callback to wait for enough data to read + return [2 /*return*/, new Promise(function (resolve, reject) { + var cleanUp = function () { + _this._readable.removeListener("readable", readableCallback); + _this._readable.removeListener("error", rejectCallback); + _this._readable.removeListener("end", rejectCallback); + _this._readable.removeListener("close", rejectCallback); + if (options.abortSignal) { + options.abortSignal.removeEventListener("abort", abortHandler); + } + }; + var readableCallback = function () { + var chunk = _this._readable.read(size); + if (chunk) { + _this._position += chunk.length; + cleanUp(); + // chunk.length maybe less than desired size if the stream ends. + resolve(_this.toUint8Array(chunk)); + } + }; + var rejectCallback = function () { + cleanUp(); + reject(); + }; + var abortHandler = function () { + cleanUp(); + reject(ABORT_ERROR$1); + }; + _this._readable.on("readable", readableCallback); + _this._readable.once("error", rejectCallback); + _this._readable.once("end", rejectCallback); + _this._readable.once("close", rejectCallback); + if (options.abortSignal) { + options.abortSignal.addEventListener("abort", abortHandler); + } + })]; + } + }); + }); + }; + return AvroReadableFromStream; +}(AvroReadable)); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * A Node.js BlobQuickQueryStream will internally parse avro data stream for blob query. + * + * @class BlobQuickQueryStream + * @extends {Readable} + */ +var BlobQuickQueryStream = /** @class */ (function (_super) { + tslib.__extends(BlobQuickQueryStream, _super); + /** + * Creates an instance of BlobQuickQueryStream. + * + * @param {NodeJS.ReadableStream} source The current ReadableStream returned from getter + * @param {BlobQuickQueryStreamOptions} [options={}] + * @memberof BlobQuickQueryStream + */ + function BlobQuickQueryStream(source, options) { + if (options === void 0) { options = {}; } + var _this = _super.call(this) || this; + _this.source = source; + _this.onProgress = options.onProgress; + _this.onError = options.onError; + _this.avroReader = new AvroReader(new AvroReadableFromStream(_this.source)); + _this.avroIter = _this.avroReader.parseObjects({ abortSignal: options.abortSignal }); + return _this; + } + BlobQuickQueryStream.prototype._read = function () { + var _this = this; + this.readInternal().catch(function (err) { + _this.emit("error", err); + }); + }; + BlobQuickQueryStream.prototype.readInternal = function () { + var e_1, _a; + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, _c, obj, schema, exit, data, bytesScanned, totalBytes, fatal, name_1, description, position, e_1_1; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _d.trys.push([0, 5, 6, 11]); + _b = tslib.__asyncValues(this.avroIter); + _d.label = 1; + case 1: return [4 /*yield*/, _b.next()]; + case 2: + if (!(_c = _d.sent(), !_c.done)) return [3 /*break*/, 4]; + obj = _c.value; + schema = obj.$schema; + if (typeof schema !== "string") { + throw Error("Missing schema in avro record."); + } + exit = false; + switch (schema) { + case "com.microsoft.azure.storage.queryBlobContents.resultData": + data = obj.data; + if (data instanceof Uint8Array === false) { + throw Error("Invalid data in avro result record."); + } + if (!this.push(Buffer.from(data))) { + exit = true; + } + break; + case "com.microsoft.azure.storage.queryBlobContents.progress": + bytesScanned = obj.bytesScanned; + if (typeof bytesScanned !== "number") { + throw Error("Invalid bytesScanned in avro progress record."); + } + if (this.onProgress) { + this.onProgress({ loadedBytes: bytesScanned }); + } + break; + case "com.microsoft.azure.storage.queryBlobContents.end": + if (this.onProgress) { + totalBytes = obj.totalBytes; + if (typeof totalBytes !== "number") { + throw Error("Invalid totalBytes in avro end record."); + } + this.onProgress({ loadedBytes: totalBytes }); + } + this.push(null); + break; + case "com.microsoft.azure.storage.queryBlobContents.error": + if (this.onError) { + fatal = obj.fatal; + if (typeof fatal !== "boolean") { + throw Error("Invalid fatal in avro error record."); + } + name_1 = obj.name; + if (typeof name_1 !== "string") { + throw Error("Invalid name in avro error record."); + } + description = obj.description; + if (typeof description !== "string") { + throw Error("Invalid description in avro error record."); + } + position = obj.position; + if (typeof position !== "number") { + throw Error("Invalid position in avro error record."); + } + this.onError({ + position: position, + name: name_1, + isFatal: fatal, + description: description + }); + } + break; + default: + throw Error("Unknown schema " + schema + " in avro progress record."); + } + if (exit) { + return [3 /*break*/, 4]; + } + _d.label = 3; + case 3: return [3 /*break*/, 1]; + case 4: return [3 /*break*/, 11]; + case 5: + e_1_1 = _d.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 11]; + case 6: + _d.trys.push([6, , 9, 10]); + if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 8]; + return [4 /*yield*/, _a.call(_b)]; + case 7: + _d.sent(); + _d.label = 8; + case 8: return [3 /*break*/, 10]; + case 9: + if (e_1) throw e_1.error; + return [7 /*endfinally*/]; + case 10: return [7 /*endfinally*/]; + case 11: return [2 /*return*/]; + } + }); + }); + }; + return BlobQuickQueryStream; +}(stream.Readable)); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * BlobQueryResponse implements BlobDownloadResponseModel interface, and in Node.js runtime it will + * parse avor data returned by blob query. + * + * @export + * @class BlobQueryResponse + * @implements {BlobDownloadResponseModel} + */ +var BlobQueryResponse = /** @class */ (function () { + /** + * Creates an instance of BlobQueryResponse. + * + * @param {BlobQueryResponseModel} originalResponse + * @param {BlobQuickQueryStreamOptions} [options={}] + * @memberof BlobQueryResponse + */ + function BlobQueryResponse(originalResponse, options) { + if (options === void 0) { options = {}; } + this.originalResponse = originalResponse; + this.blobDownloadStream = new BlobQuickQueryStream(this.originalResponse.readableStreamBody, options); + } + Object.defineProperty(BlobQueryResponse.prototype, "acceptRanges", { + /** + * Indicates that the service supports + * requests for partial file content. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.acceptRanges; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "cacheControl", { + /** + * Returns if it was previously specified + * for the file. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.cacheControl; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "contentDisposition", { + /** + * Returns the value that was specified + * for the 'x-ms-content-disposition' header and specifies how to process the + * response. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.contentDisposition; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "contentEncoding", { + /** + * Returns the value that was specified + * for the Content-Encoding request header. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.contentEncoding; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "contentLanguage", { + /** + * Returns the value that was specified + * for the Content-Language request header. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.contentLanguage; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "blobSequenceNumber", { + /** + * The current sequence number for a + * page blob. This header is not returned for block blobs or append blobs. + * + * @readonly + * @type {(number | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.blobSequenceNumber; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "blobType", { + /** + * The blob's type. Possible values include: + * 'BlockBlob', 'PageBlob', 'AppendBlob'. + * + * @readonly + * @type {(BlobType | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.blobType; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "contentLength", { + /** + * The number of bytes present in the + * response body. + * + * @readonly + * @type {(number | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.contentLength; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "contentMD5", { + /** + * If the file has an MD5 hash and the + * request is to read the full file, this response header is returned so that + * the client can check for message content integrity. If the request is to + * read a specified range and the 'x-ms-range-get-content-md5' is set to + * true, then the request returns an MD5 hash for the range, as long as the + * range size is less than or equal to 4 MB. If neither of these sets of + * conditions is true, then no value is returned for the 'Content-MD5' + * header. + * + * @readonly + * @type {(Uint8Array | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.contentMD5; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "contentRange", { + /** + * Indicates the range of bytes returned if + * the client requested a subset of the file by setting the Range request + * header. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.contentRange; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "contentType", { + /** + * The content type specified for the file. + * The default content type is 'application/octet-stream' + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.contentType; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "copyCompletedOn", { + /** + * Conclusion time of the last attempted + * Copy File operation where this file was the destination file. This value + * can specify the time of a completed, aborted, or failed copy attempt. + * + * @readonly + * @type {(Date | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return undefined; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "copyId", { + /** + * String identifier for the last attempted Copy + * File operation where this file was the destination file. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.copyId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "copyProgress", { + /** + * Contains the number of bytes copied and + * the total bytes in the source in the last attempted Copy File operation + * where this file was the destination file. Can show between 0 and + * Content-Length bytes copied. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.copyProgress; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "copySource", { + /** + * URL up to 2KB in length that specifies the + * source file used in the last attempted Copy File operation where this file + * was the destination file. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.copySource; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "copyStatus", { + /** + * State of the copy operation + * identified by 'x-ms-copy-id'. Possible values include: 'pending', + * 'success', 'aborted', 'failed' + * + * @readonly + * @type {(CopyStatusType | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.copyStatus; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "copyStatusDescription", { + /** + * Only appears when + * x-ms-copy-status is failed or pending. Describes cause of fatal or + * non-fatal copy operation failure. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.copyStatusDescription; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "leaseDuration", { + /** + * When a blob is leased, + * specifies whether the lease is of infinite or fixed duration. Possible + * values include: 'infinite', 'fixed'. + * + * @readonly + * @type {(LeaseDurationType | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.leaseDuration; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "leaseState", { + /** + * Lease state of the blob. Possible + * values include: 'available', 'leased', 'expired', 'breaking', 'broken'. + * + * @readonly + * @type {(LeaseStateType | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.leaseState; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "leaseStatus", { + /** + * The current lease status of the + * blob. Possible values include: 'locked', 'unlocked'. + * + * @readonly + * @type {(LeaseStatusType | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.leaseStatus; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "date", { + /** + * A UTC date/time value generated by the service that + * indicates the time at which the response was initiated. + * + * @readonly + * @type {(Date | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.date; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "blobCommittedBlockCount", { + /** + * The number of committed blocks + * present in the blob. This header is returned only for append blobs. + * + * @readonly + * @type {(number | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.blobCommittedBlockCount; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "etag", { + /** + * The ETag contains a value that you can use to + * perform operations conditionally, in quotes. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.etag; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "errorCode", { + /** + * The error code. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.errorCode; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "isServerEncrypted", { + /** + * The value of this header is set to + * true if the file data and application metadata are completely encrypted + * using the specified algorithm. Otherwise, the value is set to false (when + * the file is unencrypted, or if only parts of the file/application metadata + * are encrypted). + * + * @readonly + * @type {(boolean | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.isServerEncrypted; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "blobContentMD5", { + /** + * If the blob has a MD5 hash, and if + * request contains range header (Range or x-ms-range), this response header + * is returned with the value of the whole blob's MD5 value. This value may + * or may not be equal to the value returned in Content-MD5 header, with the + * latter calculated from the requested range. + * + * @readonly + * @type {(Uint8Array | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.blobContentMD5; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "lastModified", { + /** + * Returns the date and time the file was last + * modified. Any operation that modifies the file or its properties updates + * the last modified time. + * + * @readonly + * @type {(Date | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.lastModified; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "metadata", { + /** + * A name-value pair + * to associate with a file storage object. + * + * @readonly + * @type {(Metadata | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.metadata; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "requestId", { + /** + * This header uniquely identifies the request + * that was made and can be used for troubleshooting the request. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.requestId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "clientRequestId", { + /** + * If a client request id header is sent in the request, this header will be present in the + * response with the same value. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.clientRequestId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "version", { + /** + * Indicates the version of the File service used + * to execute the request. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.version; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "encryptionKeySha256", { + /** + * The SHA-256 hash of the encryption key used to encrypt the blob. This value is only returned + * when the blob was encrypted with a customer-provided key. + * + * @readonly + * @type {(string | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.encryptionKeySha256; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "contentCrc64", { + /** + * If the request is to read a specified range and the x-ms-range-get-content-crc64 is set to + * true, then the request returns a crc64 for the range, as long as the range size is less than + * or equal to 4 MB. If both x-ms-range-get-content-crc64 & x-ms-range-get-content-md5 is + * specified in the same request, it will fail with 400(Bad Request) + * + * @type {(Uint8Array | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse.contentCrc64; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "blobBody", { + /** + * The response body as a browser Blob. + * Always undefined in node.js. + * + * @readonly + * @type {(Promise | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return undefined; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "readableStreamBody", { + /** + * The response body as a node.js Readable stream. + * Always undefined in the browser. + * + * It will parse avor data returned by blob query. + * + * @readonly + * @type {(NodeJS.ReadableStream | undefined)} + * @memberof BlobQueryResponse + */ + get: function () { + return coreHttp.isNode ? this.blobDownloadStream : undefined; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobQueryResponse.prototype, "_response", { + /** + * The HTTP response. + * + * @type {HttpResponse} + * @memberof BlobQueryResponse + */ + get: function () { + return this.originalResponse._response; + }, + enumerable: false, + configurable: true + }); + return BlobQueryResponse; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * StorageSharedKeyCredentialPolicy is a policy used to sign HTTP request with a shared key. + * + * @export + * @class StorageSharedKeyCredentialPolicy + * @extends {CredentialPolicy} + */ +var StorageSharedKeyCredentialPolicy = /** @class */ (function (_super) { + tslib.__extends(StorageSharedKeyCredentialPolicy, _super); + /** + * Creates an instance of StorageSharedKeyCredentialPolicy. + * @param {RequestPolicy} nextPolicy + * @param {RequestPolicyOptions} options + * @param {StorageSharedKeyCredential} factory + * @memberof StorageSharedKeyCredentialPolicy + */ + function StorageSharedKeyCredentialPolicy(nextPolicy, options, factory) { + var _this = _super.call(this, nextPolicy, options) || this; + _this.factory = factory; + return _this; + } + /** + * Signs request. + * + * @protected + * @param {WebResource} request + * @returns {WebResource} + * @memberof StorageSharedKeyCredentialPolicy + */ + StorageSharedKeyCredentialPolicy.prototype.signRequest = function (request) { + request.headers.set(HeaderConstants.X_MS_DATE, new Date().toUTCString()); + if (request.body && typeof request.body === "string" && request.body.length > 0) { + request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); + } + var stringToSign = [ + request.method.toUpperCase(), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE), + this.getHeaderValueToSign(request, HeaderConstants.DATE), + this.getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE), + this.getHeaderValueToSign(request, HeaderConstants.IF_MATCH), + this.getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH), + this.getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE), + this.getHeaderValueToSign(request, HeaderConstants.RANGE) + ].join("\n") + + "\n" + + this.getCanonicalizedHeadersString(request) + + this.getCanonicalizedResourceString(request); + var signature = this.factory.computeHMACSHA256(stringToSign); + request.headers.set(HeaderConstants.AUTHORIZATION, "SharedKey " + this.factory.accountName + ":" + signature); + // console.log(`[URL]:${request.url}`); + // console.log(`[HEADERS]:${request.headers.toString()}`); + // console.log(`[STRING TO SIGN]:${JSON.stringify(stringToSign)}`); + // console.log(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`); + return request; + }; + /** + * Retrieve header value according to shared key sign rules. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key + * + * @private + * @param {WebResource} request + * @param {string} headerName + * @returns {string} + * @memberof StorageSharedKeyCredentialPolicy + */ + StorageSharedKeyCredentialPolicy.prototype.getHeaderValueToSign = function (request, headerName) { + var value = request.headers.get(headerName); + if (!value) { + return ""; + } + // When using version 2015-02-21 or later, if Content-Length is zero, then + // set the Content-Length part of the StringToSign to an empty string. + // https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key + if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") { + return ""; + } + return value; + }; + /** + * To construct the CanonicalizedHeaders portion of the signature string, follow these steps: + * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. + * 2. Convert each HTTP header name to lowercase. + * 3. Sort the headers lexicographically by header name, in ascending order. + * Each header may appear only once in the string. + * 4. Replace any linear whitespace in the header value with a single space. + * 5. Trim any whitespace around the colon in the header. + * 6. Finally, append a new-line character to each canonicalized header in the resulting list. + * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. + * + * @private + * @param {WebResource} request + * @returns {string} + * @memberof StorageSharedKeyCredentialPolicy + */ + StorageSharedKeyCredentialPolicy.prototype.getCanonicalizedHeadersString = function (request) { + var headersArray = request.headers.headersArray().filter(function (value) { + return value.name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE); + }); + headersArray.sort(function (a, b) { + return a.name.toLowerCase().localeCompare(b.name.toLowerCase()); + }); + // Remove duplicate headers + headersArray = headersArray.filter(function (value, index, array) { + if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { + return false; + } + return true; + }); + var canonicalizedHeadersStringToSign = ""; + headersArray.forEach(function (header) { + canonicalizedHeadersStringToSign += header.name + .toLowerCase() + .trimRight() + ":" + header.value.trimLeft() + "\n"; + }); + return canonicalizedHeadersStringToSign; + }; + /** + * Retrieves the webResource canonicalized resource string. + * + * @private + * @param {WebResource} request + * @returns {string} + * @memberof StorageSharedKeyCredentialPolicy + */ + StorageSharedKeyCredentialPolicy.prototype.getCanonicalizedResourceString = function (request) { + var path = getURLPath(request.url) || "/"; + var canonicalizedResourceString = ""; + canonicalizedResourceString += "/" + this.factory.accountName + path; + var queries = getURLQueries(request.url); + var lowercaseQueries = {}; + if (queries) { + var queryKeys = []; + for (var key in queries) { + if (queries.hasOwnProperty(key)) { + var lowercaseKey = key.toLowerCase(); + lowercaseQueries[lowercaseKey] = queries[key]; + queryKeys.push(lowercaseKey); + } + } + queryKeys.sort(); + for (var _i = 0, queryKeys_1 = queryKeys; _i < queryKeys_1.length; _i++) { + var key = queryKeys_1[_i]; + canonicalizedResourceString += "\n" + key + ":" + decodeURIComponent(lowercaseQueries[key]); + } + } + return canonicalizedResourceString; + }; + return StorageSharedKeyCredentialPolicy; +}(CredentialPolicy)); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * StorageSharedKeyCredential for account key authorization of Azure Storage service. + * + * @export + * @class StorageSharedKeyCredential + * @extends {Credential} + */ +var StorageSharedKeyCredential = /** @class */ (function (_super) { + tslib.__extends(StorageSharedKeyCredential, _super); + /** + * Creates an instance of StorageSharedKeyCredential. + * @param {string} accountName + * @param {string} accountKey + * @memberof StorageSharedKeyCredential + */ + function StorageSharedKeyCredential(accountName, accountKey) { + var _this = _super.call(this) || this; + _this.accountName = accountName; + _this.accountKey = Buffer.from(accountKey, "base64"); + return _this; + } + /** + * Creates a StorageSharedKeyCredentialPolicy object. + * + * @param {RequestPolicy} nextPolicy + * @param {RequestPolicyOptions} options + * @returns {StorageSharedKeyCredentialPolicy} + * @memberof StorageSharedKeyCredential + */ + StorageSharedKeyCredential.prototype.create = function (nextPolicy, options) { + return new StorageSharedKeyCredentialPolicy(nextPolicy, options, this); + }; + /** + * Generates a hash signature for an HTTP request or for a SAS. + * + * @param {string} stringToSign + * @returns {string} + * @memberof StorageSharedKeyCredential + */ + StorageSharedKeyCredential.prototype.computeHMACSHA256 = function (stringToSign) { + return crypto.createHmac("sha256", this.accountKey) + .update(stringToSign, "utf8") + .digest("base64"); + }; + return StorageSharedKeyCredential; +}(Credential)); + +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ +var packageName = "azure-storage-blob"; +var packageVersion = "12.2.1"; +var StorageClientContext = /** @class */ (function (_super) { + tslib.__extends(StorageClientContext, _super); + /** + * Initializes a new instance of the StorageClientContext class. + * @param url The URL of the service account, container, or blob that is the targe of the desired + * operation. + * @param [options] The parameter options + */ + function StorageClientContext(url, options) { + var _this = this; + if (url == undefined) { + throw new Error("'url' cannot be null."); + } + if (!options) { + options = {}; + } + if (!options.userAgent) { + var defaultUserAgent = coreHttp.getDefaultUserAgentValue(); + options.userAgent = packageName + "/" + packageVersion + " " + defaultUserAgent; + } + _this = _super.call(this, undefined, options) || this; + _this.version = "2019-12-12"; + _this.baseUri = "{url}"; + _this.requestContentType = "application/json; charset=utf-8"; + _this.url = url; + return _this; + } + return StorageClientContext; +}(coreHttp.ServiceClient)); + +// Copyright (c) Microsoft Corporation. All rights reserved. +(function (BlockBlobTier) { + /** + * Optimized for storing data that is accessed frequently. + */ + BlockBlobTier["Hot"] = "Hot"; + /** + * Optimized for storing data that is infrequently accessed and stored for at least 30 days. + */ + BlockBlobTier["Cool"] = "Cool"; + /** + * Optimized for storing data that is rarely accessed and stored for at least 180 days + * with flexible latency requirements (on the order of hours). + */ + BlockBlobTier["Archive"] = "Archive"; +})(exports.BlockBlobTier || (exports.BlockBlobTier = {})); +(function (PremiumPageBlobTier) { + /** + * P4 Tier. + */ + PremiumPageBlobTier["P4"] = "P4"; + /** + * P6 Tier. + */ + PremiumPageBlobTier["P6"] = "P6"; + /** + * P10 Tier. + */ + PremiumPageBlobTier["P10"] = "P10"; + /** + * P15 Tier. + */ + PremiumPageBlobTier["P15"] = "P15"; + /** + * P20 Tier. + */ + PremiumPageBlobTier["P20"] = "P20"; + /** + * P30 Tier. + */ + PremiumPageBlobTier["P30"] = "P30"; + /** + * P40 Tier. + */ + PremiumPageBlobTier["P40"] = "P40"; + /** + * P50 Tier. + */ + PremiumPageBlobTier["P50"] = "P50"; + /** + * P60 Tier. + */ + PremiumPageBlobTier["P60"] = "P60"; + /** + * P70 Tier. + */ + PremiumPageBlobTier["P70"] = "P70"; + /** + * P80 Tier. + */ + PremiumPageBlobTier["P80"] = "P80"; +})(exports.PremiumPageBlobTier || (exports.PremiumPageBlobTier = {})); +function toAccessTier(tier) { + if (tier == undefined) { + return undefined; + } + return tier; // No more check if string is a valid AccessTier, and left this to underlay logic to decide(service). +} +function ensureCpkIfSpecified(cpk, isHttps) { + if (cpk && !isHttps) { + throw new RangeError("Customer-provided encryption key must be used over HTTPS."); + } + if (cpk && !cpk.encryptionAlgorithm) { + cpk.encryptionAlgorithm = EncryptionAlgorithmAES25; + } +} + +/** + * Function that converts PageRange and ClearRange to a common Range object. + * PageRange and ClearRange have start and end while Range offset and count + * this function normalizes to Range. + * @param response Model PageBlob Range response + */ +function rangeResponseFromModel(response) { + var pageRange = (response._response.parsedBody.pageRange || []).map(function (x) { return ({ + offset: x.start, + count: x.end - x.start + }); }); + var clearRange = (response._response.parsedBody.clearRange || []).map(function (x) { return ({ + offset: x.start, + count: x.end - x.start + }); }); + return tslib.__assign(tslib.__assign({}, response), { pageRange: pageRange, + clearRange: clearRange, _response: tslib.__assign(tslib.__assign({}, response._response), { parsedBody: { + pageRange: pageRange, + clearRange: clearRange + } }) }); +} + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * This is the poller returned by {@link BlobClient.beginCopyFromURL}. + * This can not be instantiated directly outside of this package. + * + * @ignore + */ +var BlobBeginCopyFromUrlPoller = /** @class */ (function (_super) { + tslib.__extends(BlobBeginCopyFromUrlPoller, _super); + function BlobBeginCopyFromUrlPoller(options) { + var _this = this; + var blobClient = options.blobClient, copySource = options.copySource, _a = options.intervalInMs, intervalInMs = _a === void 0 ? 15000 : _a, onProgress = options.onProgress, resumeFrom = options.resumeFrom, startCopyFromURLOptions = options.startCopyFromURLOptions; + var state; + if (resumeFrom) { + state = JSON.parse(resumeFrom).state; + } + var operation = makeBlobBeginCopyFromURLPollOperation(tslib.__assign(tslib.__assign({}, state), { blobClient: blobClient, + copySource: copySource, + startCopyFromURLOptions: startCopyFromURLOptions })); + _this = _super.call(this, operation) || this; + if (typeof onProgress === "function") { + _this.onProgress(onProgress); + } + _this.intervalInMs = intervalInMs; + return _this; + } + BlobBeginCopyFromUrlPoller.prototype.delay = function () { + return coreHttp.delay(this.intervalInMs); + }; + return BlobBeginCopyFromUrlPoller; +}(coreLro.Poller)); +/** + * Note: Intentionally using function expression over arrow function expression + * so that the function can be invoked with a different context. + * This affects what `this` refers to. + * @ignore + */ +var cancel = function cancel(options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var state, copyId; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + state = this.state; + copyId = state.copyId; + if (state.isCompleted) { + return [2 /*return*/, makeBlobBeginCopyFromURLPollOperation(state)]; + } + if (!copyId) { + state.isCancelled = true; + return [2 /*return*/, makeBlobBeginCopyFromURLPollOperation(state)]; + } + // if abortCopyFromURL throws, it will bubble up to user's poller.cancelOperation call + return [4 /*yield*/, state.blobClient.abortCopyFromURL(copyId, { + abortSignal: options.abortSignal + })]; + case 1: + // if abortCopyFromURL throws, it will bubble up to user's poller.cancelOperation call + _a.sent(); + state.isCancelled = true; + return [2 /*return*/, makeBlobBeginCopyFromURLPollOperation(state)]; + } + }); + }); +}; +/** + * Note: Intentionally using function expression over arrow function expression + * so that the function can be invoked with a different context. + * This affects what `this` refers to. + * @ignore + */ +var update = function update(options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var state, blobClient, copySource, startCopyFromURLOptions, result, result, copyStatus, copyProgress, prevCopyProgress, err_1; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + state = this.state; + blobClient = state.blobClient, copySource = state.copySource, startCopyFromURLOptions = state.startCopyFromURLOptions; + if (!!state.isStarted) return [3 /*break*/, 2]; + state.isStarted = true; + return [4 /*yield*/, blobClient.startCopyFromURL(copySource, startCopyFromURLOptions)]; + case 1: + result = _a.sent(); + // copyId is needed to abort + state.copyId = result.copyId; + if (result.copyStatus === "success") { + state.result = result; + state.isCompleted = true; + } + return [3 /*break*/, 6]; + case 2: + if (!!state.isCompleted) return [3 /*break*/, 6]; + _a.label = 3; + case 3: + _a.trys.push([3, 5, , 6]); + return [4 /*yield*/, state.blobClient.getProperties({ abortSignal: options.abortSignal })]; + case 4: + result = _a.sent(); + copyStatus = result.copyStatus, copyProgress = result.copyProgress; + prevCopyProgress = state.copyProgress; + if (copyProgress) { + state.copyProgress = copyProgress; + } + if (copyStatus === "pending" && + copyProgress !== prevCopyProgress && + typeof options.fireProgress === "function") { + // trigger in setTimeout, or swallow error? + options.fireProgress(state); + } + else if (copyStatus === "success") { + state.result = result; + state.isCompleted = true; + } + else if (copyStatus === "failed") { + state.error = new Error("Blob copy failed with reason: \"" + (result.copyStatusDescription || "unknown") + "\""); + state.isCompleted = true; + } + return [3 /*break*/, 6]; + case 5: + err_1 = _a.sent(); + state.error = err_1; + state.isCompleted = true; + return [3 /*break*/, 6]; + case 6: return [2 /*return*/, makeBlobBeginCopyFromURLPollOperation(state)]; + } + }); + }); +}; +/** + * Note: Intentionally using function expression over arrow function expression + * so that the function can be invoked with a different context. + * This affects what `this` refers to. + * @ignore + */ +var toString = function toString() { + return JSON.stringify({ state: this.state }, function (key, value) { + // remove blobClient from serialized state since a client can't be hydrated from this info. + if (key === "blobClient") { + return undefined; + } + return value; + }); +}; +/** + * Creates a poll operation given the provided state. + * @ignore + */ +function makeBlobBeginCopyFromURLPollOperation(state) { + return { + state: tslib.__assign({}, state), + cancel: cancel, + toString: toString, + update: update + }; +} + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * Generate a range string. For example: + * + * "bytes=255-" or "bytes=0-511" + * + * @export + * @param {Range} iRange + * @returns {string} + */ +function rangeToString(iRange) { + if (iRange.offset < 0) { + throw new RangeError("Range.offset cannot be smaller than 0."); + } + if (iRange.count && iRange.count <= 0) { + throw new RangeError("Range.count must be larger than 0. Leave it undefined if you want a range from offset to the end."); + } + return iRange.count + ? "bytes=" + iRange.offset + "-" + (iRange.offset + iRange.count - 1) + : "bytes=" + iRange.offset + "-"; +} + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * A StorageClient represents a based URL class for {@link BlobServiceClient}, {@link ContainerClient} + * and etc. + * + * @export + * @class StorageClient + */ +var StorageClient = /** @class */ (function () { + /** + * Creates an instance of StorageClient. + * @param {string} url url to resource + * @param {Pipeline} pipeline request policy pipeline. + * @memberof StorageClient + */ + function StorageClient(url, pipeline) { + // URL should be encoded and only once, protocol layer shouldn't encode URL again + this.url = escapeURLPath(url); + this.accountName = getAccountNameFromUrl(url); + this.pipeline = pipeline; + this.storageClientContext = new StorageClientContext(this.url, pipeline.toServiceClientOptions()); + this.isHttps = iEqual(getURLScheme(this.url) || "", "https"); + this.credential = new AnonymousCredential(); + for (var _i = 0, _a = this.pipeline.factories; _i < _a.length; _i++) { + var factory = _a[_i]; + if ((coreHttp.isNode && factory instanceof StorageSharedKeyCredential) || + factory instanceof AnonymousCredential || + coreHttp.isTokenCredential(factory)) { + this.credential = factory; + } + } + // Override protocol layer's default content-type + var storageClientContext = this.storageClientContext; + storageClientContext.requestContentType = undefined; + } + return StorageClient; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * States for Batch. + * + * @enum {number} + */ +var BatchStates; +(function (BatchStates) { + BatchStates[BatchStates["Good"] = 0] = "Good"; + BatchStates[BatchStates["Error"] = 1] = "Error"; +})(BatchStates || (BatchStates = {})); +/** + * Batch provides basic parallel execution with concurrency limits. + * Will stop execute left operations when one of the executed operation throws an error. + * But Batch cannot cancel ongoing operations, you need to cancel them by yourself. + * + * @export + * @class Batch + */ +var Batch = /** @class */ (function () { + /** + * Creates an instance of Batch. + * @param {number} [concurrency=5] + * @memberof Batch + */ + function Batch(concurrency) { + if (concurrency === void 0) { concurrency = 5; } + /** + * Number of active operations under execution. + * + * @private + * @type {number} + * @memberof Batch + */ + this.actives = 0; + /** + * Number of completed operations under execution. + * + * @private + * @type {number} + * @memberof Batch + */ + this.completed = 0; + /** + * Offset of next operation to be executed. + * + * @private + * @type {number} + * @memberof Batch + */ + this.offset = 0; + /** + * Operation array to be executed. + * + * @private + * @type {Operation[]} + * @memberof Batch + */ + this.operations = []; + /** + * States of Batch. When an error happens, state will turn into error. + * Batch will stop execute left operations. + * + * @private + * @type {BatchStates} + * @memberof Batch + */ + this.state = BatchStates.Good; + if (concurrency < 1) { + throw new RangeError("concurrency must be larger than 0"); + } + this.concurrency = concurrency; + this.emitter = new events.EventEmitter(); + } + /** + * Add a operation into queue. + * + * @param {Operation} operation + * @memberof Batch + */ + Batch.prototype.addOperation = function (operation) { + var _this = this; + this.operations.push(function () { return tslib.__awaiter(_this, void 0, void 0, function () { + var error_1; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + this.actives++; + return [4 /*yield*/, operation()]; + case 1: + _a.sent(); + this.actives--; + this.completed++; + this.parallelExecute(); + return [3 /*break*/, 3]; + case 2: + error_1 = _a.sent(); + this.emitter.emit("error", error_1); + return [3 /*break*/, 3]; + case 3: return [2 /*return*/]; + } + }); + }); }); + }; + /** + * Start execute operations in the queue. + * + * @returns {Promise} + * @memberof Batch + */ + Batch.prototype.do = function () { + return tslib.__awaiter(this, void 0, void 0, function () { + var _this = this; + return tslib.__generator(this, function (_a) { + if (this.operations.length === 0) { + return [2 /*return*/, Promise.resolve()]; + } + this.parallelExecute(); + return [2 /*return*/, new Promise(function (resolve, reject) { + _this.emitter.on("finish", resolve); + _this.emitter.on("error", function (error) { + _this.state = BatchStates.Error; + reject(error); + }); + })]; + }); + }); + }; + /** + * Get next operation to be executed. Return null when reaching ends. + * + * @private + * @returns {(Operation | null)} + * @memberof Batch + */ + Batch.prototype.nextOperation = function () { + if (this.offset < this.operations.length) { + return this.operations[this.offset++]; + } + return null; + }; + /** + * Start execute operations. One one the most important difference between + * this method with do() is that do() wraps as an sync method. + * + * @private + * @returns {void} + * @memberof Batch + */ + Batch.prototype.parallelExecute = function () { + if (this.state === BatchStates.Error) { + return; + } + if (this.completed >= this.operations.length) { + this.emitter.emit("finish"); + return; + } + while (this.actives < this.concurrency) { + var operation = this.nextOperation(); + if (operation) { + operation(); + } + else { + return; + } + } + }; + return Batch; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * This class generates a readable stream from the data in an array of buffers. + * + * @export + * @class BuffersStream + */ +var BuffersStream = /** @class */ (function (_super) { + tslib.__extends(BuffersStream, _super); + /** + * Creates an instance of BuffersStream that will emit the data + * contained in the array of buffers. + * + * @param {Buffer[]} buffers Array of buffers containing the data + * @param {number} byteLength The total length of data contained in the buffers + * @memberof BuffersStream + */ + function BuffersStream(buffers, byteLength, options) { + var _this = _super.call(this, options) || this; + _this.buffers = buffers; + _this.byteLength = byteLength; + _this.byteOffsetInCurrentBuffer = 0; + _this.bufferIndex = 0; + _this.pushedBytesLength = 0; + // check byteLength is no larger than buffers[] total length + var buffersLength = 0; + for (var _i = 0, _a = _this.buffers; _i < _a.length; _i++) { + var buf = _a[_i]; + buffersLength += buf.byteLength; + } + if (buffersLength < _this.byteLength) { + throw new Error("Data size shouldn't be larger than the total length of buffers."); + } + return _this; + } + /** + * Internal _read() that will be called when the stream wants to pull more data in. + * + * @param {number} size Optional. The size of data to be read + * @memberof BuffersStream + */ + BuffersStream.prototype._read = function (size) { + if (this.pushedBytesLength >= this.byteLength) { + this.push(null); + } + if (!size) { + size = this.readableHighWaterMark; + } + var outBuffers = []; + var i = 0; + while (i < size && this.pushedBytesLength < this.byteLength) { + // The last buffer may be longer than the data it contains. + var remainingDataInAllBuffers = this.byteLength - this.pushedBytesLength; + var remainingCapacityInThisBuffer = this.buffers[this.bufferIndex].byteLength - this.byteOffsetInCurrentBuffer; + var remaining = Math.min(remainingCapacityInThisBuffer, remainingDataInAllBuffers); + if (remaining > size - i) { + // chunkSize = size - i + var end = this.byteOffsetInCurrentBuffer + size - i; + outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); + this.pushedBytesLength += size - i; + this.byteOffsetInCurrentBuffer = end; + i = size; + break; + } + else { + // chunkSize = remaining + var end = this.byteOffsetInCurrentBuffer + remaining; + outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); + if (remaining === remainingCapacityInThisBuffer) { + // this.buffers[this.bufferIndex] used up, shift to next one + this.byteOffsetInCurrentBuffer = 0; + this.bufferIndex++; + } + else { + this.byteOffsetInCurrentBuffer = end; + } + this.pushedBytesLength += remaining; + i += remaining; + } + } + if (outBuffers.length > 1) { + this.push(Buffer.concat(outBuffers)); + } + else if (outBuffers.length === 1) { + this.push(outBuffers[0]); + } + }; + return BuffersStream; +}(stream.Readable)); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * maxBufferLength is max size of each buffer in the pooled buffers. + */ +// Can't use import as Typescript doesn't recognize "buffer". +var maxBufferLength = __webpack_require__(293).constants.MAX_LENGTH; +/** + * This class provides a buffer container which conceptually has no hard size limit. + * It accepts a capacity, an array of input buffers and the total length of input data. + * It will allocate an internal "buffer" of the capacity and fill the data in the input buffers + * into the internal "buffer" serially with respect to the total length. + * Then by calling PooledBuffer.getReadableStream(), you can get a readable stream + * assembled from all the data in the internal "buffer". + * + * @export + * @class BufferScheduler + */ +var PooledBuffer = /** @class */ (function () { + function PooledBuffer(capacity, buffers, totalLength) { + /** + * Internal buffers used to keep the data. + * Each buffer has a length of the maxBufferLength except last one. + * + * @private + * @type {Buffer[]} + * @memberof PooledBuffer + */ + this.buffers = []; + this.capacity = capacity; + this._size = 0; + // allocate + var bufferNum = Math.ceil(capacity / maxBufferLength); + for (var i = 0; i < bufferNum; i++) { + var len = i === bufferNum - 1 ? capacity % maxBufferLength : maxBufferLength; + if (len === 0) { + len = maxBufferLength; + } + this.buffers.push(Buffer.allocUnsafe(len)); + } + if (buffers) { + this.fill(buffers, totalLength); + } + } + Object.defineProperty(PooledBuffer.prototype, "size", { + /** + * The size of the data contained in the pooled buffers. + */ + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + /** + * Fill the internal buffers with data in the input buffers serially + * with respect to the total length and the total capacity of the internal buffers. + * Data copied will be shift out of the input buffers. + * + * @param {Buffer[]} buffers Input buffers containing the data to be filled in the pooled buffer + * @param {number} totalLength Total length of the data to be filled in. + * + * @returns {void} + * @memberof PooledBuffer + */ + PooledBuffer.prototype.fill = function (buffers, totalLength) { + this._size = Math.min(this.capacity, totalLength); + var i = 0, j = 0, targetOffset = 0, sourceOffset = 0, totalCopiedNum = 0; + while (totalCopiedNum < this._size) { + var source = buffers[i]; + var target = this.buffers[j]; + var copiedNum = source.copy(target, targetOffset, sourceOffset); + totalCopiedNum += copiedNum; + sourceOffset += copiedNum; + targetOffset += copiedNum; + if (sourceOffset === source.length) { + i++; + sourceOffset = 0; + } + if (targetOffset === target.length) { + j++; + targetOffset = 0; + } + } + // clear copied from source buffers + buffers.splice(0, i); + if (buffers.length > 0) { + buffers[0] = buffers[0].slice(sourceOffset); + } + }; + /** + * Get the readable stream assembled from all the data in the internal buffers. + * + * @returns {Readable} + * @memberof PooledBuffer + */ + PooledBuffer.prototype.getReadableStream = function () { + return new BuffersStream(this.buffers, this.size); + }; + return PooledBuffer; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * This class accepts a Node.js Readable stream as input, and keeps reading data + * from the stream into the internal buffer structure, until it reaches maxBuffers. + * Every available buffer will try to trigger outgoingHandler. + * + * The internal buffer structure includes an incoming buffer array, and a outgoing + * buffer array. The incoming buffer array includes the "empty" buffers can be filled + * with new incoming data. The outgoing array includes the filled buffers to be + * handled by outgoingHandler. Every above buffer size is defined by parameter bufferSize. + * + * NUM_OF_ALL_BUFFERS = BUFFERS_IN_INCOMING + BUFFERS_IN_OUTGOING + BUFFERS_UNDER_HANDLING + * + * NUM_OF_ALL_BUFFERS <= maxBuffers + * + * PERFORMANCE IMPROVEMENT TIPS: + * 1. Input stream highWaterMark is better to set a same value with bufferSize + * parameter, which will avoid Buffer.concat() operations. + * 2. concurrency should set a smaller value than maxBuffers, which is helpful to + * reduce the possibility when a outgoing handler waits for the stream data. + * in this situation, outgoing handlers are blocked. + * Outgoing queue shouldn't be empty. + * @export + * @class BufferScheduler + */ +var BufferScheduler = /** @class */ (function () { + /** + * Creates an instance of BufferScheduler. + * + * @param {Readable} readable A Node.js Readable stream + * @param {number} bufferSize Buffer size of every maintained buffer + * @param {number} maxBuffers How many buffers can be allocated + * @param {OutgoingHandler} outgoingHandler An async function scheduled to be + * triggered when a buffer fully filled + * with stream data + * @param {number} concurrency Concurrency of executing outgoingHandlers (>0) + * @param {string} [encoding] [Optional] Encoding of Readable stream when it's a string stream + * @memberof BufferScheduler + */ + function BufferScheduler(readable, bufferSize, maxBuffers, outgoingHandler, concurrency, encoding) { + /** + * An internal event emitter. + * + * @private + * @type {EventEmitter} + * @memberof BufferScheduler + */ + this.emitter = new events.EventEmitter(); + /** + * An internal offset marker to track data offset in bytes of next outgoingHandler. + * + * @private + * @type {number} + * @memberof BufferScheduler + */ + this.offset = 0; + /** + * An internal marker to track whether stream is end. + * + * @private + * @type {boolean} + * @memberof BufferScheduler + */ + this.isStreamEnd = false; + /** + * An internal marker to track whether stream or outgoingHandler returns error. + * + * @private + * @type {boolean} + * @memberof BufferScheduler + */ + this.isError = false; + /** + * How many handlers are executing. + * + * @private + * @type {number} + * @memberof BufferScheduler + */ + this.executingOutgoingHandlers = 0; + /** + * How many buffers have been allocated. + * + * @private + * @type {number} + * @memberof BufferScheduler + */ + this.numBuffers = 0; + /** + * Because this class doesn't know how much data every time stream pops, which + * is defined by highWaterMarker of the stream. So BufferScheduler will cache + * data received from the stream, when data in unresolvedDataArray exceeds the + * blockSize defined, it will try to concat a blockSize of buffer, fill into available + * buffers from incoming and push to outgoing array. + * + * @private + * @type {Buffer[]} + * @memberof BufferScheduler + */ + this.unresolvedDataArray = []; + /** + * How much data consisted in unresolvedDataArray. + * + * @private + * @type {number} + * @memberof BufferScheduler + */ + this.unresolvedLength = 0; + /** + * The array includes all the available buffers can be used to fill data from stream. + * + * @private + * @type {PooledBuffer[]} + * @memberof BufferScheduler + */ + this.incoming = []; + /** + * The array (queue) includes all the buffers filled from stream data. + * + * @private + * @type {PooledBuffer[]} + * @memberof BufferScheduler + */ + this.outgoing = []; + if (bufferSize <= 0) { + throw new RangeError("bufferSize must be larger than 0, current is " + bufferSize); + } + if (maxBuffers <= 0) { + throw new RangeError("maxBuffers must be larger than 0, current is " + maxBuffers); + } + if (concurrency <= 0) { + throw new RangeError("concurrency must be larger than 0, current is " + concurrency); + } + this.bufferSize = bufferSize; + this.maxBuffers = maxBuffers; + this.readable = readable; + this.outgoingHandler = outgoingHandler; + this.concurrency = concurrency; + this.encoding = encoding; + } + /** + * Start the scheduler, will return error when stream of any of the outgoingHandlers + * returns error. + * + * @returns {Promise} + * @memberof BufferScheduler + */ + BufferScheduler.prototype.do = function () { + return tslib.__awaiter(this, void 0, void 0, function () { + var _this = this; + return tslib.__generator(this, function (_a) { + return [2 /*return*/, new Promise(function (resolve, reject) { + _this.readable.on("data", function (data) { + data = typeof data === "string" ? Buffer.from(data, _this.encoding) : data; + _this.appendUnresolvedData(data); + if (!_this.resolveData()) { + _this.readable.pause(); + } + }); + _this.readable.on("error", function (err) { + _this.emitter.emit("error", err); + }); + _this.readable.on("end", function () { + _this.isStreamEnd = true; + _this.emitter.emit("checkEnd"); + }); + _this.emitter.on("error", function (err) { + _this.isError = true; + _this.readable.pause(); + reject(err); + }); + _this.emitter.on("checkEnd", function () { + if (_this.outgoing.length > 0) { + _this.triggerOutgoingHandlers(); + return; + } + if (_this.isStreamEnd && _this.executingOutgoingHandlers === 0) { + if (_this.unresolvedLength > 0 && _this.unresolvedLength < _this.bufferSize) { + var buffer_1 = _this.shiftBufferFromUnresolvedDataArray(); + _this.outgoingHandler(function () { return buffer_1.getReadableStream(); }, buffer_1.size, _this.offset) + .then(resolve) + .catch(reject); + } + else if (_this.unresolvedLength >= _this.bufferSize) { + return; + } + else { + resolve(); + } + } + }); + })]; + }); + }); + }; + /** + * Insert a new data into unresolved array. + * + * @private + * @param {Buffer} data + * @memberof BufferScheduler + */ + BufferScheduler.prototype.appendUnresolvedData = function (data) { + this.unresolvedDataArray.push(data); + this.unresolvedLength += data.length; + }; + /** + * Try to shift a buffer with size in blockSize. The buffer returned may be less + * than blockSize when data in unresolvedDataArray is less than bufferSize. + * + * @private + * @returns {PooledBuffer} + * @memberof BufferScheduler + */ + BufferScheduler.prototype.shiftBufferFromUnresolvedDataArray = function (buffer) { + if (!buffer) { + buffer = new PooledBuffer(this.bufferSize, this.unresolvedDataArray, this.unresolvedLength); + } + else { + buffer.fill(this.unresolvedDataArray, this.unresolvedLength); + } + this.unresolvedLength -= buffer.size; + return buffer; + }; + /** + * Resolve data in unresolvedDataArray. For every buffer with size in blockSize + * shifted, it will try to get (or allocate a buffer) from incoming, and fill it, + * then push it into outgoing to be handled by outgoing handler. + * + * Return false when available buffers in incoming are not enough, else true. + * + * @private + * @returns {boolean} Return false when buffers in incoming are not enough, else true. + * @memberof BufferScheduler + */ + BufferScheduler.prototype.resolveData = function () { + while (this.unresolvedLength >= this.bufferSize) { + var buffer = void 0; + if (this.incoming.length > 0) { + buffer = this.incoming.shift(); + this.shiftBufferFromUnresolvedDataArray(buffer); + } + else { + if (this.numBuffers < this.maxBuffers) { + buffer = this.shiftBufferFromUnresolvedDataArray(); + this.numBuffers++; + } + else { + // No available buffer, wait for buffer returned + return false; + } + } + this.outgoing.push(buffer); + this.triggerOutgoingHandlers(); + } + return true; + }; + /** + * Try to trigger a outgoing handler for every buffer in outgoing. Stop when + * concurrency reaches. + * + * @private + * @memberof BufferScheduler + */ + BufferScheduler.prototype.triggerOutgoingHandlers = function () { + return tslib.__awaiter(this, void 0, void 0, function () { + var buffer; + return tslib.__generator(this, function (_a) { + do { + if (this.executingOutgoingHandlers >= this.concurrency) { + return [2 /*return*/]; + } + buffer = this.outgoing.shift(); + if (buffer) { + this.triggerOutgoingHandler(buffer); + } + } while (buffer); + return [2 /*return*/]; + }); + }); + }; + /** + * Trigger a outgoing handler for a buffer shifted from outgoing. + * + * @private + * @param {Buffer} buffer + * @returns {Promise} + * @memberof BufferScheduler + */ + BufferScheduler.prototype.triggerOutgoingHandler = function (buffer) { + return tslib.__awaiter(this, void 0, void 0, function () { + var bufferLength, err_1; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + bufferLength = buffer.size; + this.executingOutgoingHandlers++; + this.offset += bufferLength; + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + return [4 /*yield*/, this.outgoingHandler(function () { return buffer.getReadableStream(); }, bufferLength, this.offset - bufferLength)]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + err_1 = _a.sent(); + this.emitter.emit("error", err_1); + return [2 /*return*/]; + case 4: + this.executingOutgoingHandlers--; + this.reuseBuffer(buffer); + this.emitter.emit("checkEnd"); + return [2 /*return*/]; + } + }); + }); + }; + /** + * Return buffer used by outgoing handler into incoming. + * + * @private + * @param {Buffer} buffer + * @memberof BufferScheduler + */ + BufferScheduler.prototype.reuseBuffer = function (buffer) { + this.incoming.push(buffer); + if (!this.isError && this.resolveData() && !this.isStreamEnd) { + this.readable.resume(); + } + }; + return BufferScheduler; +}()); + +// Copyright (c) Microsoft Corporation. +/** + * Creates a span using the global tracer. + * @param name The name of the operation being performed. + * @param tracingOptions The options for the underlying http request. + */ +function createSpan(operationName, tracingOptions) { + if (tracingOptions === void 0) { tracingOptions = {}; } + var tracer = coreTracing.getTracer(); + var spanOptions = tslib.__assign(tslib.__assign({}, tracingOptions.spanOptions), { kind: api.SpanKind.INTERNAL }); + var span = tracer.startSpan("Azure.Storage.Blob." + operationName, spanOptions); + span.setAttribute("az.namespace", "Microsoft.Storage"); + var newOptions = tracingOptions.spanOptions || {}; + if (span.isRecording()) { + newOptions = tslib.__assign(tslib.__assign({}, tracingOptions.spanOptions), { parent: span.context(), attributes: tslib.__assign(tslib.__assign({}, spanOptions.attributes), { "az.namespace": "Microsoft.Storage" }) }); + } + return { + span: span, + spanOptions: newOptions + }; +} + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * Reads a readable stream into buffer. Fill the buffer from offset to end. + * + * @export + * @param {NodeJS.ReadableStream} stream A Node.js Readable stream + * @param {Buffer} buffer Buffer to be filled, length must >= offset + * @param {number} offset From which position in the buffer to be filled, inclusive + * @param {number} end To which position in the buffer to be filled, exclusive + * @param {string} [encoding] Encoding of the Readable stream + * @returns {Promise} + */ +function streamToBuffer(stream, buffer, offset, end, encoding) { + return tslib.__awaiter(this, void 0, void 0, function () { + var pos, count; + return tslib.__generator(this, function (_a) { + pos = 0; + count = end - offset; + return [2 /*return*/, new Promise(function (resolve, reject) { + stream.on("readable", function () { + if (pos >= count) { + resolve(); + return; + } + var chunk = stream.read(); + if (!chunk) { + return; + } + if (typeof chunk === "string") { + chunk = Buffer.from(chunk, encoding); + } + // How much data needed in this chunk + var chunkLength = pos + chunk.length > count ? count - pos : chunk.length; + buffer.fill(chunk.slice(0, chunkLength), offset + pos, offset + pos + chunkLength); + pos += chunkLength; + }); + stream.on("end", function () { + if (pos < count) { + reject(new Error("Stream drains before getting enough data needed. Data read: " + pos + ", data need: " + count)); + } + resolve(); + }); + stream.on("error", reject); + })]; + }); + }); +} +/** + * Reads a readable stream into buffer entirely. + * + * @export + * @param {NodeJS.ReadableStream} stream A Node.js Readable stream + * @param {Buffer} buffer Buffer to be filled, length must >= offset + * @param {string} [encoding] Encoding of the Readable stream + * @returns {Promise} with the count of bytes read. + * @throws {RangeError} If buffer size is not big enough. + */ +function streamToBuffer2(stream, buffer, encoding) { + return tslib.__awaiter(this, void 0, void 0, function () { + var pos, bufferSize; + return tslib.__generator(this, function (_a) { + pos = 0; + bufferSize = buffer.length; + return [2 /*return*/, new Promise(function (resolve, reject) { + stream.on("readable", function () { + var chunk = stream.read(); + if (!chunk) { + return; + } + if (typeof chunk === "string") { + chunk = Buffer.from(chunk, encoding); + } + if (pos + chunk.length > bufferSize) { + reject(new Error("Stream exceeds buffer size. Buffer size: " + bufferSize)); + return; + } + buffer.fill(chunk, pos, pos + chunk.length); + pos += chunk.length; + }); + stream.on("end", function () { + resolve(pos); + }); + stream.on("error", reject); + })]; + }); + }); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Writes the content of a readstream to a local file. Returns a Promise which is completed after the file handle is closed. + * + * @export + * @param {NodeJS.ReadableStream} rs The read stream. + * @param {string} file Destination file path. + * @returns {Promise} + */ +function readStreamToLocalFile(rs, file) { + return tslib.__awaiter(this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + return [2 /*return*/, new Promise(function (resolve, reject) { + var ws = fs.createWriteStream(file); + rs.on("error", function (err) { + reject(err); + }); + ws.on("error", function (err) { + reject(err); + }); + ws.on("close", resolve); + rs.pipe(ws); + })]; + }); + }); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Promisified version of fs.stat(). + */ +var fsStat = util.promisify(fs.stat); +var fsCreateReadStream = fs.createReadStream; + +/** + * A BlobClient represents a URL to an Azure Storage blob; the blob may be a block blob, + * append blob, or page blob. + * + * @export + * @class BlobClient + */ +var BlobClient = /** @class */ (function (_super) { + tslib.__extends(BlobClient, _super); + function BlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { + var _a; + var _this = this; + options = options || {}; + var pipeline; + var url; + if (credentialOrPipelineOrContainerName instanceof Pipeline) { + // (url: string, pipeline: Pipeline) + url = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } + else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || + credentialOrPipelineOrContainerName instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + url = urlOrConnectionString; + options = blobNameOrOptions; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } + else if (!credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName !== "string") { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + // The second parameter is undefined. Use anonymous credential. + url = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else if (credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName === "string" && + blobNameOrOptions && + typeof blobNameOrOptions === "string") { + // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) + var containerName = credentialOrPipelineOrContainerName; + var blobName = blobNameOrOptions; + var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + pipeline = newPipeline(sharedKeyCredential, options); + } + } + else if (extractedCreds.kind === "SASConnString") { + url = + appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + + "?" + + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } + else { + throw new Error("Expecting non-empty strings for containerName and blobName parameters"); + } + _this = _super.call(this, url, pipeline) || this; + (_a = _this.getBlobAndContainerNamesFromUrl(), _this._name = _a.blobName, _this._containerName = _a.containerName); + _this.blobContext = new Blob$1(_this.storageClientContext); + return _this; + } + Object.defineProperty(BlobClient.prototype, "name", { + /** + * The name of the blob. + */ + get: function () { + return this._name; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobClient.prototype, "containerName", { + /** + * The name of the storage container the blob is associated with. + */ + get: function () { + return this._containerName; + }, + enumerable: false, + configurable: true + }); + /** + * Creates a new BlobClient object identical to the source but with the specified snapshot timestamp. + * Provide "" will remove the snapshot and return a Client to the base blob. + * + * @param {string} snapshot The snapshot timestamp. + * @returns {BlobClient} A new BlobClient object identical to the source but with the specified snapshot timestamp + * @memberof BlobClient + */ + BlobClient.prototype.withSnapshot = function (snapshot) { + return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); + }; + /** + * Creates a new BlobClient object pointing to a version of this blob. + * Provide "" will remove the versionId and return a Client to the base blob. + * + * @param {string} versionId The versionId. + * @returns {BlobClient} A new BlobClient object pointing to the version of this blob. + * @memberof BlobClient + */ + BlobClient.prototype.withVersion = function (versionId) { + return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.VERSIONID, versionId.length === 0 ? undefined : versionId), this.pipeline); + }; + /** + * Creates a AppendBlobClient object. + * + * @returns {AppendBlobClient} + * @memberof BlobClient + */ + BlobClient.prototype.getAppendBlobClient = function () { + return new AppendBlobClient(this.url, this.pipeline); + }; + /** + * Creates a BlockBlobClient object. + * + * @returns {BlockBlobClient} + * @memberof BlobClient + */ + BlobClient.prototype.getBlockBlobClient = function () { + return new BlockBlobClient(this.url, this.pipeline); + }; + /** + * Creates a PageBlobClient object. + * + * @returns {PageBlobClient} + * @memberof BlobClient + */ + BlobClient.prototype.getPageBlobClient = function () { + return new PageBlobClient(this.url, this.pipeline); + }; + /** + * Reads or downloads a blob from the system, including its metadata and properties. + * You can also call Get Blob to read a snapshot. + * + * * In Node.js, data returns in a Readable stream readableStreamBody + * * In browsers, data returns in a promise blobBody + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob + * + * @param {number} [offset] From which position of the blob to download, >= 0 + * @param {number} [count] How much data to be downloaded, > 0. Will download to the end when undefined + * @param {BlobDownloadOptions} [options] Optional options to Blob Download operation. + * @returns {Promise} + * @memberof BlobClient + * + * Example usage (Node.js): + * + * ```js + * // Download and convert a blob to a string + * const downloadBlockBlobResponse = await blobClient.download(); + * const downloaded = await streamToBuffer(downloadBlockBlobResponse.readableStreamBody); + * console.log("Downloaded blob content:", downloaded.toString()); + * + * async function streamToBuffer(readableStream) { + * return new Promise((resolve, reject) => { + * const chunks = []; + * readableStream.on("data", (data) => { + * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); + * }); + * readableStream.on("end", () => { + * resolve(Buffer.concat(chunks)); + * }); + * readableStream.on("error", reject); + * }); + * } + * ``` + * + * Example usage (browser): + * + * ```js + * // Download and convert a blob to a string + * const downloadBlockBlobResponse = await blobClient.download(); + * const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody); + * console.log( + * "Downloaded blob content", + * downloaded + * ); + * + * async function blobToString(blob: Blob): Promise { + * const fileReader = new FileReader(); + * return new Promise((resolve, reject) => { + * fileReader.onloadend = (ev: any) => { + * resolve(ev.target!.result); + * }; + * fileReader.onerror = reject; + * fileReader.readAsText(blob); + * }); + * } + * ``` + */ + BlobClient.prototype.download = function (offset, count, options) { + var _a; + if (offset === void 0) { offset = 0; } + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, res_1, wrappedRes, e_1; + var _this = this; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + _b = createSpan("BlobClient-download", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blobContext.download({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + onDownloadProgress: coreHttp.isNode ? undefined : options.onProgress, + range: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), + rangeGetContentMD5: options.rangeGetContentMD5, + rangeGetContentCRC64: options.rangeGetContentCrc64, + snapshot: options.snapshot, + cpkInfo: options.customerProvidedKey, + spanOptions: spanOptions + })]; + case 2: + res_1 = _c.sent(); + wrappedRes = tslib.__assign(tslib.__assign({}, res_1), { _response: res_1._response, objectReplicationDestinationPolicyId: res_1.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res_1.objectReplicationRules) }); + // We support retrying when download stream unexpected ends in Node.js runtime + // Following code shouldn't be bundled into browser build, however some + // bundlers may try to bundle following code and "FileReadResponse.ts". + // In this case, "FileDownloadResponse.browser.ts" will be used as a shim of "FileDownloadResponse.ts" + // The config is in package.json "browser" field + if (options.maxRetryRequests === undefined || options.maxRetryRequests < 0) { + // TODO: Default value or make it a required parameter? + options.maxRetryRequests = DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS; + } + if (res_1.contentLength === undefined) { + throw new RangeError("File download response doesn't contain valid content length header"); + } + if (!res_1.etag) { + throw new RangeError("File download response doesn't contain valid etag header"); + } + return [2 /*return*/, new BlobDownloadResponse(wrappedRes, function (start) { return tslib.__awaiter(_this, void 0, void 0, function () { + var updatedOptions; + var _a; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + updatedOptions = { + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ifMatch: options.conditions.ifMatch || res_1.etag, + ifModifiedSince: options.conditions.ifModifiedSince, + ifNoneMatch: options.conditions.ifNoneMatch, + ifUnmodifiedSince: options.conditions.ifUnmodifiedSince, + ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions + }, + range: rangeToString({ + count: offset + res_1.contentLength - start, + offset: start + }), + rangeGetContentMD5: options.rangeGetContentMD5, + rangeGetContentCRC64: options.rangeGetContentCrc64, + snapshot: options.snapshot, + cpkInfo: options.customerProvidedKey + }; + return [4 /*yield*/, this.blobContext.download(tslib.__assign({ abortSignal: options.abortSignal }, updatedOptions))]; + case 1: + // Debug purpose only + // console.log( + // `Read from internal stream, range: ${ + // updatedOptions.range + // }, options: ${JSON.stringify(updatedOptions)}` + // ); + return [2 /*return*/, (_b.sent()).readableStreamBody]; + } + }); + }); }, offset, res_1.contentLength, { + abortSignal: options.abortSignal, + maxRetryRequests: options.maxRetryRequests, + onProgress: options.onProgress + })]; + case 3: + e_1 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_1.message + }); + throw e_1; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns true if the Azure blob resource represented by this client exists; false otherwise. + * + * NOTE: use this function with care since an existing blob might be deleted by other clients or + * applications. Vice versa new blobs might be added by other clients or applications after this + * function completes. + * + * @param {BlobExistsOptions} [options] options to Exists operation. + * @returns {Promise} + * @memberof BlobClient + */ + BlobClient.prototype.exists = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_2; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobClient-exists", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.getProperties({ + abortSignal: options.abortSignal, + customerProvidedKey: options.customerProvidedKey, + conditions: options.conditions, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; + case 2: + _b.sent(); + return [2 /*return*/, true]; + case 3: + e_2 = _b.sent(); + if (e_2.statusCode === 404) { + span.setStatus({ + code: api.CanonicalCode.NOT_FOUND, + message: "Expected exception when checking blob existence" + }); + return [2 /*return*/, false]; + } + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_2.message + }); + throw e_2; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns all user-defined metadata, standard HTTP properties, and system properties + * for the blob. It does not return the content of the blob. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties + * + * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if + * they originally contained uppercase characters. This differs from the metadata keys returned by + * the methods of {@link ContainerClient} that list blobs using the `includeMetadata` option, which + * will retain their original casing. + * + * @param {BlobGetPropertiesOptions} [options] Optional options to Get Properties operation. + * @returns {Promise} + * @memberof BlobClient + */ + BlobClient.prototype.getProperties = function (options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, res, e_3; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("BlobClient-getProperties", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blobContext.getProperties({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + spanOptions: spanOptions + })]; + case 2: + res = _c.sent(); + return [2 /*return*/, tslib.__assign(tslib.__assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) })]; + case 3: + e_3 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_3.message + }); + throw e_3; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Marks the specified blob or snapshot for deletion. The blob is later deleted + * during garbage collection. Note that in order to delete a blob, you must delete + * all of its snapshots. You can delete both at the same time with the Delete + * Blob operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob + * + * @param {BlobDeleteOptions} [options] Optional options to Blob Delete operation. + * @returns {Promise} + * @memberof BlobClient + */ + BlobClient.prototype.delete = function (options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_4; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("BlobClient-delete", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.conditions = options.conditions || {}; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blobContext.deleteMethod({ + abortSignal: options.abortSignal, + deleteSnapshots: options.deleteSnapshots, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_4 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_4.message + }); + throw e_4; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Marks the specified blob or snapshot for deletion if it exists. The blob is later deleted + * during garbage collection. Note that in order to delete a blob, you must delete + * all of its snapshots. You can delete both at the same time with the Delete + * Blob operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob + * + * @param {BlobDeleteOptions} [options] Optional options to Blob Delete operation. + * @returns {Promise} + * @memberof BlobClient + */ + BlobClient.prototype.deleteIfExists = function (options) { + var _a, _b; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _c, span, spanOptions, res, e_5; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _c = createSpan("BlobClient-deleteIfExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; + _d.label = 1; + case 1: + _d.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + res = _d.sent(); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + })]; + case 3: + e_5 = _d.sent(); + if (((_a = e_5.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobNotFound") { + span.setStatus({ + code: api.CanonicalCode.NOT_FOUND, + message: "Expected exception when deleting a blob or snapshot only if it exists." + }); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_5.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_5.response })]; + } + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_5.message + }); + throw e_5; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Restores the contents and metadata of soft deleted blob and any associated + * soft deleted snapshots. Undelete Blob is supported only on version 2017-07-29 + * or later. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/undelete-blob + * + * @param {BlobUndeleteOptions} [options] Optional options to Blob Undelete operation. + * @returns {Promise} + * @memberof BlobClient + */ + BlobClient.prototype.undelete = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_6; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobClient-undelete", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blobContext.undelete({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_6 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_6.message + }); + throw e_6; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Sets system properties on the blob. + * + * If no value provided, or no value provided for the specified blob HTTP headers, + * these blob HTTP headers without a value will be cleared. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties + * + * @param {BlobHTTPHeaders} [blobHTTPHeaders] If no value provided, or no value provided for + * the specified blob HTTP headers, these blob HTTP + * headers without a value will be cleared. + * @param {BlobSetHTTPHeadersOptions} [options] Optional options to Blob Set HTTP Headers operation. + * @returns {Promise} + * @memberof BlobClient + */ + BlobClient.prototype.setHTTPHeaders = function (blobHTTPHeaders, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_7; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("BlobClient-setHTTPHeaders", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.conditions = options.conditions || {}; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blobContext.setHTTPHeaders({ + abortSignal: options.abortSignal, + blobHTTPHeaders: blobHTTPHeaders, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_7 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_7.message + }); + throw e_7; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Sets user-defined metadata for the specified blob as one or more name-value pairs. + * + * If no option provided, or no metadata defined in the parameter, the blob + * metadata will be removed. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-metadata + * + * @param {Metadata} [metadata] Replace existing metadata with this value. + * If no value provided the existing metadata will be removed. + * @param {BlobSetMetadataOptions} [options] Optional options to Set Metadata operation. + * @returns {Promise} + * @memberof BlobClient + */ + BlobClient.prototype.setMetadata = function (metadata, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_8; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("BlobClient-setMetadata", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.conditions = options.conditions || {}; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blobContext.setMetadata({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + metadata: metadata, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_8 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_8.message + }); + throw e_8; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Sets tags on the underlying blob. + * A blob can have up to 10 tags. Tag keys must be between 1 and 128 characters. Tag values must be between 0 and 256 characters. + * Valid tag key and value characters include lower and upper case letters, digits (0-9), + * space (' '), plus ('+'), minus ('-'), period ('.'), foward slash ('/'), colon (':'), equals ('='), and underscore ('_'). + * + * @param {Tags} tags + * @param {BlobSetTagsOptions} [options={}] + * @returns {Promise} + * @memberof BlobClient + */ + BlobClient.prototype.setTags = function (tags, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_9; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("BlobClient-setTags", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blobContext.setTags({ + abortSignal: options.abortSignal, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + spanOptions: spanOptions, + tags: toBlobTags(tags) + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_9 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_9.message + }); + throw e_9; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Gets the tags associated with the underlying blob. + * + * @param {BlobGetTagsOptions} [options={}] + * @returns {Promise} + * @memberof BlobClient + */ + BlobClient.prototype.getTags = function (options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, response, wrappedResponse, e_10; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("BlobClient-getTags", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blobContext.getTags({ + abortSignal: options.abortSignal, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + spanOptions: spanOptions + })]; + case 2: + response = _c.sent(); + wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, tags: toTags({ blobTagSet: response.blobTagSet }) || {} }); + return [2 /*return*/, wrappedResponse]; + case 3: + e_10 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_10.message + }); + throw e_10; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Get a {@link BlobLeaseClient} that manages leases on the blob. + * + * @param {string} [proposeLeaseId] Initial proposed lease Id. + * @returns {BlobLeaseClient} A new BlobLeaseClient object for managing leases on the blob. + * @memberof BlobClient + */ + BlobClient.prototype.getBlobLeaseClient = function (proposeLeaseId) { + return new BlobLeaseClient(this, proposeLeaseId); + }; + /** + * Creates a read-only snapshot of a blob. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/snapshot-blob + * + * @param {BlobCreateSnapshotOptions} [options] Optional options to the Blob Create Snapshot operation. + * @returns {Promise} + * @memberof BlobClient + */ + BlobClient.prototype.createSnapshot = function (options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_11; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("BlobClient-createSnapshot", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.conditions = options.conditions || {}; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blobContext.createSnapshot({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_11 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_11.message + }); + throw e_11; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Asynchronously copies a blob to a destination within the storage account. + * This method returns a long running operation poller that allows you to wait + * indefinitely until the copy is completed. + * You can also cancel a copy before it is completed by calling `cancelOperation` on the poller. + * Note that the onProgress callback will not be invoked if the operation completes in the first + * request, and attempting to cancel a completed copy will result in an error being thrown. + * + * In version 2012-02-12 and later, the source for a Copy Blob operation can be + * a committed blob in any Azure storage account. + * Beginning with version 2015-02-21, the source for a Copy Blob operation can be + * an Azure file in any Azure storage account. + * Only storage accounts created on or after June 7th, 2012 allow the Copy Blob + * operation to copy from another storage account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob + * + * Example using automatic polling: + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url'); + * const result = await copyPoller.pollUntilDone(); + * ``` + * + * Example using manual polling: + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url'); + * while (!poller.isDone()) { + * await poller.poll(); + * } + * const result = copyPoller.getResult(); + * ``` + * + * Example using progress updates: + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url', { + * onProgress(state) { + * console.log(`Progress: ${state.copyProgress}`); + * } + * }); + * const result = await copyPoller.pollUntilDone(); + * ``` + * + * Example using a changing polling interval (default 15 seconds): + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url', { + * intervalInMs: 1000 // poll blob every 1 second for copy progress + * }); + * const result = await copyPoller.pollUntilDone(); + * ``` + * + * Example using copy cancellation: + * + * ```js + * const copyPoller = await blobClient.beginCopyFromURL('url'); + * // cancel operation after starting it. + * try { + * await copyPoller.cancelOperation(); + * // calls to get the result now throw PollerCancelledError + * await copyPoller.getResult(); + * } catch (err) { + * if (err.name === 'PollerCancelledError') { + * console.log('The copy was cancelled.'); + * } + * } + * ``` + * + * @param {string} copySource url to the source Azure Blob/File. + * @param {BlobBeginCopyFromURLOptions} [options] Optional options to the Blob Start Copy From URL operation. + */ + BlobClient.prototype.beginCopyFromURL = function (copySource, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var client, poller; + var _this = this; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + client = { + abortCopyFromURL: function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return _this.abortCopyFromURL.apply(_this, args); + }, + getProperties: function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return _this.getProperties.apply(_this, args); + }, + startCopyFromURL: function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return _this.startCopyFromURL.apply(_this, args); + } + }; + poller = new BlobBeginCopyFromUrlPoller({ + blobClient: client, + copySource: copySource, + intervalInMs: options.intervalInMs, + onProgress: options.onProgress, + resumeFrom: options.resumeFrom, + startCopyFromURLOptions: options + }); + // Trigger the startCopyFromURL call by calling poll. + // Any errors from this method should be surfaced to the user. + return [4 /*yield*/, poller.poll()]; + case 1: + // Trigger the startCopyFromURL call by calling poll. + // Any errors from this method should be surfaced to the user. + _a.sent(); + return [2 /*return*/, poller]; + } + }); + }); + }; + /** + * Aborts a pending asynchronous Copy Blob operation, and leaves a destination blob with zero + * length and full metadata. Version 2012-02-12 and newer. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/abort-copy-blob + * + * @param {string} copyId Id of the Copy From URL operation. + * @param {BlobAbortCopyFromURLOptions} [options] Optional options to the Blob Abort Copy From URL operation. + * @returns {Promise} + * @memberof BlobClient + */ + BlobClient.prototype.abortCopyFromURL = function (copyId, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_12; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobClient-abortCopyFromURL", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blobContext.abortCopyFromURL(copyId, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_12 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_12.message + }); + throw e_12; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * The synchronous Copy From URL operation copies a blob or an internet resource to a new blob. It will not + * return a response until the copy is complete. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob-from-url + * + * @param {string} copySource The source URL to copy from, Shared Access Signature(SAS) maybe needed for authentication + * @param {BlobSyncCopyFromURLOptions} [options={}] + * @returns {Promise} + * @memberof BlobClient + */ + BlobClient.prototype.syncCopyFromURL = function (copySource, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_13; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("BlobClient-syncCopyFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blobContext.copyFromURL(copySource, { + abortSignal: options.abortSignal, + metadata: options.metadata, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince + }, + sourceContentMD5: options.sourceContentMD5, + blobTagsString: toBlobTagsString(options.tags), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_13 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_13.message + }); + throw e_13; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Sets the tier on a blob. The operation is allowed on a page blob in a premium + * storage account and on a block blob in a blob storage account (locally redundant + * storage only). A premium page blob's tier determines the allowed size, IOPS, + * and bandwidth of the blob. A block blob's tier determines Hot/Cool/Archive + * storage type. This operation does not update the blob's ETag. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-tier + * + * @param {BlockBlobTier | PremiumPageBlobTier | string} tier The tier to be set on the blob. Valid values are Hot, Cool, or Archive. + * @param {BlobSetTierOptions} [options] Optional options to the Blob Set Tier operation. + * @returns {Promise} + * @memberof BlobClient + */ + BlobClient.prototype.setAccessTier = function (tier, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_14; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("BlobClient-setAccessTier", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blobContext.setTier(toAccessTier(tier), { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + rehydratePriority: options.rehydratePriority, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_14 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_14.message + }); + throw e_14; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + BlobClient.prototype.downloadToBuffer = function (param1, param2, param3, param4) { + if (param4 === void 0) { param4 = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var buffer, offset, count, options, _a, span, spanOptions, response, transferProgress_1, batch, _loop_1, off, e_15; + var _this = this; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + offset = 0; + count = 0; + options = param4; + if (param1 instanceof Buffer) { + buffer = param1; + offset = param2 || 0; + count = typeof param3 === "number" ? param3 : 0; + } + else { + offset = typeof param1 === "number" ? param1 : 0; + count = typeof param2 === "number" ? param2 : 0; + options = param3 || {}; + } + _a = createSpan("BlobClient-downloadToBuffer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 5, 6, 7]); + if (!options.blockSize) { + options.blockSize = 0; + } + if (options.blockSize < 0) { + throw new RangeError("blockSize option must be >= 0"); + } + if (options.blockSize === 0) { + options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; + } + if (offset < 0) { + throw new RangeError("offset option must be >= 0"); + } + if (count && count <= 0) { + throw new RangeError("count option must be > 0"); + } + if (!options.conditions) { + options.conditions = {}; + } + if (!!count) return [3 /*break*/, 3]; + return [4 /*yield*/, this.getProperties(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + response = _b.sent(); + count = response.contentLength - offset; + if (count < 0) { + throw new RangeError("offset " + offset + " shouldn't be larger than blob size " + response.contentLength); + } + _b.label = 3; + case 3: + // Allocate the buffer of size = count if the buffer is not provided + if (!buffer) { + try { + buffer = Buffer.alloc(count); + } + catch (error) { + throw new Error("Unable to allocate the buffer of size: " + count + "(in bytes). Please try passing your own buffer to the \"downloadToBuffer\" method or try using other methods like \"download\" or \"downloadToFile\".\t " + error.message); + } + } + if (buffer.length < count) { + throw new RangeError("The buffer's size should be equal to or larger than the request count of bytes: " + count); + } + transferProgress_1 = 0; + batch = new Batch(options.concurrency); + _loop_1 = function (off) { + batch.addOperation(function () { return tslib.__awaiter(_this, void 0, void 0, function () { + var chunkEnd, response, stream; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + chunkEnd = offset + count; + if (off + options.blockSize < chunkEnd) { + chunkEnd = off + options.blockSize; + } + return [4 /*yield*/, this.download(off, chunkEnd - off, { + abortSignal: options.abortSignal, + conditions: options.conditions, + maxRetryRequests: options.maxRetryRequestsPerBlock, + customerProvidedKey: options.customerProvidedKey, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; + case 1: + response = _a.sent(); + stream = response.readableStreamBody; + return [4 /*yield*/, streamToBuffer(stream, buffer, off - offset, chunkEnd - offset)]; + case 2: + _a.sent(); + // Update progress after block is downloaded, in case of block trying + // Could provide finer grained progress updating inside HTTP requests, + // only if convenience layer download try is enabled + transferProgress_1 += chunkEnd - off; + if (options.onProgress) { + options.onProgress({ loadedBytes: transferProgress_1 }); + } + return [2 /*return*/]; + } + }); + }); }); + }; + for (off = offset; off < offset + count; off = off + options.blockSize) { + _loop_1(off); + } + return [4 /*yield*/, batch.do()]; + case 4: + _b.sent(); + return [2 /*return*/, buffer]; + case 5: + e_15 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_15.message + }); + throw e_15; + case 6: + span.end(); + return [7 /*endfinally*/]; + case 7: return [2 /*return*/]; + } + }); + }); + }; + /** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Downloads an Azure Blob to a local file. + * Fails if the the given file path already exits. + * Offset and count are optional, pass 0 and undefined respectively to download the entire blob. + * + * @param {string} filePath + * @param {number} [offset] From which position of the block blob to download. + * @param {number} [count] How much data to be downloaded. Will download to the end when passing undefined. + * @param {BlobDownloadOptions} [options] Options to Blob download options. + * @returns {Promise} The response data for blob download operation, + * but with readableStreamBody set to undefined since its + * content is already read and written into a local file + * at the specified path. + * @memberof BlobClient + */ + BlobClient.prototype.downloadToFile = function (filePath, offset, count, options) { + if (offset === void 0) { offset = 0; } + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, response, e_16; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobClient-downloadToFile", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 5, 6, 7]); + return [4 /*yield*/, this.download(offset, count, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + response = _b.sent(); + if (!response.readableStreamBody) return [3 /*break*/, 4]; + return [4 /*yield*/, readStreamToLocalFile(response.readableStreamBody, filePath)]; + case 3: + _b.sent(); + _b.label = 4; + case 4: + // The stream is no longer accessible so setting it to undefined. + response.blobDownloadStream = undefined; + return [2 /*return*/, response]; + case 5: + e_16 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_16.message + }); + throw e_16; + case 6: + span.end(); + return [7 /*endfinally*/]; + case 7: return [2 /*return*/]; + } + }); + }); + }; + BlobClient.prototype.getBlobAndContainerNamesFromUrl = function () { + var containerName; + var blobName; + try { + // URL may look like the following + // "https://myaccount.blob.core.windows.net/mycontainer/blob?sasString"; + // "https://myaccount.blob.core.windows.net/mycontainer/blob"; + // "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt?sasString"; + // "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt"; + // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername/blob` + // http://localhost:10001/devstoreaccount1/containername/blob + var parsedUrl = coreHttp.URLBuilder.parse(this.url); + if (parsedUrl.getHost().split(".")[1] === "blob") { + // "https://myaccount.blob.core.windows.net/containername/blob". + // .getPath() -> /containername/blob + var pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); + containerName = pathComponents[1]; + blobName = pathComponents[3]; + } + else if (isIpEndpointStyle(parsedUrl)) { + // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername/blob + // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername/blob + // .getPath() -> /devstoreaccount1/containername/blob + var pathComponents = parsedUrl.getPath().match("/([^/]*)/([^/]*)(/(.*))?"); + containerName = pathComponents[2]; + blobName = pathComponents[4]; + } + else { + // "https://customdomain.com/containername/blob". + // .getPath() -> /containername/blob + var pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); + containerName = pathComponents[1]; + blobName = pathComponents[3]; + } + // decode the encoded blobName, containerName - to get all the special characters that might be present in them + containerName = decodeURIComponent(containerName); + blobName = decodeURIComponent(blobName); + // Azure Storage Server will replace "\" with "/" in the blob names + // doing the same in the SDK side so that the user doesn't have to replace "\" instances in the blobName + blobName = blobName.replace(/\\/g, "/"); + if (!blobName) { + throw new Error("Provided blobName is invalid."); + } + else if (!containerName) { + throw new Error("Provided containerName is invalid."); + } + return { blobName: blobName, containerName: containerName }; + } + catch (error) { + throw new Error("Unable to extract blobName and containerName with provided information."); + } + }; + /** + * Asynchronously copies a blob to a destination within the storage account. + * In version 2012-02-12 and later, the source for a Copy Blob operation can be + * a committed blob in any Azure storage account. + * Beginning with version 2015-02-21, the source for a Copy Blob operation can be + * an Azure file in any Azure storage account. + * Only storage accounts created on or after June 7th, 2012 allow the Copy Blob + * operation to copy from another storage account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob + * + * @param {string} copySource url to the source Azure Blob/File. + * @param {BlobStartCopyFromURLOptions} [options] Optional options to the Blob Start Copy From URL operation. + * @returns {Promise} + * @memberof BlobClient + */ + BlobClient.prototype.startCopyFromURL = function (copySource, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_17; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("BlobClient-startCopyFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blobContext.startCopyFromURL(copySource, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, + sourceIfTags: options.sourceConditions.tagConditions + }, + rehydratePriority: options.rehydratePriority, + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), + sealBlob: options.sealBlob, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_17 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_17.message + }); + throw e_17; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + return BlobClient; +}(StorageClient)); +/** + * AppendBlobClient defines a set of operations applicable to append blobs. + * + * @export + * @class AppendBlobClient + * @extends {BlobClient} + */ +var AppendBlobClient = /** @class */ (function (_super) { + tslib.__extends(AppendBlobClient, _super); + function AppendBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { + var _this = this; + // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. + // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); + var pipeline; + var url; + options = options || {}; + if (credentialOrPipelineOrContainerName instanceof Pipeline) { + // (url: string, pipeline: Pipeline) + url = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } + else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || + credentialOrPipelineOrContainerName instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; + url = urlOrConnectionString; + options = blobNameOrOptions; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } + else if (!credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName !== "string") { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + url = urlOrConnectionString; + // The second parameter is undefined. Use anonymous credential. + pipeline = newPipeline(new AnonymousCredential(), options); + } + else if (credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName === "string" && + blobNameOrOptions && + typeof blobNameOrOptions === "string") { + // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) + var containerName = credentialOrPipelineOrContainerName; + var blobName = blobNameOrOptions; + var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + pipeline = newPipeline(sharedKeyCredential, options); + } + } + else if (extractedCreds.kind === "SASConnString") { + url = + appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + + "?" + + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } + else { + throw new Error("Expecting non-empty strings for containerName and blobName parameters"); + } + _this = _super.call(this, url, pipeline) || this; + _this.appendBlobContext = new AppendBlob(_this.storageClientContext); + return _this; + } + /** + * Creates a new AppendBlobClient object identical to the source but with the + * specified snapshot timestamp. + * Provide "" will remove the snapshot and return a Client to the base blob. + * + * @param {string} snapshot The snapshot timestamp. + * @returns {AppendBlobClient} A new AppendBlobClient object identical to the source but with the specified snapshot timestamp. + * @memberof AppendBlobClient + */ + AppendBlobClient.prototype.withSnapshot = function (snapshot) { + return new AppendBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); + }; + /** + * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param {AppendBlobCreateOptions} [options] Options to the Append Block Create operation. + * @returns {Promise} + * @memberof AppendBlobClient + * + * Example usage: + * + * ```js + * const appendBlobClient = containerClient.getAppendBlobClient(""); + * await appendBlobClient.create(); + * ``` + */ + AppendBlobClient.prototype.create = function (options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_18; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("AppendBlobClient-create", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.conditions = options.conditions || {}; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.appendBlobContext.create(0, { + abortSignal: options.abortSignal, + blobHTTPHeaders: options.blobHTTPHeaders, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + blobTagsString: toBlobTagsString(options.tags), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_18 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_18.message + }); + throw e_18; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. + * If the blob with the same name already exists, the content of the existing blob will remain unchanged. + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param {AppendBlobCreateIfNotExistsOptions} [options] + * @returns {Promise} + * @memberof AppendBlobClient + */ + AppendBlobClient.prototype.createIfNotExists = function (options) { + var _a, _b; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _c, span, spanOptions, conditions, res, e_19; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _c = createSpan("AppendBlobClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; + conditions = { ifNoneMatch: ETagAny }; + _d.label = 1; + case 1: + _d.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.create(tslib.__assign(tslib.__assign({}, options), { conditions: conditions, tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + res = _d.sent(); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + })]; + case 3: + e_19 = _d.sent(); + if (((_a = e_19.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { + span.setStatus({ + code: api.CanonicalCode.ALREADY_EXISTS, + message: "Expected exception when creating a blob only if it does not already exist." + }); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_19.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_19.response })]; + } + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_19.message + }); + throw e_19; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Seals the append blob, making it read only. + * + * @param {AppendBlobSealOptions} [options={}] + * @returns {Promise} + * @memberof AppendBlobClient + */ + AppendBlobClient.prototype.seal = function (options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_20; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("AppendBlobClient-seal", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.conditions = options.conditions || {}; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.appendBlobContext.seal({ + abortSignal: options.abortSignal, + appendPositionAccessConditions: options.conditions, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_20 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_20.message + }); + throw e_20; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Commits a new block of data to the end of the existing append blob. + * @see https://docs.microsoft.com/rest/api/storageservices/append-block + * + * @param {HttpRequestBody} body Data to be appended. + * @param {number} contentLength Length of the body in bytes. + * @param {AppendBlobAppendBlockOptions} [options] Options to the Append Block operation. + * @returns {Promise} + * @memberof AppendBlobClient + * + * Example usage: + * + * ```js + * const content = "Hello World!"; + * + * // Create a new append blob and append data to the blob. + * const newAppendBlobClient = containerClient.getAppendBlobClient(""); + * await newAppendBlobClient.create(); + * await newAppendBlobClient.appendBlock(content, content.length); + * + * // Append data to an existing append blob. + * const existingAppendBlobClient = containerClient.getAppendBlobClient(""); + * await existingAppendBlobClient.appendBlock(content, content.length); + * ``` + */ + AppendBlobClient.prototype.appendBlock = function (body, contentLength, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_21; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("AppendBlobClient-appendBlock", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.conditions = options.conditions || {}; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.appendBlobContext.appendBlock(body, contentLength, { + abortSignal: options.abortSignal, + appendPositionAccessConditions: options.conditions, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + onUploadProgress: options.onProgress, + transactionalContentMD5: options.transactionalContentMD5, + transactionalContentCrc64: options.transactionalContentCrc64, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_21 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_21.message + }); + throw e_21; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * The Append Block operation commits a new block of data to the end of an existing append blob + * where the contents are read from a source url. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/append-block-from-url + * + * @param {string} sourceURL + * The url to the blob that will be the source of the copy. A source blob in the same storage account can + * be authenticated via Shared Key. However, if the source is a blob in another account, the source blob + * must either be public or must be authenticated via a shared access signature. If the source blob is + * public, no authentication is required to perform the operation. + * @param {number} sourceOffset Offset in source to be appended + * @param {number} count Number of bytes to be appended as a block + * @param {AppendBlobAppendBlockFromURLOptions} [options={}] + * @returns {Promise} + * @memberof AppendBlobClient + */ + AppendBlobClient.prototype.appendBlockFromURL = function (sourceURL, sourceOffset, count, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_22; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("AppendBlobClient-appendBlockFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.appendBlobContext.appendBlockFromUrl(sourceURL, 0, { + abortSignal: options.abortSignal, + sourceRange: rangeToString({ offset: sourceOffset, count: count }), + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, + leaseAccessConditions: options.conditions, + appendPositionAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_22 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_22.message + }); + throw e_22; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + return AppendBlobClient; +}(BlobClient)); +/** + * BlockBlobClient defines a set of operations applicable to block blobs. + * + * @export + * @class BlockBlobClient + * @extends {BlobClient} + */ +var BlockBlobClient = /** @class */ (function (_super) { + tslib.__extends(BlockBlobClient, _super); + function BlockBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { + var _this = this; + // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. + // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); + var pipeline; + var url; + options = options || {}; + if (credentialOrPipelineOrContainerName instanceof Pipeline) { + // (url: string, pipeline: Pipeline) + url = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } + else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || + credentialOrPipelineOrContainerName instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + url = urlOrConnectionString; + options = blobNameOrOptions; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } + else if (!credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName !== "string") { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + // The second parameter is undefined. Use anonymous credential. + url = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else if (credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName === "string" && + blobNameOrOptions && + typeof blobNameOrOptions === "string") { + // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) + var containerName = credentialOrPipelineOrContainerName; + var blobName = blobNameOrOptions; + var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + pipeline = newPipeline(sharedKeyCredential, options); + } + } + else if (extractedCreds.kind === "SASConnString") { + url = + appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + + "?" + + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } + else { + throw new Error("Expecting non-empty strings for containerName and blobName parameters"); + } + _this = _super.call(this, url, pipeline) || this; + _this.blockBlobContext = new BlockBlob(_this.storageClientContext); + _this._blobContext = new Blob$1(_this.storageClientContext); + return _this; + } + /** + * Creates a new BlockBlobClient object identical to the source but with the + * specified snapshot timestamp. + * Provide "" will remove the snapshot and return a URL to the base blob. + * + * @param {string} snapshot The snapshot timestamp. + * @returns {BlockBlobClient} A new BlockBlobClient object identical to the source but with the specified snapshot timestamp. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.withSnapshot = function (snapshot) { + return new BlockBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); + }; + /** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Quick query for a JSON or CSV formatted blob. + * + * Example usage (Node.js): + * + * ```js + * // Query and convert a blob to a string + * const queryBlockBlobResponse = await blockBlobClient.query("select * from BlobStorage"); + * const downloaded = (await streamToBuffer(queryBlockBlobResponse.readableStreamBody)).toString(); + * console.log("Query blob content:", downloaded); + * + * async function streamToBuffer(readableStream) { + * return new Promise((resolve, reject) => { + * const chunks = []; + * readableStream.on("data", (data) => { + * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); + * }); + * readableStream.on("end", () => { + * resolve(Buffer.concat(chunks)); + * }); + * readableStream.on("error", reject); + * }); + * } + * ``` + * + * @param {string} query + * @param {BlockBlobQueryOptions} [options={}] + * @returns {Promise} + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.query = function (query, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, response, e_23; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + _b = createSpan("BlockBlobClient-query", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this._blobContext.query({ + abortSignal: options.abortSignal, + queryRequest: { + expression: query, + inputSerialization: toQuerySerialization(options.inputTextConfiguration), + outputSerialization: toQuerySerialization(options.outputTextConfiguration) + }, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + spanOptions: spanOptions + })]; + case 2: + response = _c.sent(); + return [2 /*return*/, new BlobQueryResponse(response, { + abortSignal: options.abortSignal, + onProgress: options.onProgress, + onError: options.onError + })]; + case 3: + e_23 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_23.message + }); + throw e_23; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Creates a new block blob, or updates the content of an existing block blob. + * Updating an existing block blob overwrites any existing metadata on the blob. + * Partial updates are not supported; the content of the existing blob is + * overwritten with the new content. To perform a partial update of a block blob's, + * use {@link stageBlock} and {@link commitBlockList}. + * + * This is a non-parallel uploading method, please use {@link uploadFile}, + * {@link uploadStream} or {@link uploadBrowserData} for better performance + * with concurrency uploading. + * + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param {HttpRequestBody} body Blob, string, ArrayBuffer, ArrayBufferView or a function + * which returns a new Readable stream whose offset is from data source beginning. + * @param {number} contentLength Length of body in bytes. Use Buffer.byteLength() to calculate body length for a + * string including non non-Base64/Hex-encoded characters. + * @param {BlockBlobUploadOptions} [options] Options to the Block Blob Upload operation. + * @returns {Promise} Response data for the Block Blob Upload operation. + * @memberof BlockBlobClient + * + * Example usage: + * + * ```js + * const content = "Hello world!"; + * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); + * ``` + */ + BlockBlobClient.prototype.upload = function (body, contentLength, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_24; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("BlockBlobClient-upload", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blockBlobContext.upload(body, contentLength, { + abortSignal: options.abortSignal, + blobHTTPHeaders: options.blobHTTPHeaders, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + onUploadProgress: options.onProgress, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_24 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_24.message + }); + throw e_24; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Uploads the specified block to the block blob's "staging area" to be later + * committed by a call to commitBlockList. + * @see https://docs.microsoft.com/rest/api/storageservices/put-block + * + * @param {string} blockId A 64-byte value that is base64-encoded + * @param {HttpRequestBody} body Data to upload to the staging area. + * @param {number} contentLength Number of bytes to upload. + * @param {BlockBlobStageBlockOptions} [options] Options to the Block Blob Stage Block operation. + * @returns {Promise} Response data for the Block Blob Stage Block operation. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.stageBlock = function (blockId, body, contentLength, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_25; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlockBlobClient-stageBlock", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blockBlobContext.stageBlock(blockId, contentLength, body, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + onUploadProgress: options.onProgress, + transactionalContentMD5: options.transactionalContentMD5, + transactionalContentCrc64: options.transactionalContentCrc64, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_25 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_25.message + }); + throw e_25; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * The Stage Block From URL operation creates a new block to be committed as part + * of a blob where the contents are read from a URL. + * This API is available starting in version 2018-03-28. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url + * + * @param {string} blockId A 64-byte value that is base64-encoded + * @param {string} sourceURL Specifies the URL of the blob. The value + * may be a URL of up to 2 KB in length that specifies a blob. + * The value should be URL-encoded as it would appear + * in a request URI. The source blob must either be public + * or must be authenticated via a shared access signature. + * If the source blob is public, no authentication is required + * to perform the operation. Here are some examples of source object URLs: + * - https://myaccount.blob.core.windows.net/mycontainer/myblob + * - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= + * @param {number} [offset] From which position of the blob to download, >= 0 + * @param {number} [count] How much data to be downloaded, > 0. Will download to the end when undefined + * @param {BlockBlobStageBlockFromURLOptions} [options={}] Options to the Block Blob Stage Block From URL operation. + * @returns {Promise} Response data for the Block Blob Stage Block From URL operation. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.stageBlockFromURL = function (blockId, sourceURL, offset, count, options) { + if (offset === void 0) { offset = 0; } + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_26; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlockBlobClient-stageBlockFromURL", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blockBlobContext.stageBlockFromURL(blockId, 0, sourceURL, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, + sourceRange: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_26 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_26.message + }); + throw e_26; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Writes a blob by specifying the list of block IDs that make up the blob. + * In order to be written as part of a blob, a block must have been successfully written + * to the server in a prior {@link stageBlock} operation. You can call {@link commitBlockList} to + * update a blob by uploading only those blocks that have changed, then committing the new and existing + * blocks together. Any blocks not specified in the block list and permanently deleted. + * @see https://docs.microsoft.com/rest/api/storageservices/put-block-list + * + * @param {string[]} blocks Array of 64-byte value that is base64-encoded + * @param {BlockBlobCommitBlockListOptions} [options] Options to the Block Blob Commit Block List operation. + * @returns {Promise} Response data for the Block Blob Commit Block List operation. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.commitBlockList = function (blocks, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_27; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("BlockBlobClient-commitBlockList", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blockBlobContext.commitBlockList({ latest: blocks }, { + abortSignal: options.abortSignal, + blobHTTPHeaders: options.blobHTTPHeaders, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_27 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_27.message + }); + throw e_27; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns the list of blocks that have been uploaded as part of a block blob + * using the specified block list filter. + * @see https://docs.microsoft.com/rest/api/storageservices/get-block-list + * + * @param {BlockListType} listType Specifies whether to return the list of committed blocks, + * the list of uncommitted blocks, or both lists together. + * @param {BlockBlobGetBlockListOptions} [options] Options to the Block Blob Get Block List operation. + * @returns {Promise} Response data for the Block Blob Get Block List operation. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.getBlockList = function (listType, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, res, e_28; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("BlockBlobClient-getBlockList", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blockBlobContext.getBlockList(listType, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + spanOptions: spanOptions + })]; + case 2: + res = _c.sent(); + if (!res.committedBlocks) { + res.committedBlocks = []; + } + if (!res.uncommittedBlocks) { + res.uncommittedBlocks = []; + } + return [2 /*return*/, res]; + case 3: + e_28 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_28.message + }); + throw e_28; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + // High level functions + /** + * ONLY AVAILABLE IN BROWSERS. + * + * Uploads a browser Blob/File/ArrayBuffer/ArrayBufferView object to block blob. + * + * When buffer length <= 256MB, this method will use 1 upload call to finish the upload. + * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call + * {@link commitBlockList} to commit the block list. + * + * @export + * @param {Blob | ArrayBuffer | ArrayBufferView} browserData Blob, File, ArrayBuffer or ArrayBufferView + * @param {BlockBlobParallelUploadOptions} [options] Options to upload browser data. + * @returns {Promise} Response data for the Blob Upload operation. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.uploadBrowserData = function (browserData, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, browserBlob_1, e_29; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlockBlobClient-uploadBrowserData", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + browserBlob_1 = new Blob([browserData]); + return [4 /*yield*/, this.uploadSeekableBlob(function (offset, size) { + return browserBlob_1.slice(offset, offset + size); + }, browserBlob_1.size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_29 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_29.message + }); + throw e_29; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * ONLY AVAILABLE IN BROWSERS. + * + * Uploads a browser {@link Blob} object to block blob. Requires a blobFactory as the data source, + * which need to return a {@link Blob} object with the offset and size provided. + * + * When buffer length <= 256MB, this method will use 1 upload call to finish the upload. + * Otherwise, this method will call stageBlock to upload blocks, and finally call commitBlockList + * to commit the block list. + * + * @param {(offset: number, size: number) => Blob} blobFactory + * @param {number} size size of the data to upload. + * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. + * @returns {Promise} Response data for the Blob Upload operation. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.uploadSeekableBlob = function (blobFactory, size, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, numBlocks_1, blockList_1, blockIDPrefix_1, transferProgress_2, batch, _loop_2, i, e_30; + var _this = this; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!options.blockSize) { + options.blockSize = 0; + } + if (options.blockSize < 0 || options.blockSize > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { + throw new RangeError("blockSize option must be >= 0 and <= " + BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES); + } + if (options.maxSingleShotSize !== 0 && !options.maxSingleShotSize) { + options.maxSingleShotSize = BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES; + } + if (options.maxSingleShotSize < 0 || + options.maxSingleShotSize > BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES) { + throw new RangeError("maxSingleShotSize option must be >= 0 and <= " + BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES); + } + if (options.blockSize === 0) { + if (size > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES * BLOCK_BLOB_MAX_BLOCKS) { + throw new RangeError(size + " is too larger to upload to a block blob."); + } + if (size > options.maxSingleShotSize) { + options.blockSize = Math.ceil(size / BLOCK_BLOB_MAX_BLOCKS); + if (options.blockSize < DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES) { + options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; + } + } + } + if (!options.blobHTTPHeaders) { + options.blobHTTPHeaders = {}; + } + if (!options.conditions) { + options.conditions = {}; + } + _a = createSpan("BlockBlobClient-UploadSeekableBlob", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 5, 6, 7]); + if (!(size <= options.maxSingleShotSize)) return [3 /*break*/, 3]; + return [4 /*yield*/, this.upload(blobFactory(0, size), size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + numBlocks_1 = Math.floor((size - 1) / options.blockSize) + 1; + if (numBlocks_1 > BLOCK_BLOB_MAX_BLOCKS) { + throw new RangeError("The buffer's size is too big or the BlockSize is too small;" + + ("the number of blocks must be <= " + BLOCK_BLOB_MAX_BLOCKS)); + } + blockList_1 = []; + blockIDPrefix_1 = coreHttp.generateUuid(); + transferProgress_2 = 0; + batch = new Batch(options.concurrency); + _loop_2 = function (i) { + batch.addOperation(function () { return tslib.__awaiter(_this, void 0, void 0, function () { + var blockID, start, end, contentLength; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + blockID = generateBlockID(blockIDPrefix_1, i); + start = options.blockSize * i; + end = i === numBlocks_1 - 1 ? size : start + options.blockSize; + contentLength = end - start; + blockList_1.push(blockID); + return [4 /*yield*/, this.stageBlock(blockID, blobFactory(start, contentLength), contentLength, { + abortSignal: options.abortSignal, + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; + case 1: + _a.sent(); + // Update progress after block is successfully uploaded to server, in case of block trying + // TODO: Hook with convenience layer progress event in finer level + transferProgress_2 += contentLength; + if (options.onProgress) { + options.onProgress({ + loadedBytes: transferProgress_2 + }); + } + return [2 /*return*/]; + } + }); + }); }); + }; + for (i = 0; i < numBlocks_1; i++) { + _loop_2(i); + } + return [4 /*yield*/, batch.do()]; + case 4: + _b.sent(); + return [2 /*return*/, this.commitBlockList(blockList_1, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 5: + e_30 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_30.message + }); + throw e_30; + case 6: + span.end(); + return [7 /*endfinally*/]; + case 7: return [2 /*return*/]; + } + }); + }); + }; + /** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Uploads a local file in blocks to a block blob. + * + * When file size <= 256MB, this method will use 1 upload call to finish the upload. + * Otherwise, this method will call stageBlock to upload blocks, and finally call commitBlockList + * to commit the block list. + * + * @param {string} filePath Full path of local file + * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. + * @returns {(Promise)} Response data for the Blob Upload operation. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.uploadFile = function (filePath, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, size, e_31; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlockBlobClient-uploadFile", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 4, 5, 6]); + return [4 /*yield*/, fsStat(filePath)]; + case 2: + size = (_b.sent()).size; + return [4 /*yield*/, this.uploadResetableStream(function (offset, count) { + return fsCreateReadStream(filePath, { + autoClose: true, + end: count ? offset + count - 1 : Infinity, + start: offset + }); + }, size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 3: return [2 /*return*/, _b.sent()]; + case 4: + e_31 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_31.message + }); + throw e_31; + case 5: + span.end(); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); + }); + }; + /** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Uploads a Node.js Readable stream into block blob. + * + * PERFORMANCE IMPROVEMENT TIPS: + * * Input stream highWaterMark is better to set a same value with bufferSize + * parameter, which will avoid Buffer.concat() operations. + * + * @param {Readable} stream Node.js Readable stream + * @param {number} bufferSize Size of every buffer allocated, also the block size in the uploaded block blob. Default value is 8MB + * @param {number} maxConcurrency Max concurrency indicates the max number of buffers that can be allocated, + * positive correlation with max uploading concurrency. Default value is 5 + * @param {BlockBlobUploadStreamOptions} [options] Options to Upload Stream to Block Blob operation. + * @returns {Promise} Response data for the Blob Upload operation. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.uploadStream = function (stream, bufferSize, maxConcurrency, options) { + if (bufferSize === void 0) { bufferSize = DEFAULT_BLOCK_BUFFER_SIZE_BYTES; } + if (maxConcurrency === void 0) { maxConcurrency = 5; } + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, blockNum_1, blockIDPrefix_2, transferProgress_3, blockList_2, scheduler, e_32; + var _this = this; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!options.blobHTTPHeaders) { + options.blobHTTPHeaders = {}; + } + if (!options.conditions) { + options.conditions = {}; + } + _a = createSpan("BlockBlobClient-uploadStream", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 4, 5, 6]); + blockNum_1 = 0; + blockIDPrefix_2 = coreHttp.generateUuid(); + transferProgress_3 = 0; + blockList_2 = []; + scheduler = new BufferScheduler(stream, bufferSize, maxConcurrency, function (body, length) { return tslib.__awaiter(_this, void 0, void 0, function () { + var blockID; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + blockID = generateBlockID(blockIDPrefix_2, blockNum_1); + blockList_2.push(blockID); + blockNum_1++; + return [4 /*yield*/, this.stageBlock(blockID, body, length, { + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; + case 1: + _a.sent(); + // Update progress after block is successfully uploaded to server, in case of block trying + transferProgress_3 += length; + if (options.onProgress) { + options.onProgress({ loadedBytes: transferProgress_3 }); + } + return [2 /*return*/]; + } + }); + }); }, + // concurrency should set a smaller value than maxConcurrency, which is helpful to + // reduce the possibility when a outgoing handler waits for stream data, in + // this situation, outgoing handlers are blocked. + // Outgoing queue shouldn't be empty. + Math.ceil((maxConcurrency / 4) * 3)); + return [4 /*yield*/, scheduler.do()]; + case 2: + _b.sent(); + return [4 /*yield*/, this.commitBlockList(blockList_2, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 3: return [2 /*return*/, _b.sent()]; + case 4: + e_32 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_32.message + }); + throw e_32; + case 5: + span.end(); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); + }); + }; + /** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Accepts a Node.js Readable stream factory, and uploads in blocks to a block blob. + * The Readable stream factory must returns a Node.js Readable stream starting from the offset defined. The offset + * is the offset in the block blob to be uploaded. + * + * When buffer length <= 256MB, this method will use 1 upload call to finish the upload. + * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} + * to commit the block list. + * + * @export + * @param {(offset: number) => NodeJS.ReadableStream} streamFactory Returns a Node.js Readable stream starting + * from the offset defined + * @param {number} size Size of the block blob + * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. + * @returns {(Promise)} Response data for the Blob Upload operation. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.uploadResetableStream = function (streamFactory, size, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, numBlocks_2, blockList_3, blockIDPrefix_3, transferProgress_4, batch, _loop_3, i, e_33; + var _this = this; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!options.blockSize) { + options.blockSize = 0; + } + if (options.blockSize < 0 || options.blockSize > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { + throw new RangeError("blockSize option must be >= 0 and <= " + BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES); + } + if (options.maxSingleShotSize !== 0 && !options.maxSingleShotSize) { + options.maxSingleShotSize = BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES; + } + if (options.maxSingleShotSize < 0 || + options.maxSingleShotSize > BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES) { + throw new RangeError("maxSingleShotSize option must be >= 0 and <= " + BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES); + } + if (options.blockSize === 0) { + if (size > BLOCK_BLOB_MAX_BLOCKS * BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { + throw new RangeError(size + " is too larger to upload to a block blob."); + } + if (size > options.maxSingleShotSize) { + options.blockSize = Math.ceil(size / BLOCK_BLOB_MAX_BLOCKS); + if (options.blockSize < DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES) { + options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; + } + } + } + if (!options.blobHTTPHeaders) { + options.blobHTTPHeaders = {}; + } + if (!options.conditions) { + options.conditions = {}; + } + _a = createSpan("BlockBlobClient-uploadResetableStream", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 6, 7, 8]); + if (!(size <= options.maxSingleShotSize)) return [3 /*break*/, 3]; + return [4 /*yield*/, this.upload(function () { return streamFactory(0); }, size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + numBlocks_2 = Math.floor((size - 1) / options.blockSize) + 1; + if (numBlocks_2 > BLOCK_BLOB_MAX_BLOCKS) { + throw new RangeError("The buffer's size is too big or the BlockSize is too small;" + + ("the number of blocks must be <= " + BLOCK_BLOB_MAX_BLOCKS)); + } + blockList_3 = []; + blockIDPrefix_3 = coreHttp.generateUuid(); + transferProgress_4 = 0; + batch = new Batch(options.concurrency); + _loop_3 = function (i) { + batch.addOperation(function () { return tslib.__awaiter(_this, void 0, void 0, function () { + var blockID, start, end, contentLength; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + blockID = generateBlockID(blockIDPrefix_3, i); + start = options.blockSize * i; + end = i === numBlocks_2 - 1 ? size : start + options.blockSize; + contentLength = end - start; + blockList_3.push(blockID); + return [4 /*yield*/, this.stageBlock(blockID, function () { return streamFactory(start, contentLength); }, contentLength, { + abortSignal: options.abortSignal, + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; + case 1: + _a.sent(); + // Update progress after block is successfully uploaded to server, in case of block trying + transferProgress_4 += contentLength; + if (options.onProgress) { + options.onProgress({ loadedBytes: transferProgress_4 }); + } + return [2 /*return*/]; + } + }); + }); }); + }; + for (i = 0; i < numBlocks_2; i++) { + _loop_3(i); + } + return [4 /*yield*/, batch.do()]; + case 4: + _b.sent(); + return [4 /*yield*/, this.commitBlockList(blockList_3, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 5: return [2 /*return*/, _b.sent()]; + case 6: + e_33 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_33.message + }); + throw e_33; + case 7: + span.end(); + return [7 /*endfinally*/]; + case 8: return [2 /*return*/]; + } + }); + }); + }; + return BlockBlobClient; +}(BlobClient)); +/** + * PageBlobClient defines a set of operations applicable to page blobs. + * + * @export + * @class PageBlobClient + * @extends {BlobClient} + */ +var PageBlobClient = /** @class */ (function (_super) { + tslib.__extends(PageBlobClient, _super); + function PageBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { + var _this = this; + // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. + // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); + var pipeline; + var url; + options = options || {}; + if (credentialOrPipelineOrContainerName instanceof Pipeline) { + // (url: string, pipeline: Pipeline) + url = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } + else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || + credentialOrPipelineOrContainerName instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + url = urlOrConnectionString; + options = blobNameOrOptions; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } + else if (!credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName !== "string") { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + // The second parameter is undefined. Use anonymous credential. + url = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else if (credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName === "string" && + blobNameOrOptions && + typeof blobNameOrOptions === "string") { + // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) + var containerName = credentialOrPipelineOrContainerName; + var blobName = blobNameOrOptions; + var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + pipeline = newPipeline(sharedKeyCredential, options); + } + } + else if (extractedCreds.kind === "SASConnString") { + url = + appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + + "?" + + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } + else { + throw new Error("Expecting non-empty strings for containerName and blobName parameters"); + } + _this = _super.call(this, url, pipeline) || this; + _this.pageBlobContext = new PageBlob(_this.storageClientContext); + return _this; + } + /** + * Creates a new PageBlobClient object identical to the source but with the + * specified snapshot timestamp. + * Provide "" will remove the snapshot and return a Client to the base blob. + * + * @param {string} snapshot The snapshot timestamp. + * @returns {PageBlobClient} A new PageBlobClient object identical to the source but with the specified snapshot timestamp. + * @memberof PageBlobClient + */ + PageBlobClient.prototype.withSnapshot = function (snapshot) { + return new PageBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); + }; + /** + * Creates a page blob of the specified length. Call uploadPages to upload data + * data to a page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param {number} size size of the page blob. + * @param {PageBlobCreateOptions} [options] Options to the Page Blob Create operation. + * @returns {Promise} Response data for the Page Blob Create operation. + * @memberof PageBlobClient + */ + PageBlobClient.prototype.create = function (size, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_34; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-create", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.pageBlobContext.create(0, size, { + abortSignal: options.abortSignal, + blobHTTPHeaders: options.blobHTTPHeaders, + blobSequenceNumber: options.blobSequenceNumber, + leaseAccessConditions: options.conditions, + metadata: options.metadata, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + tier: toAccessTier(options.tier), + blobTagsString: toBlobTagsString(options.tags), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_34 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_34.message + }); + throw e_34; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Creates a page blob of the specified length. Call uploadPages to upload data + * data to a page blob. If the blob with the same name already exists, the content + * of the existing blob will remain unchanged. + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param {number} size size of the page blob. + * @param {PageBlobCreateIfNotExistsOptions} [options] + * @returns {Promise} + * @memberof PageBlobClient + */ + PageBlobClient.prototype.createIfNotExists = function (size, options) { + var _a, _b; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _c, span, spanOptions, conditions, res, e_35; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _c = createSpan("PageBlobClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; + _d.label = 1; + case 1: + _d.trys.push([1, 3, 4, 5]); + conditions = { ifNoneMatch: ETagAny }; + return [4 /*yield*/, this.create(size, tslib.__assign(tslib.__assign({}, options), { conditions: conditions, tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + res = _d.sent(); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + })]; + case 3: + e_35 = _d.sent(); + if (((_a = e_35.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { + span.setStatus({ + code: api.CanonicalCode.ALREADY_EXISTS, + message: "Expected exception when creating a blob only if it does not already exist." + }); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_35.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_35.response })]; + } + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_35.message + }); + throw e_35; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512. + * @see https://docs.microsoft.com/rest/api/storageservices/put-page + * + * @param {HttpRequestBody} body Data to upload + * @param {number} offset Offset of destination page blob + * @param {number} count Content length of the body, also number of bytes to be uploaded + * @param {PageBlobUploadPagesOptions} [options] Options to the Page Blob Upload Pages operation. + * @returns {Promise} Response data for the Page Blob Upload Pages operation. + * @memberof PageBlobClient + */ + PageBlobClient.prototype.uploadPages = function (body, offset, count, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_36; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-uploadPages", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.pageBlobContext.uploadPages(body, count, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + onUploadProgress: options.onProgress, + range: rangeToString({ offset: offset, count: count }), + sequenceNumberAccessConditions: options.conditions, + transactionalContentMD5: options.transactionalContentMD5, + transactionalContentCrc64: options.transactionalContentCrc64, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_36 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_36.message + }); + throw e_36; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * The Upload Pages operation writes a range of pages to a page blob where the + * contents are read from a URL. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-page-from-url + * + * @param {string} sourceURL Specify a URL to the copy source, Shared Access Signature(SAS) maybe needed for authentication + * @param {number} sourceOffset The source offset to copy from. Pass 0 to copy from the beginning of source page blob + * @param {number} destOffset Offset of destination page blob + * @param {number} count Number of bytes to be uploaded from source page blob + * @param {PageBlobUploadPagesFromURLOptions} [options={}] + * @returns {Promise} + * @memberof PageBlobClient + */ + PageBlobClient.prototype.uploadPagesFromURL = function (sourceURL, sourceOffset, destOffset, count, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_37; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + _b = createSpan("PageBlobClient-uploadPagesFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count: count }), 0, rangeToString({ offset: destOffset, count: count }), { + abortSignal: options.abortSignal, + sourceContentMD5: options.sourceContentMD5, + sourceContentCrc64: options.sourceContentCrc64, + leaseAccessConditions: options.conditions, + sequenceNumberAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince + }, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_37 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_37.message + }); + throw e_37; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Frees the specified pages from the page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/put-page + * + * @param {number} [offset] Starting byte position of the pages to clear. + * @param {number} [count] Number of bytes to clear. + * @param {PageBlobClearPagesOptions} [options] Options to the Page Blob Clear Pages operation. + * @returns {Promise} Response data for the Page Blob Clear Pages operation. + * @memberof PageBlobClient + */ + PageBlobClient.prototype.clearPages = function (offset, count, options) { + var _a; + if (offset === void 0) { offset = 0; } + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_38; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-clearPages", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext.clearPages(0, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + range: rangeToString({ offset: offset, count: count }), + sequenceNumberAccessConditions: options.conditions, + cpkInfo: options.customerProvidedKey, + encryptionScope: options.encryptionScope, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_38 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_38.message + }); + throw e_38; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns the list of valid page ranges for a page blob or snapshot of a page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * @param {number} [offset] Starting byte position of the page ranges. + * @param {number} [count] Number of bytes to get. + * @param {PageBlobGetPageRangesOptions} [options] Options to the Page Blob Get Ranges operation. + * @returns {Promise} Response data for the Page Blob Get Ranges operation. + * @memberof PageBlobClient + */ + PageBlobClient.prototype.getPageRanges = function (offset, count, options) { + var _a; + if (offset === void 0) { offset = 0; } + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_39; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-getPageRanges", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext + .getPageRanges({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + range: rangeToString({ offset: offset, count: count }), + spanOptions: spanOptions + }) + .then(rangeResponseFromModel)]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_39 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_39.message + }); + throw e_39; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Gets the collection of page ranges that differ between a specified snapshot and this page blob. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * @param {number} offset Starting byte position of the page blob + * @param {number} count Number of bytes to get ranges diff. + * @param {string} prevSnapshot Timestamp of snapshot to retrieve the difference. + * @param {PageBlobGetPageRangesDiffOptions} [options] Options to the Page Blob Get Page Ranges Diff operation. + * @returns {Promise} Response data for the Page Blob Get Page Range Diff operation. + * @memberof PageBlobClient + */ + PageBlobClient.prototype.getPageRangesDiff = function (offset, count, prevSnapshot, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_40; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-getPageRangesDiff", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext + .getPageRangesDiff({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + prevsnapshot: prevSnapshot, + range: rangeToString({ offset: offset, count: count }), + spanOptions: spanOptions + }) + .then(rangeResponseFromModel)]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_40 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_40.message + }); + throw e_40; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Gets the collection of page ranges that differ between a specified snapshot and this page blob for managed disks. + * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges + * + * @param {number} offset Starting byte position of the page blob + * @param {number} count Number of bytes to get ranges diff. + * @param {string} prevSnapshotUrl URL of snapshot to retrieve the difference. + * @param {PageBlobGetPageRangesDiffOptions} [options] Options to the Page Blob Get Page Ranges Diff operation. + * @returns {Promise} Response data for the Page Blob Get Page Range Diff operation. + * @memberof PageBlobClient + */ + PageBlobClient.prototype.getPageRangesDiffForManagedDisks = function (offset, count, prevSnapshotUrl, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_41; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext + .getPageRangesDiff({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + prevSnapshotUrl: prevSnapshotUrl, + range: rangeToString({ offset: offset, count: count }), + spanOptions: spanOptions + }) + .then(rangeResponseFromModel)]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_41 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_41.message + }); + throw e_41; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Resizes the page blob to the specified size (which must be a multiple of 512). + * @see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties + * + * @param {number} size Target size + * @param {PageBlobResizeOptions} [options] Options to the Page Blob Resize operation. + * @returns {Promise} Response data for the Page Blob Resize operation. + * @memberof PageBlobClient + */ + PageBlobClient.prototype.resize = function (size, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_42; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-resize", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext.resize(size, { + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + encryptionScope: options.encryptionScope, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_42 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_42.message + }); + throw e_42; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Sets a page blob's sequence number. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties + * + * @param {SequenceNumberActionType} sequenceNumberAction Indicates how the service should modify the blob's sequence number. + * @param {number} [sequenceNumber] Required if sequenceNumberAction is max or update + * @param {PageBlobUpdateSequenceNumberOptions} [options] Options to the Page Blob Update Sequence Number operation. + * @returns {Promise} Response data for the Page Blob Update Sequence Number operation. + * @memberof PageBlobClient + */ + PageBlobClient.prototype.updateSequenceNumber = function (sequenceNumberAction, sequenceNumber, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_43; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _b = createSpan("PageBlobClient-updateSequenceNumber", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext.updateSequenceNumber(sequenceNumberAction, { + abortSignal: options.abortSignal, + blobSequenceNumber: sequenceNumber, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_43 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_43.message + }); + throw e_43; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Begins an operation to start an incremental copy from one page blob's snapshot to this page blob. + * The snapshot is copied such that only the differential changes between the previously + * copied snapshot are transferred to the destination. + * The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual. + * @see https://docs.microsoft.com/rest/api/storageservices/incremental-copy-blob + * @see https://docs.microsoft.com/en-us/azure/virtual-machines/windows/incremental-snapshots + * + * @param {string} copySource Specifies the name of the source page blob snapshot. For example, + * https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= + * @param {PageBlobStartCopyIncrementalOptions} [options] Options to the Page Blob Copy Incremental operation. + * @returns {Promise} Response data for the Page Blob Copy Incremental operation. + * @memberof PageBlobClient + */ + PageBlobClient.prototype.startCopyIncremental = function (copySource, options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, e_44; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("PageBlobClient-startCopyIncremental", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.pageBlobContext.copyIncremental(copySource, { + abortSignal: options.abortSignal, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_44 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_44.message + }); + throw e_44; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + return PageBlobClient; +}(BlobClient)); +/** + * A client that manages leases for a {@link ContainerClient} or a {@link BlobClient}. + * + * @export + * @class BlobLeaseClient + */ +var BlobLeaseClient = /** @class */ (function () { + /** + * Creates an instance of BlobLeaseClient. + * @param {(ContainerClient | BlobClient)} client The client to make the lease operation requests. + * @param {string} leaseId Initial proposed lease id. + * @memberof BlobLeaseClient + */ + function BlobLeaseClient(client, leaseId) { + var clientContext = new StorageClientContext(client.url, client.pipeline.toServiceClientOptions()); + this._url = client.url; + if (client instanceof ContainerClient) { + this._isContainer = true; + this._containerOrBlobOperation = new Container(clientContext); + } + else { + this._isContainer = false; + this._containerOrBlobOperation = new Blob$1(clientContext); + } + if (!leaseId) { + leaseId = coreHttp.generateUuid(); + } + this._leaseId = leaseId; + } + Object.defineProperty(BlobLeaseClient.prototype, "leaseId", { + /** + * Gets the lease Id. + * + * @readonly + * @memberof BlobLeaseClient + * @type {string} + */ + get: function () { + return this._leaseId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobLeaseClient.prototype, "url", { + /** + * Gets the url. + * + * @readonly + * @memberof BlobLeaseClient + * @type {string} + */ + get: function () { + return this._url; + }, + enumerable: false, + configurable: true + }); + /** + * Establishes and manages a lock on a container for delete operations, or on a blob + * for write and delete operations. + * The lock duration can be 15 to 60 seconds, or can be infinite. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * + * @param {number} duration Must be between 15 to 60 seconds, or infinite (-1) + * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. + * @returns {Promise} Response data for acquire lease operation. + * @memberof BlobLeaseClient + */ + BlobLeaseClient.prototype.acquireLease = function (duration, options) { + var _a, _b, _c, _d, _e, _f; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _g, span, spanOptions, e_45; + return tslib.__generator(this, function (_h) { + switch (_h.label) { + case 0: + _g = createSpan("BlobLeaseClient-acquireLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + _h.label = 1; + case 1: + _h.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this._containerOrBlobOperation.acquireLease({ + abortSignal: options.abortSignal, + duration: duration, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), + proposedLeaseId: this._leaseId, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _h.sent()]; + case 3: + e_45 = _h.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_45.message + }); + throw e_45; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * To change the ID of the lease. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * + * @param {string} proposedLeaseId the proposed new lease Id. + * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. + * @returns {Promise} Response data for change lease operation. + * @memberof BlobLeaseClient + */ + BlobLeaseClient.prototype.changeLease = function (proposedLeaseId, options) { + var _a, _b, _c, _d, _e, _f; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _g, span, spanOptions, response, e_46; + return tslib.__generator(this, function (_h) { + switch (_h.label) { + case 0: + _g = createSpan("BlobLeaseClient-changeLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + _h.label = 1; + case 1: + _h.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this._containerOrBlobOperation.changeLease(this._leaseId, proposedLeaseId, { + abortSignal: options.abortSignal, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), + spanOptions: spanOptions + })]; + case 2: + response = _h.sent(); + this._leaseId = proposedLeaseId; + return [2 /*return*/, response]; + case 3: + e_46 = _h.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_46.message + }); + throw e_46; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * To free the lease if it is no longer needed so that another client may + * immediately acquire a lease against the container or the blob. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * + * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. + * @returns {Promise} Response data for release lease operation. + * @memberof BlobLeaseClient + */ + BlobLeaseClient.prototype.releaseLease = function (options) { + var _a, _b, _c, _d, _e, _f; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _g, span, spanOptions, e_47; + return tslib.__generator(this, function (_h) { + switch (_h.label) { + case 0: + _g = createSpan("BlobLeaseClient-releaseLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + _h.label = 1; + case 1: + _h.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this._containerOrBlobOperation.releaseLease(this._leaseId, { + abortSignal: options.abortSignal, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _h.sent()]; + case 3: + e_47 = _h.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_47.message + }); + throw e_47; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * To renew the lease. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * + * @param {LeaseOperationOptions} [options={}] Optional option to configure lease management operations. + * @returns {Promise} Response data for renew lease operation. + * @memberof BlobLeaseClient + */ + BlobLeaseClient.prototype.renewLease = function (options) { + var _a, _b, _c, _d, _e, _f; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _g, span, spanOptions, e_48; + return tslib.__generator(this, function (_h) { + switch (_h.label) { + case 0: + _g = createSpan("BlobLeaseClient-renewLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + _h.label = 1; + case 1: + _h.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this._containerOrBlobOperation.renewLease(this._leaseId, { + abortSignal: options.abortSignal, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _h.sent()]; + case 3: + e_48 = _h.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_48.message + }); + throw e_48; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * To end the lease but ensure that another client cannot acquire a new lease + * until the current lease period has expired. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container + * and + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob + * + * @static + * @param {number} breakPeriod Break period + * @param {LeaseOperationOptions} [options={}] Optional options to configure lease management operations. + * @returns {Promise} Response data for break lease operation. + * @memberof BlobLeaseClient + */ + BlobLeaseClient.prototype.breakLease = function (breakPeriod, options) { + var _a, _b, _c, _d, _e, _f; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _g, span, spanOptions, operationOptions, e_49; + return tslib.__generator(this, function (_h) { + switch (_h.label) { + case 0: + _g = createSpan("BlobLeaseClient-breakLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + _h.label = 1; + case 1: + _h.trys.push([1, 3, 4, 5]); + operationOptions = { + abortSignal: options.abortSignal, + breakPeriod: breakPeriod, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), + spanOptions: spanOptions + }; + return [4 /*yield*/, this._containerOrBlobOperation.breakLease(operationOptions)]; + case 2: return [2 /*return*/, _h.sent()]; + case 3: + e_49 = _h.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_49.message + }); + throw e_49; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + return BlobLeaseClient; +}()); +/** + * A ContainerClient represents a URL to the Azure Storage container allowing you to manipulate its blobs. + * + * @export + * @class ContainerClient + */ +var ContainerClient = /** @class */ (function (_super) { + tslib.__extends(ContainerClient, _super); + function ContainerClient(urlOrConnectionString, credentialOrPipelineOrContainerName, options) { + var _this = this; + var pipeline; + var url; + options = options || {}; + if (credentialOrPipelineOrContainerName instanceof Pipeline) { + // (url: string, pipeline: Pipeline) + url = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } + else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || + credentialOrPipelineOrContainerName instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + url = urlOrConnectionString; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } + else if (!credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName !== "string") { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + // The second parameter is undefined. Use anonymous credential. + url = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else if (credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName === "string") { + // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) + var containerName = credentialOrPipelineOrContainerName; + var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + pipeline = newPipeline(sharedKeyCredential, options); + } + } + else if (extractedCreds.kind === "SASConnString") { + url = + appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)) + + "?" + + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } + else { + throw new Error("Expecting non-empty strings for containerName parameter"); + } + _this = _super.call(this, url, pipeline) || this; + _this._containerName = _this.getContainerNameFromUrl(); + _this.containerContext = new Container(_this.storageClientContext); + return _this; + } + Object.defineProperty(ContainerClient.prototype, "containerName", { + /** + * The name of the container. + */ + get: function () { + return this._containerName; + }, + enumerable: false, + configurable: true + }); + /** + * Creates a new container under the specified account. If the container with + * the same name already exists, the operation fails. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container + * + * @param {ContainerCreateOptions} [options] Options to Container Create operation. + * @returns {Promise} + * @memberof ContainerClient + * + * Example usage: + * + * ```js + * const containerClient = blobServiceClient.getContainerClient(""); + * const createContainerResponse = await containerClient.create(); + * console.log("Container was created successfully", createContainerResponse.requestId); + * ``` + */ + ContainerClient.prototype.create = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_50; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("ContainerClient-create", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.create(tslib.__assign(tslib.__assign({}, options), { spanOptions: spanOptions }))]; + case 2: + // Spread operator in destructuring assignments, + // this will filter out unwanted properties from the response object into result object + return [2 /*return*/, _b.sent()]; + case 3: + e_50 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_50.message + }); + throw e_50; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Creates a new container under the specified account. If the container with + * the same name already exists, it is not changed. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container + * + * @param {ContainerCreateOptions} [options] + * @returns {Promise} + * @memberof ContainerClient + */ + ContainerClient.prototype.createIfNotExists = function (options) { + var _a, _b; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _c, span, spanOptions, res, e_51; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _c = createSpan("ContainerClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; + _d.label = 1; + case 1: + _d.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.create(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + res = _d.sent(); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + })]; + case 3: + e_51 = _d.sent(); + if (((_a = e_51.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { + span.setStatus({ + code: api.CanonicalCode.ALREADY_EXISTS, + message: "Expected exception when creating a container only if it does not already exist." + }); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_51.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_51.response })]; + } + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_51.message + }); + throw e_51; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns true if the Azure container resource represented by this client exists; false otherwise. + * + * NOTE: use this function with care since an existing container might be deleted by other clients or + * applications. Vice versa new containers with the same name might be added by other clients or + * applications after this function completes. + * + * @param {ContainerExistsOptions} [options={}] + * @returns {Promise} + * @memberof ContainerClient + */ + ContainerClient.prototype.exists = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_52; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("ContainerClient-exists", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.getProperties({ + abortSignal: options.abortSignal, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; + case 2: + _b.sent(); + return [2 /*return*/, true]; + case 3: + e_52 = _b.sent(); + if (e_52.statusCode === 404) { + span.setStatus({ + code: api.CanonicalCode.NOT_FOUND, + message: "Expected exception when checking container existence" + }); + return [2 /*return*/, false]; + } + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_52.message + }); + throw e_52; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Creates a {@link BlobClient} + * + * @param {string} blobName A blob name + * @returns {BlobClient} A new BlobClient object for the given blob name. + * @memberof ContainerClient + */ + ContainerClient.prototype.getBlobClient = function (blobName) { + return new BlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + }; + /** + * Creates an {@link AppendBlobClient} + * + * @param {string} blobName An append blob name + * @returns {AppendBlobClient} + * @memberof ContainerClient + */ + ContainerClient.prototype.getAppendBlobClient = function (blobName) { + return new AppendBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + }; + /** + * Creates a {@link BlockBlobClient} + * + * @param {string} blobName A block blob name + * @returns {BlockBlobClient} + * @memberof ContainerClient + * + * Example usage: + * + * ```js + * const content = "Hello world!"; + * + * const blockBlobClient = containerClient.getBlockBlobClient(""); + * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); + * ``` + */ + ContainerClient.prototype.getBlockBlobClient = function (blobName) { + return new BlockBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + }; + /** + * Creates a {@link PageBlobClient} + * + * @param {string} blobName A page blob name + * @returns {PageBlobClient} + * @memberof ContainerClient + */ + ContainerClient.prototype.getPageBlobClient = function (blobName) { + return new PageBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + }; + /** + * Returns all user-defined metadata and system properties for the specified + * container. The data returned does not include the container's list of blobs. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-properties + * + * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if + * they originally contained uppercase characters. This differs from the metadata keys returned by + * the `listContainers` method of {@link BlobServiceClient} using the `includeMetadata` option, which + * will retain their original casing. + * + * @param {ContainerGetPropertiesOptions} [options] Options to Container Get Properties operation. + * @returns {Promise} + * @memberof ContainerClient + */ + ContainerClient.prototype.getProperties = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_53; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!options.conditions) { + options.conditions = {}; + } + _a = createSpan("ContainerClient-getProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.getProperties(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal }, options.conditions), { spanOptions: spanOptions }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_53 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_53.message + }); + throw e_53; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Marks the specified container for deletion. The container and any blobs + * contained within it are later deleted during garbage collection. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container + * + * @param {ContainerDeleteMethodOptions} [options] Options to Container Delete operation. + * @returns {Promise} + * @memberof ContainerClient + */ + ContainerClient.prototype.delete = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_54; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!options.conditions) { + options.conditions = {}; + } + _a = createSpan("ContainerClient-delete", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.deleteMethod({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: options.conditions, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_54 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_54.message + }); + throw e_54; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Marks the specified container for deletion if it exists. The container and any blobs + * contained within it are later deleted during garbage collection. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container + * + * @param {ContainerDeleteMethodOptions} [options] Options to Container Delete operation. + * @returns {Promise} + * @memberof ContainerClient + */ + ContainerClient.prototype.deleteIfExists = function (options) { + var _a, _b; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _c, span, spanOptions, res, e_55; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _c = createSpan("ContainerClient-deleteIfExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; + _d.label = 1; + case 1: + _d.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + res = _d.sent(); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + })]; + case 3: + e_55 = _d.sent(); + if (((_a = e_55.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { + span.setStatus({ + code: api.CanonicalCode.NOT_FOUND, + message: "Expected exception when deleting a container only if it exists." + }); + return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_55.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_55.response })]; + } + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_55.message + }); + throw e_55; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Sets one or more user-defined name-value pairs for the specified container. + * + * If no option provided, or no metadata defined in the parameter, the container + * metadata will be removed. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-metadata + * + * @param {Metadata} [metadata] Replace existing metadata with this value. + * If no value provided the existing metadata will be removed. + * @param {ContainerSetMetadataOptions} [options] Options to Container Set Metadata operation. + * @returns {Promise} + * @memberof ContainerClient + */ + ContainerClient.prototype.setMetadata = function (metadata, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_56; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!options.conditions) { + options.conditions = {}; + } + if (options.conditions.ifUnmodifiedSince) { + throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service"); + } + _a = createSpan("ContainerClient-setMetadata", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.setMetadata({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + metadata: metadata, + modifiedAccessConditions: options.conditions, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_56 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_56.message + }); + throw e_56; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Gets the permissions for the specified container. The permissions indicate + * whether container data may be accessed publicly. + * + * WARNING: JavaScript Date will potentially lose precision when parsing startsOn and expiresOn strings. + * For example, new Date("2018-12-31T03:44:23.8827891Z").toISOString() will get "2018-12-31T03:44:23.882Z". + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-acl + * + * @param {ContainerGetAccessPolicyOptions} [options] Options to Container Get Access Policy operation. + * @returns {Promise} + * @memberof ContainerClient + */ + ContainerClient.prototype.getAccessPolicy = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, response, res, _i, response_1, identifier, accessPolicy, e_57; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!options.conditions) { + options.conditions = {}; + } + _a = createSpan("ContainerClient-getAccessPolicy", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.getAccessPolicy({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + spanOptions: spanOptions + })]; + case 2: + response = _b.sent(); + res = { + _response: response._response, + blobPublicAccess: response.blobPublicAccess, + date: response.date, + etag: response.etag, + errorCode: response.errorCode, + lastModified: response.lastModified, + requestId: response.requestId, + clientRequestId: response.clientRequestId, + signedIdentifiers: [], + version: response.version + }; + for (_i = 0, response_1 = response; _i < response_1.length; _i++) { + identifier = response_1[_i]; + accessPolicy = undefined; + if (identifier.accessPolicy) { + accessPolicy = { + permissions: identifier.accessPolicy.permissions + }; + if (identifier.accessPolicy.expiresOn) { + accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); + } + if (identifier.accessPolicy.startsOn) { + accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); + } + } + res.signedIdentifiers.push({ + accessPolicy: accessPolicy, + id: identifier.id + }); + } + return [2 /*return*/, res]; + case 3: + e_57 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_57.message + }); + throw e_57; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Sets the permissions for the specified container. The permissions indicate + * whether blobs in a container may be accessed publicly. + * + * When you set permissions for a container, the existing permissions are replaced. + * If no access or containerAcl provided, the existing container ACL will be + * removed. + * + * When you establish a stored access policy on a container, it may take up to 30 seconds to take effect. + * During this interval, a shared access signature that is associated with the stored access policy will + * fail with status code 403 (Forbidden), until the access policy becomes active. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-acl + * + * @param {PublicAccessType} [access] The level of public access to data in the container. + * @param {SignedIdentifier[]} [containerAcl] Array of elements each having a unique Id and details of the access policy. + * @param {ContainerSetAccessPolicyOptions} [options] Options to Container Set Access Policy operation. + * @returns {Promise} + * @memberof ContainerClient + */ + ContainerClient.prototype.setAccessPolicy = function (access, containerAcl, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, acl, _i, _b, identifier, e_58; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + _a = createSpan("ContainerClient-setAccessPolicy", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + acl = []; + for (_i = 0, _b = containerAcl || []; _i < _b.length; _i++) { + identifier = _b[_i]; + acl.push({ + accessPolicy: { + expiresOn: identifier.accessPolicy.expiresOn + ? truncatedISO8061Date(identifier.accessPolicy.expiresOn) + : "", + permissions: identifier.accessPolicy.permissions, + startsOn: identifier.accessPolicy.startsOn + ? truncatedISO8061Date(identifier.accessPolicy.startsOn) + : "" + }, + id: identifier.id + }); + } + return [4 /*yield*/, this.containerContext.setAccessPolicy({ + abortSignal: options.abortSignal, + access: access, + containerAcl: acl, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: options.conditions, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _c.sent()]; + case 3: + e_58 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_58.message + }); + throw e_58; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Get a {@link BlobLeaseClient} that manages leases on the container. + * + * @param {string} [proposeLeaseId] Initial proposed lease Id. + * @returns {BlobLeaseClient} A new BlobLeaseClient object for managing leases on the container. + * @memberof ContainerClient + */ + ContainerClient.prototype.getBlobLeaseClient = function (proposeLeaseId) { + return new BlobLeaseClient(this, proposeLeaseId); + }; + /** + * Creates a new block blob, or updates the content of an existing block blob. + * + * Updating an existing block blob overwrites any existing metadata on the blob. + * Partial updates are not supported; the content of the existing blob is + * overwritten with the new content. To perform a partial update of a block blob's, + * use {@link BlockBlobClient.stageBlock} and {@link BlockBlobClient.commitBlockList}. + * + * This is a non-parallel uploading method, please use {@link BlockBlobClient.uploadFile}, + * {@link BlockBlobClient.uploadStream} or {@link BlockBlobClient.uploadBrowserData} for better + * performance with concurrency uploading. + * + * @see https://docs.microsoft.com/rest/api/storageservices/put-blob + * + * @param {string} blobName Name of the block blob to create or update. + * @param {HttpRequestBody} body Blob, string, ArrayBuffer, ArrayBufferView or a function + * which returns a new Readable stream whose offset is from data source beginning. + * @param {number} contentLength Length of body in bytes. Use Buffer.byteLength() to calculate body length for a + * string including non non-Base64/Hex-encoded characters. + * @param {BlockBlobUploadOptions} [options] Options to configure the Block Blob Upload operation. + * @returns {Promise<{ blockBlobClient: BlockBlobClient; response: BlockBlobUploadResponse }>} Block Blob upload response data and the corresponding BlockBlobClient instance. + * @memberof ContainerClient + */ + ContainerClient.prototype.uploadBlockBlob = function (blobName, body, contentLength, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, blockBlobClient, response, e_59; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("ContainerClient-uploadBlockBlob", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + blockBlobClient = this.getBlockBlobClient(blobName); + return [4 /*yield*/, blockBlobClient.upload(body, contentLength, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + response = _b.sent(); + return [2 /*return*/, { + blockBlobClient: blockBlobClient, + response: response + }]; + case 3: + e_59 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_59.message + }); + throw e_59; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Marks the specified blob or snapshot for deletion. The blob is later deleted + * during garbage collection. Note that in order to delete a blob, you must delete + * all of its snapshots. You can delete both at the same time with the Delete + * Blob operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob + * + * @param {string} blobName + * @param {ContainerDeleteBlobOptions} [options] Options to Blob Delete operation. + * @returns {Promise} Block blob deletion response data. + * @memberof ContainerClient + */ + ContainerClient.prototype.deleteBlob = function (blobName, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, blobClient, e_60; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("ContainerClient-deleteBlob", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + blobClient = this.getBlobClient(blobName); + if (options.versionId) { + blobClient = blobClient.withVersion(options.versionId); + } + return [4 /*yield*/, blobClient.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_60 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_60.message + }); + throw e_60; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * listBlobFlatSegment returns a single segment of blobs starting from the + * specified Marker. Use an empty Marker to start enumeration from the beginning. + * After getting a segment, process it, and then call listBlobsFlatSegment again + * (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * + * @param {string} [marker] A string value that identifies the portion of the list to be returned with the next list operation. + * @param {ContainerListBlobsSegmentOptions} [options] Options to Container List Blob Flat Segment operation. + * @returns {Promise} + * @memberof ContainerClient + */ + ContainerClient.prototype.listBlobFlatSegment = function (marker, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, response, wrappedResponse, e_61; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("ContainerClient-listBlobFlatSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.listBlobFlatSegment(tslib.__assign(tslib.__assign({ marker: marker }, options), { spanOptions: spanOptions }))]; + case 2: + response = _b.sent(); + wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, segment: tslib.__assign(tslib.__assign({}, response.segment), { blobItems: response.segment.blobItems.map(function (blobItemInteral) { + var blobItem = tslib.__assign(tslib.__assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); + return blobItem; + }) }) }); + return [2 /*return*/, wrappedResponse]; + case 3: + e_61 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_61.message + }); + throw e_61; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * listBlobHierarchySegment returns a single segment of blobs starting from + * the specified Marker. Use an empty Marker to start enumeration from the + * beginning. After getting a segment, process it, and then call listBlobsHierarchicalSegment + * again (passing the the previously-returned Marker) to get the next segment. + * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs + * + * @param {string} delimiter The character or string used to define the virtual hierarchy + * @param {string} [marker] A string value that identifies the portion of the list to be returned with the next list operation. + * @param {ContainerListBlobsSegmentOptions} [options] Options to Container List Blob Hierarchy Segment operation. + * @returns {Promise} + * @memberof ContainerClient + */ + ContainerClient.prototype.listBlobHierarchySegment = function (delimiter, marker, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, response, wrappedResponse, e_62; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("ContainerClient-listBlobHierarchySegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.containerContext.listBlobHierarchySegment(delimiter, tslib.__assign(tslib.__assign({ marker: marker }, options), { spanOptions: spanOptions }))]; + case 2: + response = _b.sent(); + wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, segment: tslib.__assign(tslib.__assign({}, response.segment), { blobItems: response.segment.blobItems.map(function (blobItemInteral) { + var blobItem = tslib.__assign(tslib.__assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); + return blobItem; + }) }) }); + return [2 /*return*/, wrappedResponse]; + case 3: + e_62 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_62.message + }); + throw e_62; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an AsyncIterableIterator for ContainerListBlobFlatSegmentResponse + * + * @private + * @param {string} [marker] A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the ContinuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. + * @returns {AsyncIterableIterator} + * @memberof ContainerClient + */ + ContainerClient.prototype.listSegments = function (marker, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listSegments_1() { + var listBlobsFlatSegmentResponse; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; + _a.label = 1; + case 1: return [4 /*yield*/, tslib.__await(this.listBlobFlatSegment(marker, options))]; + case 2: + listBlobsFlatSegmentResponse = _a.sent(); + marker = listBlobsFlatSegmentResponse.continuationToken; + return [4 /*yield*/, tslib.__await(listBlobsFlatSegmentResponse)]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; + case 4: return [4 /*yield*/, _a.sent()]; + case 5: + _a.sent(); + _a.label = 6; + case 6: + if (marker) return [3 /*break*/, 1]; + _a.label = 7; + case 7: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an AsyncIterableIterator of {@link BlobItem} objects + * + * @private + * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. + * @returns {AsyncIterableIterator} + * @memberof ContainerClient + */ + ContainerClient.prototype.listItems = function (options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listItems_1() { + var marker, _a, _b, listBlobsFlatSegmentResponse, e_63_1; + var e_63, _c; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _d.trys.push([0, 7, 8, 13]); + _a = tslib.__asyncValues(this.listSegments(marker, options)); + _d.label = 1; + case 1: return [4 /*yield*/, tslib.__await(_a.next())]; + case 2: + if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; + listBlobsFlatSegmentResponse = _b.value; + return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems)))]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; + case 4: + _d.sent(); + _d.label = 5; + case 5: return [3 /*break*/, 1]; + case 6: return [3 /*break*/, 13]; + case 7: + e_63_1 = _d.sent(); + e_63 = { error: e_63_1 }; + return [3 /*break*/, 13]; + case 8: + _d.trys.push([8, , 11, 12]); + if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; + return [4 /*yield*/, tslib.__await(_c.call(_a))]; + case 9: + _d.sent(); + _d.label = 10; + case 10: return [3 /*break*/, 12]; + case 11: + if (e_63) throw e_63.error; + return [7 /*endfinally*/]; + case 12: return [7 /*endfinally*/]; + case 13: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an async iterable iterator to list all the blobs + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the blobs in pages. + * + * Example using `for await` syntax: + * + * ```js + * // Get the containerClient before you run these snippets, + * // Can be obtained from `blobServiceClient.getContainerClient("");` + * let i = 1; + * for await (const blob of containerClient.listBlobsFlat()) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * let iter = containerClient.listBlobsFlat(); + * let blobItem = await iter.next(); + * while (!blobItem.done) { + * console.log(`Blob ${i++}: ${blobItem.value.name}`); + * blobItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of containerClient.listBlobsFlat().byPage({ maxPageSize: 20 })) { + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = containerClient.listBlobsFlat().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 blob names + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * + * // Passing next marker as continuationToken + * + * iterator = containerClient.listBlobsFlat().byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 blob names + * for (const blob of response.segment.blobItems) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * ``` + * + * @param {ContainerListBlobsOptions} [options={}] Options to list blobs. + * @returns {PagedAsyncIterableIterator} An asyncIterableIterator that supports paging. + * @memberof ContainerClient + */ + ContainerClient.prototype.listBlobsFlat = function (options) { + var _a; + var _this = this; + if (options === void 0) { options = {}; } + var include = []; + if (options.includeCopy) { + include.push("copy"); + } + if (options.includeDeleted) { + include.push("deleted"); + } + if (options.includeMetadata) { + include.push("metadata"); + } + if (options.includeSnapshots) { + include.push("snapshots"); + } + if (options.includeVersions) { + include.push("versions"); + } + if (options.includeUncommitedBlobs) { + include.push("uncommittedblobs"); + } + if (options.includeTags) { + include.push("tags"); + } + if (options.prefix === "") { + options.prefix = undefined; + } + var updatedOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); + // AsyncIterableIterator to iterate over blobs + var iter = this.listItems(updatedOptions); + return _a = { + /** + * @member {Promise} [next] The next method, part of the iteration protocol + */ + next: function () { + return iter.next(); + } + }, + /** + * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol + */ + _a[Symbol.asyncIterator] = function () { + return this; + }, + /** + * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time + */ + _a.byPage = function (settings) { + if (settings === void 0) { settings = {}; } + return _this.listSegments(settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + }, + _a; + }; + /** + * Returns an AsyncIterableIterator for ContainerListBlobHierarchySegmentResponse + * + * @private + * @param {string} delimiter The character or string used to define the virtual hierarchy + * @param {string} [marker] A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the ContinuationToken value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The ContinuationToken value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. + * @returns {AsyncIterableIterator} + * @memberof ContainerClient + */ + ContainerClient.prototype.listHierarchySegments = function (delimiter, marker, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listHierarchySegments_1() { + var listBlobsHierarchySegmentResponse; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; + _a.label = 1; + case 1: return [4 /*yield*/, tslib.__await(this.listBlobHierarchySegment(delimiter, marker, options))]; + case 2: + listBlobsHierarchySegmentResponse = _a.sent(); + marker = listBlobsHierarchySegmentResponse.continuationToken; + return [4 /*yield*/, tslib.__await(listBlobsHierarchySegmentResponse)]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; + case 4: return [4 /*yield*/, _a.sent()]; + case 5: + _a.sent(); + _a.label = 6; + case 6: + if (marker) return [3 /*break*/, 1]; + _a.label = 7; + case 7: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an AsyncIterableIterator for {@link BlobPrefix} and {@link BlobItem} objects. + * + * @private + * @param {string} delimiter The character or string used to define the virtual hierarchy + * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. + * @returns {AsyncIterableIterator<{ kind: "prefix" } & BlobPrefix | { kind: "blob" } & BlobItem>} + * @memberof ContainerClient + */ + ContainerClient.prototype.listItemsByHierarchy = function (delimiter, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listItemsByHierarchy_1() { + var marker, _a, _b, listBlobsHierarchySegmentResponse, segment, _i, _c, prefix, _d, _e, blob, e_64_1; + var e_64, _f; + return tslib.__generator(this, function (_g) { + switch (_g.label) { + case 0: + _g.trys.push([0, 14, 15, 20]); + _a = tslib.__asyncValues(this.listHierarchySegments(delimiter, marker, options)); + _g.label = 1; + case 1: return [4 /*yield*/, tslib.__await(_a.next())]; + case 2: + if (!(_b = _g.sent(), !_b.done)) return [3 /*break*/, 13]; + listBlobsHierarchySegmentResponse = _b.value; + segment = listBlobsHierarchySegmentResponse.segment; + if (!segment.blobPrefixes) return [3 /*break*/, 7]; + _i = 0, _c = segment.blobPrefixes; + _g.label = 3; + case 3: + if (!(_i < _c.length)) return [3 /*break*/, 7]; + prefix = _c[_i]; + return [4 /*yield*/, tslib.__await(tslib.__assign({ kind: "prefix" }, prefix))]; + case 4: return [4 /*yield*/, _g.sent()]; + case 5: + _g.sent(); + _g.label = 6; + case 6: + _i++; + return [3 /*break*/, 3]; + case 7: + _d = 0, _e = segment.blobItems; + _g.label = 8; + case 8: + if (!(_d < _e.length)) return [3 /*break*/, 12]; + blob = _e[_d]; + return [4 /*yield*/, tslib.__await(tslib.__assign({ kind: "blob" }, blob))]; + case 9: return [4 /*yield*/, _g.sent()]; + case 10: + _g.sent(); + _g.label = 11; + case 11: + _d++; + return [3 /*break*/, 8]; + case 12: return [3 /*break*/, 1]; + case 13: return [3 /*break*/, 20]; + case 14: + e_64_1 = _g.sent(); + e_64 = { error: e_64_1 }; + return [3 /*break*/, 20]; + case 15: + _g.trys.push([15, , 18, 19]); + if (!(_b && !_b.done && (_f = _a.return))) return [3 /*break*/, 17]; + return [4 /*yield*/, tslib.__await(_f.call(_a))]; + case 16: + _g.sent(); + _g.label = 17; + case 17: return [3 /*break*/, 19]; + case 18: + if (e_64) throw e_64.error; + return [7 /*endfinally*/]; + case 19: return [7 /*endfinally*/]; + case 20: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an async iterable iterator to list all the blobs by hierarchy. + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the blobs by hierarchy in pages. + * + * Example using `for await` syntax: + * + * ```js + * for await (const item of containerClient.listBlobsByHierarchy("/")) { + * if (item.kind === "prefix") { + * console.log(`\tBlobPrefix: ${item.name}`); + * } else { + * console.log(`\tBlobItem: name - ${item.name}, last modified - ${item.properties.lastModified}`); + * } + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let iter = containerClient.listBlobsByHierarchy("/", { prefix: "prefix1/" }); + * let entity = await iter.next(); + * while (!entity.done) { + * let item = entity.value; + * if (item.kind === "prefix") { + * console.log(`\tBlobPrefix: ${item.name}`); + * } else { + * console.log(`\tBlobItem: name - ${item.name}, last modified - ${item.properties.lastModified}`); + * } + * entity = await iter.next(); + * } + * ```js + * + * Example using `byPage()`: + * + * ```js + * console.log("Listing blobs by hierarchy by page"); + * for await (const response of containerClient.listBlobsByHierarchy("/").byPage()) { + * const segment = response.segment; + * if (segment.blobPrefixes) { + * for (const prefix of segment.blobPrefixes) { + * console.log(`\tBlobPrefix: ${prefix.name}`); + * } + * } + * for (const blob of response.segment.blobItems) { + * console.log(`\tBlobItem: name - ${blob.name}, last modified - ${blob.properties.lastModified}`); + * } + * } + * ``` + * + * Example using paging with a max page size: + * + * ```js + * console.log("Listing blobs by hierarchy by page, specifying a prefix and a max page size"); + * + * let i = 1; + * for await (const response of containerClient.listBlobsByHierarchy("/", { prefix: "prefix2/sub1/"}).byPage({ maxPageSize: 2 })) { + * console.log(`Page ${i++}`); + * const segment = response.segment; + * + * if (segment.blobPrefixes) { + * for (const prefix of segment.blobPrefixes) { + * console.log(`\tBlobPrefix: ${prefix.name}`); + * } + * } + * + * for (const blob of response.segment.blobItems) { + * console.log(`\tBlobItem: name - ${blob.name}, last modified - ${blob.properties.lastModified}`); + * } + * } + * ``` + * + * @param {string} delimiter The character or string used to define the virtual hierarchy + * @param {ContainerListBlobsOptions} [options={}] Options to list blobs operation. + * @returns {(PagedAsyncIterableIterator< + * { kind: "prefix" } & BlobPrefix | { kind: "blob" } & BlobItem, + * ContainerListBlobHierarchySegmentResponse + * >)} + * @memberof ContainerClient + */ + ContainerClient.prototype.listBlobsByHierarchy = function (delimiter, options) { + var _a; + var _this = this; + if (options === void 0) { options = {}; } + if (delimiter === "") { + throw new RangeError("delimiter should contain one or more characters"); + } + var include = []; + if (options.includeCopy) { + include.push("copy"); + } + if (options.includeDeleted) { + include.push("deleted"); + } + if (options.includeMetadata) { + include.push("metadata"); + } + if (options.includeSnapshots) { + include.push("snapshots"); + } + if (options.includeVersions) { + include.push("versions"); + } + if (options.includeUncommitedBlobs) { + include.push("uncommittedblobs"); + } + if (options.includeTags) { + include.push("tags"); + } + if (options.prefix === "") { + options.prefix = undefined; + } + var updatedOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); + // AsyncIterableIterator to iterate over blob prefixes and blobs + var iter = this.listItemsByHierarchy(delimiter, updatedOptions); + return _a = { + /** + * @member {Promise} [next] The next method, part of the iteration protocol + */ + next: function () { + return tslib.__awaiter(this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + return [2 /*return*/, iter.next()]; + }); + }); + } + }, + /** + * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol + */ + _a[Symbol.asyncIterator] = function () { + return this; + }, + /** + * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time + */ + _a.byPage = function (settings) { + if (settings === void 0) { settings = {}; } + return _this.listHierarchySegments(delimiter, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + }, + _a; + }; + ContainerClient.prototype.getContainerNameFromUrl = function () { + var containerName; + try { + // URL may look like the following + // "https://myaccount.blob.core.windows.net/mycontainer?sasString"; + // "https://myaccount.blob.core.windows.net/mycontainer"; + // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername` + // http://localhost:10001/devstoreaccount1/containername + var parsedUrl = coreHttp.URLBuilder.parse(this.url); + if (parsedUrl.getHost().split(".")[1] === "blob") { + // "https://myaccount.blob.core.windows.net/containername". + // "https://customdomain.com/containername". + // .getPath() -> /containername + containerName = parsedUrl.getPath().split("/")[1]; + } + else if (isIpEndpointStyle(parsedUrl)) { + // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername + // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername + // .getPath() -> /devstoreaccount1/containername + containerName = parsedUrl.getPath().split("/")[2]; + } + else { + // "https://customdomain.com/containername". + // .getPath() -> /containername + containerName = parsedUrl.getPath().split("/")[1]; + } + // decode the encoded containerName - to get all the special characters that might be present in it + containerName = decodeURIComponent(containerName); + if (!containerName) { + throw new Error("Provided containerName is invalid."); + } + return containerName; + } + catch (error) { + throw new Error("Unable to extract containerName with provided information."); + } + }; + return ContainerClient; +}(StorageClient)); + +function getBodyAsText(batchResponse) { + return tslib.__awaiter(this, void 0, void 0, function () { + var buffer, responseLength; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + buffer = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); + return [4 /*yield*/, streamToBuffer2(batchResponse.readableStreamBody, buffer)]; + case 1: + responseLength = _a.sent(); + // Slice the buffer to trim the empty ending. + buffer = buffer.slice(0, responseLength); + return [2 /*return*/, buffer.toString()]; + } + }); + }); +} +function utf8ByteLength(str) { + return Buffer.byteLength(str); +} + +var HTTP_HEADER_DELIMITER = ": "; +var SPACE_DELIMITER = " "; +var NOT_FOUND = -1; +/** + * Util class for parsing batch response. + */ +var BatchResponseParser = /** @class */ (function () { + function BatchResponseParser(batchResponse, subRequests) { + if (!batchResponse || !batchResponse.contentType) { + // In special case(reported), server may return invalid content-type which could not be parsed. + throw new RangeError("batchResponse is malformed or doesn't contain valid content-type."); + } + if (!subRequests || subRequests.size === 0) { + // This should be prevent during coding. + throw new RangeError("Invalid state: subRequests is not provided or size is 0."); + } + this.batchResponse = batchResponse; + this.subRequests = subRequests; + this.responseBatchBoundary = this.batchResponse.contentType.split("=")[1]; + this.perResponsePrefix = "--" + this.responseBatchBoundary + HTTP_LINE_ENDING; + this.batchResponseEnding = "--" + this.responseBatchBoundary + "--"; + } + // For example of response, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#response + BatchResponseParser.prototype.parseBatchResponse = function () { + return tslib.__awaiter(this, void 0, void 0, function () { + var responseBodyAsText, subResponses, subResponseCount, deserializedSubResponses, subResponsesSucceededCount, subResponsesFailedCount, index, subResponse, deserializedSubResponse, responseLines, subRespHeaderStartFound, subRespHeaderEndFound, subRespFailed, contentId, _i, responseLines_1, responseLine, tokens, tokens; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + // When logic reach here, suppose batch request has already succeeded with 202, so we can further parse + // sub request's response. + if (this.batchResponse._response.status != HTTPURLConnection.HTTP_ACCEPTED) { + throw new Error("Invalid state: batch request failed with status: '" + this.batchResponse._response.status + "'."); + } + return [4 /*yield*/, getBodyAsText(this.batchResponse)]; + case 1: + responseBodyAsText = _a.sent(); + subResponses = responseBodyAsText + .split(this.batchResponseEnding)[0] // string after ending is useless + .split(this.perResponsePrefix) + .slice(1); + subResponseCount = subResponses.length; + // Defensive coding in case of potential error parsing. + // Note: subResponseCount == 1 is special case where sub request is invalid. + // We try to prevent such cases through early validation, e.g. validate sub request count >= 1. + // While in unexpected sub request invalid case, we allow sub response to be parsed and return to user. + if (subResponseCount != this.subRequests.size && subResponseCount != 1) { + throw new Error("Invalid state: sub responses' count is not equal to sub requests' count."); + } + deserializedSubResponses = new Array(subResponseCount); + subResponsesSucceededCount = 0; + subResponsesFailedCount = 0; + // Parse sub subResponses. + for (index = 0; index < subResponseCount; index++) { + subResponse = subResponses[index]; + deserializedSubResponses[index] = {}; + deserializedSubResponse = deserializedSubResponses[index]; + deserializedSubResponse.headers = new coreHttp.HttpHeaders(); + responseLines = subResponse.split("" + HTTP_LINE_ENDING); + subRespHeaderStartFound = false; + subRespHeaderEndFound = false; + subRespFailed = false; + contentId = NOT_FOUND; + for (_i = 0, responseLines_1 = responseLines; _i < responseLines_1.length; _i++) { + responseLine = responseLines_1[_i]; + if (!subRespHeaderStartFound) { + // Convention line to indicate content ID + if (responseLine.startsWith(HeaderConstants.CONTENT_ID)) { + contentId = parseInt(responseLine.split(HTTP_HEADER_DELIMITER)[1]); + } + // Http version line with status code indicates the start of sub request's response. + // Example: HTTP/1.1 202 Accepted + if (responseLine.startsWith(HTTP_VERSION_1_1)) { + subRespHeaderStartFound = true; + tokens = responseLine.split(SPACE_DELIMITER); + deserializedSubResponse.status = parseInt(tokens[1]); + deserializedSubResponse.statusMessage = tokens.slice(2).join(SPACE_DELIMITER); + } + continue; // Skip convention headers not specifically for sub request i.e. Content-Type: application/http and Content-ID: * + } + if (responseLine.trim() === "") { + // Sub response's header start line already found, and the first empty line indicates header end line found. + if (!subRespHeaderEndFound) { + subRespHeaderEndFound = true; + } + continue; // Skip empty line + } + // Note: when code reach here, it indicates subRespHeaderStartFound == true + if (!subRespHeaderEndFound) { + if (responseLine.indexOf(HTTP_HEADER_DELIMITER) === -1) { + // Defensive coding to prevent from missing valuable lines. + throw new Error("Invalid state: find non-empty line '" + responseLine + "' without HTTP header delimiter '" + HTTP_HEADER_DELIMITER + "'."); + } + tokens = responseLine.split(HTTP_HEADER_DELIMITER); + deserializedSubResponse.headers.set(tokens[0], tokens[1]); + if (tokens[0] === HeaderConstants.X_MS_ERROR_CODE) { + deserializedSubResponse.errorCode = tokens[1]; + subRespFailed = true; + } + } + else { + // Assemble body of sub response. + if (!deserializedSubResponse.bodyAsText) { + deserializedSubResponse.bodyAsText = ""; + } + deserializedSubResponse.bodyAsText += responseLine; + } + } // Inner for end + if (contentId != NOT_FOUND) { + deserializedSubResponse._request = this.subRequests.get(contentId); + } + if (subRespFailed) { + subResponsesFailedCount++; + } + else { + subResponsesSucceededCount++; + } + } + return [2 /*return*/, { + subResponses: deserializedSubResponses, + subResponsesSucceededCount: subResponsesSucceededCount, + subResponsesFailedCount: subResponsesFailedCount + }]; + } + }); + }); + }; + return BatchResponseParser; +}()); + +var MutexLockStatus; +(function (MutexLockStatus) { + MutexLockStatus[MutexLockStatus["LOCKED"] = 0] = "LOCKED"; + MutexLockStatus[MutexLockStatus["UNLOCKED"] = 1] = "UNLOCKED"; +})(MutexLockStatus || (MutexLockStatus = {})); +/** + * An async mutex lock. + * + * @export + * @class Mutex + */ +var Mutex = /** @class */ (function () { + function Mutex() { + } + /** + * Lock for a specific key. If the lock has been acquired by another customer, then + * will wait until getting the lock. + * + * @static + * @param {string} key lock key + * @returns {Promise} + * @memberof Mutex + */ + Mutex.lock = function (key) { + return tslib.__awaiter(this, void 0, void 0, function () { + var _this = this; + return tslib.__generator(this, function (_a) { + return [2 /*return*/, new Promise(function (resolve) { + if (_this.keys[key] === undefined || _this.keys[key] === MutexLockStatus.UNLOCKED) { + _this.keys[key] = MutexLockStatus.LOCKED; + resolve(); + } + else { + _this.onUnlockEvent(key, function () { + _this.keys[key] = MutexLockStatus.LOCKED; + resolve(); + }); + } + })]; + }); + }); + }; + /** + * Unlock a key. + * + * @static + * @param {string} key + * @returns {Promise} + * @memberof Mutex + */ + Mutex.unlock = function (key) { + return tslib.__awaiter(this, void 0, void 0, function () { + var _this = this; + return tslib.__generator(this, function (_a) { + return [2 /*return*/, new Promise(function (resolve) { + if (_this.keys[key] === MutexLockStatus.LOCKED) { + _this.emitUnlockEvent(key); + } + delete _this.keys[key]; + resolve(); + })]; + }); + }); + }; + Mutex.onUnlockEvent = function (key, handler) { + if (this.listeners[key] === undefined) { + this.listeners[key] = [handler]; + } + else { + this.listeners[key].push(handler); + } + }; + Mutex.emitUnlockEvent = function (key) { + var _this = this; + if (this.listeners[key] !== undefined && this.listeners[key].length > 0) { + var handler_1 = this.listeners[key].shift(); + setImmediate(function () { + handler_1.call(_this); + }); + } + }; + Mutex.keys = {}; + Mutex.listeners = {}; + return Mutex; +}()); + +/** + * A BlobBatch represents an aggregated set of operations on blobs. + * Currently, only `delete` and `setAccessTier` are supported. + * + * @export + * @class BlobBatch + */ +var BlobBatch = /** @class */ (function () { + function BlobBatch() { + this.batch = "batch"; + this.batchRequest = new InnerBatchRequest(); + } + /** + * Get the value of Content-Type for a batch request. + * The value must be multipart/mixed with a batch boundary. + * Example: multipart/mixed; boundary=batch_a81786c8-e301-4e42-a729-a32ca24ae252 + */ + BlobBatch.prototype.getMultiPartContentType = function () { + return this.batchRequest.getMultipartContentType(); + }; + /** + * Get assembled HTTP request body for sub requests. + */ + BlobBatch.prototype.getHttpRequestBody = function () { + return this.batchRequest.getHttpRequestBody(); + }; + /** + * Get sub requests that are added into the batch request. + */ + BlobBatch.prototype.getSubRequests = function () { + return this.batchRequest.getSubRequests(); + }; + BlobBatch.prototype.addSubRequestInternal = function (subRequest, assembleSubRequestFunc) { + return tslib.__awaiter(this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Mutex.lock(this.batch)]; + case 1: + _a.sent(); + _a.label = 2; + case 2: + _a.trys.push([2, , 4, 6]); + this.batchRequest.preAddSubRequest(subRequest); + return [4 /*yield*/, assembleSubRequestFunc()]; + case 3: + _a.sent(); + this.batchRequest.postAddSubRequest(subRequest); + return [3 /*break*/, 6]; + case 4: return [4 /*yield*/, Mutex.unlock(this.batch)]; + case 5: + _a.sent(); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); + }); + }; + BlobBatch.prototype.setBatchType = function (batchType) { + if (!this.batchType) { + this.batchType = batchType; + } + if (this.batchType !== batchType) { + throw new RangeError("BlobBatch only supports one operation type per batch and it already is being used for " + this.batchType + " operations."); + } + }; + BlobBatch.prototype.deleteBlob = function (urlOrBlobClient, credentialOrOptions, options) { + return tslib.__awaiter(this, void 0, void 0, function () { + var url, credential, _a, span, spanOptions, e_1; + var _this = this; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (typeof urlOrBlobClient === "string" && + ((coreHttp.isNode && credentialOrOptions instanceof StorageSharedKeyCredential) || + credentialOrOptions instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrOptions))) { + // First overload + url = urlOrBlobClient; + credential = credentialOrOptions; + } + else if (urlOrBlobClient instanceof BlobClient) { + // Second overload + url = urlOrBlobClient.url; + credential = urlOrBlobClient.credential; + options = credentialOrOptions; + } + else { + throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + } + if (!options) { + options = {}; + } + _a = createSpan("BatchDeleteRequest-addSubRequest", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + this.setBatchType("delete"); + return [4 /*yield*/, this.addSubRequestInternal({ + url: url, + credential: credential + }, function () { return tslib.__awaiter(_this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, new BlobClient(url, this.batchRequest.createPipeline(credential)).delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); })]; + case 2: + _b.sent(); + return [3 /*break*/, 5]; + case 3: + e_1 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_1.message + }); + throw e_1; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + BlobBatch.prototype.setBlobAccessTier = function (urlOrBlobClient, credentialOrTier, tierOrOptions, options) { + return tslib.__awaiter(this, void 0, void 0, function () { + var url, credential, tier, _a, span, spanOptions, e_2; + var _this = this; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (typeof urlOrBlobClient === "string" && + ((coreHttp.isNode && credentialOrTier instanceof StorageSharedKeyCredential) || + credentialOrTier instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrTier))) { + // First overload + url = urlOrBlobClient; + credential = credentialOrTier; + tier = tierOrOptions; + } + else if (urlOrBlobClient instanceof BlobClient) { + // Second overload + url = urlOrBlobClient.url; + credential = urlOrBlobClient.credential; + tier = credentialOrTier; + options = tierOrOptions; + } + else { + throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + } + if (!options) { + options = {}; + } + _a = createSpan("BatchSetTierRequest-addSubRequest", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + this.setBatchType("setAccessTier"); + return [4 /*yield*/, this.addSubRequestInternal({ + url: url, + credential: credential + }, function () { return tslib.__awaiter(_this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, new BlobClient(url, this.batchRequest.createPipeline(credential)).setAccessTier(tier, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); })]; + case 2: + _b.sent(); + return [3 /*break*/, 5]; + case 3: + e_2 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_2.message + }); + throw e_2; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + return BlobBatch; +}()); +/** + * Inner batch request class which is responsible for assembling and serializing sub requests. + * See https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#request-body for how requests are assembled. + */ +var InnerBatchRequest = /** @class */ (function () { + function InnerBatchRequest() { + this.operationCount = 0; + this.body = ""; + var tempGuid = coreHttp.generateUuid(); + // batch_{batchid} + this.boundary = "batch_" + tempGuid; + // --batch_{batchid} + // Content-Type: application/http + // Content-Transfer-Encoding: binary + this.subRequestPrefix = "--" + this.boundary + HTTP_LINE_ENDING + HeaderConstants.CONTENT_TYPE + ": application/http" + HTTP_LINE_ENDING + HeaderConstants.CONTENT_TRANSFER_ENCODING + ": binary"; + // multipart/mixed; boundary=batch_{batchid} + this.multipartContentType = "multipart/mixed; boundary=" + this.boundary; + // --batch_{batchid}-- + this.batchRequestEnding = "--" + this.boundary + "--"; + this.subRequests = new Map(); + } + /** + * Create pipeline to assemble sub requests. The idea here is to use existing + * credential and serialization/deserialization components, with additional policies to + * filter unnecessary headers, assemble sub requests into request's body + * and intercept request from going to wire. + * @param {StorageSharedKeyCredential | AnonymousCredential | TokenCredential} credential Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the @azure/identity package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. + */ + InnerBatchRequest.prototype.createPipeline = function (credential) { + var isAnonymousCreds = credential instanceof AnonymousCredential; + var policyFactoryLength = 3 + (isAnonymousCreds ? 0 : 1); // [deserializationPolicy, BatchHeaderFilterPolicyFactory, (Optional)Credential, BatchRequestAssemblePolicyFactory] + var factories = new Array(policyFactoryLength); + factories[0] = coreHttp.deserializationPolicy(); // Default deserializationPolicy is provided by protocol layer + factories[1] = new BatchHeaderFilterPolicyFactory(); // Use batch header filter policy to exclude unnecessary headers + if (!isAnonymousCreds) { + factories[2] = coreHttp.isTokenCredential(credential) + ? coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes) + : credential; + } + factories[policyFactoryLength - 1] = new BatchRequestAssemblePolicyFactory(this); // Use batch assemble policy to assemble request and intercept request from going to wire + return new Pipeline(factories, {}); + }; + InnerBatchRequest.prototype.appendSubRequestToBody = function (request) { + // Start to assemble sub request + this.body += [ + this.subRequestPrefix, + HeaderConstants.CONTENT_ID + ": " + this.operationCount, + "", + request.method.toString() + " " + getURLPathAndQuery(request.url) + " " + HTTP_VERSION_1_1 + HTTP_LINE_ENDING // sub request start line with method + ].join(HTTP_LINE_ENDING); + for (var _i = 0, _a = request.headers.headersArray(); _i < _a.length; _i++) { + var header = _a[_i]; + this.body += header.name + ": " + header.value + HTTP_LINE_ENDING; + } + this.body += HTTP_LINE_ENDING; // sub request's headers need be ending with an empty line + // No body to assemble for current batch request support + // End to assemble sub request + }; + InnerBatchRequest.prototype.preAddSubRequest = function (subRequest) { + if (this.operationCount >= BATCH_MAX_REQUEST) { + throw new RangeError("Cannot exceed " + BATCH_MAX_REQUEST + " sub requests in a single batch"); + } + // Fast fail if url for sub request is invalid + var path = getURLPath(subRequest.url); + if (!path || path == "") { + throw new RangeError("Invalid url for sub request: '" + subRequest.url + "'"); + } + }; + InnerBatchRequest.prototype.postAddSubRequest = function (subRequest) { + this.subRequests.set(this.operationCount, subRequest); + this.operationCount++; + }; + // Return the http request body with assembling the ending line to the sub request body. + InnerBatchRequest.prototype.getHttpRequestBody = function () { + return "" + this.body + this.batchRequestEnding + HTTP_LINE_ENDING; + }; + InnerBatchRequest.prototype.getMultipartContentType = function () { + return this.multipartContentType; + }; + InnerBatchRequest.prototype.getSubRequests = function () { + return this.subRequests; + }; + return InnerBatchRequest; +}()); +var BatchRequestAssemblePolicy = /** @class */ (function (_super) { + tslib.__extends(BatchRequestAssemblePolicy, _super); + function BatchRequestAssemblePolicy(batchRequest, nextPolicy, options) { + var _this = _super.call(this, nextPolicy, options) || this; + _this.dummyResponse = { + request: new coreHttp.WebResource(), + status: 200, + headers: new coreHttp.HttpHeaders() + }; + _this.batchRequest = batchRequest; + return _this; + } + BatchRequestAssemblePolicy.prototype.sendRequest = function (request) { + return tslib.__awaiter(this, void 0, void 0, function () { + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.batchRequest.appendSubRequestToBody(request)]; + case 1: + _a.sent(); + return [2 /*return*/, this.dummyResponse]; // Intercept request from going to wire + } + }); + }); + }; + return BatchRequestAssemblePolicy; +}(coreHttp.BaseRequestPolicy)); +var BatchRequestAssemblePolicyFactory = /** @class */ (function () { + function BatchRequestAssemblePolicyFactory(batchRequest) { + this.batchRequest = batchRequest; + } + BatchRequestAssemblePolicyFactory.prototype.create = function (nextPolicy, options) { + return new BatchRequestAssemblePolicy(this.batchRequest, nextPolicy, options); + }; + return BatchRequestAssemblePolicyFactory; +}()); +var BatchHeaderFilterPolicy = /** @class */ (function (_super) { + tslib.__extends(BatchHeaderFilterPolicy, _super); + function BatchHeaderFilterPolicy(nextPolicy, options) { + return _super.call(this, nextPolicy, options) || this; + } + BatchHeaderFilterPolicy.prototype.sendRequest = function (request) { + return tslib.__awaiter(this, void 0, void 0, function () { + var xMsHeaderName, _i, _a, header; + return tslib.__generator(this, function (_b) { + xMsHeaderName = ""; + for (_i = 0, _a = request.headers.headersArray(); _i < _a.length; _i++) { + header = _a[_i]; + if (iEqual(header.name, HeaderConstants.X_MS_VERSION)) { + xMsHeaderName = header.name; + } + } + if (xMsHeaderName !== "") { + request.headers.remove(xMsHeaderName); // The subrequests should not have the x-ms-version header. + } + return [2 /*return*/, this._nextPolicy.sendRequest(request)]; + }); + }); + }; + return BatchHeaderFilterPolicy; +}(coreHttp.BaseRequestPolicy)); +var BatchHeaderFilterPolicyFactory = /** @class */ (function () { + function BatchHeaderFilterPolicyFactory() { + } + BatchHeaderFilterPolicyFactory.prototype.create = function (nextPolicy, options) { + return new BatchHeaderFilterPolicy(nextPolicy, options); + }; + return BatchHeaderFilterPolicyFactory; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * A BlobBatchClient allows you to make batched requests to the Azure Storage Blob service. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + */ +var BlobBatchClient = /** @class */ (function () { + function BlobBatchClient(url, credentialOrPipeline, options) { + var pipeline; + if (credentialOrPipeline instanceof Pipeline) { + pipeline = credentialOrPipeline; + } + else if (!credentialOrPipeline) { + // no credential provided + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + pipeline = newPipeline(credentialOrPipeline, options); + } + var storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions()); + this._serviceContext = new Service(storageClientContext); + } + /** + * Creates a {@link BlobBatch}. + * A BlobBatch represents an aggregated set of operations on blobs. + */ + BlobBatchClient.prototype.createBatch = function () { + return new BlobBatch(); + }; + BlobBatchClient.prototype.deleteBlobs = function (urlsOrBlobClients, credentialOrOptions, options) { + return tslib.__awaiter(this, void 0, void 0, function () { + var batch, _i, urlsOrBlobClients_1, urlOrBlobClient; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + batch = new BlobBatch(); + _i = 0, urlsOrBlobClients_1 = urlsOrBlobClients; + _a.label = 1; + case 1: + if (!(_i < urlsOrBlobClients_1.length)) return [3 /*break*/, 6]; + urlOrBlobClient = urlsOrBlobClients_1[_i]; + if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; + return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options)]; + case 2: + _a.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions)]; + case 4: + _a.sent(); + _a.label = 5; + case 5: + _i++; + return [3 /*break*/, 1]; + case 6: return [2 /*return*/, this.submitBatch(batch)]; + } + }); + }); + }; + BlobBatchClient.prototype.setBlobsAccessTier = function (urlsOrBlobClients, credentialOrTier, tierOrOptions, options) { + return tslib.__awaiter(this, void 0, void 0, function () { + var batch, _i, urlsOrBlobClients_2, urlOrBlobClient; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + batch = new BlobBatch(); + _i = 0, urlsOrBlobClients_2 = urlsOrBlobClients; + _a.label = 1; + case 1: + if (!(_i < urlsOrBlobClients_2.length)) return [3 /*break*/, 6]; + urlOrBlobClient = urlsOrBlobClients_2[_i]; + if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; + return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options)]; + case 2: + _a.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions)]; + case 4: + _a.sent(); + _a.label = 5; + case 5: + _i++; + return [3 /*break*/, 1]; + case 6: return [2 /*return*/, this.submitBatch(batch)]; + } + }); + }); + }; + /** + * Submit batch request which consists of multiple subrequests. + * + * Get `blobBatchClient` and other details before running the snippets. + * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` + * + * Example usage: + * + * ```js + * let batchRequest = new BlobBatch(); + * await batchRequest.deleteBlob(urlInString0, credential0); + * await batchRequest.deleteBlob(urlInString1, credential1, { + * deleteSnapshots: "include" + * }); + * const batchResp = await blobBatchClient.submitBatch(batchRequest); + * console.log(batchResp.subResponsesSucceededCount); + * ``` + * + * Example using a lease: + * + * ```js + * let batchRequest = new BlobBatch(); + * await batchRequest.setBlobAccessTier(blockBlobClient0, "Cool"); + * await batchRequest.setBlobAccessTier(blockBlobClient1, "Cool", { + * conditions: { leaseId: leaseId } + * }); + * const batchResp = await blobBatchClient.submitBatch(batchRequest); + * console.log(batchResp.subResponsesSucceededCount); + * ``` + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * + * @param {BlobBatch} batchRequest A set of Delete or SetTier operations. + * @param {BlobBatchSubmitBatchOptionalParams} [options] + * @returns {Promise} + * @memberof BlobBatchClient + */ + BlobBatchClient.prototype.submitBatch = function (batchRequest, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, batchRequestBody, rawBatchResponse, batchResponseParser, responseSummary, res, e_1; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!batchRequest || batchRequest.getSubRequests().size == 0) { + throw new RangeError("Batch request should contain one or more sub requests."); + } + _a = createSpan("BlobBatchClient-submitBatch", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 4, 5, 6]); + batchRequestBody = batchRequest.getHttpRequestBody(); + return [4 /*yield*/, this._serviceContext.submitBatch(batchRequestBody, utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), tslib.__assign(tslib.__assign({}, options), { spanOptions: spanOptions }))]; + case 2: + rawBatchResponse = _b.sent(); + batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); + return [4 /*yield*/, batchResponseParser.parseBatchResponse()]; + case 3: + responseSummary = _b.sent(); + res = { + _response: rawBatchResponse._response, + contentType: rawBatchResponse.contentType, + errorCode: rawBatchResponse.errorCode, + requestId: rawBatchResponse.requestId, + clientRequestId: rawBatchResponse.clientRequestId, + version: rawBatchResponse.version, + subResponses: responseSummary.subResponses, + subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, + subResponsesFailedCount: responseSummary.subResponsesFailedCount + }; + return [2 /*return*/, res]; + case 4: + e_1 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_1.message + }); + throw e_1; + case 5: + span.end(); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); + }); + }; + return BlobBatchClient; +}()); + +/** + * A BlobServiceClient represents a Client to the Azure Storage Blob service allowing you + * to manipulate blob containers. + * + * @export + * @class BlobServiceClient + */ +var BlobServiceClient = /** @class */ (function (_super) { + tslib.__extends(BlobServiceClient, _super); + function BlobServiceClient(url, credentialOrPipeline, options) { + var _this = this; + var pipeline; + if (credentialOrPipeline instanceof Pipeline) { + pipeline = credentialOrPipeline; + } + else if ((coreHttp.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential) || + credentialOrPipeline instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipeline)) { + pipeline = newPipeline(credentialOrPipeline, options); + } + else { + // The second parameter is undefined. Use anonymous credential + pipeline = newPipeline(new AnonymousCredential(), options); + } + _this = _super.call(this, url, pipeline) || this; + _this.serviceContext = new Service(_this.storageClientContext); + return _this; + } + /** + * + * Creates an instance of BlobServiceClient from connection string. + * + * @param {string} connectionString Account connection string or a SAS connection string of an Azure storage account. + * [ Note - Account connection string can only be used in NODE.JS runtime. ] + * Account connection string example - + * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net` + * SAS connection string example - + * `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString` + * @param {StoragePipelineOptions} [options] Optional. Options to configure the HTTP pipeline. + * @memberof BlobServiceClient + */ + BlobServiceClient.fromConnectionString = function (connectionString, options) { + options = options || {}; + var extractedCreds = extractConnectionStringParts(connectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + var pipeline = newPipeline(sharedKeyCredential, options); + return new BlobServiceClient(extractedCreds.url, pipeline); + } + } + else if (extractedCreds.kind === "SASConnString") { + var pipeline = newPipeline(new AnonymousCredential(), options); + return new BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + }; + /** + * Creates a {@link ContainerClient} object + * + * @param {string} containerName A container name + * @returns {ContainerClient} A new ContainerClient object for the given container name. + * @memberof BlobServiceClient + * + * Example usage: + * + * ```js + * const containerClient = blobServiceClient.getContainerClient(""); + * ``` + */ + BlobServiceClient.prototype.getContainerClient = function (containerName) { + return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); + }; + /** + * Create a Blob container. + * + * @param {string} containerName Name of the container to create. + * @param {ContainerCreateOptions} [options] Options to configure Container Create operation. + * @returns {Promise<{ containerClient: ContainerClient; containerCreateResponse: ContainerCreateResponse }>} Container creation response and the corresponding container client. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.createContainer = function (containerName, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, containerClient, containerCreateResponse, e_1; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-createContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + containerClient = this.getContainerClient(containerName); + return [4 /*yield*/, containerClient.create(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + containerCreateResponse = _b.sent(); + return [2 /*return*/, { + containerClient: containerClient, + containerCreateResponse: containerCreateResponse + }]; + case 3: + e_1 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_1.message + }); + throw e_1; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Deletes a Blob container. + * + * @param {string} containerName Name of the container to delete. + * @param {ContainerDeleteMethodOptions} [options] Options to configure Container Delete operation. + * @returns {Promise} Container deletion response. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.deleteContainer = function (containerName, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, containerClient, e_2; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-deleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + containerClient = this.getContainerClient(containerName); + return [4 /*yield*/, containerClient.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_2 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_2.message + }); + throw e_2; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Gets the properties of a storage account’s Blob service, including properties + * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties + * + * @param {ServiceGetPropertiesOptions} [options] Options to the Service Get Properties operation. + * @returns {Promise} Response data for the Service Get Properties operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.getProperties = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_3; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getProperties({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_3 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_3.message + }); + throw e_3; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Sets properties for a storage account’s Blob service endpoint, including properties + * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties} + * + * @param {BlobServiceProperties} properties + * @param {ServiceSetPropertiesOptions} [options] Options to the Service Set Properties operation. + * @returns {Promise} Response data for the Service Set Properties operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.setProperties = function (properties, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_4; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-setProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.setProperties(properties, { + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_4 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_4.message + }); + throw e_4; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Retrieves statistics related to replication for the Blob service. It is only + * available on the secondary location endpoint when read-access geo-redundant + * replication is enabled for the storage account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats} + * + * @param {ServiceGetStatisticsOptions} [options] Options to the Service Get Statistics operation. + * @returns {Promise} Response data for the Service Get Statistics operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.getStatistics = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_5; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getStatistics", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getStatistics({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_5 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_5.message + }); + throw e_5; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * The Get Account Information operation returns the sku name and account kind + * for the specified account. + * The Get Account Information operation is available on service versions beginning + * with version 2018-03-28. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information + * + * @param {ServiceGetAccountInfoOptions} [options] Options to the Service Get Account Info operation. + * @returns {Promise} Response data for the Service Get Account Info operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.getAccountInfo = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_6; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getAccountInfo", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getAccountInfo({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_6 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_6.message + }); + throw e_6; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns a list of the containers under the specified account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 + * + * @param {string} [marker] A string value that identifies the portion of + * the list of containers to be returned with the next listing operation. The + * operation returns the NextMarker value within the response body if the + * listing operation did not return all containers remaining to be listed + * with the current page. The NextMarker value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceListContainersSegmentOptions} [options] Options to the Service List Container Segment operation. + * @returns {Promise} Response data for the Service List Container Segment operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.listContainersSegment = function (marker, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_7; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-listContainersSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.listContainersSegment(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal, marker: marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include, spanOptions: spanOptions }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_7 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_7.message + }); + throw e_7; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * The Filter Blobs operation enables callers to list blobs across all containers whose tags + * match a given search expression. Filter blobs searches across all containers within a + * storage account but can be scoped within the expression to a single container. + * + * @private + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {string} [marker] A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the NextMarker value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The NextMarker value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. + * @returns {Promise} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.findBlobsByTagsSegment = function (tagFilterSqlExpression, marker, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_8; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-findBlobsByTagsSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.filterBlobs({ + abortSignal: options.abortSignal, + where: tagFilterSqlExpression, + marker: marker, + maxPageSize: options.maxPageSize, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_8 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_8.message + }); + throw e_8; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. + * + * @private + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {string} [marker] A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the NextMarker value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The NextMarker value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.findBlobsByTagsSegments = function (tagFilterSqlExpression, marker, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsSegments_1() { + var response; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!(!!marker || marker === undefined)) return [3 /*break*/, 6]; + _a.label = 1; + case 1: return [4 /*yield*/, tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options))]; + case 2: + response = _a.sent(); + response.blobs = response.blobs || []; + marker = response.continuationToken; + return [4 /*yield*/, tslib.__await(response)]; + case 3: return [4 /*yield*/, _a.sent()]; + case 4: + _a.sent(); + _a.label = 5; + case 5: + if (marker) return [3 /*break*/, 1]; + _a.label = 6; + case 6: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an AsyncIterableIterator for blobs. + * + * @private + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to findBlobsByTagsItems. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.findBlobsByTagsItems = function (tagFilterSqlExpression, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsItems_1() { + var marker, _a, _b, segment, e_9_1; + var e_9, _c; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _d.trys.push([0, 7, 8, 13]); + _a = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)); + _d.label = 1; + case 1: return [4 /*yield*/, tslib.__await(_a.next())]; + case 2: + if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; + segment = _b.value; + return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs)))]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; + case 4: + _d.sent(); + _d.label = 5; + case 5: return [3 /*break*/, 1]; + case 6: return [3 /*break*/, 13]; + case 7: + e_9_1 = _d.sent(); + e_9 = { error: e_9_1 }; + return [3 /*break*/, 13]; + case 8: + _d.trys.push([8, , 11, 12]); + if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; + return [4 /*yield*/, tslib.__await(_c.call(_a))]; + case 9: + _d.sent(); + _d.label = 10; + case 10: return [3 /*break*/, 12]; + case 11: + if (e_9) throw e_9.error; + return [7 /*endfinally*/]; + case 12: return [7 /*endfinally*/]; + case 13: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an async iterable iterator to find all blobs with specified tag + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the blobs in pages. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties + * + * Example using `for await` syntax: + * + * ```js + * let i = 1; + * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) { + * console.log(`Blob ${i++}: ${container.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'"); + * let blobItem = await iter.next(); + * while (!blobItem.done) { + * console.log(`Blob ${i++}: ${blobItem.value.name}`); + * blobItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = blobServiceClient + * .findBlobsByTags("tagkey='tagvalue'") + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * ``` + * + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {ServiceFindBlobByTagsOptions} [options={}] Options to find blobs by tags. + * @returns {PagedAsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.findBlobsByTags = function (tagFilterSqlExpression, options) { + var _a; + var _this = this; + if (options === void 0) { options = {}; } + // AsyncIterableIterator to iterate over blobs + var listSegmentOptions = tslib.__assign({}, options); + var iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); + return _a = { + /** + * @member {Promise} [next] The next method, part of the iteration protocol + */ + next: function () { + return iter.next(); + } + }, + /** + * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol + */ + _a[Symbol.asyncIterator] = function () { + return this; + }, + /** + * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time + */ + _a.byPage = function (settings) { + if (settings === void 0) { settings = {}; } + return _this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + }, + _a; + }; + /** + * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses + * + * @private + * @param {string} [marker] A string value that identifies the portion of + * the list of containers to be returned with the next listing operation. The + * operation returns the NextMarker value within the response body if the + * listing operation did not return all containers remaining to be listed + * with the current page. The NextMarker value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.listSegments = function (marker, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listSegments_1() { + var listContainersSegmentResponse; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; + _a.label = 1; + case 1: return [4 /*yield*/, tslib.__await(this.listContainersSegment(marker, options))]; + case 2: + listContainersSegmentResponse = _a.sent(); + listContainersSegmentResponse.containerItems = + listContainersSegmentResponse.containerItems || []; + marker = listContainersSegmentResponse.continuationToken; + return [4 /*yield*/, tslib.__await(listContainersSegmentResponse)]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; + case 4: return [4 /*yield*/, _a.sent()]; + case 5: + _a.sent(); + _a.label = 6; + case 6: + if (marker) return [3 /*break*/, 1]; + _a.label = 7; + case 7: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an AsyncIterableIterator for Container Items + * + * @private + * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.listItems = function (options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listItems_1() { + var marker, _a, _b, segment, e_10_1; + var e_10, _c; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _d.trys.push([0, 7, 8, 13]); + _a = tslib.__asyncValues(this.listSegments(marker, options)); + _d.label = 1; + case 1: return [4 /*yield*/, tslib.__await(_a.next())]; + case 2: + if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; + segment = _b.value; + return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems)))]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; + case 4: + _d.sent(); + _d.label = 5; + case 5: return [3 /*break*/, 1]; + case 6: return [3 /*break*/, 13]; + case 7: + e_10_1 = _d.sent(); + e_10 = { error: e_10_1 }; + return [3 /*break*/, 13]; + case 8: + _d.trys.push([8, , 11, 12]); + if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; + return [4 /*yield*/, tslib.__await(_c.call(_a))]; + case 9: + _d.sent(); + _d.label = 10; + case 10: return [3 /*break*/, 12]; + case 11: + if (e_10) throw e_10.error; + return [7 /*endfinally*/]; + case 12: return [7 /*endfinally*/]; + case 13: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an async iterable iterator to list all the containers + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the containers in pages. + * + * Example using `for await` syntax: + * + * ```js + * let i = 1; + * for await (const container of blobServiceClient.listContainers()) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * const iter = blobServiceClient.listContainers(); + * let containerItem = await iter.next(); + * while (!containerItem.done) { + * console.log(`Container ${i++}: ${containerItem.value.name}`); + * containerItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = blobServiceClient.listContainers().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 container names + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = blobServiceClient + * .listContainers() + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 container names + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * ``` + * + * @param {ServiceListContainersOptions} [options={}] Options to list containers. + * @returns {PagedAsyncIterableIterator} An asyncIterableIterator that supports paging. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.listContainers = function (options) { + var _a; + var _this = this; + if (options === void 0) { options = {}; } + if (options.prefix === "") { + options.prefix = undefined; + } + // AsyncIterableIterator to iterate over containers + var listSegmentOptions = tslib.__assign(tslib.__assign({}, options), (options.includeMetadata ? { include: "metadata" } : {})); + var iter = this.listItems(listSegmentOptions); + return _a = { + /** + * @member {Promise} [next] The next method, part of the iteration protocol + */ + next: function () { + return iter.next(); + } + }, + /** + * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol + */ + _a[Symbol.asyncIterator] = function () { + return this; + }, + /** + * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time + */ + _a.byPage = function (settings) { + if (settings === void 0) { settings = {}; } + return _this.listSegments(settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + }, + _a; + }; + /** + * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). + * + * Retrieves a user delegation key for the Blob service. This is only a valid operation when using + * bearer token authentication. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key + * + * @param {Date} startsOn The start time for the user delegation SAS. Must be within 7 days of the current time + * @param {Date} expiresOn The end time for the user delegation SAS. Must be within 7 days of the current time + * @returns {Promise} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.getUserDelegationKey = function (startsOn, expiresOn, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, response, userDelegationKey, res, e_11; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getUserDelegationKey", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getUserDelegationKey({ + startsOn: truncatedISO8061Date(startsOn, false), + expiresOn: truncatedISO8061Date(expiresOn, false) + }, { + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: + response = _b.sent(); + userDelegationKey = { + signedObjectId: response.signedObjectId, + signedTenantId: response.signedTenantId, + signedStartsOn: new Date(response.signedStartsOn), + signedExpiresOn: new Date(response.signedExpiresOn), + signedService: response.signedService, + signedVersion: response.signedVersion, + value: response.value + }; + res = tslib.__assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); + return [2 /*return*/, res]; + case 3: + e_11 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_11.message + }); + throw e_11; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Creates a BlobBatchClient object to conduct batch operations. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * + * @returns {BlobBatchClient} A new BlobBatchClient object for this service. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.getBlobBatchClient = function () { + return new BlobBatchClient(this.url, this.pipeline); + }; + return BlobServiceClient; +}(StorageClient)); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the permissions granted by an AccountSAS. Setting a value + * to true means that any SAS which uses these permissions will grant permissions for that operation. Once all the + * values are set, this should be serialized with toString and set as the permissions field on an + * {@link AccountSASSignatureValues} object. It is possible to construct the permissions string without this class, but + * the order of the permissions is particular and this class guarantees correctness. + * + * @export + * @class AccountSASPermissions + */ +var AccountSASPermissions = /** @class */ (function () { + function AccountSASPermissions() { + /** + * Permission to read resources and list queues and tables granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.read = false; + /** + * Permission to write resources granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.write = false; + /** + * Permission to create blobs and files granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.delete = false; + /** + * Permission to delete versions granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.deleteVersion = false; + /** + * Permission to list blob containers, blobs, shares, directories, and files granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.list = false; + /** + * Permission to add messages, table entities, and append to blobs granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.add = false; + /** + * Permission to create blobs and files granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.create = false; + /** + * Permissions to update messages and table entities granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.update = false; + /** + * Permission to get and delete messages granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.process = false; + /** + * Specfies Tag access granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.tag = false; + /** + * Permission to filter blobs. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.filter = false; + } + /** + * Parse initializes the AccountSASPermissions fields from a string. + * + * @static + * @param {string} permissions + * @returns {AccountSASPermissions} + * @memberof AccountSASPermissions + */ + AccountSASPermissions.parse = function (permissions) { + var accountSASPermissions = new AccountSASPermissions(); + for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { + var c = permissions_1[_i]; + switch (c) { + case "r": + accountSASPermissions.read = true; + break; + case "w": + accountSASPermissions.write = true; + break; + case "d": + accountSASPermissions.delete = true; + break; + case "x": + accountSASPermissions.deleteVersion = true; + break; + case "l": + accountSASPermissions.list = true; + break; + case "a": + accountSASPermissions.add = true; + break; + case "c": + accountSASPermissions.create = true; + break; + case "u": + accountSASPermissions.update = true; + break; + case "p": + accountSASPermissions.process = true; + break; + case "t": + accountSASPermissions.tag = true; + break; + case "f": + accountSASPermissions.filter = true; + break; + default: + throw new RangeError("Invalid permission character: " + c); + } + } + return accountSASPermissions; + }; + /** + * Produces the SAS permissions string for an Azure Storage account. + * Call this method to set AccountSASSignatureValues Permissions field. + * + * Using this method will guarantee the resource types are in + * an order accepted by the service. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + * + * @returns {string} + * @memberof AccountSASPermissions + */ + AccountSASPermissions.prototype.toString = function () { + // The order of the characters should be as specified here to ensure correctness: + // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + // Use a string array instead of string concatenating += operator for performance + var permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.filter) { + permissions.push("f"); + } + if (this.tag) { + permissions.push("t"); + } + if (this.list) { + permissions.push("l"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.update) { + permissions.push("u"); + } + if (this.process) { + permissions.push("p"); + } + return permissions.join(""); + }; + return AccountSASPermissions; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the resources accessible by an AccountSAS. Setting a value + * to true means that any SAS which uses these permissions will grant access to that resource type. Once all the + * values are set, this should be serialized with toString and set as the resources field on an + * {@link AccountSASSignatureValues} object. It is possible to construct the resources string without this class, but + * the order of the resources is particular and this class guarantees correctness. + * + * @export + * @class AccountSASResourceTypes + */ +var AccountSASResourceTypes = /** @class */ (function () { + function AccountSASResourceTypes() { + /** + * Permission to access service level APIs granted. + * + * @type {boolean} + * @memberof AccountSASResourceTypes + */ + this.service = false; + /** + * Permission to access container level APIs (Blob Containers, Tables, Queues, File Shares) granted. + * + * @type {boolean} + * @memberof AccountSASResourceTypes + */ + this.container = false; + /** + * Permission to access object level APIs (Blobs, Table Entities, Queue Messages, Files) granted. + * + * @type {boolean} + * @memberof AccountSASResourceTypes + */ + this.object = false; + } + /** + * Creates an {@link AccountSASResourceTypes} from the specified resource types string. This method will throw an + * Error if it encounters a character that does not correspond to a valid resource type. + * + * @static + * @param {string} resourceTypes + * @returns {AccountSASResourceTypes} + * @memberof AccountSASResourceTypes + */ + AccountSASResourceTypes.parse = function (resourceTypes) { + var accountSASResourceTypes = new AccountSASResourceTypes(); + for (var _i = 0, resourceTypes_1 = resourceTypes; _i < resourceTypes_1.length; _i++) { + var c = resourceTypes_1[_i]; + switch (c) { + case "s": + accountSASResourceTypes.service = true; + break; + case "c": + accountSASResourceTypes.container = true; + break; + case "o": + accountSASResourceTypes.object = true; + break; + default: + throw new RangeError("Invalid resource type: " + c); + } + } + return accountSASResourceTypes; + }; + /** + * Converts the given resource types to a string. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + * + * @returns {string} + * @memberof AccountSASResourceTypes + */ + AccountSASResourceTypes.prototype.toString = function () { + var resourceTypes = []; + if (this.service) { + resourceTypes.push("s"); + } + if (this.container) { + resourceTypes.push("c"); + } + if (this.object) { + resourceTypes.push("o"); + } + return resourceTypes.join(""); + }; + return AccountSASResourceTypes; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the services accessible by an AccountSAS. Setting a value + * to true means that any SAS which uses these permissions will grant access to that service. Once all the + * values are set, this should be serialized with toString and set as the services field on an + * {@link AccountSASSignatureValues} object. It is possible to construct the services string without this class, but + * the order of the services is particular and this class guarantees correctness. + * + * @export + * @class AccountSASServices + */ +var AccountSASServices = /** @class */ (function () { + function AccountSASServices() { + /** + * Permission to access blob resources granted. + * + * @type {boolean} + * @memberof AccountSASServices + */ + this.blob = false; + /** + * Permission to access file resources granted. + * + * @type {boolean} + * @memberof AccountSASServices + */ + this.file = false; + /** + * Permission to access queue resources granted. + * + * @type {boolean} + * @memberof AccountSASServices + */ + this.queue = false; + /** + * Permission to access table resources granted. + * + * @type {boolean} + * @memberof AccountSASServices + */ + this.table = false; + } + /** + * Creates an {@link AccountSASServices} from the specified services string. This method will throw an + * Error if it encounters a character that does not correspond to a valid service. + * + * @static + * @param {string} services + * @returns {AccountSASServices} + * @memberof AccountSASServices + */ + AccountSASServices.parse = function (services) { + var accountSASServices = new AccountSASServices(); + for (var _i = 0, services_1 = services; _i < services_1.length; _i++) { + var c = services_1[_i]; + switch (c) { + case "b": + accountSASServices.blob = true; + break; + case "f": + accountSASServices.file = true; + break; + case "q": + accountSASServices.queue = true; + break; + case "t": + accountSASServices.table = true; + break; + default: + throw new RangeError("Invalid service character: " + c); + } + } + return accountSASServices; + }; + /** + * Converts the given services to a string. + * + * @returns {string} + * @memberof AccountSASServices + */ + AccountSASServices.prototype.toString = function () { + var services = []; + if (this.blob) { + services.push("b"); + } + if (this.table) { + services.push("t"); + } + if (this.queue) { + services.push("q"); + } + if (this.file) { + services.push("f"); + } + return services.join(""); + }; + return AccountSASServices; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * Generate SasIPRange format string. For example: + * + * "8.8.8.8" or "1.1.1.1-255.255.255.255" + * + * @export + * @param {SasIPRange} ipRange + * @returns {string} + */ +function ipRangeToString(ipRange) { + return ipRange.end ? ipRange.start + "-" + ipRange.end : ipRange.start; +} + +// Copyright (c) Microsoft Corporation. All rights reserved. +(function (SASProtocol) { + /** + * Protocol that allows HTTPS only + */ + SASProtocol["Https"] = "https"; + /** + * Protocol that allows both HTTPS and HTTP + */ + SASProtocol["HttpsAndHttp"] = "https,http"; +})(exports.SASProtocol || (exports.SASProtocol = {})); +/** + * Represents the components that make up an Azure Storage SAS' query parameters. This type is not constructed directly + * by the user; it is only generated by the {@link AccountSASSignatureValues} and {@link BlobSASSignatureValues} + * types. Once generated, it can be encoded into a {@code String} and appended to a URL directly (though caution should + * be taken here in case there are existing query parameters, which might affect the appropriate means of appending + * these query parameters). + * + * NOTE: Instances of this class are immutable. + * + * @export + * @class SASQueryParameters + */ +var SASQueryParameters = /** @class */ (function () { + /** + * Creates an instance of SASQueryParameters. + * + * @param {string} version Representing the storage version + * @param {string} signature Representing the signature for the SAS token + * @param {string} [permissions] Representing the storage permissions + * @param {string} [services] Representing the storage services being accessed (only for Account SAS) + * @param {string} [resourceTypes] Representing the storage resource types being accessed (only for Account SAS) + * @param {SASProtocol} [protocol] Representing the allowed HTTP protocol(s) + * @param {Date} [startsOn] Representing the start time for this SAS token + * @param {Date} [expiresOn] Representing the expiry time for this SAS token + * @param {SasIPRange} [ipRange] Representing the range of valid IP addresses for this SAS token + * @param {string} [identifier] Representing the signed identifier (only for Service SAS) + * @param {string} [resource] Representing the storage container or blob (only for Service SAS) + * @param {string} [cacheControl] Representing the cache-control header (only for Blob/File Service SAS) + * @param {string} [contentDisposition] Representing the content-disposition header (only for Blob/File Service SAS) + * @param {string} [contentEncoding] Representing the content-encoding header (only for Blob/File Service SAS) + * @param {string} [contentLanguage] Representing the content-language header (only for Blob/File Service SAS) + * @param {string} [contentType] Representing the content-type header (only for Blob/File Service SAS) + * @param {userDelegationKey} [userDelegationKey] Representing the user delegation key properties + * @memberof SASQueryParameters + */ + function SASQueryParameters(version, signature, permissions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, userDelegationKey) { + this.version = version; + this.services = services; + this.resourceTypes = resourceTypes; + this.expiresOn = expiresOn; + this.permissions = permissions; + this.protocol = protocol; + this.startsOn = startsOn; + this.ipRangeInner = ipRange; + this.identifier = identifier; + this.resource = resource; + this.signature = signature; + this.cacheControl = cacheControl; + this.contentDisposition = contentDisposition; + this.contentEncoding = contentEncoding; + this.contentLanguage = contentLanguage; + this.contentType = contentType; + if (userDelegationKey) { + this.signedOid = userDelegationKey.signedObjectId; + this.signedTenantId = userDelegationKey.signedTenantId; + this.signedStartsOn = userDelegationKey.signedStartsOn; + this.signedExpiresOn = userDelegationKey.signedExpiresOn; + this.signedService = userDelegationKey.signedService; + this.signedVersion = userDelegationKey.signedVersion; + } + } + Object.defineProperty(SASQueryParameters.prototype, "ipRange", { + /** + * Optional. IP range allowed for this SAS. + * + * @readonly + * @type {(SasIPRange | undefined)} + * @memberof SASQueryParameters + */ + get: function () { + if (this.ipRangeInner) { + return { + end: this.ipRangeInner.end, + start: this.ipRangeInner.start + }; + } + return undefined; + }, + enumerable: false, + configurable: true + }); + /** + * Encodes all SAS query parameters into a string that can be appended to a URL. + * + * @returns {string} + * @memberof SASQueryParameters + */ + SASQueryParameters.prototype.toString = function () { + var params = [ + "sv", + "ss", + "srt", + "spr", + "st", + "se", + "sip", + "si", + "skoid", + "sktid", + "skt", + "ske", + "sks", + "skv", + "sr", + "sp", + "sig", + "rscc", + "rscd", + "rsce", + "rscl", + "rsct" + ]; + var queries = []; + for (var _i = 0, params_1 = params; _i < params_1.length; _i++) { + var param = params_1[_i]; + switch (param) { + case "sv": + this.tryAppendQueryParameter(queries, param, this.version); + break; + case "ss": + this.tryAppendQueryParameter(queries, param, this.services); + break; + case "srt": + this.tryAppendQueryParameter(queries, param, this.resourceTypes); + break; + case "spr": + this.tryAppendQueryParameter(queries, param, this.protocol); + break; + case "st": + this.tryAppendQueryParameter(queries, param, this.startsOn ? truncatedISO8061Date(this.startsOn, false) : undefined); + break; + case "se": + this.tryAppendQueryParameter(queries, param, this.expiresOn ? truncatedISO8061Date(this.expiresOn, false) : undefined); + break; + case "sip": + this.tryAppendQueryParameter(queries, param, this.ipRange ? ipRangeToString(this.ipRange) : undefined); + break; + case "si": + this.tryAppendQueryParameter(queries, param, this.identifier); + break; + case "skoid": // Signed object ID + this.tryAppendQueryParameter(queries, param, this.signedOid); + break; + case "sktid": // Signed tenant ID + this.tryAppendQueryParameter(queries, param, this.signedTenantId); + break; + case "skt": // Signed key start time + this.tryAppendQueryParameter(queries, param, this.signedStartsOn ? truncatedISO8061Date(this.signedStartsOn, false) : undefined); + break; + case "ske": // Signed key expiry time + this.tryAppendQueryParameter(queries, param, this.signedExpiresOn ? truncatedISO8061Date(this.signedExpiresOn, false) : undefined); + break; + case "sks": // Signed key service + this.tryAppendQueryParameter(queries, param, this.signedService); + break; + case "skv": // Signed key version + this.tryAppendQueryParameter(queries, param, this.signedVersion); + break; + case "sr": + this.tryAppendQueryParameter(queries, param, this.resource); + break; + case "sp": + this.tryAppendQueryParameter(queries, param, this.permissions); + break; + case "sig": + this.tryAppendQueryParameter(queries, param, this.signature); + break; + case "rscc": + this.tryAppendQueryParameter(queries, param, this.cacheControl); + break; + case "rscd": + this.tryAppendQueryParameter(queries, param, this.contentDisposition); + break; + case "rsce": + this.tryAppendQueryParameter(queries, param, this.contentEncoding); + break; + case "rscl": + this.tryAppendQueryParameter(queries, param, this.contentLanguage); + break; + case "rsct": + this.tryAppendQueryParameter(queries, param, this.contentType); + break; + } + } + return queries.join("&"); + }; + /** + * A private helper method used to filter and append query key/value pairs into an array. + * + * @private + * @param {string[]} queries + * @param {string} key + * @param {string} [value] + * @returns {void} + * @memberof SASQueryParameters + */ + SASQueryParameters.prototype.tryAppendQueryParameter = function (queries, key, value) { + if (!value) { + return; + } + key = encodeURIComponent(key); + value = encodeURIComponent(value); + if (key.length > 0 && value.length > 0) { + queries.push(key + "=" + value); + } + }; + return SASQueryParameters; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Generates a {@link SASQueryParameters} object which contains all SAS query parameters needed to make an actual + * REST request. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + * + * @param {AccountSASSignatureValues} accountSASSignatureValues + * @param {StorageSharedKeyCredential} sharedKeyCredential + * @returns {SASQueryParameters} + * @memberof AccountSASSignatureValues + */ +function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { + var version = accountSASSignatureValues.version + ? accountSASSignatureValues.version + : SERVICE_VERSION; + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.filter && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); + } + var parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); + var parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); + var parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); + var stringToSign = [ + sharedKeyCredential.accountName, + parsedPermissions, + parsedServices, + parsedResourceTypes, + accountSASSignatureValues.startsOn + ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) + : "", + truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), + accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", + accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", + version, + "" // Account SAS requires an additional newline character + ].join("\n"); + var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange); +} + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a blob. Setting + * a value to true means that any SAS which uses these permissions will grant permissions for that operation. Once all + * the values are set, this should be serialized with toString and set as the permissions field on a + * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but + * the order of the permissions is particular and this class guarantees correctness. + * + * @export + * @class BlobSASPermissions + */ +var BlobSASPermissions = /** @class */ (function () { + function BlobSASPermissions() { + /** + * Specifies Read access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.read = false; + /** + * Specifies Add access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.add = false; + /** + * Specifies Create access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.create = false; + /** + * Specifies Write access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.write = false; + /** + * Specifies Delete access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.delete = false; + /** + * Specifies Delete version access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.deleteVersion = false; + /** + * Specfies Tag access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.tag = false; + } + /** + * Creates a {@link BlobSASPermissions} from the specified permissions string. This method will throw an + * Error if it encounters a character that does not correspond to a valid permission. + * + * @static + * @param {string} permissions + * @returns {BlobSASPermissions} + * @memberof BlobSASPermissions + */ + BlobSASPermissions.parse = function (permissions) { + var blobSASPermissions = new BlobSASPermissions(); + for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { + var char = permissions_1[_i]; + switch (char) { + case "r": + blobSASPermissions.read = true; + break; + case "a": + blobSASPermissions.add = true; + break; + case "c": + blobSASPermissions.create = true; + break; + case "w": + blobSASPermissions.write = true; + break; + case "d": + blobSASPermissions.delete = true; + break; + case "x": + blobSASPermissions.deleteVersion = true; + break; + case "t": + blobSASPermissions.tag = true; + break; + default: + throw new RangeError("Invalid permission: " + char); + } + } + return blobSASPermissions; + }; + /** + * Converts the given permissions to a string. Using this method will guarantee the permissions are in an + * order accepted by the service. + * + * @returns {string} A string which represents the BlobSASPermissions + * @memberof BlobSASPermissions + */ + BlobSASPermissions.prototype.toString = function () { + var permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.tag) { + permissions.push("t"); + } + return permissions.join(""); + }; + return BlobSASPermissions; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a container. + * Setting a value to true means that any SAS which uses these permissions will grant permissions for that operation. + * Once all the values are set, this should be serialized with toString and set as the permissions field on a + * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but + * the order of the permissions is particular and this class guarantees correctness. + * + * @export + * @class ContainerSASPermissions + */ +var ContainerSASPermissions = /** @class */ (function () { + function ContainerSASPermissions() { + /** + * Specifies Read access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.read = false; + /** + * Specifies Add access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.add = false; + /** + * Specifies Create access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.create = false; + /** + * Specifies Write access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.write = false; + /** + * Specifies Delete access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.delete = false; + /** + * Specifies Delete version access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.deleteVersion = false; + /** + * Specifies List access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.list = false; + /** + * Specfies Tag access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.tag = false; + } + /** + * Creates an {@link ContainerSASPermissions} from the specified permissions string. This method will throw an + * Error if it encounters a character that does not correspond to a valid permission. + * + * @static + * @param {string} permissions + * @returns {ContainerSASPermissions} + * @memberof ContainerSASPermissions + */ + ContainerSASPermissions.parse = function (permissions) { + var containerSASPermissions = new ContainerSASPermissions(); + for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { + var char = permissions_1[_i]; + switch (char) { + case "r": + containerSASPermissions.read = true; + break; + case "a": + containerSASPermissions.add = true; + break; + case "c": + containerSASPermissions.create = true; + break; + case "w": + containerSASPermissions.write = true; + break; + case "d": + containerSASPermissions.delete = true; + break; + case "l": + containerSASPermissions.list = true; + break; + case "t": + containerSASPermissions.tag = true; + break; + case "x": + containerSASPermissions.deleteVersion = true; + break; + default: + throw new RangeError("Invalid permission " + char); + } + } + return containerSASPermissions; + }; + /** + * Converts the given permissions to a string. Using this method will guarantee the permissions are in an + * order accepted by the service. + * + * The order of the characters should be as specified here to ensure correctness. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * + * @returns {string} + * @memberof ContainerSASPermissions + */ + ContainerSASPermissions.prototype.toString = function () { + var permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.list) { + permissions.push("l"); + } + if (this.tag) { + permissions.push("t"); + } + return permissions.join(""); + }; + return ContainerSASPermissions; +}()); + +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * UserDelegationKeyCredential is only used for generation of user delegation SAS. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas + * + * @export + * @class UserDelegationKeyCredential + */ +var UserDelegationKeyCredential = /** @class */ (function () { + /** + * Creates an instance of UserDelegationKeyCredential. + * @param {string} accountName + * @param {UserDelegationKey} userDelegationKey + * @memberof UserDelegationKeyCredential + */ + function UserDelegationKeyCredential(accountName, userDelegationKey) { + this.accountName = accountName; + this.userDelegationKey = userDelegationKey; + this.key = Buffer.from(userDelegationKey.value, "base64"); + } + /** + * Generates a hash signature for an HTTP request or for a SAS. + * + * @param {string} stringToSign + * @returns {string} + * @memberof UserDelegationKeyCredential + */ + UserDelegationKeyCredential.prototype.computeHMACSHA256 = function (stringToSign) { + // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`); + return crypto.createHmac("sha256", this.key) + .update(stringToSign, "utf8") + .digest("base64"); + }; + return UserDelegationKeyCredential; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { + var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + var sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential + ? sharedKeyCredentialOrUserDelegationKey + : undefined; + var userDelegationKeyCredential; + if (sharedKeyCredential === undefined && accountName !== undefined) { + userDelegationKeyCredential = new UserDelegationKeyCredential(accountName, sharedKeyCredentialOrUserDelegationKey); + } + if (sharedKeyCredential === undefined && userDelegationKeyCredential === undefined) { + throw TypeError("Invalid sharedKeyCredential, userDelegationKey or accountName."); + } + // Version 2019-12-12 adds support for the blob tags permission. + // Version 2018-11-09 adds support for the signed resource and signed blob snapshot time fields. + // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas#constructing-the-signature-string + if (version >= "2018-11-09") { + if (sharedKeyCredential !== undefined) { + return generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential); + } + else { + return generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential); + } + } + if (version >= "2015-04-05") { + if (sharedKeyCredential !== undefined) { + return generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential); + } + else { + throw new RangeError("'version' must be >= '2018-11-09' when generating user delegation SAS using user delegation key."); + } + } + throw new RangeError("'version' must be >= '2015-04-05'."); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2015-04-05 AND BEFORE 2018-11-09. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn and identifier. + * + * WARNING: When identifier is not provided, permissions and expiresOn are required. + * You MUST assign value to identifier or expiresOn & permissions manually if you initial with + * this constructor. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {StorageSharedKeyCredential} sharedKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential) { + if (!blobSASSignatureValues.identifier && + !blobSASSignatureValues.permissions && + !blobSASSignatureValues.expiresOn) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + } + var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + var resource = "c"; + var verifiedPermissions; + if (blobSASSignatureValues.snapshotTime) { + throw RangeError("'version' must be >= '2018-11-09' when provided 'snapshotTime'."); + } + if (blobSASSignatureValues.versionId) { + throw RangeError("'version' must be >= '2019-10-10' when provided 'versionId'."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + if (blobSASSignatureValues.blobName) { + resource = "b"; + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.identifier, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + version, + blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", + blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", + blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", + blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", + blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" + ].join("\n"); + var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn and identifier. + * + * WARNING: When identifier is not provided, permissions and expiresOn are required. + * You MUST assign value to identifier or expiresOn & permissions manually if you initial with + * this constructor. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {StorageSharedKeyCredential} sharedKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential) { + if (!blobSASSignatureValues.identifier && + !blobSASSignatureValues.permissions && + !blobSASSignatureValues.expiresOn) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + } + var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + var resource = "c"; + var verifiedPermissions; + if (blobSASSignatureValues.versionId && version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'versionId'."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.snapshotTime) { + throw RangeError("Must provide 'blobName' when provided 'snapshotTime'."); + } + if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.versionId) { + throw RangeError("Must provide 'blobName' when provided 'versionId'."); + } + var timestamp = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.identifier, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + version, + resource, + timestamp, + blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", + blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", + blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", + blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", + blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" + ].join("\n"); + var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn and identifier. + * + * WARNING: identifier will be ignored, permissions and expiresOn are required. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {UserDelegationKeyCredential} userDelegationKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential) { + if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); + } + var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + if (blobSASSignatureValues.versionId && version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'versionId'."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + var resource = "c"; + var verifiedPermissions; + if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.snapshotTime) { + throw RangeError("Must provide 'blobName' when provided 'snapshotTime'."); + } + if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.versionId) { + throw RangeError("Must provide 'blobName' when provided 'versionId'."); + } + var timestamp = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + userDelegationKeyCredential.userDelegationKey.signedObjectId, + userDelegationKeyCredential.userDelegationKey.signedTenantId, + userDelegationKeyCredential.userDelegationKey.signedStartsOn + ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) + : "", + userDelegationKeyCredential.userDelegationKey.signedExpiresOn + ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) + : "", + userDelegationKeyCredential.userDelegationKey.signedService, + userDelegationKeyCredential.userDelegationKey.signedVersion, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + version, + resource, + timestamp, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType + ].join("\n"); + var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey); +} +function getCanonicalName(accountName, containerName, blobName) { + // Container: "/blob/account/containerName" + // Blob: "/blob/account/containerName/blobName" + var elements = ["/blob/" + accountName + "/" + containerName]; + if (blobName) { + elements.push("/" + blobName); + } + return elements.join(""); +} + +Object.defineProperty(exports, 'BaseRequestPolicy', { + enumerable: true, + get: function () { + return coreHttp.BaseRequestPolicy; + } +}); +Object.defineProperty(exports, 'HttpHeaders', { + enumerable: true, + get: function () { + return coreHttp.HttpHeaders; + } +}); +Object.defineProperty(exports, 'RequestPolicyOptions', { + enumerable: true, + get: function () { + return coreHttp.RequestPolicyOptions; + } +}); +Object.defineProperty(exports, 'RestError', { + enumerable: true, + get: function () { + return coreHttp.RestError; + } +}); +Object.defineProperty(exports, 'WebResource', { + enumerable: true, + get: function () { + return coreHttp.WebResource; + } +}); +Object.defineProperty(exports, 'deserializationPolicy', { + enumerable: true, + get: function () { + return coreHttp.deserializationPolicy; + } +}); +exports.AccountSASPermissions = AccountSASPermissions; +exports.AccountSASResourceTypes = AccountSASResourceTypes; +exports.AccountSASServices = AccountSASServices; +exports.AnonymousCredential = AnonymousCredential; +exports.AnonymousCredentialPolicy = AnonymousCredentialPolicy; +exports.AppendBlobClient = AppendBlobClient; +exports.BlobBatch = BlobBatch; +exports.BlobBatchClient = BlobBatchClient; +exports.BlobClient = BlobClient; +exports.BlobLeaseClient = BlobLeaseClient; +exports.BlobSASPermissions = BlobSASPermissions; +exports.BlobServiceClient = BlobServiceClient; +exports.BlockBlobClient = BlockBlobClient; +exports.ContainerClient = ContainerClient; +exports.ContainerSASPermissions = ContainerSASPermissions; +exports.Credential = Credential; +exports.CredentialPolicy = CredentialPolicy; +exports.PageBlobClient = PageBlobClient; +exports.Pipeline = Pipeline; +exports.SASQueryParameters = SASQueryParameters; +exports.StorageBrowserPolicy = StorageBrowserPolicy; +exports.StorageBrowserPolicyFactory = StorageBrowserPolicyFactory; +exports.StorageOAuthScopes = StorageOAuthScopes; +exports.StorageRetryPolicy = StorageRetryPolicy; +exports.StorageRetryPolicyFactory = StorageRetryPolicyFactory; +exports.StorageSharedKeyCredential = StorageSharedKeyCredential; +exports.StorageSharedKeyCredentialPolicy = StorageSharedKeyCredentialPolicy; +exports.generateAccountSASQueryParameters = generateAccountSASQueryParameters; +exports.generateBlobSASQueryParameters = generateBlobSASQueryParameters; +exports.logger = logger; +exports.newPipeline = newPipeline; +//# sourceMappingURL=index.js.map + + +/***/ }), +/* 374 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +module.exports = __webpack_require__(990) + + +/***/ }), +/* 375 */, +/* 376 */, +/* 377 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + +module.exports = function(Promise, INTERNAL) { +var util = __webpack_require__(248); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) return obj; + var then = getThen(obj); + if (then === errorObj) { + if (context) context._pushContext(); + var ret = Promise.reject(then.e); + if (context) context._popContext(); + return ret; + } else if (typeof then === "function") { + if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfill, + ret._reject, + undefined, + ret, + null + ); + return ret; + } + return doThenable(obj, then, context); + } + } + return obj; +} + +function doGetThen(obj) { + return obj.then; +} + +function getThen(obj) { + try { + return doGetThen(obj); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + try { + return hasProp.call(obj, "_promise0"); + } catch (e) { + return false; + } +} + +function doThenable(x, then, context) { + var promise = new Promise(INTERNAL); + var ret = promise; + if (context) context._pushContext(); + promise._captureStackTrace(); + if (context) context._popContext(); + var synchronous = true; + var result = util.tryCatch(then).call(x, resolve, reject); + synchronous = false; + + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolve(value) { + if (!promise) return; + promise._resolveCallback(value); + promise = null; + } + + function reject(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + return ret; +} + +return tryConvertToPromise; +}; + + +/***/ }), +/* 378 */, +/* 379 */, +/* 380 */, +/* 381 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +var errcode = __webpack_require__(120); +var retry = __webpack_require__(58); + +var hasOwn = Object.prototype.hasOwnProperty; + +function isRetryError(err) { + return err && err.code === 'EPROMISERETRY' && hasOwn.call(err, 'retried'); +} + +function promiseRetry(fn, options) { + var temp; + var operation; + + if (typeof fn === 'object' && typeof options === 'function') { + // Swap options and fn when using alternate signature (options, fn) + temp = options; + options = fn; + fn = temp; + } + + operation = retry.operation(options); + + return new Promise(function (resolve, reject) { + operation.attempt(function (number) { + Promise.resolve() + .then(function () { + return fn(function (err) { + if (isRetryError(err)) { + err = err.retried; + } + + throw errcode('Retrying', 'EPROMISERETRY', { retried: err }); + }, number); + }) + .then(resolve, function (err) { + if (isRetryError(err)) { + err = err.retried; + + if (operation.retry(err || new Error())) { + return; + } + } + + reject(err); + }); + }); + }); +} + +module.exports = promiseRetry; + + +/***/ }), +/* 382 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +var iconvLite = __webpack_require__(841); + +// Expose to the world +module.exports.convert = convert; + +/** + * Convert encoding of an UTF-8 string or a buffer + * + * @param {String|Buffer} str String to be converted + * @param {String} to Encoding to be converted to + * @param {String} [from='UTF-8'] Encoding to be converted from + * @return {Buffer} Encoded string + */ +function convert(str, to, from) { + from = checkEncoding(from || 'UTF-8'); + to = checkEncoding(to || 'UTF-8'); + str = str || ''; + + var result; + + if (from !== 'UTF-8' && typeof str === 'string') { + str = Buffer.from(str, 'binary'); + } + + if (from === to) { + if (typeof str === 'string') { + result = Buffer.from(str); + } else { + result = str; + } + } else { + try { + result = convertIconvLite(str, to, from); + } catch (E) { + console.error(E); + result = str; + } + } + + if (typeof result === 'string') { + result = Buffer.from(result, 'utf-8'); + } + + return result; +} + +/** + * Convert encoding of astring with iconv-lite + * + * @param {String|Buffer} str String to be converted + * @param {String} to Encoding to be converted to + * @param {String} [from='UTF-8'] Encoding to be converted from + * @return {Buffer} Encoded string + */ +function convertIconvLite(str, to, from) { + if (to === 'UTF-8') { + return iconvLite.decode(str, from); + } else if (from === 'UTF-8') { + return iconvLite.encode(str, to); + } else { + return iconvLite.encode(iconvLite.decode(str, from), to); + } +} + +/** + * Converts charset name if needed + * + * @param {String} name Character set + * @return {String} Character set name + */ +function checkEncoding(name) { + return (name || '') + .toString() + .trim() + .replace(/^latin[\-_]?(\d+)$/i, 'ISO-8859-$1') + .replace(/^win(?:dows)?[\-_]?(\d+)$/i, 'WINDOWS-$1') + .replace(/^utf[\-_]?(\d+)$/i, 'UTF-$1') + .replace(/^ks_c_5601\-1987$/i, 'CP949') + .replace(/^us[\-_]?ascii$/i, 'ASCII') + .toUpperCase(); +} + + +/***/ }), +/* 383 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const assert = __webpack_require__(357); +const path = __webpack_require__(622); +const pathHelper = __webpack_require__(972); +const IS_WINDOWS = process.platform === 'win32'; +/** + * Helper class for parsing paths into segments + */ +class Path { + /** + * Constructs a Path + * @param itemPath Path or array of segments + */ + constructor(itemPath) { + this.segments = []; + // String + if (typeof itemPath === 'string') { + assert(itemPath, `Parameter 'itemPath' must not be empty`); + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + // Not rooted + if (!pathHelper.hasRoot(itemPath)) { + this.segments = itemPath.split(path.sep); + } + // Rooted + else { + // Add all segments, while not at the root + let remaining = itemPath; + let dir = pathHelper.dirname(remaining); + while (dir !== remaining) { + // Add the segment + const basename = path.basename(remaining); + this.segments.unshift(basename); + // Truncate the last segment + remaining = dir; + dir = pathHelper.dirname(remaining); + } + // Remainder is the root + this.segments.unshift(remaining); + } + } + // Array + else { + // Must not be empty + assert(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); + // Each segment + for (let i = 0; i < itemPath.length; i++) { + let segment = itemPath[i]; + // Must not be empty + assert(segment, `Parameter 'itemPath' must not contain any empty segments`); + // Normalize slashes + segment = pathHelper.normalizeSeparators(itemPath[i]); + // Root segment + if (i === 0 && pathHelper.hasRoot(segment)) { + segment = pathHelper.safeTrimTrailingSeparator(segment); + assert(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); + this.segments.push(segment); + } + // All other segments + else { + // Must not contain slash + assert(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); + this.segments.push(segment); + } + } + } + } + /** + * Converts the path to it's string representation + */ + toString() { + // First segment + let result = this.segments[0]; + // All others + let skipSlash = result.endsWith(path.sep) || (IS_WINDOWS && /^[A-Z]:$/i.test(result)); + for (let i = 1; i < this.segments.length; i++) { + if (skipSlash) { + skipSlash = false; + } + else { + result += path.sep; + } + result += this.segments[i]; + } + return result; + } +} +exports.Path = Path; +//# sourceMappingURL=internal-path.js.map + +/***/ }), +/* 384 */ +/***/ (function(module) { + +"use strict"; + + +module.exports.isObjectProto = isObjectProto +function isObjectProto (obj) { + return obj === Object.prototype +} + +const _null = {} +const _undefined = {} +const Bool = Boolean +const Num = Number +const Str = String +const boolCache = { + true: new Bool(true), + false: new Bool(false) +} +const numCache = {} +const strCache = {} + +/* + * Returns a useful dispatch object for value using a process similar to + * the ToObject operation specified in http://es5.github.com/#x9.9 + */ +module.exports.dispatchableObject = dispatchableObject +function dispatchableObject (value) { + // To shut up jshint, which doesn't let me turn off this warning. + const Obj = Object + if (value === null) { return _null } + if (value === undefined) { return _undefined } + switch (typeof value) { + case 'object': return value + case 'boolean': return boolCache[value] + case 'number': return numCache[value] || (numCache[value] = new Num(value)) + case 'string': return strCache[value] || (strCache[value] = new Str(value)) + default: return new Obj(value) + } +} + + +/***/ }), +/* 385 */, +/* 386 */, +/* 387 */ +/***/ (function(module) { + +module.exports = {"name":"node-gyp","description":"Node.js native addon build tool","license":"MIT","keywords":["native","addon","module","c","c++","bindings","gyp"],"version":"5.1.1","installVersion":9,"author":"Nathan Rajlich (http://tootallnate.net)","repository":{"type":"git","url":"git://github.com/nodejs/node-gyp.git"},"preferGlobal":true,"bin":"./bin/node-gyp.js","main":"./lib/node-gyp.js","dependencies":{"env-paths":"^2.2.0","glob":"^7.1.4","graceful-fs":"^4.2.2","mkdirp":"^0.5.1","nopt":"^4.0.1","npmlog":"^4.1.2","request":"^2.88.0","rimraf":"^2.6.3","semver":"^5.7.1","tar":"^4.4.12","which":"^1.3.1"},"engines":{"node":">= 6.0.0"},"devDependencies":{"bindings":"^1.5.0","nan":"^2.14.0","require-inject":"^1.4.4","standard":"^14.3.1","tap":"~12.7.0"},"scripts":{"lint":"standard */*.js test/**/*.js","test":"npm run lint && tap --timeout=120 test/test-*"}}; + +/***/ }), +/* 388 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer') { + module.exports = __webpack_require__(592); +} else { + module.exports = __webpack_require__(161); +} + + +/***/ }), +/* 389 */, +/* 390 */, +/* 391 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +var current = (process.versions && process.versions.node && process.versions.node.split('.')) || []; + +function specifierIncluded(specifier) { + var parts = specifier.split(' '); + var op = parts.length > 1 ? parts[0] : '='; + var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); + + for (var i = 0; i < 3; ++i) { + var cur = Number(current[i] || 0); + var ver = Number(versionParts[i] || 0); + if (cur === ver) { + continue; // eslint-disable-line no-restricted-syntax, no-continue + } + if (op === '<') { + return cur < ver; + } else if (op === '>=') { + return cur >= ver; + } else { + return false; + } + } + return op === '>='; +} + +function matchesRange(range) { + var specifiers = range.split(/ ?&& ?/); + if (specifiers.length === 0) { return false; } + for (var i = 0; i < specifiers.length; ++i) { + if (!specifierIncluded(specifiers[i])) { return false; } + } + return true; +} + +function versionIncluded(specifierValue) { + if (typeof specifierValue === 'boolean') { return specifierValue; } + if (specifierValue && typeof specifierValue === 'object') { + for (var i = 0; i < specifierValue.length; ++i) { + if (matchesRange(specifierValue[i])) { return true; } + } + return false; + } + return matchesRange(specifierValue); +} + +var data = __webpack_require__(656); + +var core = {}; +for (var mod in data) { // eslint-disable-line no-restricted-syntax + if (Object.prototype.hasOwnProperty.call(data, mod)) { + core[mod] = versionIncluded(data[mod]); + } +} +module.exports = core; + + +/***/ }), +/* 392 */, +/* 393 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +const punycode = __webpack_require__(213); +const urlParse = __webpack_require__(835).parse; +const util = __webpack_require__(669); +const pubsuffix = __webpack_require__(562); +const Store = __webpack_require__(338).Store; +const MemoryCookieStore = __webpack_require__(332).MemoryCookieStore; +const pathMatch = __webpack_require__(348).pathMatch; +const VERSION = __webpack_require__(460); +const { fromCallback } = __webpack_require__(147); + +// From RFC6265 S4.1.1 +// note that it excludes \x3B ";" +const COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/; + +const CONTROL_CHARS = /[\x00-\x1F]/; + +// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in +// the "relaxed" mode, see: +// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60 +const TERMINATORS = ["\n", "\r", "\0"]; + +// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"' +// Note ';' is \x3B +const PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/; + +// date-time parsing constants (RFC6265 S5.1.1) + +const DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; + +const MONTH_TO_NUM = { + jan: 0, + feb: 1, + mar: 2, + apr: 3, + may: 4, + jun: 5, + jul: 6, + aug: 7, + sep: 8, + oct: 9, + nov: 10, + dec: 11 +}; + +const MAX_TIME = 2147483647000; // 31-bit max +const MIN_TIME = 0; // 31-bit min +const SAME_SITE_CONTEXT_VAL_ERR = + 'Invalid sameSiteContext option for getCookies(); expected one of "strict", "lax", or "none"'; + +function checkSameSiteContext(value) { + const context = String(value).toLowerCase(); + if (context === "none" || context === "lax" || context === "strict") { + return context; + } else { + return null; + } +} + +const PrefixSecurityEnum = Object.freeze({ + SILENT: "silent", + STRICT: "strict", + DISABLED: "unsafe-disabled" +}); + +// Dumped from ip-regex@4.0.0, with the following changes: +// * all capturing groups converted to non-capturing -- "(?:)" +// * support for IPv6 Scoped Literal ("%eth1") removed +// * lowercase hexadecimal only +var IP_REGEX_LOWERCASE =/(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$)|(?:^(?:(?:[a-f\d]{1,4}:){7}(?:[a-f\d]{1,4}|:)|(?:[a-f\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-f\d]{1,4}|:)|(?:[a-f\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,2}|:)|(?:[a-f\d]{1,4}:){4}(?:(?::[a-f\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,3}|:)|(?:[a-f\d]{1,4}:){3}(?:(?::[a-f\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,4}|:)|(?:[a-f\d]{1,4}:){2}(?:(?::[a-f\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,5}|:)|(?:[a-f\d]{1,4}:){1}(?:(?::[a-f\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,6}|:)|(?::(?:(?::[a-f\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,7}|:)))$)/; + +/* + * Parses a Natural number (i.e., non-negative integer) with either the + * *DIGIT ( non-digit *OCTET ) + * or + * *DIGIT + * grammar (RFC6265 S5.1.1). + * + * The "trailingOK" boolean controls if the grammar accepts a + * "( non-digit *OCTET )" trailer. + */ +function parseDigits(token, minDigits, maxDigits, trailingOK) { + let count = 0; + while (count < token.length) { + const c = token.charCodeAt(count); + // "non-digit = %x00-2F / %x3A-FF" + if (c <= 0x2f || c >= 0x3a) { + break; + } + count++; + } + + // constrain to a minimum and maximum number of digits. + if (count < minDigits || count > maxDigits) { + return null; + } + + if (!trailingOK && count != token.length) { + return null; + } + + return parseInt(token.substr(0, count), 10); +} + +function parseTime(token) { + const parts = token.split(":"); + const result = [0, 0, 0]; + + /* RF6256 S5.1.1: + * time = hms-time ( non-digit *OCTET ) + * hms-time = time-field ":" time-field ":" time-field + * time-field = 1*2DIGIT + */ + + if (parts.length !== 3) { + return null; + } + + for (let i = 0; i < 3; i++) { + // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be + // followed by "( non-digit *OCTET )" so therefore the last time-field can + // have a trailer + const trailingOK = i == 2; + const num = parseDigits(parts[i], 1, 2, trailingOK); + if (num === null) { + return null; + } + result[i] = num; + } + + return result; +} + +function parseMonth(token) { + token = String(token) + .substr(0, 3) + .toLowerCase(); + const num = MONTH_TO_NUM[token]; + return num >= 0 ? num : null; +} + +/* + * RFC6265 S5.1.1 date parser (see RFC for full grammar) + */ +function parseDate(str) { + if (!str) { + return; + } + + /* RFC6265 S5.1.1: + * 2. Process each date-token sequentially in the order the date-tokens + * appear in the cookie-date + */ + const tokens = str.split(DATE_DELIM); + if (!tokens) { + return; + } + + let hour = null; + let minute = null; + let second = null; + let dayOfMonth = null; + let month = null; + let year = null; + + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i].trim(); + if (!token.length) { + continue; + } + + let result; + + /* 2.1. If the found-time flag is not set and the token matches the time + * production, set the found-time flag and set the hour- value, + * minute-value, and second-value to the numbers denoted by the digits in + * the date-token, respectively. Skip the remaining sub-steps and continue + * to the next date-token. + */ + if (second === null) { + result = parseTime(token); + if (result) { + hour = result[0]; + minute = result[1]; + second = result[2]; + continue; + } + } + + /* 2.2. If the found-day-of-month flag is not set and the date-token matches + * the day-of-month production, set the found-day-of- month flag and set + * the day-of-month-value to the number denoted by the date-token. Skip + * the remaining sub-steps and continue to the next date-token. + */ + if (dayOfMonth === null) { + // "day-of-month = 1*2DIGIT ( non-digit *OCTET )" + result = parseDigits(token, 1, 2, true); + if (result !== null) { + dayOfMonth = result; + continue; + } + } + + /* 2.3. If the found-month flag is not set and the date-token matches the + * month production, set the found-month flag and set the month-value to + * the month denoted by the date-token. Skip the remaining sub-steps and + * continue to the next date-token. + */ + if (month === null) { + result = parseMonth(token); + if (result !== null) { + month = result; + continue; + } + } + + /* 2.4. If the found-year flag is not set and the date-token matches the + * year production, set the found-year flag and set the year-value to the + * number denoted by the date-token. Skip the remaining sub-steps and + * continue to the next date-token. + */ + if (year === null) { + // "year = 2*4DIGIT ( non-digit *OCTET )" + result = parseDigits(token, 2, 4, true); + if (result !== null) { + year = result; + /* From S5.1.1: + * 3. If the year-value is greater than or equal to 70 and less + * than or equal to 99, increment the year-value by 1900. + * 4. If the year-value is greater than or equal to 0 and less + * than or equal to 69, increment the year-value by 2000. + */ + if (year >= 70 && year <= 99) { + year += 1900; + } else if (year >= 0 && year <= 69) { + year += 2000; + } + } + } + } + + /* RFC 6265 S5.1.1 + * "5. Abort these steps and fail to parse the cookie-date if: + * * at least one of the found-day-of-month, found-month, found- + * year, or found-time flags is not set, + * * the day-of-month-value is less than 1 or greater than 31, + * * the year-value is less than 1601, + * * the hour-value is greater than 23, + * * the minute-value is greater than 59, or + * * the second-value is greater than 59. + * (Note that leap seconds cannot be represented in this syntax.)" + * + * So, in order as above: + */ + if ( + dayOfMonth === null || + month === null || + year === null || + second === null || + dayOfMonth < 1 || + dayOfMonth > 31 || + year < 1601 || + hour > 23 || + minute > 59 || + second > 59 + ) { + return; + } + + return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second)); +} + +function formatDate(date) { + return date.toUTCString(); +} + +// S5.1.2 Canonicalized Host Names +function canonicalDomain(str) { + if (str == null) { + return null; + } + str = str.trim().replace(/^\./, ""); // S4.1.2.3 & S5.2.3: ignore leading . + + // convert to IDN if any non-ASCII characters + if (punycode && /[^\u0001-\u007f]/.test(str)) { + str = punycode.toASCII(str); + } + + return str.toLowerCase(); +} + +// S5.1.3 Domain Matching +function domainMatch(str, domStr, canonicalize) { + if (str == null || domStr == null) { + return null; + } + if (canonicalize !== false) { + str = canonicalDomain(str); + domStr = canonicalDomain(domStr); + } + + /* + * S5.1.3: + * "A string domain-matches a given domain string if at least one of the + * following conditions hold:" + * + * " o The domain string and the string are identical. (Note that both the + * domain string and the string will have been canonicalized to lower case at + * this point)" + */ + if (str == domStr) { + return true; + } + + /* " o All of the following [three] conditions hold:" */ + + /* "* The domain string is a suffix of the string" */ + const idx = str.indexOf(domStr); + if (idx <= 0) { + return false; // it's a non-match (-1) or prefix (0) + } + + // next, check it's a proper suffix + // e.g., "a.b.c".indexOf("b.c") === 2 + // 5 === 3+2 + if (str.length !== domStr.length + idx) { + return false; // it's not a suffix + } + + /* " * The last character of the string that is not included in the + * domain string is a %x2E (".") character." */ + if (str.substr(idx-1,1) !== '.') { + return false; // doesn't align on "." + } + + /* " * The string is a host name (i.e., not an IP address)." */ + if (IP_REGEX_LOWERCASE.test(str)) { + return false; // it's an IP address + } + + return true; +} + +// RFC6265 S5.1.4 Paths and Path-Match + +/* + * "The user agent MUST use an algorithm equivalent to the following algorithm + * to compute the default-path of a cookie:" + * + * Assumption: the path (and not query part or absolute uri) is passed in. + */ +function defaultPath(path) { + // "2. If the uri-path is empty or if the first character of the uri-path is not + // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. + if (!path || path.substr(0, 1) !== "/") { + return "/"; + } + + // "3. If the uri-path contains no more than one %x2F ("/") character, output + // %x2F ("/") and skip the remaining step." + if (path === "/") { + return path; + } + + const rightSlash = path.lastIndexOf("/"); + if (rightSlash === 0) { + return "/"; + } + + // "4. Output the characters of the uri-path from the first character up to, + // but not including, the right-most %x2F ("/")." + return path.slice(0, rightSlash); +} + +function trimTerminator(str) { + for (let t = 0; t < TERMINATORS.length; t++) { + const terminatorIdx = str.indexOf(TERMINATORS[t]); + if (terminatorIdx !== -1) { + str = str.substr(0, terminatorIdx); + } + } + + return str; +} + +function parseCookiePair(cookiePair, looseMode) { + cookiePair = trimTerminator(cookiePair); + + let firstEq = cookiePair.indexOf("="); + if (looseMode) { + if (firstEq === 0) { + // '=' is immediately at start + cookiePair = cookiePair.substr(1); + firstEq = cookiePair.indexOf("="); // might still need to split on '=' + } + } else { + // non-loose mode + if (firstEq <= 0) { + // no '=' or is at start + return; // needs to have non-empty "cookie-name" + } + } + + let cookieName, cookieValue; + if (firstEq <= 0) { + cookieName = ""; + cookieValue = cookiePair.trim(); + } else { + cookieName = cookiePair.substr(0, firstEq).trim(); + cookieValue = cookiePair.substr(firstEq + 1).trim(); + } + + if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) { + return; + } + + const c = new Cookie(); + c.key = cookieName; + c.value = cookieValue; + return c; +} + +function parse(str, options) { + if (!options || typeof options !== "object") { + options = {}; + } + str = str.trim(); + + // We use a regex to parse the "name-value-pair" part of S5.2 + const firstSemi = str.indexOf(";"); // S5.2 step 1 + const cookiePair = firstSemi === -1 ? str : str.substr(0, firstSemi); + const c = parseCookiePair(cookiePair, !!options.loose); + if (!c) { + return; + } + + if (firstSemi === -1) { + return c; + } + + // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question)." plus later on in the same section + // "discard the first ";" and trim". + const unparsed = str.slice(firstSemi + 1).trim(); + + // "If the unparsed-attributes string is empty, skip the rest of these + // steps." + if (unparsed.length === 0) { + return c; + } + + /* + * S5.2 says that when looping over the items "[p]rocess the attribute-name + * and attribute-value according to the requirements in the following + * subsections" for every item. Plus, for many of the individual attributes + * in S5.3 it says to use the "attribute-value of the last attribute in the + * cookie-attribute-list". Therefore, in this implementation, we overwrite + * the previous value. + */ + const cookie_avs = unparsed.split(";"); + while (cookie_avs.length) { + const av = cookie_avs.shift().trim(); + if (av.length === 0) { + // happens if ";;" appears + continue; + } + const av_sep = av.indexOf("="); + let av_key, av_value; + + if (av_sep === -1) { + av_key = av; + av_value = null; + } else { + av_key = av.substr(0, av_sep); + av_value = av.substr(av_sep + 1); + } + + av_key = av_key.trim().toLowerCase(); + + if (av_value) { + av_value = av_value.trim(); + } + + switch (av_key) { + case "expires": // S5.2.1 + if (av_value) { + const exp = parseDate(av_value); + // "If the attribute-value failed to parse as a cookie date, ignore the + // cookie-av." + if (exp) { + // over and underflow not realistically a concern: V8's getTime() seems to + // store something larger than a 32-bit time_t (even with 32-bit node) + c.expires = exp; + } + } + break; + + case "max-age": // S5.2.2 + if (av_value) { + // "If the first character of the attribute-value is not a DIGIT or a "-" + // character ...[or]... If the remainder of attribute-value contains a + // non-DIGIT character, ignore the cookie-av." + if (/^-?[0-9]+$/.test(av_value)) { + const delta = parseInt(av_value, 10); + // "If delta-seconds is less than or equal to zero (0), let expiry-time + // be the earliest representable date and time." + c.setMaxAge(delta); + } + } + break; + + case "domain": // S5.2.3 + // "If the attribute-value is empty, the behavior is undefined. However, + // the user agent SHOULD ignore the cookie-av entirely." + if (av_value) { + // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E + // (".") character." + const domain = av_value.trim().replace(/^\./, ""); + if (domain) { + // "Convert the cookie-domain to lower case." + c.domain = domain.toLowerCase(); + } + } + break; + + case "path": // S5.2.4 + /* + * "If the attribute-value is empty or if the first character of the + * attribute-value is not %x2F ("/"): + * Let cookie-path be the default-path. + * Otherwise: + * Let cookie-path be the attribute-value." + * + * We'll represent the default-path as null since it depends on the + * context of the parsing. + */ + c.path = av_value && av_value[0] === "/" ? av_value : null; + break; + + case "secure": // S5.2.5 + /* + * "If the attribute-name case-insensitively matches the string "Secure", + * the user agent MUST append an attribute to the cookie-attribute-list + * with an attribute-name of Secure and an empty attribute-value." + */ + c.secure = true; + break; + + case "httponly": // S5.2.6 -- effectively the same as 'secure' + c.httpOnly = true; + break; + + case "samesite": // RFC6265bis-02 S5.3.7 + const enforcement = av_value ? av_value.toLowerCase() : ""; + switch (enforcement) { + case "strict": + c.sameSite = "strict"; + break; + case "lax": + c.sameSite = "lax"; + break; + default: + // RFC6265bis-02 S5.3.7 step 1: + // "If cookie-av's attribute-value is not a case-insensitive match + // for "Strict" or "Lax", ignore the "cookie-av"." + // This effectively sets it to 'none' from the prototype. + break; + } + break; + + default: + c.extensions = c.extensions || []; + c.extensions.push(av); + break; + } + } + + return c; +} + +/** + * If the cookie-name begins with a case-sensitive match for the + * string "__Secure-", abort these steps and ignore the cookie + * entirely unless the cookie's secure-only-flag is true. + * @param cookie + * @returns boolean + */ +function isSecurePrefixConditionMet(cookie) { + return !cookie.key.startsWith("__Secure-") || cookie.secure; +} + +/** + * If the cookie-name begins with a case-sensitive match for the + * string "__Host-", abort these steps and ignore the cookie + * entirely unless the cookie meets all the following criteria: + * 1. The cookie's secure-only-flag is true. + * 2. The cookie's host-only-flag is true. + * 3. The cookie-attribute-list contains an attribute with an + * attribute-name of "Path", and the cookie's path is "/". + * @param cookie + * @returns boolean + */ +function isHostPrefixConditionMet(cookie) { + return ( + !cookie.key.startsWith("__Host-") || + (cookie.secure && + cookie.hostOnly && + cookie.path != null && + cookie.path === "/") + ); +} + +// avoid the V8 deoptimization monster! +function jsonParse(str) { + let obj; + try { + obj = JSON.parse(str); + } catch (e) { + return e; + } + return obj; +} + +function fromJSON(str) { + if (!str) { + return null; + } + + let obj; + if (typeof str === "string") { + obj = jsonParse(str); + if (obj instanceof Error) { + return null; + } + } else { + // assume it's an Object + obj = str; + } + + const c = new Cookie(); + for (let i = 0; i < Cookie.serializableProperties.length; i++) { + const prop = Cookie.serializableProperties[i]; + if (obj[prop] === undefined || obj[prop] === cookieDefaults[prop]) { + continue; // leave as prototype default + } + + if (prop === "expires" || prop === "creation" || prop === "lastAccessed") { + if (obj[prop] === null) { + c[prop] = null; + } else { + c[prop] = obj[prop] == "Infinity" ? "Infinity" : new Date(obj[prop]); + } + } else { + c[prop] = obj[prop]; + } + } + + return c; +} + +/* Section 5.4 part 2: + * "* Cookies with longer paths are listed before cookies with + * shorter paths. + * + * * Among cookies that have equal-length path fields, cookies with + * earlier creation-times are listed before cookies with later + * creation-times." + */ + +function cookieCompare(a, b) { + let cmp = 0; + + // descending for length: b CMP a + const aPathLen = a.path ? a.path.length : 0; + const bPathLen = b.path ? b.path.length : 0; + cmp = bPathLen - aPathLen; + if (cmp !== 0) { + return cmp; + } + + // ascending for time: a CMP b + const aTime = a.creation ? a.creation.getTime() : MAX_TIME; + const bTime = b.creation ? b.creation.getTime() : MAX_TIME; + cmp = aTime - bTime; + if (cmp !== 0) { + return cmp; + } + + // break ties for the same millisecond (precision of JavaScript's clock) + cmp = a.creationIndex - b.creationIndex; + + return cmp; +} + +// Gives the permutation of all possible pathMatch()es of a given path. The +// array is in longest-to-shortest order. Handy for indexing. +function permutePath(path) { + if (path === "/") { + return ["/"]; + } + const permutations = [path]; + while (path.length > 1) { + const lindex = path.lastIndexOf("/"); + if (lindex === 0) { + break; + } + path = path.substr(0, lindex); + permutations.push(path); + } + permutations.push("/"); + return permutations; +} + +function getCookieContext(url) { + if (url instanceof Object) { + return url; + } + // NOTE: decodeURI will throw on malformed URIs (see GH-32). + // Therefore, we will just skip decoding for such URIs. + try { + url = decodeURI(url); + } catch (err) { + // Silently swallow error + } + + return urlParse(url); +} + +const cookieDefaults = { + // the order in which the RFC has them: + key: "", + value: "", + expires: "Infinity", + maxAge: null, + domain: null, + path: null, + secure: false, + httpOnly: false, + extensions: null, + // set by the CookieJar: + hostOnly: null, + pathIsDefault: null, + creation: null, + lastAccessed: null, + sameSite: "none" +}; + +class Cookie { + constructor(options = {}) { + if (util.inspect.custom) { + this[util.inspect.custom] = this.inspect; + } + + Object.assign(this, cookieDefaults, options); + this.creation = this.creation || new Date(); + + // used to break creation ties in cookieCompare(): + Object.defineProperty(this, "creationIndex", { + configurable: false, + enumerable: false, // important for assert.deepEqual checks + writable: true, + value: ++Cookie.cookiesCreated + }); + } + + inspect() { + const now = Date.now(); + const hostOnly = this.hostOnly != null ? this.hostOnly : "?"; + const createAge = this.creation + ? `${now - this.creation.getTime()}ms` + : "?"; + const accessAge = this.lastAccessed + ? `${now - this.lastAccessed.getTime()}ms` + : "?"; + return `Cookie="${this.toString()}; hostOnly=${hostOnly}; aAge=${accessAge}; cAge=${createAge}"`; + } + + toJSON() { + const obj = {}; + + for (const prop of Cookie.serializableProperties) { + if (this[prop] === cookieDefaults[prop]) { + continue; // leave as prototype default + } + + if ( + prop === "expires" || + prop === "creation" || + prop === "lastAccessed" + ) { + if (this[prop] === null) { + obj[prop] = null; + } else { + obj[prop] = + this[prop] == "Infinity" // intentionally not === + ? "Infinity" + : this[prop].toISOString(); + } + } else if (prop === "maxAge") { + if (this[prop] !== null) { + // again, intentionally not === + obj[prop] = + this[prop] == Infinity || this[prop] == -Infinity + ? this[prop].toString() + : this[prop]; + } + } else { + if (this[prop] !== cookieDefaults[prop]) { + obj[prop] = this[prop]; + } + } + } + + return obj; + } + + clone() { + return fromJSON(this.toJSON()); + } + + validate() { + if (!COOKIE_OCTETS.test(this.value)) { + return false; + } + if ( + this.expires != Infinity && + !(this.expires instanceof Date) && + !parseDate(this.expires) + ) { + return false; + } + if (this.maxAge != null && this.maxAge <= 0) { + return false; // "Max-Age=" non-zero-digit *DIGIT + } + if (this.path != null && !PATH_VALUE.test(this.path)) { + return false; + } + + const cdomain = this.cdomain(); + if (cdomain) { + if (cdomain.match(/\.$/)) { + return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this + } + const suffix = pubsuffix.getPublicSuffix(cdomain); + if (suffix == null) { + // it's a public suffix + return false; + } + } + return true; + } + + setExpires(exp) { + if (exp instanceof Date) { + this.expires = exp; + } else { + this.expires = parseDate(exp) || "Infinity"; + } + } + + setMaxAge(age) { + if (age === Infinity || age === -Infinity) { + this.maxAge = age.toString(); // so JSON.stringify() works + } else { + this.maxAge = age; + } + } + + cookieString() { + let val = this.value; + if (val == null) { + val = ""; + } + if (this.key === "") { + return val; + } + return `${this.key}=${val}`; + } + + // gives Set-Cookie header format + toString() { + let str = this.cookieString(); + + if (this.expires != Infinity) { + if (this.expires instanceof Date) { + str += `; Expires=${formatDate(this.expires)}`; + } else { + str += `; Expires=${this.expires}`; + } + } + + if (this.maxAge != null && this.maxAge != Infinity) { + str += `; Max-Age=${this.maxAge}`; + } + + if (this.domain && !this.hostOnly) { + str += `; Domain=${this.domain}`; + } + if (this.path) { + str += `; Path=${this.path}`; + } + + if (this.secure) { + str += "; Secure"; + } + if (this.httpOnly) { + str += "; HttpOnly"; + } + if (this.sameSite && this.sameSite !== "none") { + const ssCanon = Cookie.sameSiteCanonical[this.sameSite.toLowerCase()]; + str += `; SameSite=${ssCanon ? ssCanon : this.sameSite}`; + } + if (this.extensions) { + this.extensions.forEach(ext => { + str += `; ${ext}`; + }); + } + + return str; + } + + // TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie() + // elsewhere) + // S5.3 says to give the "latest representable date" for which we use Infinity + // For "expired" we use 0 + TTL(now) { + /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires + * attribute, the Max-Age attribute has precedence and controls the + * expiration date of the cookie. + * (Concurs with S5.3 step 3) + */ + if (this.maxAge != null) { + return this.maxAge <= 0 ? 0 : this.maxAge * 1000; + } + + let expires = this.expires; + if (expires != Infinity) { + if (!(expires instanceof Date)) { + expires = parseDate(expires) || Infinity; + } + + if (expires == Infinity) { + return Infinity; + } + + return expires.getTime() - (now || Date.now()); + } + + return Infinity; + } + + // expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() + // elsewhere) + expiryTime(now) { + if (this.maxAge != null) { + const relativeTo = now || this.creation || new Date(); + const age = this.maxAge <= 0 ? -Infinity : this.maxAge * 1000; + return relativeTo.getTime() + age; + } + + if (this.expires == Infinity) { + return Infinity; + } + return this.expires.getTime(); + } + + // expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() + // elsewhere), except it returns a Date + expiryDate(now) { + const millisec = this.expiryTime(now); + if (millisec == Infinity) { + return new Date(MAX_TIME); + } else if (millisec == -Infinity) { + return new Date(MIN_TIME); + } else { + return new Date(millisec); + } + } + + // This replaces the "persistent-flag" parts of S5.3 step 3 + isPersistent() { + return this.maxAge != null || this.expires != Infinity; + } + + // Mostly S5.1.2 and S5.2.3: + canonicalizedDomain() { + if (this.domain == null) { + return null; + } + return canonicalDomain(this.domain); + } + + cdomain() { + return this.canonicalizedDomain(); + } +} + +Cookie.cookiesCreated = 0; +Cookie.parse = parse; +Cookie.fromJSON = fromJSON; +Cookie.serializableProperties = Object.keys(cookieDefaults); +Cookie.sameSiteLevel = { + strict: 3, + lax: 2, + none: 1 +}; + +Cookie.sameSiteCanonical = { + strict: "Strict", + lax: "Lax" +}; + +function getNormalizedPrefixSecurity(prefixSecurity) { + if (prefixSecurity != null) { + const normalizedPrefixSecurity = prefixSecurity.toLowerCase(); + /* The three supported options */ + switch (normalizedPrefixSecurity) { + case PrefixSecurityEnum.STRICT: + case PrefixSecurityEnum.SILENT: + case PrefixSecurityEnum.DISABLED: + return normalizedPrefixSecurity; + } + } + /* Default is SILENT */ + return PrefixSecurityEnum.SILENT; +} + +class CookieJar { + constructor(store, options = { rejectPublicSuffixes: true }) { + if (typeof options === "boolean") { + options = { rejectPublicSuffixes: options }; + } + this.rejectPublicSuffixes = options.rejectPublicSuffixes; + this.enableLooseMode = !!options.looseMode; + this.allowSpecialUseDomain = !!options.allowSpecialUseDomain; + this.store = store || new MemoryCookieStore(); + this.prefixSecurity = getNormalizedPrefixSecurity(options.prefixSecurity); + this._cloneSync = syncWrap("clone"); + this._importCookiesSync = syncWrap("_importCookies"); + this.getCookiesSync = syncWrap("getCookies"); + this.getCookieStringSync = syncWrap("getCookieString"); + this.getSetCookieStringsSync = syncWrap("getSetCookieStrings"); + this.removeAllCookiesSync = syncWrap("removeAllCookies"); + this.setCookieSync = syncWrap("setCookie"); + this.serializeSync = syncWrap("serialize"); + } + + setCookie(cookie, url, options, cb) { + let err; + const context = getCookieContext(url); + if (typeof options === "function") { + cb = options; + options = {}; + } + + const host = canonicalDomain(context.hostname); + const loose = options.loose || this.enableLooseMode; + + let sameSiteContext = null; + if (options.sameSiteContext) { + sameSiteContext = checkSameSiteContext(options.sameSiteContext); + if (!sameSiteContext) { + return cb(new Error(SAME_SITE_CONTEXT_VAL_ERR)); + } + } + + // S5.3 step 1 + if (typeof cookie === "string" || cookie instanceof String) { + cookie = Cookie.parse(cookie, { loose: loose }); + if (!cookie) { + err = new Error("Cookie failed to parse"); + return cb(options.ignoreError ? null : err); + } + } else if (!(cookie instanceof Cookie)) { + // If you're seeing this error, and are passing in a Cookie object, + // it *might* be a Cookie object from another loaded version of tough-cookie. + err = new Error( + "First argument to setCookie must be a Cookie object or string" + ); + return cb(options.ignoreError ? null : err); + } + + // S5.3 step 2 + const now = options.now || new Date(); // will assign later to save effort in the face of errors + + // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie() + + // S5.3 step 4: NOOP; domain is null by default + + // S5.3 step 5: public suffixes + if (this.rejectPublicSuffixes && cookie.domain) { + const suffix = pubsuffix.getPublicSuffix(cookie.cdomain()); + if (suffix == null) { + // e.g. "com" + err = new Error("Cookie has domain set to a public suffix"); + return cb(options.ignoreError ? null : err); + } + } + + // S5.3 step 6: + if (cookie.domain) { + if (!domainMatch(host, cookie.cdomain(), false)) { + err = new Error( + `Cookie not in this host's domain. Cookie:${cookie.cdomain()} Request:${host}` + ); + return cb(options.ignoreError ? null : err); + } + + if (cookie.hostOnly == null) { + // don't reset if already set + cookie.hostOnly = false; + } + } else { + cookie.hostOnly = true; + cookie.domain = host; + } + + //S5.2.4 If the attribute-value is empty or if the first character of the + //attribute-value is not %x2F ("/"): + //Let cookie-path be the default-path. + if (!cookie.path || cookie.path[0] !== "/") { + cookie.path = defaultPath(context.pathname); + cookie.pathIsDefault = true; + } + + // S5.3 step 8: NOOP; secure attribute + // S5.3 step 9: NOOP; httpOnly attribute + + // S5.3 step 10 + if (options.http === false && cookie.httpOnly) { + err = new Error("Cookie is HttpOnly and this isn't an HTTP API"); + return cb(options.ignoreError ? null : err); + } + + // 6252bis-02 S5.4 Step 13 & 14: + if (cookie.sameSite !== "none" && sameSiteContext) { + // "If the cookie's "same-site-flag" is not "None", and the cookie + // is being set from a context whose "site for cookies" is not an + // exact match for request-uri's host's registered domain, then + // abort these steps and ignore the newly created cookie entirely." + if (sameSiteContext === "none") { + err = new Error( + "Cookie is SameSite but this is a cross-origin request" + ); + return cb(options.ignoreError ? null : err); + } + } + + /* 6265bis-02 S5.4 Steps 15 & 16 */ + const ignoreErrorForPrefixSecurity = + this.prefixSecurity === PrefixSecurityEnum.SILENT; + const prefixSecurityDisabled = + this.prefixSecurity === PrefixSecurityEnum.DISABLED; + /* If prefix checking is not disabled ...*/ + if (!prefixSecurityDisabled) { + let errorFound = false; + let errorMsg; + /* Check secure prefix condition */ + if (!isSecurePrefixConditionMet(cookie)) { + errorFound = true; + errorMsg = "Cookie has __Secure prefix but Secure attribute is not set"; + } else if (!isHostPrefixConditionMet(cookie)) { + /* Check host prefix condition */ + errorFound = true; + errorMsg = + "Cookie has __Host prefix but either Secure or HostOnly attribute is not set or Path is not '/'"; + } + if (errorFound) { + return cb( + options.ignoreError || ignoreErrorForPrefixSecurity + ? null + : new Error(errorMsg) + ); + } + } + + const store = this.store; + + if (!store.updateCookie) { + store.updateCookie = function(oldCookie, newCookie, cb) { + this.putCookie(newCookie, cb); + }; + } + + function withCookie(err, oldCookie) { + if (err) { + return cb(err); + } + + const next = function(err) { + if (err) { + return cb(err); + } else { + cb(null, cookie); + } + }; + + if (oldCookie) { + // S5.3 step 11 - "If the cookie store contains a cookie with the same name, + // domain, and path as the newly created cookie:" + if (options.http === false && oldCookie.httpOnly) { + // step 11.2 + err = new Error("old Cookie is HttpOnly and this isn't an HTTP API"); + return cb(options.ignoreError ? null : err); + } + cookie.creation = oldCookie.creation; // step 11.3 + cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker + cookie.lastAccessed = now; + // Step 11.4 (delete cookie) is implied by just setting the new one: + store.updateCookie(oldCookie, cookie, next); // step 12 + } else { + cookie.creation = cookie.lastAccessed = now; + store.putCookie(cookie, next); // step 12 + } + } + + store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie); + } + + // RFC6365 S5.4 + getCookies(url, options, cb) { + const context = getCookieContext(url); + if (typeof options === "function") { + cb = options; + options = {}; + } + + const host = canonicalDomain(context.hostname); + const path = context.pathname || "/"; + + let secure = options.secure; + if ( + secure == null && + context.protocol && + (context.protocol == "https:" || context.protocol == "wss:") + ) { + secure = true; + } + + let sameSiteLevel = 0; + if (options.sameSiteContext) { + const sameSiteContext = checkSameSiteContext(options.sameSiteContext); + sameSiteLevel = Cookie.sameSiteLevel[sameSiteContext]; + if (!sameSiteLevel) { + return cb(new Error(SAME_SITE_CONTEXT_VAL_ERR)); + } + } + + let http = options.http; + if (http == null) { + http = true; + } + + const now = options.now || Date.now(); + const expireCheck = options.expire !== false; + const allPaths = !!options.allPaths; + const store = this.store; + + function matchingCookie(c) { + // "Either: + // The cookie's host-only-flag is true and the canonicalized + // request-host is identical to the cookie's domain. + // Or: + // The cookie's host-only-flag is false and the canonicalized + // request-host domain-matches the cookie's domain." + if (c.hostOnly) { + if (c.domain != host) { + return false; + } + } else { + if (!domainMatch(host, c.domain, false)) { + return false; + } + } + + // "The request-uri's path path-matches the cookie's path." + if (!allPaths && !pathMatch(path, c.path)) { + return false; + } + + // "If the cookie's secure-only-flag is true, then the request-uri's + // scheme must denote a "secure" protocol" + if (c.secure && !secure) { + return false; + } + + // "If the cookie's http-only-flag is true, then exclude the cookie if the + // cookie-string is being generated for a "non-HTTP" API" + if (c.httpOnly && !http) { + return false; + } + + // RFC6265bis-02 S5.3.7 + if (sameSiteLevel) { + const cookieLevel = Cookie.sameSiteLevel[c.sameSite || "none"]; + if (cookieLevel > sameSiteLevel) { + // only allow cookies at or below the request level + return false; + } + } + + // deferred from S5.3 + // non-RFC: allow retention of expired cookies by choice + if (expireCheck && c.expiryTime() <= now) { + store.removeCookie(c.domain, c.path, c.key, () => {}); // result ignored + return false; + } + + return true; + } + + store.findCookies( + host, + allPaths ? null : path, + this.allowSpecialUseDomain, + (err, cookies) => { + if (err) { + return cb(err); + } + + cookies = cookies.filter(matchingCookie); + + // sorting of S5.4 part 2 + if (options.sort !== false) { + cookies = cookies.sort(cookieCompare); + } + + // S5.4 part 3 + const now = new Date(); + for (const cookie of cookies) { + cookie.lastAccessed = now; + } + // TODO persist lastAccessed + + cb(null, cookies); + } + ); + } + + getCookieString(...args) { + const cb = args.pop(); + const next = function(err, cookies) { + if (err) { + cb(err); + } else { + cb( + null, + cookies + .sort(cookieCompare) + .map(c => c.cookieString()) + .join("; ") + ); + } + }; + args.push(next); + this.getCookies.apply(this, args); + } + + getSetCookieStrings(...args) { + const cb = args.pop(); + const next = function(err, cookies) { + if (err) { + cb(err); + } else { + cb( + null, + cookies.map(c => { + return c.toString(); + }) + ); + } + }; + args.push(next); + this.getCookies.apply(this, args); + } + + serialize(cb) { + let type = this.store.constructor.name; + if (type === "Object") { + type = null; + } + + // update README.md "Serialization Format" if you change this, please! + const serialized = { + // The version of tough-cookie that serialized this jar. Generally a good + // practice since future versions can make data import decisions based on + // known past behavior. When/if this matters, use `semver`. + version: `tough-cookie@${VERSION}`, + + // add the store type, to make humans happy: + storeType: type, + + // CookieJar configuration: + rejectPublicSuffixes: !!this.rejectPublicSuffixes, + + // this gets filled from getAllCookies: + cookies: [] + }; + + if ( + !( + this.store.getAllCookies && + typeof this.store.getAllCookies === "function" + ) + ) { + return cb( + new Error( + "store does not support getAllCookies and cannot be serialized" + ) + ); + } + + this.store.getAllCookies((err, cookies) => { + if (err) { + return cb(err); + } + + serialized.cookies = cookies.map(cookie => { + // convert to serialized 'raw' cookies + cookie = cookie instanceof Cookie ? cookie.toJSON() : cookie; + + // Remove the index so new ones get assigned during deserialization + delete cookie.creationIndex; + + return cookie; + }); + + return cb(null, serialized); + }); + } + + toJSON() { + return this.serializeSync(); + } + + // use the class method CookieJar.deserialize instead of calling this directly + _importCookies(serialized, cb) { + let cookies = serialized.cookies; + if (!cookies || !Array.isArray(cookies)) { + return cb(new Error("serialized jar has no cookies array")); + } + cookies = cookies.slice(); // do not modify the original + + const putNext = err => { + if (err) { + return cb(err); + } + + if (!cookies.length) { + return cb(err, this); + } + + let cookie; + try { + cookie = fromJSON(cookies.shift()); + } catch (e) { + return cb(e); + } + + if (cookie === null) { + return putNext(null); // skip this cookie + } + + this.store.putCookie(cookie, putNext); + }; + + putNext(); + } + + clone(newStore, cb) { + if (arguments.length === 1) { + cb = newStore; + newStore = null; + } + + this.serialize((err, serialized) => { + if (err) { + return cb(err); + } + CookieJar.deserialize(serialized, newStore, cb); + }); + } + + cloneSync(newStore) { + if (arguments.length === 0) { + return this._cloneSync(); + } + if (!newStore.synchronous) { + throw new Error( + "CookieJar clone destination store is not synchronous; use async API instead." + ); + } + return this._cloneSync(newStore); + } + + removeAllCookies(cb) { + const store = this.store; + + // Check that the store implements its own removeAllCookies(). The default + // implementation in Store will immediately call the callback with a "not + // implemented" Error. + if ( + typeof store.removeAllCookies === "function" && + store.removeAllCookies !== Store.prototype.removeAllCookies + ) { + return store.removeAllCookies(cb); + } + + store.getAllCookies((err, cookies) => { + if (err) { + return cb(err); + } + + if (cookies.length === 0) { + return cb(null); + } + + let completedCount = 0; + const removeErrors = []; + + function removeCookieCb(removeErr) { + if (removeErr) { + removeErrors.push(removeErr); + } + + completedCount++; + + if (completedCount === cookies.length) { + return cb(removeErrors.length ? removeErrors[0] : null); + } + } + + cookies.forEach(cookie => { + store.removeCookie( + cookie.domain, + cookie.path, + cookie.key, + removeCookieCb + ); + }); + }); + } + + static deserialize(strOrObj, store, cb) { + if (arguments.length !== 3) { + // store is optional + cb = store; + store = null; + } + + let serialized; + if (typeof strOrObj === "string") { + serialized = jsonParse(strOrObj); + if (serialized instanceof Error) { + return cb(serialized); + } + } else { + serialized = strOrObj; + } + + const jar = new CookieJar(store, serialized.rejectPublicSuffixes); + jar._importCookies(serialized, err => { + if (err) { + return cb(err); + } + cb(null, jar); + }); + } + + static deserializeSync(strOrObj, store) { + const serialized = + typeof strOrObj === "string" ? JSON.parse(strOrObj) : strOrObj; + const jar = new CookieJar(store, serialized.rejectPublicSuffixes); + + // catch this mistake early: + if (!jar.store.synchronous) { + throw new Error( + "CookieJar store is not synchronous; use async API instead." + ); + } + + jar._importCookiesSync(serialized); + return jar; + } +} +CookieJar.fromJSON = CookieJar.deserializeSync; + +[ + "_importCookies", + "clone", + "getCookies", + "getCookieString", + "getSetCookieStrings", + "removeAllCookies", + "serialize", + "setCookie" +].forEach(name => { + CookieJar.prototype[name] = fromCallback(CookieJar.prototype[name]); +}); +CookieJar.deserialize = fromCallback(CookieJar.deserialize); + +// Use a closure to provide a true imperative API for synchronous stores. +function syncWrap(method) { + return function(...args) { + if (!this.store.synchronous) { + throw new Error( + "CookieJar store is not synchronous; use async API instead." + ); + } + + let syncErr, syncResult; + this[method](...args, (err, result) => { + syncErr = err; + syncResult = result; + }); + + if (syncErr) { + throw syncErr; + } + return syncResult; + }; +} + +exports.version = VERSION; +exports.CookieJar = CookieJar; +exports.Cookie = Cookie; +exports.Store = Store; +exports.MemoryCookieStore = MemoryCookieStore; +exports.parseDate = parseDate; +exports.formatDate = formatDate; +exports.parse = parse; +exports.fromJSON = fromJSON; +exports.domainMatch = domainMatch; +exports.defaultPath = defaultPath; +exports.pathMatch = pathMatch; +exports.getPublicSuffix = pubsuffix.getPublicSuffix; +exports.cookieCompare = cookieCompare; +exports.permuteDomain = __webpack_require__(89).permuteDomain; +exports.permutePath = permutePath; +exports.canonicalDomain = canonicalDomain; +exports.PrefixSecurityEnum = PrefixSecurityEnum; + + +/***/ }), +/* 394 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +var stream = __webpack_require__(914) +var eos = __webpack_require__(3) +var inherits = __webpack_require__(689) +var shift = __webpack_require__(475) + +var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from) + ? Buffer.from([0]) + : new Buffer([0]) + +var onuncork = function(self, fn) { + if (self._corked) self.once('uncork', fn) + else fn() +} + +var autoDestroy = function (self, err) { + if (self._autoDestroy) self.destroy(err) +} + +var destroyer = function(self, end) { + return function(err) { + if (err) autoDestroy(self, err.message === 'premature close' ? null : err) + else if (end && !self._ended) self.end() + } +} + +var end = function(ws, fn) { + if (!ws) return fn() + if (ws._writableState && ws._writableState.finished) return fn() + if (ws._writableState) return ws.end(fn) + ws.end() + fn() +} + +var toStreams2 = function(rs) { + return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs) +} + +var Duplexify = function(writable, readable, opts) { + if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts) + stream.Duplex.call(this, opts) + + this._writable = null + this._readable = null + this._readable2 = null + + this._autoDestroy = !opts || opts.autoDestroy !== false + this._forwardDestroy = !opts || opts.destroy !== false + this._forwardEnd = !opts || opts.end !== false + this._corked = 1 // start corked + this._ondrain = null + this._drained = false + this._forwarding = false + this._unwrite = null + this._unread = null + this._ended = false + + this.destroyed = false + + if (writable) this.setWritable(writable) + if (readable) this.setReadable(readable) +} + +inherits(Duplexify, stream.Duplex) + +Duplexify.obj = function(writable, readable, opts) { + if (!opts) opts = {} + opts.objectMode = true + opts.highWaterMark = 16 + return new Duplexify(writable, readable, opts) +} + +Duplexify.prototype.cork = function() { + if (++this._corked === 1) this.emit('cork') +} + +Duplexify.prototype.uncork = function() { + if (this._corked && --this._corked === 0) this.emit('uncork') +} + +Duplexify.prototype.setWritable = function(writable) { + if (this._unwrite) this._unwrite() + + if (this.destroyed) { + if (writable && writable.destroy) writable.destroy() + return + } + + if (writable === null || writable === false) { + this.end() + return + } + + var self = this + var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd)) + + var ondrain = function() { + var ondrain = self._ondrain + self._ondrain = null + if (ondrain) ondrain() + } + + var clear = function() { + self._writable.removeListener('drain', ondrain) + unend() + } + + if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks + + this._writable = writable + this._writable.on('drain', ondrain) + this._unwrite = clear + + this.uncork() // always uncork setWritable +} + +Duplexify.prototype.setReadable = function(readable) { + if (this._unread) this._unread() + + if (this.destroyed) { + if (readable && readable.destroy) readable.destroy() + return + } + + if (readable === null || readable === false) { + this.push(null) + this.resume() + return + } + + var self = this + var unend = eos(readable, {writable:false, readable:true}, destroyer(this)) + + var onreadable = function() { + self._forward() + } + + var onend = function() { + self.push(null) + } + + var clear = function() { + self._readable2.removeListener('readable', onreadable) + self._readable2.removeListener('end', onend) + unend() + } + + this._drained = true + this._readable = readable + this._readable2 = readable._readableState ? readable : toStreams2(readable) + this._readable2.on('readable', onreadable) + this._readable2.on('end', onend) + this._unread = clear + + this._forward() +} + +Duplexify.prototype._read = function() { + this._drained = true + this._forward() +} + +Duplexify.prototype._forward = function() { + if (this._forwarding || !this._readable2 || !this._drained) return + this._forwarding = true + + var data + + while (this._drained && (data = shift(this._readable2)) !== null) { + if (this.destroyed) continue + this._drained = this.push(data) + } + + this._forwarding = false +} + +Duplexify.prototype.destroy = function(err) { + if (this.destroyed) return + this.destroyed = true + + var self = this + process.nextTick(function() { + self._destroy(err) + }) +} + +Duplexify.prototype._destroy = function(err) { + if (err) { + var ondrain = this._ondrain + this._ondrain = null + if (ondrain) ondrain(err) + else this.emit('error', err) + } + + if (this._forwardDestroy) { + if (this._readable && this._readable.destroy) this._readable.destroy() + if (this._writable && this._writable.destroy) this._writable.destroy() + } + + this.emit('close') +} + +Duplexify.prototype._write = function(data, enc, cb) { + if (this.destroyed) return cb() + if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb)) + if (data === SIGNAL_FLUSH) return this._finish(cb) + if (!this._writable) return cb() + + if (this._writable.write(data) === false) this._ondrain = cb + else cb() +} + +Duplexify.prototype._finish = function(cb) { + var self = this + this.emit('preend') + onuncork(this, function() { + end(self._forwardEnd && self._writable, function() { + // haxx to not emit prefinish twice + if (self._writableState.prefinished === false) self._writableState.prefinished = true + self.emit('prefinish') + onuncork(self, cb) + }) + }) +} + +Duplexify.prototype.end = function(data, enc, cb) { + if (typeof data === 'function') return this.end(null, null, data) + if (typeof enc === 'function') return this.end(data, null, enc) + this._ended = true + if (data) this.write(data) + if (!this._writableState.ending) this.write(SIGNAL_FLUSH) + return stream.Writable.prototype.end.call(this, cb) +} + +module.exports = Duplexify + + +/***/ }), +/* 395 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const cloneDeep = __webpack_require__(452) +const figgyPudding = __webpack_require__(122) +const { fixer } = __webpack_require__(167) +const getStream = __webpack_require__(341) +const npa = __webpack_require__(482) +const npmAuth = __webpack_require__(872) +const npmFetch = __webpack_require__(789) +const semver = __webpack_require__(280) +const ssri = __webpack_require__(951) +const url = __webpack_require__(835) +const validate = __webpack_require__(772) + +const PublishConfig = figgyPudding({ + access: {}, + algorithms: { default: ['sha512'] }, + npmVersion: {}, + tag: { default: 'latest' }, + Promise: { default: () => Promise } +}) + +module.exports = publish +function publish (manifest, tarball, opts) { + opts = PublishConfig(opts) + return new opts.Promise(resolve => resolve()).then(() => { + validate('OSO|OOO', [manifest, tarball, opts]) + if (manifest.private) { + throw Object.assign(new Error( + 'This package has been marked as private\n' + + "Remove the 'private' field from the package.json to publish it." + ), { code: 'EPRIVATE' }) + } + const spec = npa.resolve(manifest.name, manifest.version) + // NOTE: spec is used to pick the appropriate registry/auth combo. + opts = opts.concat(manifest.publishConfig, { spec }) + const reg = npmFetch.pickRegistry(spec, opts) + const auth = npmAuth(reg, opts) + const pubManifest = patchedManifest(spec, auth, manifest, opts) + + // registry-frontdoor cares about the access level, which is only + // configurable for scoped packages + if (!spec.scope && opts.access === 'restricted') { + throw Object.assign( + new Error("Can't restrict access to unscoped packages."), + { code: 'EUNSCOPED' } + ) + } + + return slurpTarball(tarball, opts).then(tardata => { + const metadata = buildMetadata( + spec, auth, reg, pubManifest, tardata, opts + ) + return npmFetch(spec.escapedName, opts.concat({ + method: 'PUT', + body: metadata, + ignoreBody: true + })).catch(err => { + if (err.code !== 'E409') { throw err } + return npmFetch.json(spec.escapedName, opts.concat({ + query: { write: true } + })).then( + current => patchMetadata(current, metadata, opts) + ).then(newMetadata => { + return npmFetch(spec.escapedName, opts.concat({ + method: 'PUT', + body: newMetadata, + ignoreBody: true + })) + }) + }) + }) + }).then(() => true) +} + +function patchedManifest (spec, auth, base, opts) { + const manifest = cloneDeep(base) + manifest._nodeVersion = process.versions.node + if (opts.npmVersion) { + manifest._npmVersion = opts.npmVersion + } + if (auth.username || auth.email) { + // NOTE: This is basically pointless, but reproduced because it's what + // legacy does: tl;dr `auth.username` and `auth.email` are going to be + // undefined in any auth situation that uses tokens instead of plain + // auth. I can only assume some registries out there decided that + // _npmUser would be of any use to them, but _npmUser in packuments + // currently gets filled in by the npm registry itself, based on auth + // information. + manifest._npmUser = { + name: auth.username, + email: auth.email + } + } + + fixer.fixNameField(manifest, { strict: true, allowLegacyCase: true }) + const version = semver.clean(manifest.version) + if (!version) { + throw Object.assign( + new Error('invalid semver: ' + manifest.version), + { code: 'EBADSEMVER' } + ) + } + manifest.version = version + return manifest +} + +function buildMetadata (spec, auth, registry, manifest, tardata, opts) { + const root = { + _id: manifest.name, + name: manifest.name, + description: manifest.description, + 'dist-tags': {}, + versions: {}, + readme: manifest.readme || '' + } + + if (opts.access) root.access = opts.access + + if (!auth.token) { + root.maintainers = [{ name: auth.username, email: auth.email }] + manifest.maintainers = JSON.parse(JSON.stringify(root.maintainers)) + } + + root.versions[manifest.version] = manifest + const tag = manifest.tag || opts.tag + root['dist-tags'][tag] = manifest.version + + const tbName = manifest.name + '-' + manifest.version + '.tgz' + const tbURI = manifest.name + '/-/' + tbName + const integrity = ssri.fromData(tardata, { + algorithms: [...new Set(['sha1'].concat(opts.algorithms))] + }) + + manifest._id = manifest.name + '@' + manifest.version + manifest.dist = manifest.dist || {} + // Don't bother having sha1 in the actual integrity field + manifest.dist.integrity = integrity.sha512[0].toString() + // Legacy shasum support + manifest.dist.shasum = integrity.sha1[0].hexDigest() + manifest.dist.tarball = url.resolve(registry, tbURI) + .replace(/^https:\/\//, 'http://') + + root._attachments = {} + root._attachments[tbName] = { + content_type: 'application/octet-stream', + data: tardata.toString('base64'), + length: tardata.length + } + + return root +} + +function patchMetadata (current, newData, opts) { + const curVers = Object.keys(current.versions || {}).map(v => { + return semver.clean(v, true) + }).concat(Object.keys(current.time || {}).map(v => { + if (semver.valid(v, true)) { return semver.clean(v, true) } + })).filter(v => v) + + const newVersion = Object.keys(newData.versions)[0] + + if (curVers.indexOf(newVersion) !== -1) { + throw ConflictError(newData.name, newData.version) + } + + current.versions = current.versions || {} + current.versions[newVersion] = newData.versions[newVersion] + for (var i in newData) { + switch (i) { + // objects that copy over the new stuffs + case 'dist-tags': + case 'versions': + case '_attachments': + for (var j in newData[i]) { + current[i] = current[i] || {} + current[i][j] = newData[i][j] + } + break + + // ignore these + case 'maintainers': + break + + // copy + default: + current[i] = newData[i] + } + } + const maint = newData.maintainers && JSON.parse(JSON.stringify(newData.maintainers)) + newData.versions[newVersion].maintainers = maint + return current +} + +function slurpTarball (tarSrc, opts) { + if (Buffer.isBuffer(tarSrc)) { + return opts.Promise.resolve(tarSrc) + } else if (typeof tarSrc === 'string') { + return opts.Promise.resolve(Buffer.from(tarSrc, 'base64')) + } else if (typeof tarSrc.pipe === 'function') { + return getStream.buffer(tarSrc) + } else { + return opts.Promise.reject(Object.assign( + new Error('invalid tarball argument. Must be a Buffer, a base64 string, or a binary stream'), { + code: 'EBADTAR' + })) + } +} + +function ConflictError (pkgid, version) { + return Object.assign(new Error( + `Cannot publish ${pkgid}@${version} over existing version.` + ), { + code: 'EPUBLISHCONFLICT', + pkgid, + version + }) +} + + +/***/ }), +/* 396 */ +/***/ (function(module) { + +"use strict"; + +module.exports = function (Yallist) { + Yallist.prototype[Symbol.iterator] = function* () { + for (let walker = this.head; walker; walker = walker.next) { + yield walker.value + } + } +} + + +/***/ }), +/* 397 */, +/* 398 */, +/* 399 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + +module.exports = RunQueue + +var validate = __webpack_require__(904) + +function RunQueue (opts) { + validate('Z|O', [opts]) + if (!opts) opts = {} + this.finished = false + this.inflight = 0 + this.maxConcurrency = opts.maxConcurrency || 1 + this.queued = 0 + this.queue = [] + this.currentPrio = null + this.currentQueue = null + this.Promise = opts.Promise || global.Promise + this.deferred = {} +} + +RunQueue.prototype = {} + +RunQueue.prototype.run = function () { + if (arguments.length !== 0) throw new Error('RunQueue.run takes no arguments') + var self = this + var deferred = this.deferred + if (!deferred.promise) { + deferred.promise = new this.Promise(function (resolve, reject) { + deferred.resolve = resolve + deferred.reject = reject + self._runQueue() + }) + } + return deferred.promise +} + +RunQueue.prototype._runQueue = function () { + var self = this + + while ((this.inflight < this.maxConcurrency) && this.queued) { + if (!this.currentQueue || this.currentQueue.length === 0) { + // wait till the current priority is entirely processed before + // starting a new one + if (this.inflight) return + var prios = Object.keys(this.queue) + for (var ii = 0; ii < prios.length; ++ii) { + var prioQueue = this.queue[prios[ii]] + if (prioQueue.length) { + this.currentQueue = prioQueue + this.currentPrio = prios[ii] + break + } + } + } + + --this.queued + ++this.inflight + var next = this.currentQueue.shift() + var args = next.args || [] + + // we explicitly construct a promise here so that queue items can throw + // or immediately return to resolve + var queueEntry = new this.Promise(function (resolve) { + resolve(next.cmd.apply(null, args)) + }) + + queueEntry.then(function () { + --self.inflight + if (self.finished) return + if (self.queued <= 0 && self.inflight <= 0) { + self.finished = true + self.deferred.resolve() + } + self._runQueue() + }, function (err) { + self.finished = true + self.deferred.reject(err) + }) + } +} + +RunQueue.prototype.add = function (prio, cmd, args) { + if (this.finished) throw new Error("Can't add to a finished queue. Create a new queue.") + if (Math.abs(Math.floor(prio)) !== prio) throw new Error('Priorities must be a positive integer value.') + validate('NFA|NFZ', [prio, cmd, args]) + prio = Number(prio) + if (!this.queue[prio]) this.queue[prio] = [] + ++this.queued + this.queue[prio].push({cmd: cmd, args: args}) + // if this priority is higher than the one we're currently processing, + // switch back to processing its queue. + if (this.currentPrio > prio) { + this.currentQueue = this.queue[prio] + this.currentPrio = prio + } +} + + +/***/ }), +/* 400 */ +/***/ (function(module, exports, __webpack_require__) { + +var Stream = __webpack_require__(794) + +// through +// +// a stream that does nothing but re-emit the input. +// useful for aggregating a series of changing but not ending streams into one stream) + +exports = module.exports = through +through.through = through + +//create a readable writable stream. + +function through (write, end, opts) { + write = write || function (data) { this.queue(data) } + end = end || function () { this.queue(null) } + + var ended = false, destroyed = false, buffer = [], _ended = false + var stream = new Stream() + stream.readable = stream.writable = true + stream.paused = false + +// stream.autoPause = !(opts && opts.autoPause === false) + stream.autoDestroy = !(opts && opts.autoDestroy === false) + + stream.write = function (data) { + write.call(this, data) + return !stream.paused + } + + function drain() { + while(buffer.length && !stream.paused) { + var data = buffer.shift() + if(null === data) + return stream.emit('end') + else + stream.emit('data', data) + } + } + + stream.queue = stream.push = function (data) { +// console.error(ended) + if(_ended) return stream + if(data === null) _ended = true + buffer.push(data) + drain() + return stream + } + + //this will be registered as the first 'end' listener + //must call destroy next tick, to make sure we're after any + //stream piped from here. + //this is only a problem if end is not emitted synchronously. + //a nicer way to do this is to make sure this is the last listener for 'end' + + stream.on('end', function () { + stream.readable = false + if(!stream.writable && stream.autoDestroy) + process.nextTick(function () { + stream.destroy() + }) + }) + + function _end () { + stream.writable = false + end.call(stream) + if(!stream.readable && stream.autoDestroy) + stream.destroy() + } + + stream.end = function (data) { + if(ended) return + ended = true + if(arguments.length) stream.write(data) + _end() // will emit or queue + return stream + } + + stream.destroy = function () { + if(destroyed) return + destroyed = true + ended = true + buffer.length = 0 + stream.writable = stream.readable = false + stream.emit('close') + return stream + } + + stream.pause = function () { + if(stream.paused) return + stream.paused = true + return stream + } + + stream.resume = function () { + if(stream.paused) { + stream.paused = false + stream.emit('resume') + } + drain() + //may have become paused again, + //as drain emits 'data'. + if(!stream.paused) + stream.emit('drain') + return stream + } + return stream +} + + + +/***/ }), +/* 401 */ +/***/ (function(module, exports, __webpack_require__) { + +// info about each config option. + +var debug = process.env.DEBUG_NOPT || process.env.NOPT_DEBUG + ? function () { console.error.apply(console, arguments) } + : function () {} + +var url = __webpack_require__(835) + , path = __webpack_require__(622) + , Stream = __webpack_require__(794).Stream + , abbrev = __webpack_require__(916) + , osenv = __webpack_require__(580) + +module.exports = exports = nopt +exports.clean = clean + +exports.typeDefs = + { String : { type: String, validate: validateString } + , Boolean : { type: Boolean, validate: validateBoolean } + , url : { type: url, validate: validateUrl } + , Number : { type: Number, validate: validateNumber } + , path : { type: path, validate: validatePath } + , Stream : { type: Stream, validate: validateStream } + , Date : { type: Date, validate: validateDate } + } + +function nopt (types, shorthands, args, slice) { + args = args || process.argv + types = types || {} + shorthands = shorthands || {} + if (typeof slice !== "number") slice = 2 + + debug(types, shorthands, args, slice) + + args = args.slice(slice) + var data = {} + , key + , argv = { + remain: [], + cooked: args, + original: args.slice(0) + } + + parse(args, data, argv.remain, types, shorthands) + // now data is full + clean(data, types, exports.typeDefs) + data.argv = argv + Object.defineProperty(data.argv, 'toString', { value: function () { + return this.original.map(JSON.stringify).join(" ") + }, enumerable: false }) + return data +} + +function clean (data, types, typeDefs) { + typeDefs = typeDefs || exports.typeDefs + var remove = {} + , typeDefault = [false, true, null, String, Array] + + Object.keys(data).forEach(function (k) { + if (k === "argv") return + var val = data[k] + , isArray = Array.isArray(val) + , type = types[k] + if (!isArray) val = [val] + if (!type) type = typeDefault + if (type === Array) type = typeDefault.concat(Array) + if (!Array.isArray(type)) type = [type] + + debug("val=%j", val) + debug("types=", type) + val = val.map(function (val) { + // if it's an unknown value, then parse false/true/null/numbers/dates + if (typeof val === "string") { + debug("string %j", val) + val = val.trim() + if ((val === "null" && ~type.indexOf(null)) + || (val === "true" && + (~type.indexOf(true) || ~type.indexOf(Boolean))) + || (val === "false" && + (~type.indexOf(false) || ~type.indexOf(Boolean)))) { + val = JSON.parse(val) + debug("jsonable %j", val) + } else if (~type.indexOf(Number) && !isNaN(val)) { + debug("convert to number", val) + val = +val + } else if (~type.indexOf(Date) && !isNaN(Date.parse(val))) { + debug("convert to date", val) + val = new Date(val) + } + } + + if (!types.hasOwnProperty(k)) { + return val + } + + // allow `--no-blah` to set 'blah' to null if null is allowed + if (val === false && ~type.indexOf(null) && + !(~type.indexOf(false) || ~type.indexOf(Boolean))) { + val = null + } + + var d = {} + d[k] = val + debug("prevalidated val", d, val, types[k]) + if (!validate(d, k, val, types[k], typeDefs)) { + if (exports.invalidHandler) { + exports.invalidHandler(k, val, types[k], data) + } else if (exports.invalidHandler !== false) { + debug("invalid: "+k+"="+val, types[k]) + } + return remove + } + debug("validated val", d, val, types[k]) + return d[k] + }).filter(function (val) { return val !== remove }) + + // if we allow Array specifically, then an empty array is how we + // express 'no value here', not null. Allow it. + if (!val.length && type.indexOf(Array) === -1) { + debug('VAL HAS NO LENGTH, DELETE IT', val, k, type.indexOf(Array)) + delete data[k] + } + else if (isArray) { + debug(isArray, data[k], val) + data[k] = val + } else data[k] = val[0] + + debug("k=%s val=%j", k, val, data[k]) + }) +} + +function validateString (data, k, val) { + data[k] = String(val) +} + +function validatePath (data, k, val) { + if (val === true) return false + if (val === null) return true + + val = String(val) + + var isWin = process.platform === 'win32' + , homePattern = isWin ? /^~(\/|\\)/ : /^~\// + , home = osenv.home() + + if (home && val.match(homePattern)) { + data[k] = path.resolve(home, val.substr(2)) + } else { + data[k] = path.resolve(val) + } + return true +} + +function validateNumber (data, k, val) { + debug("validate Number %j %j %j", k, val, isNaN(val)) + if (isNaN(val)) return false + data[k] = +val +} + +function validateDate (data, k, val) { + var s = Date.parse(val) + debug("validate Date %j %j %j", k, val, s) + if (isNaN(s)) return false + data[k] = new Date(val) +} + +function validateBoolean (data, k, val) { + if (val instanceof Boolean) val = val.valueOf() + else if (typeof val === "string") { + if (!isNaN(val)) val = !!(+val) + else if (val === "null" || val === "false") val = false + else val = true + } else val = !!val + data[k] = val +} + +function validateUrl (data, k, val) { + val = url.parse(String(val)) + if (!val.host) return false + data[k] = val.href +} + +function validateStream (data, k, val) { + if (!(val instanceof Stream)) return false + data[k] = val +} + +function validate (data, k, val, type, typeDefs) { + // arrays are lists of types. + if (Array.isArray(type)) { + for (var i = 0, l = type.length; i < l; i ++) { + if (type[i] === Array) continue + if (validate(data, k, val, type[i], typeDefs)) return true + } + delete data[k] + return false + } + + // an array of anything? + if (type === Array) return true + + // NaN is poisonous. Means that something is not allowed. + if (type !== type) { + debug("Poison NaN", k, val, type) + delete data[k] + return false + } + + // explicit list of values + if (val === type) { + debug("Explicitly allowed %j", val) + // if (isArray) (data[k] = data[k] || []).push(val) + // else data[k] = val + data[k] = val + return true + } + + // now go through the list of typeDefs, validate against each one. + var ok = false + , types = Object.keys(typeDefs) + for (var i = 0, l = types.length; i < l; i ++) { + debug("test type %j %j %j", k, val, types[i]) + var t = typeDefs[types[i]] + if (t && + ((type && type.name && t.type && t.type.name) ? (type.name === t.type.name) : (type === t.type))) { + var d = {} + ok = false !== t.validate(d, k, val) + val = d[k] + if (ok) { + // if (isArray) (data[k] = data[k] || []).push(val) + // else data[k] = val + data[k] = val + break + } + } + } + debug("OK? %j (%j %j %j)", ok, k, val, types[i]) + + if (!ok) delete data[k] + return ok +} + +function parse (args, data, remain, types, shorthands) { + debug("parse", args, data, remain) + + var key = null + , abbrevs = abbrev(Object.keys(types)) + , shortAbbr = abbrev(Object.keys(shorthands)) + + for (var i = 0; i < args.length; i ++) { + var arg = args[i] + debug("arg", arg) + + if (arg.match(/^-{2,}$/)) { + // done with keys. + // the rest are args. + remain.push.apply(remain, args.slice(i + 1)) + args[i] = "--" + break + } + var hadEq = false + if (arg.charAt(0) === "-" && arg.length > 1) { + var at = arg.indexOf('=') + if (at > -1) { + hadEq = true + var v = arg.substr(at + 1) + arg = arg.substr(0, at) + args.splice(i, 1, arg, v) + } + + // see if it's a shorthand + // if so, splice and back up to re-parse it. + var shRes = resolveShort(arg, shorthands, shortAbbr, abbrevs) + debug("arg=%j shRes=%j", arg, shRes) + if (shRes) { + debug(arg, shRes) + args.splice.apply(args, [i, 1].concat(shRes)) + if (arg !== shRes[0]) { + i -- + continue + } + } + arg = arg.replace(/^-+/, "") + var no = null + while (arg.toLowerCase().indexOf("no-") === 0) { + no = !no + arg = arg.substr(3) + } + + if (abbrevs[arg]) arg = abbrevs[arg] + + var argType = types[arg] + var isTypeArray = Array.isArray(argType) + if (isTypeArray && argType.length === 1) { + isTypeArray = false + argType = argType[0] + } + + var isArray = argType === Array || + isTypeArray && argType.indexOf(Array) !== -1 + + // allow unknown things to be arrays if specified multiple times. + if (!types.hasOwnProperty(arg) && data.hasOwnProperty(arg)) { + if (!Array.isArray(data[arg])) + data[arg] = [data[arg]] + isArray = true + } + + var val + , la = args[i + 1] + + var isBool = typeof no === 'boolean' || + argType === Boolean || + isTypeArray && argType.indexOf(Boolean) !== -1 || + (typeof argType === 'undefined' && !hadEq) || + (la === "false" && + (argType === null || + isTypeArray && ~argType.indexOf(null))) + + if (isBool) { + // just set and move along + val = !no + // however, also support --bool true or --bool false + if (la === "true" || la === "false") { + val = JSON.parse(la) + la = null + if (no) val = !val + i ++ + } + + // also support "foo":[Boolean, "bar"] and "--foo bar" + if (isTypeArray && la) { + if (~argType.indexOf(la)) { + // an explicit type + val = la + i ++ + } else if ( la === "null" && ~argType.indexOf(null) ) { + // null allowed + val = null + i ++ + } else if ( !la.match(/^-{2,}[^-]/) && + !isNaN(la) && + ~argType.indexOf(Number) ) { + // number + val = +la + i ++ + } else if ( !la.match(/^-[^-]/) && ~argType.indexOf(String) ) { + // string + val = la + i ++ + } + } + + if (isArray) (data[arg] = data[arg] || []).push(val) + else data[arg] = val + + continue + } + + if (argType === String) { + if (la === undefined) { + la = "" + } else if (la.match(/^-{1,2}[^-]+/)) { + la = "" + i -- + } + } + + if (la && la.match(/^-{2,}$/)) { + la = undefined + i -- + } + + val = la === undefined ? true : la + if (isArray) (data[arg] = data[arg] || []).push(val) + else data[arg] = val + + i ++ + continue + } + remain.push(arg) + } +} + +function resolveShort (arg, shorthands, shortAbbr, abbrevs) { + // handle single-char shorthands glommed together, like + // npm ls -glp, but only if there is one dash, and only if + // all of the chars are single-char shorthands, and it's + // not a match to some other abbrev. + arg = arg.replace(/^-+/, '') + + // if it's an exact known option, then don't go any further + if (abbrevs[arg] === arg) + return null + + // if it's an exact known shortopt, same deal + if (shorthands[arg]) { + // make it an array, if it's a list of words + if (shorthands[arg] && !Array.isArray(shorthands[arg])) + shorthands[arg] = shorthands[arg].split(/\s+/) + + return shorthands[arg] + } + + // first check to see if this arg is a set of single-char shorthands + var singles = shorthands.___singles + if (!singles) { + singles = Object.keys(shorthands).filter(function (s) { + return s.length === 1 + }).reduce(function (l,r) { + l[r] = true + return l + }, {}) + shorthands.___singles = singles + debug('shorthand singles', singles) + } + + var chrs = arg.split("").filter(function (c) { + return singles[c] + }) + + if (chrs.join("") === arg) return chrs.map(function (c) { + return shorthands[c] + }).reduce(function (l, r) { + return l.concat(r) + }, []) + + + // if it's an arg abbrev, and not a literal shorthand, then prefer the arg + if (abbrevs[arg] && !shorthands[arg]) + return null + + // if it's an abbr for a shorthand, then use that + if (shortAbbr[arg]) + arg = shortAbbr[arg] + + // make it an array, if it's a list of words + if (shorthands[arg] && !Array.isArray(shorthands[arg])) + shorthands[arg] = shorthands[arg].split(/\s+/) + + return shorthands[arg] +} + + +/***/ }), +/* 402 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +// Approach: +// +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them +// +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. +// +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. + +module.exports = glob + +var fs = __webpack_require__(747) +var rp = __webpack_require__(302) +var minimatch = __webpack_require__(93) +var Minimatch = minimatch.Minimatch +var inherits = __webpack_require__(689) +var EE = __webpack_require__(614).EventEmitter +var path = __webpack_require__(622) +var assert = __webpack_require__(357) +var isAbsolute = __webpack_require__(681) +var globSync = __webpack_require__(544) +var common = __webpack_require__(856) +var alphasort = common.alphasort +var alphasorti = common.alphasorti +var setopts = common.setopts +var ownProp = common.ownProp +var inflight = __webpack_require__(674) +var util = __webpack_require__(669) +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored + +var once = __webpack_require__(49) + +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {} + if (!options) options = {} + + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) + } + + return new Glob(pattern, options, cb) +} + +glob.sync = globSync +var GlobSync = glob.GlobSync = globSync.GlobSync + +// old api surface +glob.glob = glob + +function extend (origin, add) { + if (add === null || typeof add !== 'object') { + return origin + } + + var keys = Object.keys(add) + var i = keys.length + while (i--) { + origin[keys[i]] = add[keys[i]] + } + return origin +} + +glob.hasMagic = function (pattern, options_) { + var options = extend({}, options_) + options.noprocess = true + + var g = new Glob(pattern, options) + var set = g.minimatch.set + + if (!pattern) + return false + + if (set.length > 1) + return true + + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } + + return false +} + +glob.Glob = Glob +inherits(Glob, EE) +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) + } + + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) + + setopts(this, pattern, options) + this._didRealPath = false + + // process each pattern in the minimatch set + var n = this.minimatch.set.length + + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n) + + if (typeof cb === 'function') { + cb = once(cb) + this.on('error', cb) + this.on('end', function (matches) { + cb(null, matches) + }) + } + + var self = this + this._processing = 0 + + this._emitQueue = [] + this._processQueue = [] + this.paused = false + + if (this.noprocess) + return this + + if (n === 0) + return done() + + var sync = true + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done) + } + sync = false + + function done () { + --self._processing + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish() + }) + } else { + self._finish() + } + } + } +} + +Glob.prototype._finish = function () { + assert(this instanceof Glob) + if (this.aborted) + return + + if (this.realpath && !this._didRealpath) + return this._realpath() + + common.finish(this) + this.emit('end', this.found) +} + +Glob.prototype._realpath = function () { + if (this._didRealpath) + return + + this._didRealpath = true + + var n = this.matches.length + if (n === 0) + return this._finish() + + var self = this + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next) + + function next () { + if (--n === 0) + self._finish() + } +} + +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index] + if (!matchset) + return cb() + + var found = Object.keys(matchset) + var self = this + var n = found.length + + if (n === 0) + return cb() + + var set = this.matches[index] = Object.create(null) + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p) + rp.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true + else if (er.syscall === 'stat') + set[p] = true + else + self.emit('error', er) // srsly wtf right here + + if (--n === 0) { + self.matches[index] = set + cb() + } + }) + }) +} + +Glob.prototype._mark = function (p) { + return common.mark(this, p) +} + +Glob.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} + +Glob.prototype.abort = function () { + this.aborted = true + this.emit('abort') +} + +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true + this.emit('pause') + } +} + +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume') + this.paused = false + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0) + this._emitQueue.length = 0 + for (var i = 0; i < eq.length; i ++) { + var e = eq[i] + this._emitMatch(e[0], e[1]) + } + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0) + this._processQueue.length = 0 + for (var i = 0; i < pq.length; i ++) { + var p = pq[i] + this._processing-- + this._process(p[0], p[1], p[2], p[3]) + } + } + } +} + +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob) + assert(typeof cb === 'function') + + if (this.aborted) + return + + this._processing++ + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]) + return + } + + //console.error('PROCESS %d', this._processing, pattern) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // see if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip _processing + if (childrenIgnored(this, read)) + return cb() + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) +} + +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return cb() + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + this._process([e].concat(remain), index, inGlobStar, cb) + } + cb() +} + +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return + + if (isIgnored(this, e)) + return + + if (this.paused) { + this._emitQueue.push([index, e]) + return + } + + var abs = isAbsolute(e) ? e : this._makeAbs(e) + + if (this.mark) + e = this._mark(e) + + if (this.absolute) + e = abs + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true + + var st = this.statCache[abs] + if (st) + this.emit('stat', e, st) + + this.emit('match', e) +} + +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return + + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) + + var lstatkey = 'lstat\0' + abs + var self = this + var lstatcb = inflight(lstatkey, lstatcb_) + + if (lstatcb) + fs.lstat(abs, lstatcb) + + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() + + var isSym = lstat && lstat.isSymbolicLink() + self.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE' + cb() + } else + self._readdir(abs, false, cb) + } +} + +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return + + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) + if (!cb) + return + + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return cb() + + if (Array.isArray(c)) + return cb(null, c) + } + + var self = this + fs.readdir(abs, readdirCb(this, abs, cb)) +} + +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb) + else + self._readdirEntries(abs, entries, cb) + } +} + +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return + + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + return cb(null, entries) +} + +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return + + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + this.emit('error', error) + this.abort() + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) { + this.emit('error', er) + // If the error is handled, then we abort + // if not, we threw out of here + this.abort() + } + if (!this.silent) + console.error('glob error', er) + break + } + + return cb() +} + +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + + +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb) + + var isSym = this.symlinks[abs] + var len = entries.length + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true, cb) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true, cb) + } + + cb() +} + +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb) + }) +} +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + + //console.error('ps2', prefix, exists) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) + cb() +} + +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return cb() + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) + + if (needDir && c === 'FILE') + return cb() + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE' + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } + } + + var self = this + var statcb = inflight('stat\0' + abs, lstatcb_) + if (statcb) + fs.lstat(abs, statcb) + + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return fs.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb) + else + self._stat2(f, abs, er, stat, cb) + }) + } else { + self._stat2(f, abs, er, lstat, cb) + } + } +} + +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return cb() + } + + var needDir = f.slice(-1) === '/' + this.statCache[abs] = stat + + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) + + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + this.cache[abs] = this.cache[abs] || c + + if (needDir && c === 'FILE') + return cb() + + return cb(null, c, stat) +} + + +/***/ }), +/* 403 */, +/* 404 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const duck = __webpack_require__(843) + +const Fetcher = duck.define(['spec', 'opts', 'manifest'], { + packument: ['spec', 'opts'], + manifest: ['spec', 'opts'], + tarball: ['spec', 'opts'], + fromManifest: ['manifest', 'spec', 'opts'], + clearMemoized () {} +}, { name: 'Fetcher' }) +module.exports = Fetcher + +module.exports.packument = packument +function packument (spec, opts) { + const fetcher = getFetcher(spec.type) + return fetcher.packument(spec, opts) +} + +module.exports.manifest = manifest +function manifest (spec, opts) { + const fetcher = getFetcher(spec.type) + return fetcher.manifest(spec, opts) +} + +module.exports.tarball = tarball +function tarball (spec, opts) { + return getFetcher(spec.type).tarball(spec, opts) +} + +module.exports.fromManifest = fromManifest +function fromManifest (manifest, spec, opts) { + return getFetcher(spec.type).fromManifest(manifest, spec, opts) +} + +const fetchers = {} + +module.exports.clearMemoized = clearMemoized +function clearMemoized () { + Object.keys(fetchers).forEach(k => { + fetchers[k].clearMemoized() + }) +} + +function getFetcher (type) { + if (!fetchers[type]) { + // This is spelled out both to prevent sketchy stuff and to make life + // easier for bundlers/preprocessors. + switch (type) { + case 'alias': + fetchers[type] = __webpack_require__(457) + break + case 'directory': + fetchers[type] = __webpack_require__(879) + break + case 'file': + fetchers[type] = __webpack_require__(212) + break + case 'git': + fetchers[type] = __webpack_require__(181) + break + case 'hosted': + fetchers[type] = __webpack_require__(804) + break + case 'range': + fetchers[type] = __webpack_require__(987) + break + case 'remote': + fetchers[type] = __webpack_require__(507) + break + case 'tag': + fetchers[type] = __webpack_require__(578) + break + case 'version': + fetchers[type] = __webpack_require__(499) + break + default: + throw new Error(`Invalid dependency type requested: ${type}`) + } + } + return fetchers[type] +} + + +/***/ }), +/* 405 */, +/* 406 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +// On windows, create a .cmd file. +// Read the #! in the file to see what it uses. The vast majority +// of the time, this will be either: +// "#!/usr/bin/env " +// or: +// "#! " +// +// Write a binroot/pkg.bin + ".cmd" file that has this line in it: +// @ %dp0% %* + +module.exports = cmdShim +cmdShim.ifExists = cmdShimIfExists + +var fs = __webpack_require__(598) + +var mkdir = __webpack_require__(626) + , path = __webpack_require__(622) + , toBatchSyntax = __webpack_require__(513) + , shebangExpr = /^#\!\s*(?:\/usr\/bin\/env)?\s*([^ \t]+=[^ \t]+\s+)*\s*([^ \t]+)(.*)$/ + +function cmdShimIfExists (from, to, cb) { + fs.stat(from, function (er) { + if (er) return cb() + cmdShim(from, to, cb) + }) +} + +// Try to unlink, but ignore errors. +// Any problems will surface later. +function rm (path, cb) { + fs.unlink(path, function(er) { + cb() + }) +} + +function cmdShim (from, to, cb) { + fs.stat(from, function (er, stat) { + if (er) + return cb(er) + + cmdShim_(from, to, cb) + }) +} + +function cmdShim_ (from, to, cb) { + var then = times(3, next, cb) + rm(to, then) + rm(to + ".cmd", then) + rm(to + ".ps1", then) + + function next(er) { + writeShim(from, to, cb) + } +} + +function writeShim (from, to, cb) { + // make a cmd file and a sh script + // First, check if the bin is a #! of some sort. + // If not, then assume it's something that'll be compiled, or some other + // sort of script, and just call it directly. + mkdir(path.dirname(to), function (er) { + if (er) + return cb(er) + fs.readFile(from, "utf8", function (er, data) { + if (er) return writeShim_(from, to, null, null, null, cb) + var firstLine = data.trim().split(/\r*\n/)[0] + , shebang = firstLine.match(shebangExpr) + if (!shebang) return writeShim_(from, to, null, null, null, cb) + var vars = shebang[1] || "" + , prog = shebang[2] + , args = shebang[3] || "" + return writeShim_(from, to, prog, args, vars, cb) + }) + }) +} + + +function writeShim_ (from, to, prog, args, variables, cb) { + var shTarget = path.relative(path.dirname(to), from) + , target = shTarget.split("/").join("\\") + , longProg + , shProg = prog && prog.split("\\").join("/") + , shLongProg + , pwshProg = shProg && "\"" + shProg + "$exe\"" + , pwshLongProg + shTarget = shTarget.split("\\").join("/") + args = args || "" + variables = variables || "" + if (!prog) { + prog = "\"%dp0%\\" + target + "\"" + shProg = "\"$basedir/" + shTarget + "\"" + pwshProg = shProg + args = "" + target = "" + shTarget = "" + } else { + longProg = "\"%dp0%\\" + prog + ".exe\"" + shLongProg = "\"$basedir/" + prog + "\"" + pwshLongProg = "\"$basedir/" + prog + "$exe\"" + target = "\"%dp0%\\" + target + "\"" + shTarget = "\"$basedir/" + shTarget + "\"" + } + + // @SETLOCAL + // @CALL :find_dp0 + // + // @IF EXIST "%dp0%\node.exe" ( + // @SET "_prog=%dp0%\node.exe" + // ) ELSE ( + // @SET "_prog=node" + // @SET PATHEXT=%PATHEXT:;.JS;=;% + // ) + // + // "%_prog%" "%dp0%\.\node_modules\npm\bin\npm-cli.js" %* + // @ENDLOCAL + // @EXIT /b %errorlevel% + // + // :find_dp0 + // SET dp0=%~dp0 + // EXIT /b + // + // Subroutine trick to fix https://github.com/npm/cmd-shim/issues/10 + var head = '@ECHO off\r\n' + + 'SETLOCAL\r\n' + + 'CALL :find_dp0\r\n' + var foot = 'ENDLOCAL\r\n' + + 'EXIT /b %errorlevel%\r\n' + + ':find_dp0\r\n' + + 'SET dp0=%~dp0\r\n' + + 'EXIT /b\r\n' + + var cmd + if (longProg) { + shLongProg = shLongProg.trim(); + args = args.trim(); + var variableDeclarationsAsBatch = toBatchSyntax.convertToSetCommands(variables) + cmd = head + + variableDeclarationsAsBatch + + "\r\n" + + "IF EXIST " + longProg + " (\r\n" + + " SET \"_prog=" + longProg.replace(/(^")|("$)/g, '') + "\"\r\n" + + ") ELSE (\r\n" + + " SET \"_prog=" + prog.replace(/(^")|("$)/g, '') + "\"\r\n" + + " SET PATHEXT=%PATHEXT:;.JS;=;%\r\n" + + ")\r\n" + + "\r\n" + + "\"%_prog%\" " + args + " " + target + " %*\r\n" + + foot + } else { + cmd = head + prog + " " + args + " " + target + " %*\r\n" + foot + } + + // #!/bin/sh + // basedir=`dirname "$0"` + // + // case `uname` in + // *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; + // esac + // + // if [ -x "$basedir/node.exe" ]; then + // "$basedir/node.exe" "$basedir/node_modules/npm/bin/npm-cli.js" "$@" + // ret=$? + // else + // node "$basedir/node_modules/npm/bin/npm-cli.js" "$@" + // ret=$? + // fi + // exit $ret + + var sh = "#!/bin/sh\n" + + sh = sh + + "basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n" + + "\n" + + "case `uname` in\n" + + " *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w \"$basedir\"`;;\n" + + "esac\n" + + "\n" + + if (shLongProg) { + sh = sh + + "if [ -x "+shLongProg+" ]; then\n" + + " " + variables + shLongProg + " " + args + " " + shTarget + " \"$@\"\n" + + " ret=$?\n" + + "else \n" + + " " + variables + shProg + " " + args + " " + shTarget + " \"$@\"\n" + + " ret=$?\n" + + "fi\n" + + "exit $ret\n" + } else { + sh = sh + + shProg + " " + args + " " + shTarget + " \"$@\"\n" + + "exit $?\n" + } + + // #!/usr/bin/env pwsh + // $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + // + // $ret=0 + // $exe = "" + // if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + // # Fix case when both the Windows and Linux builds of Node + // # are installed in the same directory + // $exe = ".exe" + // } + // if (Test-Path "$basedir/node") { + // & "$basedir/node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args + // $ret=$LASTEXITCODE + // } else { + // & "node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args + // $ret=$LASTEXITCODE + // } + // exit $ret + var pwsh = "#!/usr/bin/env pwsh\n" + + "$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent\n" + + "\n" + + "$exe=\"\"\n" + + "if ($PSVersionTable.PSVersion -lt \"6.0\" -or $IsWindows) {\n" + + " # Fix case when both the Windows and Linux builds of Node\n" + + " # are installed in the same directory\n" + + " $exe=\".exe\"\n" + + "}\n" + if (shLongProg) { + pwsh = pwsh + + "$ret=0\n" + + "if (Test-Path " + pwshLongProg + ") {\n" + + " & " + pwshLongProg + " " + args + " " + shTarget + " $args\n" + + " $ret=$LASTEXITCODE\n" + + "} else {\n" + + " & " + pwshProg + " " + args + " " + shTarget + " $args\n" + + " $ret=$LASTEXITCODE\n" + + "}\n" + + "exit $ret\n" + } else { + pwsh = pwsh + + "& " + pwshProg + " " + args + " " + shTarget + " $args\n" + + "exit $LASTEXITCODE\n" + } + + var then = times(3, next, cb) + fs.writeFile(to + ".ps1", pwsh, "utf8", then) + fs.writeFile(to + ".cmd", cmd, "utf8", then) + fs.writeFile(to, sh, "utf8", then) + function next () { + chmodShim(to, cb) + } +} + +function chmodShim (to, cb) { + var then = times(3, cb, cb) + fs.chmod(to, "0755", then) + fs.chmod(to + ".cmd", "0755", then) + fs.chmod(to + ".ps1", "0755", then) +} + +function times(n, ok, cb) { + var errState = null + return function(er) { + if (!errState) { + if (er) + cb(errState = er) + else if (--n === 0) + ok() + } + } +} + + +/***/ }), +/* 407 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const BB = __webpack_require__(489) + +const contentPath = __webpack_require__(969) +const crypto = __webpack_require__(417) +const figgyPudding = __webpack_require__(122) +const fixOwner = __webpack_require__(133) +const fs = __webpack_require__(598) +const hashToSegments = __webpack_require__(271) +const ms = __webpack_require__(371) +const path = __webpack_require__(622) +const ssri = __webpack_require__(951) +const Y = __webpack_require__(945) + +const indexV = __webpack_require__(525)['cache-version'].index + +const appendFileAsync = BB.promisify(fs.appendFile) +const readFileAsync = BB.promisify(fs.readFile) +const readdirAsync = BB.promisify(fs.readdir) +const concat = ms.concat +const from = ms.from + +module.exports.NotFoundError = class NotFoundError extends Error { + constructor (cache, key) { + super(Y`No cache entry for \`${key}\` found in \`${cache}\``) + this.code = 'ENOENT' + this.cache = cache + this.key = key + } +} + +const IndexOpts = figgyPudding({ + metadata: {}, + size: {} +}) + +module.exports.insert = insert +function insert (cache, key, integrity, opts) { + opts = IndexOpts(opts) + const bucket = bucketPath(cache, key) + const entry = { + key, + integrity: integrity && ssri.stringify(integrity), + time: Date.now(), + size: opts.size, + metadata: opts.metadata + } + return fixOwner.mkdirfix( + cache, path.dirname(bucket) + ).then(() => { + const stringified = JSON.stringify(entry) + // NOTE - Cleverness ahoy! + // + // This works because it's tremendously unlikely for an entry to corrupt + // another while still preserving the string length of the JSON in + // question. So, we just slap the length in there and verify it on read. + // + // Thanks to @isaacs for the whiteboarding session that ended up with this. + return appendFileAsync( + bucket, `\n${hashEntry(stringified)}\t${stringified}` + ) + }).then( + () => fixOwner.chownr(cache, bucket) + ).catch({ code: 'ENOENT' }, () => { + // There's a class of race conditions that happen when things get deleted + // during fixOwner, or between the two mkdirfix/chownr calls. + // + // It's perfectly fine to just not bother in those cases and lie + // that the index entry was written. Because it's a cache. + }).then(() => { + return formatEntry(cache, entry) + }) +} + +module.exports.insert.sync = insertSync +function insertSync (cache, key, integrity, opts) { + opts = IndexOpts(opts) + const bucket = bucketPath(cache, key) + const entry = { + key, + integrity: integrity && ssri.stringify(integrity), + time: Date.now(), + size: opts.size, + metadata: opts.metadata + } + fixOwner.mkdirfix.sync(cache, path.dirname(bucket)) + const stringified = JSON.stringify(entry) + fs.appendFileSync( + bucket, `\n${hashEntry(stringified)}\t${stringified}` + ) + try { + fixOwner.chownr.sync(cache, bucket) + } catch (err) { + if (err.code !== 'ENOENT') { + throw err + } + } + return formatEntry(cache, entry) +} + +module.exports.find = find +function find (cache, key) { + const bucket = bucketPath(cache, key) + return bucketEntries(bucket).then(entries => { + return entries.reduce((latest, next) => { + if (next && next.key === key) { + return formatEntry(cache, next) + } else { + return latest + } + }, null) + }).catch(err => { + if (err.code === 'ENOENT') { + return null + } else { + throw err + } + }) +} + +module.exports.find.sync = findSync +function findSync (cache, key) { + const bucket = bucketPath(cache, key) + try { + return bucketEntriesSync(bucket).reduce((latest, next) => { + if (next && next.key === key) { + return formatEntry(cache, next) + } else { + return latest + } + }, null) + } catch (err) { + if (err.code === 'ENOENT') { + return null + } else { + throw err + } + } +} + +module.exports.delete = del +function del (cache, key, opts) { + return insert(cache, key, null, opts) +} + +module.exports.delete.sync = delSync +function delSync (cache, key, opts) { + return insertSync(cache, key, null, opts) +} + +module.exports.lsStream = lsStream +function lsStream (cache) { + const indexDir = bucketDir(cache) + const stream = from.obj() + + // "/cachename/*" + readdirOrEmpty(indexDir).map(bucket => { + const bucketPath = path.join(indexDir, bucket) + + // "/cachename//*" + return readdirOrEmpty(bucketPath).map(subbucket => { + const subbucketPath = path.join(bucketPath, subbucket) + + // "/cachename///*" + return readdirOrEmpty(subbucketPath).map(entry => { + const getKeyToEntry = bucketEntries( + path.join(subbucketPath, entry) + ).reduce((acc, entry) => { + acc.set(entry.key, entry) + return acc + }, new Map()) + + return getKeyToEntry.then(reduced => { + for (let entry of reduced.values()) { + const formatted = formatEntry(cache, entry) + formatted && stream.push(formatted) + } + }).catch({ code: 'ENOENT' }, nop) + }) + }) + }).then(() => { + stream.push(null) + }, err => { + stream.emit('error', err) + }) + + return stream +} + +module.exports.ls = ls +function ls (cache) { + return BB.fromNode(cb => { + lsStream(cache).on('error', cb).pipe(concat(entries => { + cb(null, entries.reduce((acc, xs) => { + acc[xs.key] = xs + return acc + }, {})) + })) + }) +} + +function bucketEntries (bucket, filter) { + return readFileAsync( + bucket, 'utf8' + ).then(data => _bucketEntries(data, filter)) +} + +function bucketEntriesSync (bucket, filter) { + const data = fs.readFileSync(bucket, 'utf8') + return _bucketEntries(data, filter) +} + +function _bucketEntries (data, filter) { + let entries = [] + data.split('\n').forEach(entry => { + if (!entry) { return } + const pieces = entry.split('\t') + if (!pieces[1] || hashEntry(pieces[1]) !== pieces[0]) { + // Hash is no good! Corruption or malice? Doesn't matter! + // EJECT EJECT + return + } + let obj + try { + obj = JSON.parse(pieces[1]) + } catch (e) { + // Entry is corrupted! + return + } + if (obj) { + entries.push(obj) + } + }) + return entries +} + +module.exports._bucketDir = bucketDir +function bucketDir (cache) { + return path.join(cache, `index-v${indexV}`) +} + +module.exports._bucketPath = bucketPath +function bucketPath (cache, key) { + const hashed = hashKey(key) + return path.join.apply(path, [bucketDir(cache)].concat( + hashToSegments(hashed) + )) +} + +module.exports._hashKey = hashKey +function hashKey (key) { + return hash(key, 'sha256') +} + +module.exports._hashEntry = hashEntry +function hashEntry (str) { + return hash(str, 'sha1') +} + +function hash (str, digest) { + return crypto + .createHash(digest) + .update(str) + .digest('hex') +} + +function formatEntry (cache, entry) { + // Treat null digests as deletions. They'll shadow any previous entries. + if (!entry.integrity) { return null } + return { + key: entry.key, + integrity: entry.integrity, + path: contentPath(cache, entry.integrity), + size: entry.size, + time: entry.time, + metadata: entry.metadata + } +} + +function readdirOrEmpty (dir) { + return readdirAsync(dir) + .catch({ code: 'ENOENT' }, () => []) + .catch({ code: 'ENOTDIR' }, () => []) +} + +function nop () { +} + + +/***/ }), +/* 408 */ +/***/ (function(module) { + +"use strict"; + + +function isArguments (thingy) { + return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee') +} + +var types = { + '*': {label: 'any', check: function () { return true }}, + A: {label: 'array', check: function (thingy) { return Array.isArray(thingy) || isArguments(thingy) }}, + S: {label: 'string', check: function (thingy) { return typeof thingy === 'string' }}, + N: {label: 'number', check: function (thingy) { return typeof thingy === 'number' }}, + F: {label: 'function', check: function (thingy) { return typeof thingy === 'function' }}, + O: {label: 'object', check: function (thingy) { return typeof thingy === 'object' && thingy != null && !types.A.check(thingy) && !types.E.check(thingy) }}, + B: {label: 'boolean', check: function (thingy) { return typeof thingy === 'boolean' }}, + E: {label: 'error', check: function (thingy) { return thingy instanceof Error }}, + Z: {label: 'null', check: function (thingy) { return thingy == null }} +} + +function addSchema (schema, arity) { + var group = arity[schema.length] = arity[schema.length] || [] + if (group.indexOf(schema) === -1) group.push(schema) +} + +var validate = module.exports = function (rawSchemas, args) { + if (arguments.length !== 2) throw wrongNumberOfArgs(['SA'], arguments.length) + if (!rawSchemas) throw missingRequiredArg(0, 'rawSchemas') + if (!args) throw missingRequiredArg(1, 'args') + if (!types.S.check(rawSchemas)) throw invalidType(0, ['string'], rawSchemas) + if (!types.A.check(args)) throw invalidType(1, ['array'], args) + var schemas = rawSchemas.split('|') + var arity = {} + + schemas.forEach(function (schema) { + for (var ii = 0; ii < schema.length; ++ii) { + var type = schema[ii] + if (!types[type]) throw unknownType(ii, type) + } + if (/E.*E/.test(schema)) throw moreThanOneError(schema) + addSchema(schema, arity) + if (/E/.test(schema)) { + addSchema(schema.replace(/E.*$/, 'E'), arity) + addSchema(schema.replace(/E/, 'Z'), arity) + if (schema.length === 1) addSchema('', arity) + } + }) + var matching = arity[args.length] + if (!matching) { + throw wrongNumberOfArgs(Object.keys(arity), args.length) + } + for (var ii = 0; ii < args.length; ++ii) { + var newMatching = matching.filter(function (schema) { + var type = schema[ii] + var typeCheck = types[type].check + return typeCheck(args[ii]) + }) + if (!newMatching.length) { + var labels = matching.map(function (schema) { + return types[schema[ii]].label + }).filter(function (schema) { return schema != null }) + throw invalidType(ii, labels, args[ii]) + } + matching = newMatching + } +} + +function missingRequiredArg (num) { + return newException('EMISSINGARG', 'Missing required argument #' + (num + 1)) +} + +function unknownType (num, type) { + return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 1)) +} + +function invalidType (num, expectedTypes, value) { + var valueType + Object.keys(types).forEach(function (typeCode) { + if (types[typeCode].check(value)) valueType = types[typeCode].label + }) + return newException('EINVALIDTYPE', 'Argument #' + (num + 1) + ': Expected ' + + englishList(expectedTypes) + ' but got ' + valueType) +} + +function englishList (list) { + return list.join(', ').replace(/, ([^,]+)$/, ' or $1') +} + +function wrongNumberOfArgs (expected, got) { + var english = englishList(expected) + var args = expected.every(function (ex) { return ex.length === 1 }) + ? 'argument' + : 'arguments' + return newException('EWRONGARGCOUNT', 'Expected ' + english + ' ' + args + ' but got ' + got) +} + +function moreThanOneError (schema) { + return newException('ETOOMANYERRORTYPES', + 'Only one error type per argument signature is allowed, more than one found in "' + schema + '"') +} + +function newException (code, msg) { + var e = new Error(msg) + e.code = code + if (Error.captureStackTrace) Error.captureStackTrace(e, validate) + return e +} + + +/***/ }), +/* 409 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + +module.exports = function(Promise, INTERNAL, debug) { +var util = __webpack_require__(248); +var TimeoutError = Promise.TimeoutError; + +function HandleWrapper(handle) { + this.handle = handle; +} + +HandleWrapper.prototype._resultCancelled = function() { + clearTimeout(this.handle); +}; + +var afterValue = function(value) { return delay(+this).thenReturn(value); }; +var delay = Promise.delay = function (ms, value) { + var ret; + var handle; + if (value !== undefined) { + ret = Promise.resolve(value) + ._then(afterValue, null, null, ms, undefined); + if (debug.cancellation() && value instanceof Promise) { + ret._setOnCancel(value); + } + } else { + ret = new Promise(INTERNAL); + handle = setTimeout(function() { ret._fulfill(); }, +ms); + if (debug.cancellation()) { + ret._setOnCancel(new HandleWrapper(handle)); + } + ret._captureStackTrace(); + } + ret._setAsyncGuaranteed(); + return ret; +}; + +Promise.prototype.delay = function (ms) { + return delay(ms, this); +}; + +var afterTimeout = function (promise, message, parent) { + var err; + if (typeof message !== "string") { + if (message instanceof Error) { + err = message; + } else { + err = new TimeoutError("operation timed out"); + } + } else { + err = new TimeoutError(message); + } + util.markAsOriginatingFromRejection(err); + promise._attachExtraTrace(err); + promise._reject(err); + + if (parent != null) { + parent.cancel(); + } +}; + +function successClear(value) { + clearTimeout(this.handle); + return value; +} + +function failureClear(reason) { + clearTimeout(this.handle); + throw reason; +} + +Promise.prototype.timeout = function (ms, message) { + ms = +ms; + var ret, parent; + + var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { + if (ret.isPending()) { + afterTimeout(ret, message, parent); + } + }, ms)); + + if (debug.cancellation()) { + parent = this.then(); + ret = parent._then(successClear, failureClear, + undefined, handleWrapper, undefined); + ret._setOnCancel(handleWrapper); + } else { + ret = this._then(successClear, failureClear, + undefined, handleWrapper, undefined); + } + + return ret; +}; + +}; + + +/***/ }), +/* 410 */, +/* 411 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Module dependencies. + */ +var tty = __webpack_require__(867); + +var util = __webpack_require__(669); +/** + * This is the Node.js implementation of `debug()`. + */ + + +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + var supportsColor = __webpack_require__(247); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221]; + } +} catch (error) {} // Swallow - we only care if `supports-color` is available; it doesn't have to be. + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + + +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // Camel-case + var prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, function (_, k) { + return k.toUpperCase(); + }); // Coerce string value into JS value + + var val = process.env[key]; + + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); +} +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + + +function formatArgs(args) { + var name = this.namespace, + useColors = this.useColors; + + if (useColors) { + var c = this.color; + var colorCode = "\x1B[3" + (c < 8 ? c : '8;5;' + c); + var prefix = " ".concat(colorCode, ";1m").concat(name, " \x1B[0m"); + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + "\x1B[0m"); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + + return new Date().toISOString() + ' '; +} +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + + +function log() { + return process.stderr.write(util.format.apply(util, arguments) + '\n'); +} +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + + +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + + +function load() { + return process.env.DEBUG; +} +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + + +function init(debug) { + debug.inspectOpts = {}; + var keys = Object.keys(exports.inspectOpts); + + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +module.exports = __webpack_require__(783)(exports); +var formatters = module.exports.formatters; +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts).replace(/\s*\n\s*/g, ' '); +}; +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + + + +/***/ }), +/* 412 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var Progress = __webpack_require__(264) +var Gauge = __webpack_require__(568) +var EE = __webpack_require__(614).EventEmitter +var log = exports = module.exports = new EE() +var util = __webpack_require__(669) + +var setBlocking = __webpack_require__(299) +var consoleControl = __webpack_require__(920) + +setBlocking(true) +var stream = process.stderr +Object.defineProperty(log, 'stream', { + set: function (newStream) { + stream = newStream + if (this.gauge) this.gauge.setWriteTo(stream, stream) + }, + get: function () { + return stream + } +}) + +// by default, decide based on tty-ness. +var colorEnabled +log.useColor = function () { + return colorEnabled != null ? colorEnabled : stream.isTTY +} + +log.enableColor = function () { + colorEnabled = true + this.gauge.setTheme({hasColor: colorEnabled, hasUnicode: unicodeEnabled}) +} +log.disableColor = function () { + colorEnabled = false + this.gauge.setTheme({hasColor: colorEnabled, hasUnicode: unicodeEnabled}) +} + +// default level +log.level = 'info' + +log.gauge = new Gauge(stream, { + enabled: false, // no progress bars unless asked + theme: {hasColor: log.useColor()}, + template: [ + {type: 'progressbar', length: 20}, + {type: 'activityIndicator', kerning: 1, length: 1}, + {type: 'section', default: ''}, + ':', + {type: 'logline', kerning: 1, default: ''} + ] +}) + +log.tracker = new Progress.TrackerGroup() + +// we track this separately as we may need to temporarily disable the +// display of the status bar for our own loggy purposes. +log.progressEnabled = log.gauge.isEnabled() + +var unicodeEnabled + +log.enableUnicode = function () { + unicodeEnabled = true + this.gauge.setTheme({hasColor: this.useColor(), hasUnicode: unicodeEnabled}) +} + +log.disableUnicode = function () { + unicodeEnabled = false + this.gauge.setTheme({hasColor: this.useColor(), hasUnicode: unicodeEnabled}) +} + +log.setGaugeThemeset = function (themes) { + this.gauge.setThemeset(themes) +} + +log.setGaugeTemplate = function (template) { + this.gauge.setTemplate(template) +} + +log.enableProgress = function () { + if (this.progressEnabled) return + this.progressEnabled = true + this.tracker.on('change', this.showProgress) + if (this._pause) return + this.gauge.enable() +} + +log.disableProgress = function () { + if (!this.progressEnabled) return + this.progressEnabled = false + this.tracker.removeListener('change', this.showProgress) + this.gauge.disable() +} + +var trackerConstructors = ['newGroup', 'newItem', 'newStream'] + +var mixinLog = function (tracker) { + // mixin the public methods from log into the tracker + // (except: conflicts and one's we handle specially) + Object.keys(log).forEach(function (P) { + if (P[0] === '_') return + if (trackerConstructors.filter(function (C) { return C === P }).length) return + if (tracker[P]) return + if (typeof log[P] !== 'function') return + var func = log[P] + tracker[P] = function () { + return func.apply(log, arguments) + } + }) + // if the new tracker is a group, make sure any subtrackers get + // mixed in too + if (tracker instanceof Progress.TrackerGroup) { + trackerConstructors.forEach(function (C) { + var func = tracker[C] + tracker[C] = function () { return mixinLog(func.apply(tracker, arguments)) } + }) + } + return tracker +} + +// Add tracker constructors to the top level log object +trackerConstructors.forEach(function (C) { + log[C] = function () { return mixinLog(this.tracker[C].apply(this.tracker, arguments)) } +}) + +log.clearProgress = function (cb) { + if (!this.progressEnabled) return cb && process.nextTick(cb) + this.gauge.hide(cb) +} + +log.showProgress = function (name, completed) { + if (!this.progressEnabled) return + var values = {} + if (name) values.section = name + var last = log.record[log.record.length - 1] + if (last) { + values.subsection = last.prefix + var disp = log.disp[last.level] || last.level + var logline = this._format(disp, log.style[last.level]) + if (last.prefix) logline += ' ' + this._format(last.prefix, this.prefixStyle) + logline += ' ' + last.message.split(/\r?\n/)[0] + values.logline = logline + } + values.completed = completed || this.tracker.completed() + this.gauge.show(values) +}.bind(log) // bind for use in tracker's on-change listener + +// temporarily stop emitting, but don't drop +log.pause = function () { + this._paused = true + if (this.progressEnabled) this.gauge.disable() +} + +log.resume = function () { + if (!this._paused) return + this._paused = false + + var b = this._buffer + this._buffer = [] + b.forEach(function (m) { + this.emitLog(m) + }, this) + if (this.progressEnabled) this.gauge.enable() +} + +log._buffer = [] + +var id = 0 +log.record = [] +log.maxRecordSize = 10000 +log.log = function (lvl, prefix, message) { + var l = this.levels[lvl] + if (l === undefined) { + return this.emit('error', new Error(util.format( + 'Undefined log level: %j', lvl))) + } + + var a = new Array(arguments.length - 2) + var stack = null + for (var i = 2; i < arguments.length; i++) { + var arg = a[i - 2] = arguments[i] + + // resolve stack traces to a plain string. + if (typeof arg === 'object' && arg && + (arg instanceof Error) && arg.stack) { + + Object.defineProperty(arg, 'stack', { + value: stack = arg.stack + '', + enumerable: true, + writable: true + }) + } + } + if (stack) a.unshift(stack + '\n') + message = util.format.apply(util, a) + + var m = { id: id++, + level: lvl, + prefix: String(prefix || ''), + message: message, + messageRaw: a } + + this.emit('log', m) + this.emit('log.' + lvl, m) + if (m.prefix) this.emit(m.prefix, m) + + this.record.push(m) + var mrs = this.maxRecordSize + var n = this.record.length - mrs + if (n > mrs / 10) { + var newSize = Math.floor(mrs * 0.9) + this.record = this.record.slice(-1 * newSize) + } + + this.emitLog(m) +}.bind(log) + +log.emitLog = function (m) { + if (this._paused) { + this._buffer.push(m) + return + } + if (this.progressEnabled) this.gauge.pulse(m.prefix) + var l = this.levels[m.level] + if (l === undefined) return + if (l < this.levels[this.level]) return + if (l > 0 && !isFinite(l)) return + + // If 'disp' is null or undefined, use the lvl as a default + // Allows: '', 0 as valid disp + var disp = log.disp[m.level] != null ? log.disp[m.level] : m.level + this.clearProgress() + m.message.split(/\r?\n/).forEach(function (line) { + if (this.heading) { + this.write(this.heading, this.headingStyle) + this.write(' ') + } + this.write(disp, log.style[m.level]) + var p = m.prefix || '' + if (p) this.write(' ') + this.write(p, this.prefixStyle) + this.write(' ' + line + '\n') + }, this) + this.showProgress() +} + +log._format = function (msg, style) { + if (!stream) return + + var output = '' + if (this.useColor()) { + style = style || {} + var settings = [] + if (style.fg) settings.push(style.fg) + if (style.bg) settings.push('bg' + style.bg[0].toUpperCase() + style.bg.slice(1)) + if (style.bold) settings.push('bold') + if (style.underline) settings.push('underline') + if (style.inverse) settings.push('inverse') + if (settings.length) output += consoleControl.color(settings) + if (style.beep) output += consoleControl.beep() + } + output += msg + if (this.useColor()) { + output += consoleControl.color('reset') + } + return output +} + +log.write = function (msg, style) { + if (!stream) return + + stream.write(this._format(msg, style)) +} + +log.addLevel = function (lvl, n, style, disp) { + // If 'disp' is null or undefined, use the lvl as a default + if (disp == null) disp = lvl + this.levels[lvl] = n + this.style[lvl] = style + if (!this[lvl]) { + this[lvl] = function () { + var a = new Array(arguments.length + 1) + a[0] = lvl + for (var i = 0; i < arguments.length; i++) { + a[i + 1] = arguments[i] + } + return this.log.apply(this, a) + }.bind(this) + } + this.disp[lvl] = disp +} + +log.prefixStyle = { fg: 'magenta' } +log.headingStyle = { fg: 'white', bg: 'black' } + +log.style = {} +log.levels = {} +log.disp = {} +log.addLevel('silly', -Infinity, { inverse: true }, 'sill') +log.addLevel('verbose', 1000, { fg: 'blue', bg: 'black' }, 'verb') +log.addLevel('info', 2000, { fg: 'green' }) +log.addLevel('timing', 2500, { fg: 'green', bg: 'black' }) +log.addLevel('http', 3000, { fg: 'green', bg: 'black' }) +log.addLevel('notice', 3500, { fg: 'blue', bg: 'black' }) +log.addLevel('warn', 4000, { fg: 'black', bg: 'yellow' }, 'WARN') +log.addLevel('error', 5000, { fg: 'red', bg: 'black' }, 'ERR!') +log.addLevel('silent', Infinity) + +// allow 'error' prefix +log.on('error', function () {}) + + +/***/ }), +/* 413 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +module.exports = __webpack_require__(141); + + +/***/ }), +/* 414 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + +var cr = Object.create; +if (cr) { + var callerCache = cr(null); + var getterCache = cr(null); + callerCache[" size"] = getterCache[" size"] = 0; +} + +module.exports = function(Promise) { +var util = __webpack_require__(248); +var canEvaluate = util.canEvaluate; +var isIdentifier = util.isIdentifier; + +var getMethodCaller; +var getGetter; +if (true) { +var makeMethodCaller = function (methodName) { + return new Function("ensureMethod", " \n\ + return function(obj) { \n\ + 'use strict' \n\ + var len = this.length; \n\ + ensureMethod(obj, 'methodName'); \n\ + switch(len) { \n\ + case 1: return obj.methodName(this[0]); \n\ + case 2: return obj.methodName(this[0], this[1]); \n\ + case 3: return obj.methodName(this[0], this[1], this[2]); \n\ + case 0: return obj.methodName(); \n\ + default: \n\ + return obj.methodName.apply(obj, this); \n\ + } \n\ + }; \n\ + ".replace(/methodName/g, methodName))(ensureMethod); +}; + +var makeGetter = function (propertyName) { + return new Function("obj", " \n\ + 'use strict'; \n\ + return obj.propertyName; \n\ + ".replace("propertyName", propertyName)); +}; + +var getCompiled = function(name, compiler, cache) { + var ret = cache[name]; + if (typeof ret !== "function") { + if (!isIdentifier(name)) { + return null; + } + ret = compiler(name); + cache[name] = ret; + cache[" size"]++; + if (cache[" size"] > 512) { + var keys = Object.keys(cache); + for (var i = 0; i < 256; ++i) delete cache[keys[i]]; + cache[" size"] = keys.length - 256; + } + } + return ret; +}; + +getMethodCaller = function(name) { + return getCompiled(name, makeMethodCaller, callerCache); +}; + +getGetter = function(name) { + return getCompiled(name, makeGetter, getterCache); +}; +} + +function ensureMethod(obj, methodName) { + var fn; + if (obj != null) fn = obj[methodName]; + if (typeof fn !== "function") { + var message = "Object " + util.classString(obj) + " has no method '" + + util.toString(methodName) + "'"; + throw new Promise.TypeError(message); + } + return fn; +} + +function caller(obj) { + var methodName = this.pop(); + var fn = ensureMethod(obj, methodName); + return fn.apply(obj, this); +} +Promise.prototype.call = function (methodName) { + var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}; + if (true) { + if (canEvaluate) { + var maybeCaller = getMethodCaller(methodName); + if (maybeCaller !== null) { + return this._then( + maybeCaller, undefined, undefined, args, undefined); + } + } + } + args.push(methodName); + return this._then(caller, undefined, undefined, args, undefined); +}; + +function namedGetter(obj) { + return obj[this]; +} +function indexedGetter(obj) { + var index = +this; + if (index < 0) index = Math.max(0, index + obj.length); + return obj[index]; +} +Promise.prototype.get = function (propertyName) { + var isIndex = (typeof propertyName === "number"); + var getter; + if (!isIndex) { + if (canEvaluate) { + var maybeGetter = getGetter(propertyName); + getter = maybeGetter !== null ? maybeGetter : namedGetter; + } else { + getter = namedGetter; + } + } else { + getter = indexedGetter; + } + return this._then(getter, undefined, undefined, propertyName, undefined); +}; +}; + + +/***/ }), +/* 415 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const Buffer = __webpack_require__(921) + +// A readable tar stream creator +// Technically, this is a transform stream that you write paths into, +// and tar format comes out of. +// The `add()` method is like `write()` but returns this, +// and end() return `this` as well, so you can +// do `new Pack(opt).add('files').add('dir').end().pipe(output) +// You could also do something like: +// streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar')) + +class PackJob { + constructor (path, absolute) { + this.path = path || './' + this.absolute = absolute + this.entry = null + this.stat = null + this.readdir = null + this.pending = false + this.ignore = false + this.piped = false + } +} + +const MiniPass = __webpack_require__(720) +const zlib = __webpack_require__(268) +const ReadEntry = __webpack_require__(589) +const WriteEntry = __webpack_require__(485) +const WriteEntrySync = WriteEntry.Sync +const WriteEntryTar = WriteEntry.Tar +const Yallist = __webpack_require__(612) +const EOF = Buffer.alloc(1024) +const ONSTAT = Symbol('onStat') +const ENDED = Symbol('ended') +const QUEUE = Symbol('queue') +const CURRENT = Symbol('current') +const PROCESS = Symbol('process') +const PROCESSING = Symbol('processing') +const PROCESSJOB = Symbol('processJob') +const JOBS = Symbol('jobs') +const JOBDONE = Symbol('jobDone') +const ADDFSENTRY = Symbol('addFSEntry') +const ADDTARENTRY = Symbol('addTarEntry') +const STAT = Symbol('stat') +const READDIR = Symbol('readdir') +const ONREADDIR = Symbol('onreaddir') +const PIPE = Symbol('pipe') +const ENTRY = Symbol('entry') +const ENTRYOPT = Symbol('entryOpt') +const WRITEENTRYCLASS = Symbol('writeEntryClass') +const WRITE = Symbol('write') +const ONDRAIN = Symbol('ondrain') + +const fs = __webpack_require__(747) +const path = __webpack_require__(622) +const warner = __webpack_require__(571) + +const Pack = warner(class Pack extends MiniPass { + constructor (opt) { + super(opt) + opt = opt || Object.create(null) + this.opt = opt + this.cwd = opt.cwd || process.cwd() + this.maxReadSize = opt.maxReadSize + this.preservePaths = !!opt.preservePaths + this.strict = !!opt.strict + this.noPax = !!opt.noPax + this.prefix = (opt.prefix || '').replace(/(\\|\/)+$/, '') + this.linkCache = opt.linkCache || new Map() + this.statCache = opt.statCache || new Map() + this.readdirCache = opt.readdirCache || new Map() + + this[WRITEENTRYCLASS] = WriteEntry + if (typeof opt.onwarn === 'function') + this.on('warn', opt.onwarn) + + this.zip = null + if (opt.gzip) { + if (typeof opt.gzip !== 'object') + opt.gzip = {} + this.zip = new zlib.Gzip(opt.gzip) + this.zip.on('data', chunk => super.write(chunk)) + this.zip.on('end', _ => super.end()) + this.zip.on('drain', _ => this[ONDRAIN]()) + this.on('resume', _ => this.zip.resume()) + } else + this.on('drain', this[ONDRAIN]) + + this.portable = !!opt.portable + this.noDirRecurse = !!opt.noDirRecurse + this.follow = !!opt.follow + this.noMtime = !!opt.noMtime + this.mtime = opt.mtime || null + + this.filter = typeof opt.filter === 'function' ? opt.filter : _ => true + + this[QUEUE] = new Yallist + this[JOBS] = 0 + this.jobs = +opt.jobs || 4 + this[PROCESSING] = false + this[ENDED] = false + } + + [WRITE] (chunk) { + return super.write(chunk) + } + + add (path) { + this.write(path) + return this + } + + end (path) { + if (path) + this.write(path) + this[ENDED] = true + this[PROCESS]() + return this + } + + write (path) { + if (this[ENDED]) + throw new Error('write after end') + + if (path instanceof ReadEntry) + this[ADDTARENTRY](path) + else + this[ADDFSENTRY](path) + return this.flowing + } + + [ADDTARENTRY] (p) { + const absolute = path.resolve(this.cwd, p.path) + if (this.prefix) + p.path = this.prefix + '/' + p.path.replace(/^\.(\/+|$)/, '') + + // in this case, we don't have to wait for the stat + if (!this.filter(p.path, p)) + p.resume() + else { + const job = new PackJob(p.path, absolute, false) + job.entry = new WriteEntryTar(p, this[ENTRYOPT](job)) + job.entry.on('end', _ => this[JOBDONE](job)) + this[JOBS] += 1 + this[QUEUE].push(job) + } + + this[PROCESS]() + } + + [ADDFSENTRY] (p) { + const absolute = path.resolve(this.cwd, p) + if (this.prefix) + p = this.prefix + '/' + p.replace(/^\.(\/+|$)/, '') + + this[QUEUE].push(new PackJob(p, absolute)) + this[PROCESS]() + } + + [STAT] (job) { + job.pending = true + this[JOBS] += 1 + const stat = this.follow ? 'stat' : 'lstat' + fs[stat](job.absolute, (er, stat) => { + job.pending = false + this[JOBS] -= 1 + if (er) + this.emit('error', er) + else + this[ONSTAT](job, stat) + }) + } + + [ONSTAT] (job, stat) { + this.statCache.set(job.absolute, stat) + job.stat = stat + + // now we have the stat, we can filter it. + if (!this.filter(job.path, stat)) + job.ignore = true + + this[PROCESS]() + } + + [READDIR] (job) { + job.pending = true + this[JOBS] += 1 + fs.readdir(job.absolute, (er, entries) => { + job.pending = false + this[JOBS] -= 1 + if (er) + return this.emit('error', er) + this[ONREADDIR](job, entries) + }) + } + + [ONREADDIR] (job, entries) { + this.readdirCache.set(job.absolute, entries) + job.readdir = entries + this[PROCESS]() + } + + [PROCESS] () { + if (this[PROCESSING]) + return + + this[PROCESSING] = true + for (let w = this[QUEUE].head; + w !== null && this[JOBS] < this.jobs; + w = w.next) { + this[PROCESSJOB](w.value) + if (w.value.ignore) { + const p = w.next + this[QUEUE].removeNode(w) + w.next = p + } + } + + this[PROCESSING] = false + + if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) { + if (this.zip) + this.zip.end(EOF) + else { + super.write(EOF) + super.end() + } + } + } + + get [CURRENT] () { + return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value + } + + [JOBDONE] (job) { + this[QUEUE].shift() + this[JOBS] -= 1 + this[PROCESS]() + } + + [PROCESSJOB] (job) { + if (job.pending) + return + + if (job.entry) { + if (job === this[CURRENT] && !job.piped) + this[PIPE](job) + return + } + + if (!job.stat) { + if (this.statCache.has(job.absolute)) + this[ONSTAT](job, this.statCache.get(job.absolute)) + else + this[STAT](job) + } + if (!job.stat) + return + + // filtered out! + if (job.ignore) + return + + if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) { + if (this.readdirCache.has(job.absolute)) + this[ONREADDIR](job, this.readdirCache.get(job.absolute)) + else + this[READDIR](job) + if (!job.readdir) + return + } + + // we know it doesn't have an entry, because that got checked above + job.entry = this[ENTRY](job) + if (!job.entry) { + job.ignore = true + return + } + + if (job === this[CURRENT] && !job.piped) + this[PIPE](job) + } + + [ENTRYOPT] (job) { + return { + onwarn: (msg, data) => { + this.warn(msg, data) + }, + noPax: this.noPax, + cwd: this.cwd, + absolute: job.absolute, + preservePaths: this.preservePaths, + maxReadSize: this.maxReadSize, + strict: this.strict, + portable: this.portable, + linkCache: this.linkCache, + statCache: this.statCache, + noMtime: this.noMtime, + mtime: this.mtime + } + } + + [ENTRY] (job) { + this[JOBS] += 1 + try { + return new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job)) + .on('end', () => this[JOBDONE](job)) + .on('error', er => this.emit('error', er)) + } catch (er) { + this.emit('error', er) + } + } + + [ONDRAIN] () { + if (this[CURRENT] && this[CURRENT].entry) + this[CURRENT].entry.resume() + } + + // like .pipe() but using super, because our write() is special + [PIPE] (job) { + job.piped = true + + if (job.readdir) + job.readdir.forEach(entry => { + const p = this.prefix ? + job.path.slice(this.prefix.length + 1) || './' + : job.path + + const base = p === './' ? '' : p.replace(/\/*$/, '/') + this[ADDFSENTRY](base + entry) + }) + + const source = job.entry + const zip = this.zip + + if (zip) + source.on('data', chunk => { + if (!zip.write(chunk)) + source.pause() + }) + else + source.on('data', chunk => { + if (!super.write(chunk)) + source.pause() + }) + } + + pause () { + if (this.zip) + this.zip.pause() + return super.pause() + } +}) + +class PackSync extends Pack { + constructor (opt) { + super(opt) + this[WRITEENTRYCLASS] = WriteEntrySync + } + + // pause/resume are no-ops in sync streams. + pause () {} + resume () {} + + [STAT] (job) { + const stat = this.follow ? 'statSync' : 'lstatSync' + this[ONSTAT](job, fs[stat](job.absolute)) + } + + [READDIR] (job, stat) { + this[ONREADDIR](job, fs.readdirSync(job.absolute)) + } + + // gotta get it all in this tick + [PIPE] (job) { + const source = job.entry + const zip = this.zip + + if (job.readdir) + job.readdir.forEach(entry => { + const p = this.prefix ? + job.path.slice(this.prefix.length + 1) || './' + : job.path + + const base = p === './' ? '' : p.replace(/\/*$/, '/') + this[ADDFSENTRY](base + entry) + }) + + if (zip) + source.on('data', chunk => { + zip.write(chunk) + }) + else + source.on('data', chunk => { + super[WRITE](chunk) + }) + } +} + +Pack.Sync = PackSync + +module.exports = Pack + + +/***/ }), +/* 416 */, +/* 417 */ +/***/ (function(module) { + +module.exports = require("crypto"); + +/***/ }), +/* 418 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const fs = __webpack_require__(747) +const path = __webpack_require__(622) +const EE = __webpack_require__(614).EventEmitter +const Minimatch = __webpack_require__(93).Minimatch + +class Walker extends EE { + constructor (opts) { + opts = opts || {} + super(opts) + this.path = opts.path || process.cwd() + this.basename = path.basename(this.path) + this.ignoreFiles = opts.ignoreFiles || [ '.ignore' ] + this.ignoreRules = {} + this.parent = opts.parent || null + this.includeEmpty = !!opts.includeEmpty + this.root = this.parent ? this.parent.root : this.path + this.follow = !!opts.follow + this.result = this.parent ? this.parent.result : new Set() + this.entries = null + this.sawError = false + } + + sort (a, b) { + return a.localeCompare(b) + } + + emit (ev, data) { + let ret = false + if (!(this.sawError && ev === 'error')) { + if (ev === 'error') + this.sawError = true + else if (ev === 'done' && !this.parent) { + data = Array.from(data) + .map(e => /^@/.test(e) ? `./${e}` : e).sort(this.sort) + this.result = data + } + + if (ev === 'error' && this.parent) + ret = this.parent.emit('error', data) + else + ret = super.emit(ev, data) + } + return ret + } + + start () { + fs.readdir(this.path, (er, entries) => + er ? this.emit('error', er) : this.onReaddir(entries)) + return this + } + + isIgnoreFile (e) { + return e !== "." && + e !== ".." && + -1 !== this.ignoreFiles.indexOf(e) + } + + onReaddir (entries) { + this.entries = entries + if (entries.length === 0) { + if (this.includeEmpty) + this.result.add(this.path.substr(this.root.length + 1)) + this.emit('done', this.result) + } else { + const hasIg = this.entries.some(e => + this.isIgnoreFile(e)) + + if (hasIg) + this.addIgnoreFiles() + else + this.filterEntries() + } + } + + addIgnoreFiles () { + const newIg = this.entries + .filter(e => this.isIgnoreFile(e)) + + let igCount = newIg.length + const then = _ => { + if (--igCount === 0) + this.filterEntries() + } + + newIg.forEach(e => this.addIgnoreFile(e, then)) + } + + addIgnoreFile (file, then) { + const ig = path.resolve(this.path, file) + fs.readFile(ig, 'utf8', (er, data) => + er ? this.emit('error', er) : this.onReadIgnoreFile(file, data, then)) + } + + onReadIgnoreFile (file, data, then) { + const mmopt = { + matchBase: true, + dot: true, + flipNegate: true, + nocase: true + } + const rules = data.split(/\r?\n/) + .filter(line => !/^#|^$/.test(line.trim())) + .map(r => new Minimatch(r, mmopt)) + + this.ignoreRules[file] = rules + + then() + } + + filterEntries () { + // at this point we either have ignore rules, or just inheriting + // this exclusion is at the point where we know the list of + // entries in the dir, but don't know what they are. since + // some of them *might* be directories, we have to run the + // match in dir-mode as well, so that we'll pick up partials + // of files that will be included later. Anything included + // at this point will be checked again later once we know + // what it is. + const filtered = this.entries.map(entry => { + // at this point, we don't know if it's a dir or not. + const passFile = this.filterEntry(entry) + const passDir = this.filterEntry(entry, true) + return (passFile || passDir) ? [entry, passFile, passDir] : false + }).filter(e => e) + + // now we stat them all + // if it's a dir, and passes as a dir, then recurse + // if it's not a dir, but passes as a file, add to set + let entryCount = filtered.length + if (entryCount === 0) { + this.emit('done', this.result) + } else { + const then = _ => { + if (-- entryCount === 0) + this.emit('done', this.result) + } + filtered.forEach(filt => { + const entry = filt[0] + const file = filt[1] + const dir = filt[2] + this.stat(entry, file, dir, then) + }) + } + } + + onstat (st, entry, file, dir, then) { + const abs = this.path + '/' + entry + if (!st.isDirectory()) { + if (file) + this.result.add(abs.substr(this.root.length + 1)) + then() + } else { + // is a directory + if (dir) + this.walker(entry, then) + else + then() + } + } + + stat (entry, file, dir, then) { + const abs = this.path + '/' + entry + fs[this.follow ? 'stat' : 'lstat'](abs, (er, st) => { + if (er) + this.emit('error', er) + else + this.onstat(st, entry, file, dir, then) + }) + } + + walkerOpt (entry) { + return { + path: this.path + '/' + entry, + parent: this, + ignoreFiles: this.ignoreFiles, + follow: this.follow, + includeEmpty: this.includeEmpty + } + } + + walker (entry, then) { + new Walker(this.walkerOpt(entry)).on('done', then).start() + } + + filterEntry (entry, partial) { + let included = true + + // this = /a/b/c + // entry = d + // parent /a/b sees c/d + if (this.parent && this.parent.filterEntry) { + var pt = this.basename + "/" + entry + included = this.parent.filterEntry(pt, partial) + } + + this.ignoreFiles.forEach(f => { + if (this.ignoreRules[f]) { + this.ignoreRules[f].forEach(rule => { + // negation means inclusion + // so if it's negated, and already included, no need to check + // likewise if it's neither negated nor included + if (rule.negate !== included) { + // first, match against /foo/bar + // then, against foo/bar + // then, in the case of partials, match with a / + const match = rule.match('/' + entry) || + rule.match(entry) || + (!!partial && ( + rule.match('/' + entry + '/') || + rule.match(entry + '/'))) || + (!!partial && rule.negate && ( + rule.match('/' + entry, true) || + rule.match(entry, true))) + + if (match) + included = rule.negate + } + }) + } + }) + + return included + } +} + +class WalkerSync extends Walker { + constructor (opt) { + super(opt) + } + + start () { + this.onReaddir(fs.readdirSync(this.path)) + return this + } + + addIgnoreFile (file, then) { + const ig = path.resolve(this.path, file) + this.onReadIgnoreFile(file, fs.readFileSync(ig, 'utf8'), then) + } + + stat (entry, file, dir, then) { + const abs = this.path + '/' + entry + const st = fs[this.follow ? 'statSync' : 'lstatSync'](abs) + this.onstat(st, entry, file, dir, then) + } + + walker (entry, then) { + new WalkerSync(this.walkerOpt(entry)).start() + then() + } +} + +const walk = (options, callback) => { + const p = new Promise((resolve, reject) => { + new Walker(options).on('done', resolve).on('error', reject).start() + }) + return callback ? p.then(res => callback(null, res), callback) : p +} + +const walkSync = options => { + return new WalkerSync(options).start().result +} + +module.exports = walk +walk.sync = walkSync +walk.Walker = Walker +walk.WalkerSync = WalkerSync + + +/***/ }), +/* 419 */, +/* 420 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const figgyPudding = __webpack_require__(122) +const logger = __webpack_require__(354) + +const AUTH_REGEX = /^(?:.*:)?(token|_authToken|username|_password|password|email|always-auth|_auth|otp)$/ +const SCOPE_REGISTRY_REGEX = /@.*:registry$/gi +module.exports = figgyPudding({ + annotate: {}, + cache: {}, + defaultTag: 'tag', + dirPacker: {}, + dmode: {}, + 'enjoy-by': 'enjoyBy', + enjoyBy: {}, + before: 'enjoyBy', + fmode: {}, + 'fetch-retries': { default: 2 }, + 'fetch-retry-factor': { default: 10 }, + 'fetch-retry-maxtimeout': { default: 60000 }, + 'fetch-retry-mintimeout': { default: 10000 }, + fullMetadata: 'full-metadata', + 'full-metadata': { default: false }, + gid: {}, + git: {}, + includeDeprecated: { default: true }, + 'include-deprecated': 'includeDeprecated', + integrity: {}, + log: { default: logger }, + memoize: {}, + offline: {}, + preferOffline: 'prefer-offline', + 'prefer-offline': {}, + preferOnline: 'prefer-online', + 'prefer-online': {}, + registry: { default: 'https://registry.npmjs.org/' }, + resolved: {}, + retry: {}, + scope: {}, + tag: { default: 'latest' }, + uid: {}, + umask: {}, + where: {} +}, { + other (key) { + return key.match(AUTH_REGEX) || key.match(SCOPE_REGISTRY_REGEX) + } +}) + + +/***/ }), +/* 421 */ +/***/ (function(module) { + +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} + + +/***/ }), +/* 422 */ +/***/ (function(module) { + +/*! ***************************************************************************** +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. +***************************************************************************** */ + +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __createBinding; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + + __extends = function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __createBinding = function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }; + + __exportStar = function (m, exports) { + for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p]; + }; + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); + + +/***/ }), +/* 423 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, WriterState, XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLDummy, XMLElement, XMLProcessingInstruction, XMLRaw, XMLText, XMLWriterBase, assign, + hasProp = {}.hasOwnProperty; + + assign = __webpack_require__(582).assign; + + NodeType = __webpack_require__(683); + + XMLDeclaration = __webpack_require__(738); + + XMLDocType = __webpack_require__(735); + + XMLCData = __webpack_require__(657); + + XMLComment = __webpack_require__(919); + + XMLElement = __webpack_require__(796); + + XMLRaw = __webpack_require__(660); + + XMLText = __webpack_require__(708); + + XMLProcessingInstruction = __webpack_require__(491); + + XMLDummy = __webpack_require__(956); + + XMLDTDAttList = __webpack_require__(890); + + XMLDTDElement = __webpack_require__(463); + + XMLDTDEntity = __webpack_require__(661); + + XMLDTDNotation = __webpack_require__(19); + + WriterState = __webpack_require__(541); + + module.exports = XMLWriterBase = (function() { + function XMLWriterBase(options) { + var key, ref, value; + options || (options = {}); + this.options = options; + ref = options.writer || {}; + for (key in ref) { + if (!hasProp.call(ref, key)) continue; + value = ref[key]; + this["_" + key] = this[key]; + this[key] = value; + } + } + + XMLWriterBase.prototype.filterOptions = function(options) { + var filteredOptions, ref, ref1, ref2, ref3, ref4, ref5, ref6; + options || (options = {}); + options = assign({}, this.options, options); + filteredOptions = { + writer: this + }; + filteredOptions.pretty = options.pretty || false; + filteredOptions.allowEmpty = options.allowEmpty || false; + filteredOptions.indent = (ref = options.indent) != null ? ref : ' '; + filteredOptions.newline = (ref1 = options.newline) != null ? ref1 : '\n'; + filteredOptions.offset = (ref2 = options.offset) != null ? ref2 : 0; + filteredOptions.dontPrettyTextNodes = (ref3 = (ref4 = options.dontPrettyTextNodes) != null ? ref4 : options.dontprettytextnodes) != null ? ref3 : 0; + filteredOptions.spaceBeforeSlash = (ref5 = (ref6 = options.spaceBeforeSlash) != null ? ref6 : options.spacebeforeslash) != null ? ref5 : ''; + if (filteredOptions.spaceBeforeSlash === true) { + filteredOptions.spaceBeforeSlash = ' '; + } + filteredOptions.suppressPrettyCount = 0; + filteredOptions.user = {}; + filteredOptions.state = WriterState.None; + return filteredOptions; + }; + + XMLWriterBase.prototype.indent = function(node, options, level) { + var indentLevel; + if (!options.pretty || options.suppressPrettyCount) { + return ''; + } else if (options.pretty) { + indentLevel = (level || 0) + options.offset + 1; + if (indentLevel > 0) { + return new Array(indentLevel).join(options.indent); + } + } + return ''; + }; + + XMLWriterBase.prototype.endline = function(node, options, level) { + if (!options.pretty || options.suppressPrettyCount) { + return ''; + } else { + return options.newline; + } + }; + + XMLWriterBase.prototype.attribute = function(att, options, level) { + var r; + this.openAttribute(att, options, level); + r = ' ' + att.name + '="' + att.value + '"'; + this.closeAttribute(att, options, level); + return r; + }; + + XMLWriterBase.prototype.cdata = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.comment = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.declaration = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + ''; + r += this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.docType = function(node, options, level) { + var child, i, len, r, ref; + level || (level = 0); + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level); + r += ' 0) { + r += ' ['; + r += this.endline(node, options, level); + options.state = WriterState.InsideTag; + ref = node.children; + for (i = 0, len = ref.length; i < len; i++) { + child = ref[i]; + r += this.writeChildNode(child, options, level + 1); + } + options.state = WriterState.CloseTag; + r += ']'; + } + options.state = WriterState.CloseTag; + r += options.spaceBeforeSlash + '>'; + r += this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.element = function(node, options, level) { + var att, child, childNodeCount, firstChildNode, i, j, len, len1, name, prettySuppressed, r, ref, ref1, ref2; + level || (level = 0); + prettySuppressed = false; + r = ''; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r += this.indent(node, options, level) + '<' + node.name; + ref = node.attribs; + for (name in ref) { + if (!hasProp.call(ref, name)) continue; + att = ref[name]; + r += this.attribute(att, options, level); + } + childNodeCount = node.children.length; + firstChildNode = childNodeCount === 0 ? null : node.children[0]; + if (childNodeCount === 0 || node.children.every(function(e) { + return (e.type === NodeType.Text || e.type === NodeType.Raw) && e.value === ''; + })) { + if (options.allowEmpty) { + r += '>'; + options.state = WriterState.CloseTag; + r += '' + this.endline(node, options, level); + } else { + options.state = WriterState.CloseTag; + r += options.spaceBeforeSlash + '/>' + this.endline(node, options, level); + } + } else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && (firstChildNode.value != null)) { + r += '>'; + options.state = WriterState.InsideTag; + options.suppressPrettyCount++; + prettySuppressed = true; + r += this.writeChildNode(firstChildNode, options, level + 1); + options.suppressPrettyCount--; + prettySuppressed = false; + options.state = WriterState.CloseTag; + r += '' + this.endline(node, options, level); + } else { + if (options.dontPrettyTextNodes) { + ref1 = node.children; + for (i = 0, len = ref1.length; i < len; i++) { + child = ref1[i]; + if ((child.type === NodeType.Text || child.type === NodeType.Raw) && (child.value != null)) { + options.suppressPrettyCount++; + prettySuppressed = true; + break; + } + } + } + r += '>' + this.endline(node, options, level); + options.state = WriterState.InsideTag; + ref2 = node.children; + for (j = 0, len1 = ref2.length; j < len1; j++) { + child = ref2[j]; + r += this.writeChildNode(child, options, level + 1); + } + options.state = WriterState.CloseTag; + r += this.indent(node, options, level) + ''; + if (prettySuppressed) { + options.suppressPrettyCount--; + } + r += this.endline(node, options, level); + options.state = WriterState.None; + } + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.writeChildNode = function(node, options, level) { + switch (node.type) { + case NodeType.CData: + return this.cdata(node, options, level); + case NodeType.Comment: + return this.comment(node, options, level); + case NodeType.Element: + return this.element(node, options, level); + case NodeType.Raw: + return this.raw(node, options, level); + case NodeType.Text: + return this.text(node, options, level); + case NodeType.ProcessingInstruction: + return this.processingInstruction(node, options, level); + case NodeType.Dummy: + return ''; + case NodeType.Declaration: + return this.declaration(node, options, level); + case NodeType.DocType: + return this.docType(node, options, level); + case NodeType.AttributeDeclaration: + return this.dtdAttList(node, options, level); + case NodeType.ElementDeclaration: + return this.dtdElement(node, options, level); + case NodeType.EntityDeclaration: + return this.dtdEntity(node, options, level); + case NodeType.NotationDeclaration: + return this.dtdNotation(node, options, level); + default: + throw new Error("Unknown XML node type: " + node.constructor.name); + } + }; + + XMLWriterBase.prototype.processingInstruction = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + ''; + r += this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.raw = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level); + options.state = WriterState.InsideTag; + r += node.value; + options.state = WriterState.CloseTag; + r += this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.text = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level); + options.state = WriterState.InsideTag; + r += node.value; + options.state = WriterState.CloseTag; + r += this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.dtdAttList = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.dtdElement = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.dtdEntity = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.dtdNotation = function(node, options, level) { + var r; + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + r = this.indent(node, options, level) + '' + this.endline(node, options, level); + options.state = WriterState.None; + this.closeNode(node, options, level); + return r; + }; + + XMLWriterBase.prototype.openNode = function(node, options, level) {}; + + XMLWriterBase.prototype.closeNode = function(node, options, level) {}; + + XMLWriterBase.prototype.openAttribute = function(att, options, level) {}; + + XMLWriterBase.prototype.closeAttribute = function(att, options, level) {}; + + return XMLWriterBase; + + })(); + +}).call(this); + + +/***/ }), +/* 424 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +var iterate = __webpack_require__(157) + , initState = __webpack_require__(903) + , terminator = __webpack_require__(939) + ; + +// Public API +module.exports = parallel; + +/** + * Runs iterator over provided array elements in parallel + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function parallel(list, iterator, callback) +{ + var state = initState(list); + + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } + + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); + + state.index++; + } + + return terminator.bind(state, callback); +} + + +/***/ }), +/* 425 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const BB = __webpack_require__(489) + +const figgyPudding = __webpack_require__(122) +const fs = __webpack_require__(747) +const index = __webpack_require__(407) +const memo = __webpack_require__(521) +const pipe = __webpack_require__(371).pipe +const pipeline = __webpack_require__(371).pipeline +const read = __webpack_require__(185) +const through = __webpack_require__(371).through + +const GetOpts = figgyPudding({ + integrity: {}, + memoize: {}, + size: {} +}) + +module.exports = function get (cache, key, opts) { + return getData(false, cache, key, opts) +} +module.exports.byDigest = function getByDigest (cache, digest, opts) { + return getData(true, cache, digest, opts) +} +function getData (byDigest, cache, key, opts) { + opts = GetOpts(opts) + const memoized = ( + byDigest + ? memo.get.byDigest(cache, key, opts) + : memo.get(cache, key, opts) + ) + if (memoized && opts.memoize !== false) { + return BB.resolve(byDigest ? memoized : { + metadata: memoized.entry.metadata, + data: memoized.data, + integrity: memoized.entry.integrity, + size: memoized.entry.size + }) + } + return ( + byDigest ? BB.resolve(null) : index.find(cache, key, opts) + ).then(entry => { + if (!entry && !byDigest) { + throw new index.NotFoundError(cache, key) + } + return read(cache, byDigest ? key : entry.integrity, { + integrity: opts.integrity, + size: opts.size + }).then(data => byDigest ? data : { + metadata: entry.metadata, + data: data, + size: entry.size, + integrity: entry.integrity + }).then(res => { + if (opts.memoize && byDigest) { + memo.put.byDigest(cache, key, res, opts) + } else if (opts.memoize) { + memo.put(cache, entry, res.data, opts) + } + return res + }) + }) +} + +module.exports.sync = function get (cache, key, opts) { + return getDataSync(false, cache, key, opts) +} +module.exports.sync.byDigest = function getByDigest (cache, digest, opts) { + return getDataSync(true, cache, digest, opts) +} +function getDataSync (byDigest, cache, key, opts) { + opts = GetOpts(opts) + const memoized = ( + byDigest + ? memo.get.byDigest(cache, key, opts) + : memo.get(cache, key, opts) + ) + if (memoized && opts.memoize !== false) { + return byDigest ? memoized : { + metadata: memoized.entry.metadata, + data: memoized.data, + integrity: memoized.entry.integrity, + size: memoized.entry.size + } + } + const entry = !byDigest && index.find.sync(cache, key, opts) + if (!entry && !byDigest) { + throw new index.NotFoundError(cache, key) + } + const data = read.sync( + cache, + byDigest ? key : entry.integrity, + { + integrity: opts.integrity, + size: opts.size + } + ) + const res = byDigest + ? data + : { + metadata: entry.metadata, + data: data, + size: entry.size, + integrity: entry.integrity + } + if (opts.memoize && byDigest) { + memo.put.byDigest(cache, key, res, opts) + } else if (opts.memoize) { + memo.put(cache, entry, res.data, opts) + } + return res +} + +module.exports.stream = getStream +function getStream (cache, key, opts) { + opts = GetOpts(opts) + let stream = through() + const memoized = memo.get(cache, key, opts) + if (memoized && opts.memoize !== false) { + stream.on('newListener', function (ev, cb) { + ev === 'metadata' && cb(memoized.entry.metadata) + ev === 'integrity' && cb(memoized.entry.integrity) + ev === 'size' && cb(memoized.entry.size) + }) + stream.write(memoized.data, () => stream.end()) + return stream + } + index.find(cache, key).then(entry => { + if (!entry) { + return stream.emit( + 'error', new index.NotFoundError(cache, key) + ) + } + let memoStream + if (opts.memoize) { + let memoData = [] + let memoLength = 0 + memoStream = through((c, en, cb) => { + memoData && memoData.push(c) + memoLength += c.length + cb(null, c, en) + }, cb => { + memoData && memo.put(cache, entry, Buffer.concat(memoData, memoLength), opts) + cb() + }) + } else { + memoStream = through() + } + stream.emit('metadata', entry.metadata) + stream.emit('integrity', entry.integrity) + stream.emit('size', entry.size) + stream.on('newListener', function (ev, cb) { + ev === 'metadata' && cb(entry.metadata) + ev === 'integrity' && cb(entry.integrity) + ev === 'size' && cb(entry.size) + }) + pipe( + read.readStream(cache, entry.integrity, opts.concat({ + size: opts.size == null ? entry.size : opts.size + })), + memoStream, + stream + ) + }).catch(err => stream.emit('error', err)) + return stream +} + +module.exports.stream.byDigest = getStreamDigest +function getStreamDigest (cache, integrity, opts) { + opts = GetOpts(opts) + const memoized = memo.get.byDigest(cache, integrity, opts) + if (memoized && opts.memoize !== false) { + const stream = through() + stream.write(memoized, () => stream.end()) + return stream + } else { + let stream = read.readStream(cache, integrity, opts) + if (opts.memoize) { + let memoData = [] + let memoLength = 0 + const memoStream = through((c, en, cb) => { + memoData && memoData.push(c) + memoLength += c.length + cb(null, c, en) + }, cb => { + memoData && memo.put.byDigest( + cache, + integrity, + Buffer.concat(memoData, memoLength), + opts + ) + cb() + }) + stream = pipeline(stream, memoStream) + } + return stream + } +} + +module.exports.info = info +function info (cache, key, opts) { + opts = GetOpts(opts) + const memoized = memo.get(cache, key, opts) + if (memoized && opts.memoize !== false) { + return BB.resolve(memoized.entry) + } else { + return index.find(cache, key) + } +} + +module.exports.hasContent = read.hasContent + +module.exports.copy = function cp (cache, key, dest, opts) { + return copy(false, cache, key, dest, opts) +} +module.exports.copy.byDigest = function cpDigest (cache, digest, dest, opts) { + return copy(true, cache, digest, dest, opts) +} +function copy (byDigest, cache, key, dest, opts) { + opts = GetOpts(opts) + if (read.copy) { + return ( + byDigest ? BB.resolve(null) : index.find(cache, key, opts) + ).then(entry => { + if (!entry && !byDigest) { + throw new index.NotFoundError(cache, key) + } + return read.copy( + cache, byDigest ? key : entry.integrity, dest, opts + ).then(() => byDigest ? key : { + metadata: entry.metadata, + size: entry.size, + integrity: entry.integrity + }) + }) + } else { + return getData(byDigest, cache, key, opts).then(res => { + return fs.writeFileAsync(dest, byDigest ? res : res.data) + .then(() => byDigest ? key : { + metadata: res.metadata, + size: res.size, + integrity: res.integrity + }) + }) + } +} + + +/***/ }), +/* 426 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +module.exports = __webpack_require__(258) + + +/***/ }), +/* 427 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +module.exports = __webpack_require__(794); + + +/***/ }), +/* 428 */, +/* 429 */, +/* 430 */, +/* 431 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const os = __importStar(__webpack_require__(87)); +const utils_1 = __webpack_require__(82); +/** + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value + */ +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +exports.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); +} +exports.issue = issue; +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; + } + this.command = command; + this.properties = properties; + this.message = message; + } + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' '; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } + else { + cmdStr += ','; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } + } + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; + } +} +function escapeData(s) { + return utils_1.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return utils_1.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} +//# sourceMappingURL=command.js.map + +/***/ }), +/* 432 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +/**/ + +var Buffer = __webpack_require__(233).Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} + +/***/ }), +/* 433 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +exports.asyncMap = __webpack_require__(943) +exports.bindActor = __webpack_require__(111) +exports.chain = __webpack_require__(955) + + +/***/ }), +/* 434 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const exec_1 = __webpack_require__(986); +const io = __importStar(__webpack_require__(1)); +const fs_1 = __webpack_require__(747); +const path = __importStar(__webpack_require__(622)); +const utils = __importStar(__webpack_require__(15)); +const constants_1 = __webpack_require__(931); +function getTarPath(args, compressionMethod) { + return __awaiter(this, void 0, void 0, function* () { + const IS_WINDOWS = process.platform === 'win32'; + if (IS_WINDOWS) { + const systemTar = `${process.env['windir']}\\System32\\tar.exe`; + if (compressionMethod !== constants_1.CompressionMethod.Gzip) { + // We only use zstandard compression on windows when gnu tar is installed due to + // a bug with compressing large files with bsdtar + zstd + args.push('--force-local'); + } + else if (fs_1.existsSync(systemTar)) { + return systemTar; + } + else if (yield utils.isGnuTarInstalled()) { + args.push('--force-local'); + } + } + return yield io.which('tar', true); + }); +} +function execTar(args, compressionMethod, cwd) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield exec_1.exec(`"${yield getTarPath(args, compressionMethod)}"`, args, { cwd }); + } + catch (error) { + throw new Error(`Tar failed with error: ${error === null || error === void 0 ? void 0 : error.message}`); + } + }); +} +function getWorkingDirectory() { + var _a; + return (_a = process.env['GITHUB_WORKSPACE']) !== null && _a !== void 0 ? _a : process.cwd(); +} +function extractTar(archivePath, compressionMethod) { + return __awaiter(this, void 0, void 0, function* () { + // Create directory to extract tar into + const workingDirectory = getWorkingDirectory(); + yield io.mkdirP(workingDirectory); + // --d: Decompress. + // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. + // Using 30 here because we also support 32-bit self-hosted runners. + function getCompressionProgram() { + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return ['--use-compress-program', 'zstd -d --long=30']; + case constants_1.CompressionMethod.ZstdWithoutLong: + return ['--use-compress-program', 'zstd -d']; + default: + return ['-z']; + } + } + const args = [ + ...getCompressionProgram(), + '-xf', + archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), + '-P', + '-C', + workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/') + ]; + yield execTar(args, compressionMethod); + }); +} +exports.extractTar = extractTar; +function createTar(archiveFolder, sourceDirectories, compressionMethod) { + return __awaiter(this, void 0, void 0, function* () { + // Write source directories to manifest.txt to avoid command length limits + const manifestFilename = 'manifest.txt'; + const cacheFileName = utils.getCacheFileName(compressionMethod); + fs_1.writeFileSync(path.join(archiveFolder, manifestFilename), sourceDirectories.join('\n')); + const workingDirectory = getWorkingDirectory(); + // -T#: Compress using # working thread. If # is 0, attempt to detect and use the number of physical CPU cores. + // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. + // Using 30 here because we also support 32-bit self-hosted runners. + // Long range mode is added to zstd in v1.3.2 release, so we will not use --long in older version of zstd. + function getCompressionProgram() { + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return ['--use-compress-program', 'zstd -T0 --long=30']; + case constants_1.CompressionMethod.ZstdWithoutLong: + return ['--use-compress-program', 'zstd -T0']; + default: + return ['-z']; + } + } + const args = [ + '--posix', + ...getCompressionProgram(), + '-cf', + cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), + '-P', + '-C', + workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), + '--files-from', + manifestFilename + ]; + yield execTar(args, compressionMethod, archiveFolder); + }); +} +exports.createTar = createTar; +//# sourceMappingURL=tar.js.map + +/***/ }), +/* 435 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const BB = __webpack_require__(489) + +const index = __webpack_require__(407) +const memo = __webpack_require__(521) +const path = __webpack_require__(622) +const rimraf = BB.promisify(__webpack_require__(503)) +const rmContent = __webpack_require__(849) + +module.exports = entry +module.exports.entry = entry +function entry (cache, key) { + memo.clearMemoized() + return index.delete(cache, key) +} + +module.exports.content = content +function content (cache, integrity) { + memo.clearMemoized() + return rmContent(cache, integrity) +} + +module.exports.all = all +function all (cache) { + memo.clearMemoized() + return rimraf(path.join(cache, '*(content-*|index-*)')) +} + + +/***/ }), +/* 436 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + +__webpack_require__(465); +const inherits = __webpack_require__(669).inherits; +const promisify = __webpack_require__(662); +const EventEmitter = __webpack_require__(614).EventEmitter; + +module.exports = Agent; + +function isAgent(v) { + return v && typeof v.addRequest === 'function'; +} + +/** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ +function Agent(callback, _opts) { + if (!(this instanceof Agent)) { + return new Agent(callback, _opts); + } + + EventEmitter.call(this); + + // The callback gets promisified if it has 3 parameters + // (i.e. it has a callback function) lazily + this._promisifiedCallback = false; + + let opts = _opts; + if ('function' === typeof callback) { + this.callback = callback; + } else if (callback) { + opts = callback; + } + + // timeout for the socket to be returned from the callback + this.timeout = (opts && opts.timeout) || null; + + this.options = opts; +} +inherits(Agent, EventEmitter); + +/** + * Override this function in your subclass! + */ +Agent.prototype.callback = function callback(req, opts) { + throw new Error( + '"agent-base" has no default implementation, you must subclass and override `callback()`' + ); +}; + +/** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ +Agent.prototype.addRequest = function addRequest(req, _opts) { + const ownOpts = Object.assign({}, _opts); + + // Set default `host` for HTTP to localhost + if (null == ownOpts.host) { + ownOpts.host = 'localhost'; + } + + // Set default `port` for HTTP if none was explicitly specified + if (null == ownOpts.port) { + ownOpts.port = ownOpts.secureEndpoint ? 443 : 80; + } + + const opts = Object.assign({}, this.options, ownOpts); + + if (opts.host && opts.path) { + // If both a `host` and `path` are specified then it's most likely the + // result of a `url.parse()` call... we need to remove the `path` portion so + // that `net.connect()` doesn't attempt to open that as a unix socket file. + delete opts.path; + } + + delete opts.agent; + delete opts.hostname; + delete opts._defaultAgent; + delete opts.defaultPort; + delete opts.createConnection; + + // Hint to use "Connection: close" + // XXX: non-documented `http` module API :( + req._last = true; + req.shouldKeepAlive = false; + + // Create the `stream.Duplex` instance + let timeout; + let timedOut = false; + const timeoutMs = this.timeout; + const freeSocket = this.freeSocket; + + function onerror(err) { + if (req._hadError) return; + req.emit('error', err); + // For Safety. Some additional errors might fire later on + // and we need to make sure we don't double-fire the error event. + req._hadError = true; + } + + function ontimeout() { + timeout = null; + timedOut = true; + const err = new Error( + 'A "socket" was not created for HTTP request before ' + timeoutMs + 'ms' + ); + err.code = 'ETIMEOUT'; + onerror(err); + } + + function callbackError(err) { + if (timedOut) return; + if (timeout != null) { + clearTimeout(timeout); + timeout = null; + } + onerror(err); + } + + function onsocket(socket) { + if (timedOut) return; + if (timeout != null) { + clearTimeout(timeout); + timeout = null; + } + if (isAgent(socket)) { + // `socket` is actually an http.Agent instance, so relinquish + // responsibility for this `req` to the Agent from here on + socket.addRequest(req, opts); + } else if (socket) { + function onfree() { + freeSocket(socket, opts); + } + socket.on('free', onfree); + req.onSocket(socket); + } else { + const err = new Error( + 'no Duplex stream was returned to agent-base for `' + req.method + ' ' + req.path + '`' + ); + onerror(err); + } + } + + if (!this._promisifiedCallback && this.callback.length >= 3) { + // Legacy callback function - convert to a Promise + this.callback = promisify(this.callback, this); + this._promisifiedCallback = true; + } + + if (timeoutMs > 0) { + timeout = setTimeout(ontimeout, timeoutMs); + } + + try { + Promise.resolve(this.callback(req, opts)).then(onsocket, callbackError); + } catch (err) { + Promise.reject(err).catch(callbackError); + } +}; + +Agent.prototype.freeSocket = function freeSocket(socket, opts) { + // TODO reuse sockets + socket.destroy(); +}; + + +/***/ }), +/* 437 */, +/* 438 */, +/* 439 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +/* global self, window, module, global, require */ +module.exports = function () { + + "use strict"; + + var globalObject = void 0; + + function isFunction(x) { + return typeof x === "function"; + } + + // Seek the global object + if (global !== undefined) { + globalObject = global; + } else if (window !== undefined && window.document) { + globalObject = window; + } else { + globalObject = self; + } + + // Test for any native promise implementation, and if that + // implementation appears to conform to the specificaton. + // This code mostly nicked from the es6-promise module polyfill + // and then fooled with. + var hasPromiseSupport = function () { + + // No promise object at all, and it's a non-starter + if (!globalObject.hasOwnProperty("Promise")) { + return false; + } + + // There is a Promise object. Does it conform to the spec? + var P = globalObject.Promise; + + // Some of these methods are missing from + // Firefox/Chrome experimental implementations + if (!P.hasOwnProperty("resolve") || !P.hasOwnProperty("reject")) { + return false; + } + + if (!P.hasOwnProperty("all") || !P.hasOwnProperty("race")) { + return false; + } + + // Older version of the spec had a resolver object + // as the arg rather than a function + return function () { + + var resolve = void 0; + + var p = new globalObject.Promise(function (r) { + resolve = r; + }); + + if (p) { + return isFunction(resolve); + } + + return false; + }(); + }(); + + // Export the native Promise implementation if it + // looks like it matches the spec + if (hasPromiseSupport) { + return globalObject.Promise; + } + + // Otherwise, return the es6-promise polyfill by @jaffathecake. + return __webpack_require__(684).Promise; +}(); + +/***/ }), +/* 440 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.propagation = exports.metrics = exports.trace = exports.context = void 0; +__exportStar(__webpack_require__(276), exports); +__exportStar(__webpack_require__(158), exports); +__exportStar(__webpack_require__(2), exports); +__exportStar(__webpack_require__(33), exports); +__exportStar(__webpack_require__(744), exports); +__exportStar(__webpack_require__(753), exports); +__exportStar(__webpack_require__(278), exports); +__exportStar(__webpack_require__(40), exports); +__exportStar(__webpack_require__(318), exports); +__exportStar(__webpack_require__(551), exports); +__exportStar(__webpack_require__(659), exports); +__exportStar(__webpack_require__(702), exports); +__exportStar(__webpack_require__(43), exports); +__exportStar(__webpack_require__(625), exports); +__exportStar(__webpack_require__(450), exports); +__exportStar(__webpack_require__(107), exports); +__exportStar(__webpack_require__(326), exports); +__exportStar(__webpack_require__(906), exports); +__exportStar(__webpack_require__(727), exports); +__exportStar(__webpack_require__(165), exports); +__exportStar(__webpack_require__(851), exports); +__exportStar(__webpack_require__(95), exports); +__exportStar(__webpack_require__(767), exports); +__exportStar(__webpack_require__(151), exports); +__exportStar(__webpack_require__(224), exports); +__exportStar(__webpack_require__(781), exports); +__exportStar(__webpack_require__(340), exports); +__exportStar(__webpack_require__(607), exports); +__exportStar(__webpack_require__(670), exports); +__exportStar(__webpack_require__(586), exports); +__exportStar(__webpack_require__(220), exports); +__exportStar(__webpack_require__(932), exports); +__exportStar(__webpack_require__(839), exports); +__exportStar(__webpack_require__(975), exports); +__exportStar(__webpack_require__(70), exports); +__exportStar(__webpack_require__(694), exports); +__exportStar(__webpack_require__(695), exports); +var context_base_1 = __webpack_require__(459); +Object.defineProperty(exports, "Context", { enumerable: true, get: function () { return context_base_1.Context; } }); +var context_1 = __webpack_require__(77); +/** Entrypoint for context API */ +exports.context = context_1.ContextAPI.getInstance(); +var trace_1 = __webpack_require__(875); +/** Entrypoint for trace API */ +exports.trace = trace_1.TraceAPI.getInstance(); +var metrics_1 = __webpack_require__(136); +/** Entrypoint for metrics API */ +exports.metrics = metrics_1.MetricsAPI.getInstance(); +var propagation_1 = __webpack_require__(22); +/** Entrypoint for propagation API */ +exports.propagation = propagation_1.PropagationAPI.getInstance(); +exports.default = { + trace: exports.trace, + metrics: exports.metrics, + context: exports.context, + propagation: exports.propagation, +}; +//# sourceMappingURL=index.js.map + +/***/ }), +/* 441 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const eu = encodeURIComponent +const figgyPudding = __webpack_require__(122) +const getStream = __webpack_require__(341) +const npmFetch = __webpack_require__(789) +const validate = __webpack_require__(772) + +const TeamConfig = figgyPudding({ + description: {}, + Promise: { default: () => Promise } +}) + +const cmd = module.exports = {} + +cmd.create = (entity, opts) => { + opts = TeamConfig(opts) + return pwrap(opts, () => { + const { scope, team } = splitEntity(entity) + validate('SSO', [scope, team, opts]) + return npmFetch.json(`/-/org/${eu(scope)}/team`, opts.concat({ + method: 'PUT', + scope, + body: { name: team, description: opts.description } + })) + }) +} + +cmd.destroy = (entity, opts) => { + opts = TeamConfig(opts) + return pwrap(opts, () => { + const { scope, team } = splitEntity(entity) + validate('SSO', [scope, team, opts]) + return npmFetch.json(`/-/team/${eu(scope)}/${eu(team)}`, opts.concat({ + method: 'DELETE', + scope + })) + }) +} + +cmd.add = (user, entity, opts) => { + opts = TeamConfig(opts) + return pwrap(opts, () => { + const { scope, team } = splitEntity(entity) + validate('SSO', [scope, team, opts]) + return npmFetch.json(`/-/team/${eu(scope)}/${eu(team)}/user`, opts.concat({ + method: 'PUT', + scope, + body: { user } + })) + }) +} + +cmd.rm = (user, entity, opts) => { + opts = TeamConfig(opts) + return pwrap(opts, () => { + const { scope, team } = splitEntity(entity) + validate('SSO', [scope, team, opts]) + return npmFetch.json(`/-/team/${eu(scope)}/${eu(team)}/user`, opts.concat({ + method: 'DELETE', + scope, + body: { user } + })) + }) +} + +cmd.lsTeams = (scope, opts) => { + opts = TeamConfig(opts) + return pwrap(opts, () => getStream.array(cmd.lsTeams.stream(scope, opts))) +} +cmd.lsTeams.stream = (scope, opts) => { + opts = TeamConfig(opts) + validate('SO', [scope, opts]) + return npmFetch.json.stream(`/-/org/${eu(scope)}/team`, '.*', opts.concat({ + query: { format: 'cli' } + })) +} + +cmd.lsUsers = (entity, opts) => { + opts = TeamConfig(opts) + return pwrap(opts, () => getStream.array(cmd.lsUsers.stream(entity, opts))) +} +cmd.lsUsers.stream = (entity, opts) => { + opts = TeamConfig(opts) + const { scope, team } = splitEntity(entity) + validate('SSO', [scope, team, opts]) + const uri = `/-/team/${eu(scope)}/${eu(team)}/user` + return npmFetch.json.stream(uri, '.*', opts.concat({ + query: { format: 'cli' } + })) +} + +cmd.edit = () => { + throw new Error('edit is not implemented yet') +} + +function splitEntity (entity = '') { + let [, scope, team] = entity.match(/^@?([^:]+):(.*)$/) || [] + return { scope, team } +} + +function pwrap (opts, fn) { + return new opts.Promise((resolve, reject) => { + fn().then(resolve, reject) + }) +} + + +/***/ }), +/* 442 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + + +const fetch = __webpack_require__(789) +const { HttpErrorBase } = __webpack_require__(881) +const os = __webpack_require__(87) +const pudding = __webpack_require__(122) +const validate = __webpack_require__(772) + +exports.adduserCouch = adduserCouch +exports.loginCouch = loginCouch +exports.adduserWeb = adduserWeb +exports.loginWeb = loginWeb +exports.login = login +exports.adduser = adduser +exports.get = get +exports.set = set +exports.listTokens = listTokens +exports.removeToken = removeToken +exports.createToken = createToken + +const url = __webpack_require__(835) + +const isValidUrl = u => { + if (u && typeof u === 'string') { + const p = url.parse(u) + return p.slashes && p.host && p.path && /^https?:$/.test(p.protocol) + } + return false +} + +const ProfileConfig = pudding({ + creds: {}, + hostname: {}, + otp: {} +}) + +// try loginWeb, catch the "not supported" message and fall back to couch +function login (opener, prompter, opts) { + validate('FFO', arguments) + opts = ProfileConfig(opts) + return loginWeb(opener, opts).catch(er => { + if (er instanceof WebLoginNotSupported) { + process.emit('log', 'verbose', 'web login not supported, trying couch') + return prompter(opts.creds) + .then(data => loginCouch(data.username, data.password, opts)) + } else { + throw er + } + }) +} + +function adduser (opener, prompter, opts) { + validate('FFO', arguments) + opts = ProfileConfig(opts) + return adduserWeb(opener, opts).catch(er => { + if (er instanceof WebLoginNotSupported) { + process.emit('log', 'verbose', 'web adduser not supported, trying couch') + return prompter(opts.creds) + .then(data => adduserCouch(data.username, data.email, data.password, opts)) + } else { + throw er + } + }) +} + +function adduserWeb (opener, opts) { + validate('FO', arguments) + const body = { create: true } + process.emit('log', 'verbose', 'web adduser', 'before first POST') + return webAuth(opener, opts, body) +} + +function loginWeb (opener, opts) { + validate('FO', arguments) + process.emit('log', 'verbose', 'web login', 'before first POST') + return webAuth(opener, opts, {}) +} + +function webAuth (opener, opts, body) { + opts = ProfileConfig(opts) + body.hostname = opts.hostname || os.hostname() + const target = '/-/v1/login' + return fetch(target, opts.concat({ + method: 'POST', + body + })).then(res => { + return Promise.all([res, res.json()]) + }).then(([res, content]) => { + const { doneUrl, loginUrl } = content + process.emit('log', 'verbose', 'web auth', 'got response', content) + if (!isValidUrl(doneUrl) || !isValidUrl(loginUrl)) { + throw new WebLoginInvalidResponse('POST', res, content) + } + return content + }).then(({ doneUrl, loginUrl }) => { + process.emit('log', 'verbose', 'web auth', 'opening url pair') + return opener(loginUrl).then( + () => webAuthCheckLogin(doneUrl, opts.concat({ cache: false })) + ) + }).catch(er => { + if ((er.statusCode >= 400 && er.statusCode <= 499) || er.statusCode === 500) { + throw new WebLoginNotSupported('POST', { + status: er.statusCode, + headers: { raw: () => er.headers } + }, er.body) + } else { + throw er + } + }) +} + +function webAuthCheckLogin (doneUrl, opts) { + return fetch(doneUrl, opts).then(res => { + return Promise.all([res, res.json()]) + }).then(([res, content]) => { + if (res.status === 200) { + if (!content.token) { + throw new WebLoginInvalidResponse('GET', res, content) + } else { + return content + } + } else if (res.status === 202) { + const retry = +res.headers.get('retry-after') * 1000 + if (retry > 0) { + return sleep(retry).then(() => webAuthCheckLogin(doneUrl, opts)) + } else { + return webAuthCheckLogin(doneUrl, opts) + } + } else { + throw new WebLoginInvalidResponse('GET', res, content) + } + }) +} + +function adduserCouch (username, email, password, opts) { + validate('SSSO', arguments) + opts = ProfileConfig(opts) + const body = { + _id: 'org.couchdb.user:' + username, + name: username, + password: password, + email: email, + type: 'user', + roles: [], + date: new Date().toISOString() + } + const logObj = {} + Object.keys(body).forEach(k => { + logObj[k] = k === 'password' ? 'XXXXX' : body[k] + }) + process.emit('log', 'verbose', 'adduser', 'before first PUT', logObj) + + const target = '/-/user/org.couchdb.user:' + encodeURIComponent(username) + return fetch.json(target, opts.concat({ + method: 'PUT', + body + })).then(result => { + result.username = username + return result + }) +} + +function loginCouch (username, password, opts) { + validate('SSO', arguments) + opts = ProfileConfig(opts) + const body = { + _id: 'org.couchdb.user:' + username, + name: username, + password: password, + type: 'user', + roles: [], + date: new Date().toISOString() + } + const logObj = {} + Object.keys(body).forEach(k => { + logObj[k] = k === 'password' ? 'XXXXX' : body[k] + }) + process.emit('log', 'verbose', 'login', 'before first PUT', logObj) + + const target = '-/user/org.couchdb.user:' + encodeURIComponent(username) + return fetch.json(target, opts.concat({ + method: 'PUT', + body + })).catch(err => { + if (err.code === 'E400') { + err.message = `There is no user with the username "${username}".` + throw err + } + if (err.code !== 'E409') throw err + return fetch.json(target, opts.concat({ + query: { write: true } + })).then(result => { + Object.keys(result).forEach(function (k) { + if (!body[k] || k === 'roles') { + body[k] = result[k] + } + }) + return fetch.json(`${target}/-rev/${body._rev}`, opts.concat({ + method: 'PUT', + body, + forceAuth: { + username, + password: Buffer.from(password, 'utf8').toString('base64'), + otp: opts.otp + } + })) + }) + }).then(result => { + result.username = username + return result + }) +} + +function get (opts) { + validate('O', arguments) + return fetch.json('/-/npm/v1/user', opts) +} + +function set (profile, opts) { + validate('OO', arguments) + Object.keys(profile).forEach(key => { + // profile keys can't be empty strings, but they CAN be null + if (profile[key] === '') profile[key] = null + }) + return fetch.json('/-/npm/v1/user', ProfileConfig(opts, { + method: 'POST', + body: profile + })) +} + +function listTokens (opts) { + validate('O', arguments) + opts = ProfileConfig(opts) + + return untilLastPage('/-/npm/v1/tokens') + + function untilLastPage (href, objects) { + return fetch.json(href, opts).then(result => { + objects = objects ? objects.concat(result.objects) : result.objects + if (result.urls.next) { + return untilLastPage(result.urls.next, objects) + } else { + return objects + } + }) + } +} + +function removeToken (tokenKey, opts) { + validate('SO', arguments) + const target = `/-/npm/v1/tokens/token/${tokenKey}` + return fetch(target, ProfileConfig(opts, { + method: 'DELETE', + ignoreBody: true + })).then(() => null) +} + +function createToken (password, readonly, cidrs, opts) { + validate('SBAO', arguments) + return fetch.json('/-/npm/v1/tokens', ProfileConfig(opts, { + method: 'POST', + body: { + password: password, + readonly: readonly, + cidr_whitelist: cidrs + } + })) +} + +class WebLoginInvalidResponse extends HttpErrorBase { + constructor (method, res, body) { + super(method, res, body) + this.message = 'Invalid response from web login endpoint' + Error.captureStackTrace(this, WebLoginInvalidResponse) + } +} + +class WebLoginNotSupported extends HttpErrorBase { + constructor (method, res, body) { + super(method, res, body) + this.message = 'Web login not supported' + this.code = 'ENYI' + Error.captureStackTrace(this, WebLoginNotSupported) + } +} + +function sleep (ms) { + return new Promise((resolve, reject) => setTimeout(resolve, ms)) +} + + +/***/ }), +/* 443 */, +/* 444 */ +/***/ (function(module) { + +module.exports = {"name":"npm-registry-fetch","version":"4.0.7","description":"Fetch-based http client for use with npm registry APIs","main":"index.js","files":["*.js","lib"],"publishConfig":{"tag":"latest-v4"},"scripts":{"prerelease":"npm t","postrelease":"npm publish && git push --follow-tags","posttest":"standard","release":"standard-version -s","test":"tap -J --coverage test/*.js","update-coc":"weallbehave -o . && git add CODE_OF_CONDUCT.md && git commit -m 'docs(coc): updated CODE_OF_CONDUCT.md'","update-contrib":"weallcontribute -o . && git add CONTRIBUTING.md && git commit -m 'docs(contributing): updated CONTRIBUTING.md'"},"repository":"https://github.com/npm/registry-fetch","keywords":["npm","registry","fetch"],"author":{"name":"Kat Marchán","email":"kzm@sykosomatic.org","twitter":"maybekatz"},"license":"ISC","dependencies":{"JSONStream":"^1.3.4","bluebird":"^3.5.1","figgy-pudding":"^3.4.1","lru-cache":"^5.1.1","make-fetch-happen":"^5.0.0","npm-package-arg":"^6.1.0","safe-buffer":"^5.2.0"},"devDependencies":{"cacache":"^12.0.0","get-stream":"^4.0.0","mkdirp":"^0.5.1","nock":"^9.4.3","npmlog":"^4.1.2","rimraf":"^2.6.2","ssri":"^6.0.0","standard":"^11.0.1","standard-version":"^4.4.0","tap":"^12.0.1","weallbehave":"^1.2.0","weallcontribute":"^1.0.8"},"config":{"nyc":{"exclude":["node_modules/**","test/**"]}}}; + +/***/ }), +/* 445 */, +/* 446 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const cacache = __webpack_require__(426) +const Fetcher = __webpack_require__(404) +const regManifest = __webpack_require__(935) +const regPackument = __webpack_require__(590) +const regTarball = __webpack_require__(134) + +const fetchRegistry = module.exports = Object.create(null) + +Fetcher.impl(fetchRegistry, { + packument (spec, opts) { + return regPackument(spec, opts) + }, + + manifest (spec, opts) { + return regManifest(spec, opts) + }, + + tarball (spec, opts) { + return regTarball(spec, opts) + }, + + fromManifest (manifest, spec, opts) { + return regTarball.fromManifest(manifest, spec, opts) + }, + + clearMemoized () { + cacache.clearMemoized() + regPackument.clearMemoized() + } +}) + + +/***/ }), +/* 447 */ +/***/ (function(module) { + +module.exports = {"topLevel":{"dependancies":"dependencies","dependecies":"dependencies","depdenencies":"dependencies","devEependencies":"devDependencies","depends":"dependencies","dev-dependencies":"devDependencies","devDependences":"devDependencies","devDepenencies":"devDependencies","devdependencies":"devDependencies","repostitory":"repository","repo":"repository","prefereGlobal":"preferGlobal","hompage":"homepage","hampage":"homepage","autohr":"author","autor":"author","contributers":"contributors","publicationConfig":"publishConfig","script":"scripts"},"bugs":{"web":"url","name":"url"},"script":{"server":"start","tests":"test"}}; + +/***/ }), +/* 448 */ +/***/ (function(module) { + +"use strict"; + + +module.exports = () => { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, 'g'); +}; + + +/***/ }), +/* 449 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +module.exports = __webpack_require__(441) + + +/***/ }), +/* 450 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0; +var NoopMeter_1 = __webpack_require__(625); +/** + * An implementation of the {@link MeterProvider} which returns an impotent Meter + * for all calls to `getMeter` + */ +var NoopMeterProvider = /** @class */ (function () { + function NoopMeterProvider() { + } + NoopMeterProvider.prototype.getMeter = function (_name, _version) { + return NoopMeter_1.NOOP_METER; + }; + return NoopMeterProvider; +}()); +exports.NoopMeterProvider = NoopMeterProvider; +exports.NOOP_METER_PROVIDER = new NoopMeterProvider(); +//# sourceMappingURL=NoopMeterProvider.js.map + +/***/ }), +/* 451 */ +/***/ (function(module) { + +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLNamedNodeMap; + + module.exports = XMLNamedNodeMap = (function() { + function XMLNamedNodeMap(nodes) { + this.nodes = nodes; + } + + Object.defineProperty(XMLNamedNodeMap.prototype, 'length', { + get: function() { + return Object.keys(this.nodes).length || 0; + } + }); + + XMLNamedNodeMap.prototype.clone = function() { + return this.nodes = null; + }; + + XMLNamedNodeMap.prototype.getNamedItem = function(name) { + return this.nodes[name]; + }; + + XMLNamedNodeMap.prototype.setNamedItem = function(node) { + var oldNode; + oldNode = this.nodes[node.nodeName]; + this.nodes[node.nodeName] = node; + return oldNode || null; + }; + + XMLNamedNodeMap.prototype.removeNamedItem = function(name) { + var oldNode; + oldNode = this.nodes[name]; + delete this.nodes[name]; + return oldNode || null; + }; + + XMLNamedNodeMap.prototype.item = function(index) { + return this.nodes[Object.keys(this.nodes)[index]] || null; + }; + + XMLNamedNodeMap.prototype.getNamedItemNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented."); + }; + + XMLNamedNodeMap.prototype.setNamedItemNS = function(node) { + throw new Error("This DOM method is not implemented."); + }; + + XMLNamedNodeMap.prototype.removeNamedItemNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented."); + }; + + return XMLNamedNodeMap; + + })(); + +}).call(this); + + +/***/ }), +/* 452 */ +/***/ (function(module, exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + +/** Used to match `RegExp` flags from their coerced string values. */ +var reFlags = /\w*$/; + +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** Used to identify `toStringTag` values supported by `_.clone`. */ +var cloneableTags = {}; +cloneableTags[argsTag] = cloneableTags[arrayTag] = +cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = +cloneableTags[boolTag] = cloneableTags[dateTag] = +cloneableTags[float32Tag] = cloneableTags[float64Tag] = +cloneableTags[int8Tag] = cloneableTags[int16Tag] = +cloneableTags[int32Tag] = cloneableTags[mapTag] = +cloneableTags[numberTag] = cloneableTags[objectTag] = +cloneableTags[regexpTag] = cloneableTags[setTag] = +cloneableTags[stringTag] = cloneableTags[symbolTag] = +cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = +cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; +cloneableTags[errorTag] = cloneableTags[funcTag] = +cloneableTags[weakMapTag] = false; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** Detect free variable `exports`. */ +var freeExports = true && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** + * Adds the key-value `pair` to `map`. + * + * @private + * @param {Object} map The map to modify. + * @param {Array} pair The key-value pair to add. + * @returns {Object} Returns `map`. + */ +function addMapEntry(map, pair) { + // Don't return `map.set` because it's not chainable in IE 11. + map.set(pair[0], pair[1]); + return map; +} + +/** + * Adds `value` to `set`. + * + * @private + * @param {Object} set The set to modify. + * @param {*} value The value to add. + * @returns {Object} Returns `set`. + */ +function addSetEntry(set, value) { + // Don't return `set.add` because it's not chainable in IE 11. + set.add(value); + return set; +} + +/** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ +function arrayEach(array, iteratee) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; +} + +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} + +/** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ +function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array ? array.length : 0; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; +} + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} + +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} + } + return result; +} + +/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ +function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; +} + +/** Used for built-in method references. */ +var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); + +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined, + Symbol = root.Symbol, + Uint8Array = root.Uint8Array, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeKeys = overArg(Object.keys, Object); + +/* Built-in method references that are verified to be native. */ +var DataView = getNative(root, 'DataView'), + Map = getNative(root, 'Map'), + Promise = getNative(root, 'Promise'), + Set = getNative(root, 'Set'), + WeakMap = getNative(root, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + +/** Used to detect maps, sets, and weakmaps. */ +var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; +} + +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + return this.has(key) && delete this.__data__[key]; +} + +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; +} + +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); +} + +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; +} + +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; +} + +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + return true; +} + +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; +} + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; +} + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; +} + +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; +} + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + return getMapData(this, key)['delete'](key); +} + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return getMapData(this, key).get(key); +} + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + getMapData(this, key).set(key, value); + return this; +} + +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; + +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Stack(entries) { + this.__data__ = new ListCache(entries); +} + +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ +function stackClear() { + this.__data__ = new ListCache; +} + +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + return this.__data__['delete'](key); +} + +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + return this.__data__.get(key); +} + +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + return this.__data__.has(key); +} + +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ +function stackSet(key, value) { + var cache = this.__data__; + if (cache instanceof ListCache) { + var pairs = cache.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + return this; + } + cache = this.__data__ = new MapCache(pairs); + } + cache.set(key, value); + return this; +} + +// Add methods to `Stack`. +Stack.prototype.clear = stackClear; +Stack.prototype['delete'] = stackDelete; +Stack.prototype.get = stackGet; +Stack.prototype.has = stackHas; +Stack.prototype.set = stackSet; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; + + var length = result.length, + skipIndexes = !!length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); + } + } + return result; +} + +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + object[key] = value; + } +} + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; +} + +/** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ +function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); +} + +/** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @param {boolean} [isFull] Specify a clone including symbols. + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ +function baseClone(value, isDeep, isFull, customizer, key, object, stack) { + var result; + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + if (isHostObject(value)) { + return object ? value : {}; + } + result = initCloneObject(isFunc ? {} : value); + if (!isDeep) { + return copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, baseClone, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (!isArr) { + var props = isFull ? getAllKeys(value) : keys(value); + } + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack)); + }); + return result; +} + +/** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} prototype The object to inherit from. + * @returns {Object} Returns the new object. + */ +function baseCreate(proto) { + return isObject(proto) ? objectCreate(proto) : {}; +} + +/** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ +function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); +} + +/** + * The base implementation of `getTag`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + return objectToString.call(value); +} + +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +/** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ +function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var result = new buffer.constructor(buffer.length); + buffer.copy(result); + return result; +} + +/** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ +function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; +} + +/** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ +function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); +} + +/** + * Creates a clone of `map`. + * + * @private + * @param {Object} map The map to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned map. + */ +function cloneMap(map, isDeep, cloneFunc) { + var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map); + return arrayReduce(array, addMapEntry, new map.constructor); +} + +/** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ +function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; +} + +/** + * Creates a clone of `set`. + * + * @private + * @param {Object} set The set to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned set. + */ +function cloneSet(set, isDeep, cloneFunc) { + var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set); + return arrayReduce(array, addSetEntry, new set.constructor); +} + +/** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ +function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; +} + +/** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ +function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); +} + +/** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ +function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; +} + +/** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ +function copyObject(source, props, object, customizer) { + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + assignValue(object, key, newValue === undefined ? source[key] : newValue); + } + return object; +} + +/** + * Copies own symbol properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ +function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); +} + +/** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); +} + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; +} + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; +} + +/** + * Creates an array of the own enumerable symbol properties of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; + +/** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +var getTag = baseGetTag; + +// Fallback for data views, maps, sets, and weak maps in IE 11, +// for data views in Edge < 14, and promises in Node.js. +if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = objectToString.call(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : undefined; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; +} + +/** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ +function initCloneArray(array) { + var length = array.length, + result = array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; +} + +/** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; +} + +/** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneByTag(object, tag, cloneFunc, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return cloneMap(object, isDeep, cloneFunc); + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return cloneSet(object, isDeep, cloneFunc); + + case symbolTag: + return cloneSymbol(object); + } +} + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} + +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} + +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to process. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} + +/** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ +function cloneDeep(value) { + return baseClone(value, true, true); +} + +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +/** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ +function stubArray() { + return []; +} + +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ +function stubFalse() { + return false; +} + +module.exports = cloneDeep; + + +/***/ }), +/* 453 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +let path + +class LogicalTree { + constructor (name, address, opts) { + this.name = name + this.version = opts.version + this.address = address || '' + this.optional = !!opts.optional + this.dev = !!opts.dev + this.bundled = !!opts.bundled + this.resolved = opts.resolved + this.integrity = opts.integrity + this.dependencies = new Map() + this.requiredBy = new Set() + } + + get isRoot () { return !this.requiredBy.size } + + addDep (dep) { + this.dependencies.set(dep.name, dep) + dep.requiredBy.add(this) + return this + } + + delDep (dep) { + this.dependencies.delete(dep.name) + dep.requiredBy.delete(this) + return this + } + + getDep (name) { + return this.dependencies.get(name) + } + + path (prefix) { + if (this.isRoot) { + // The address of the root is the prefix itself. + return prefix || '' + } else { + if (!path) { path = __webpack_require__(622) } + return path.join( + prefix || '', + 'node_modules', + this.address.replace(/:/g, '/node_modules/') + ) + } + } + + // This finds cycles _from_ a given node: if some deeper dep has + // its own cycle, but that cycle does not refer to this node, + // it will return false. + hasCycle (_seen, _from) { + if (!_seen) { _seen = new Set() } + if (!_from) { _from = this } + for (let dep of this.dependencies.values()) { + if (_seen.has(dep)) { continue } + _seen.add(dep) + if (dep === _from || dep.hasCycle(_seen, _from)) { + return true + } } - /** - * Handles Socks v5 auth handshake response. - * @param data - */ - handleInitialSocks5AuthenticationHandshakeResponse() { - this.state = constants_1.SocksClientState.ReceivedAuthenticationResponse; - const data = this._receiveBuffer.get(2); - if (data[1] !== 0x00) { - this._closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed); - } - else { - this.sendSocks5CommandRequest(); - } + return false + } + + forEachAsync (fn, opts, _pending) { + if (!opts) { opts = _pending || {} } + if (!_pending) { _pending = new Map() } + const P = opts.Promise || Promise + if (_pending.has(this)) { + return P.resolve(this.hasCycle() || _pending.get(this)) } - /** - * Sends Socks v5 final handshake request. - */ - sendSocks5CommandRequest() { - const buff = new smart_buffer_1.SmartBuffer(); - buff.writeUInt8(0x05); - buff.writeUInt8(constants_1.SocksCommand[this._options.command]); - buff.writeUInt8(0x00); - // ipv4, ipv6, domain? - if (net.isIPv4(this._options.destination.host)) { - buff.writeUInt8(constants_1.Socks5HostType.IPv4); - buff.writeBuffer(ip.toBuffer(this._options.destination.host)); - } - else if (net.isIPv6(this._options.destination.host)) { - buff.writeUInt8(constants_1.Socks5HostType.IPv6); - buff.writeBuffer(ip.toBuffer(this._options.destination.host)); - } - else { - buff.writeUInt8(constants_1.Socks5HostType.Hostname); - buff.writeUInt8(this._options.destination.host.length); - buff.writeString(this._options.destination.host); - } - buff.writeUInt16BE(this._options.destination.port); - this._nextRequiredPacketBufferSize = - constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader; - this._socket.write(buff.toBuffer()); - this.state = constants_1.SocksClientState.SentFinalHandshake; + const pending = P.resolve().then(() => { + return fn(this, () => { + return promiseMap( + this.dependencies.values(), + dep => dep.forEachAsync(fn, opts, _pending), + opts + ) + }) + }) + _pending.set(this, pending) + return pending + } + + forEach (fn, _seen) { + if (!_seen) { _seen = new Set() } + if (_seen.has(this)) { return } + _seen.add(this) + fn(this, () => { + for (let dep of this.dependencies.values()) { + dep.forEach(fn, _seen) + } + }) + } +} + +module.exports = lockTree +function lockTree (pkg, pkgLock, opts) { + const tree = makeNode(pkg.name, null, pkg) + const allDeps = new Map() + Array.from( + new Set(Object.keys(pkg.devDependencies || {}) + .concat(Object.keys(pkg.optionalDependencies || {})) + .concat(Object.keys(pkg.dependencies || {}))) + ).forEach(name => { + let dep = allDeps.get(name) + if (!dep) { + const depNode = (pkgLock.dependencies || {})[name] + dep = makeNode(name, name, depNode) } - /** - * Handles Socks v5 final handshake response. - * @param data - */ - handleSocks5FinalHandshakeResponse() { - // Peek at available data (we need at least 5 bytes to get the hostname length) - const header = this._receiveBuffer.peek(5); - if (header[0] !== 0x05 || header[1] !== constants_1.Socks5Response.Granted) { - this._closeSocket(`${constants_1.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${constants_1.Socks5Response[header[1]]}`); - } - else { - // Read address type - const addressType = header[3]; - let remoteHost; - let buff; - // IPv4 - if (addressType === constants_1.Socks5HostType.IPv4) { - // Check if data is available. - const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4; - if (this._receiveBuffer.length < dataNeeded) { - this._nextRequiredPacketBufferSize = dataNeeded; - return; - } - buff = smart_buffer_1.SmartBuffer.fromBuffer(this._receiveBuffer.get(dataNeeded).slice(4)); - remoteHost = { - host: ip.fromLong(buff.readUInt32BE()), - port: buff.readUInt16BE() - }; - // If given host is 0.0.0.0, assume remote proxy ip instead. - if (remoteHost.host === '0.0.0.0') { - remoteHost.host = this._options.proxy.ipaddress; - } - // Hostname - } - else if (addressType === constants_1.Socks5HostType.Hostname) { - const hostLength = header[4]; - const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); // header + host length + host + port - // Check if data is available. - if (this._receiveBuffer.length < dataNeeded) { - this._nextRequiredPacketBufferSize = dataNeeded; - return; - } - buff = smart_buffer_1.SmartBuffer.fromBuffer(this._receiveBuffer.get(dataNeeded).slice(5) // Slice at 5 to skip host length - ); - remoteHost = { - host: buff.readString(hostLength), - port: buff.readUInt16BE() - }; - // IPv6 - } - else if (addressType === constants_1.Socks5HostType.IPv6) { - // Check if data is available. - const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6; - if (this._receiveBuffer.length < dataNeeded) { - this._nextRequiredPacketBufferSize = dataNeeded; - return; - } - buff = smart_buffer_1.SmartBuffer.fromBuffer(this._receiveBuffer.get(dataNeeded).slice(4)); - remoteHost = { - host: ip.toString(buff.readBuffer(16)), - port: buff.readUInt16BE() - }; - } - // We have everything we need - this.state = constants_1.SocksClientState.ReceivedFinalResponse; - // If using CONNECT, the client is now in the established state. - if (constants_1.SocksCommand[this._options.command] === constants_1.SocksCommand.connect) { - this.state = constants_1.SocksClientState.Established; - this.removeInternalSocketHandlers(); - this.emit('established', { socket: this._socket }); - } - else if (constants_1.SocksCommand[this._options.command] === constants_1.SocksCommand.bind) { - /* If using BIND, the Socks client is now in BoundWaitingForConnection state. - This means that the remote proxy server is waiting for a remote connection to the bound port. */ - this.state = constants_1.SocksClientState.BoundWaitingForConnection; - this._nextRequiredPacketBufferSize = - constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader; - this.emit('bound', { socket: this._socket, remoteHost }); - /* - If using Associate, the Socks client is now Established. And the proxy server is now accepting UDP packets at the - given bound port. This initial Socks TCP connection must remain open for the UDP relay to continue to work. - */ - } - else if (constants_1.SocksCommand[this._options.command] === constants_1.SocksCommand.associate) { - this.state = constants_1.SocksClientState.Established; - this.removeInternalSocketHandlers(); - this.emit('established', { socket: this._socket, remoteHost }); - } - } + addChild(dep, tree, allDeps, pkgLock) + }) + return tree +} + +module.exports.node = makeNode +function makeNode (name, address, opts) { + return new LogicalTree(name, address, opts || {}) +} + +function addChild (dep, tree, allDeps, pkgLock) { + tree.addDep(dep) + allDeps.set(dep.address, dep) + const addr = dep.address + const lockNode = atAddr(pkgLock, addr) + Object.keys(lockNode.requires || {}).forEach(name => { + const tdepAddr = reqAddr(pkgLock, name, addr) + let tdep = allDeps.get(tdepAddr) + if (!tdep) { + tdep = makeNode(name, tdepAddr, atAddr(pkgLock, tdepAddr)) + addChild(tdep, dep, allDeps, pkgLock) + } else { + dep.addDep(tdep) } - /** - * Handles Socks v5 incoming connection request (BIND). - */ - handleSocks5IncomingConnectionResponse() { - // Peek at available data (we need at least 5 bytes to get the hostname length) - const header = this._receiveBuffer.peek(5); - if (header[0] !== 0x05 || header[1] !== constants_1.Socks5Response.Granted) { - this._closeSocket(`${constants_1.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${constants_1.Socks5Response[header[1]]}`); - } - else { - // Read address type - const addressType = header[3]; - let remoteHost; - let buff; - // IPv4 - if (addressType === constants_1.Socks5HostType.IPv4) { - // Check if data is available. - const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4; - if (this._receiveBuffer.length < dataNeeded) { - this._nextRequiredPacketBufferSize = dataNeeded; - return; - } - buff = smart_buffer_1.SmartBuffer.fromBuffer(this._receiveBuffer.get(dataNeeded).slice(4)); - remoteHost = { - host: ip.fromLong(buff.readUInt32BE()), - port: buff.readUInt16BE() - }; - // If given host is 0.0.0.0, assume remote proxy ip instead. - if (remoteHost.host === '0.0.0.0') { - remoteHost.host = this._options.proxy.ipaddress; - } - // Hostname - } - else if (addressType === constants_1.Socks5HostType.Hostname) { - const hostLength = header[4]; - const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); // header + host length + port - // Check if data is available. - if (this._receiveBuffer.length < dataNeeded) { - this._nextRequiredPacketBufferSize = dataNeeded; - return; - } - buff = smart_buffer_1.SmartBuffer.fromBuffer(this._receiveBuffer.get(dataNeeded).slice(5) // Slice at 5 to skip host length - ); - remoteHost = { - host: buff.readString(hostLength), - port: buff.readUInt16BE() - }; - // IPv6 - } - else if (addressType === constants_1.Socks5HostType.IPv6) { - // Check if data is available. - const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6; - if (this._receiveBuffer.length < dataNeeded) { - this._nextRequiredPacketBufferSize = dataNeeded; - return; - } - buff = smart_buffer_1.SmartBuffer.fromBuffer(this._receiveBuffer.get(dataNeeded).slice(4)); - remoteHost = { - host: ip.toString(buff.readBuffer(16)), - port: buff.readUInt16BE() - }; - } - this.state = constants_1.SocksClientState.Established; - this.removeInternalSocketHandlers(); - this.emit('established', { socket: this._socket, remoteHost }); + }) +} + +module.exports._reqAddr = reqAddr +function reqAddr (pkgLock, name, fromAddr) { + const lockNode = atAddr(pkgLock, fromAddr) + const child = (lockNode.dependencies || {})[name] + if (child) { + return `${fromAddr}:${name}` + } else { + const parts = fromAddr.split(':') + while (parts.length) { + parts.pop() + const joined = parts.join(':') + const parent = atAddr(pkgLock, joined) + if (parent) { + const child = (parent.dependencies || {})[name] + if (child) { + return `${joined}${parts.length ? ':' : ''}${name}` } + } } - get socksClientOptions() { - return Object.assign({}, this._options); + const err = new Error(`${name} not accessible from ${fromAddr}`) + err.pkgLock = pkgLock + err.target = name + err.from = fromAddr + throw err + } +} + +module.exports._atAddr = atAddr +function atAddr (pkgLock, addr) { + if (!addr.length) { return pkgLock } + const parts = addr.split(':') + return parts.reduce((acc, next) => { + return acc && (acc.dependencies || {})[next] + }, pkgLock) +} + +function promiseMap (arr, fn, opts, _index) { + _index = _index || 0 + const P = (opts && opts.Promise) || Promise + if (P.map) { + return P.map(arr, fn, opts) + } else { + if (!(arr instanceof Array)) { + arr = Array.from(arr) + } + if (_index >= arr.length) { + return P.resolve() + } else { + return P.resolve(fn(arr[_index], _index, arr)) + .then(() => promiseMap(arr, fn, opts, _index + 1)) } + } } -exports.SocksClient = SocksClient; -//# sourceMappingURL=socksclient.js.map + /***/ }), -/* 360 */, -/* 361 */, -/* 362 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 454 */ +/***/ (function(module, exports, __webpack_require__) { -var util = __webpack_require__(669) -var messages = __webpack_require__(344) +"use strict"; -module.exports = function() { - var args = Array.prototype.slice.call(arguments, 0) - var warningName = args.shift() - if (warningName == "typo") { - return makeTypoWarning.apply(null,args) - } - else { - var msgTemplate = messages[warningName] ? messages[warningName] : warningName + ": '%s'" - args.unshift(msgTemplate) - return util.format.apply(null, args) - } + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var Stream = _interopDefault(__webpack_require__(794)); +var http = _interopDefault(__webpack_require__(605)); +var Url = _interopDefault(__webpack_require__(835)); +var https = _interopDefault(__webpack_require__(211)); +var zlib = _interopDefault(__webpack_require__(761)); + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } } -function makeTypoWarning (providedName, probableName, field) { - if (field) { - providedName = field + "['" + providedName + "']" - probableName = field + "['" + probableName + "']" +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; } - return util.format(messages.typo, providedName, probableName) + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); } +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; -/***/ }), -/* 363 */ -/***/ (function(module) { +let convert; +try { + convert = __webpack_require__(382).convert; +} catch (e) {} -"use strict"; +const INTERNALS = Symbol('Body internals'); -/* eslint-disable yoda */ -module.exports = x => { - if (Number.isNaN(x)) { - return false; +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; - // code points are derived from: - // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt - if ( - x >= 0x1100 && ( - x <= 0x115f || // Hangul Jamo - x === 0x2329 || // LEFT-POINTING ANGLE BRACKET - x === 0x232a || // RIGHT-POINTING ANGLE BRACKET - // CJK Radicals Supplement .. Enclosed CJK Letters and Months - (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) || - // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - (0x3250 <= x && x <= 0x4dbf) || - // CJK Unified Ideographs .. Yi Radicals - (0x4e00 <= x && x <= 0xa4c6) || - // Hangul Jamo Extended-A - (0xa960 <= x && x <= 0xa97c) || - // Hangul Syllables - (0xac00 <= x && x <= 0xd7a3) || - // CJK Compatibility Ideographs - (0xf900 <= x && x <= 0xfaff) || - // Vertical Forms - (0xfe10 <= x && x <= 0xfe19) || - // CJK Compatibility Forms .. Small Form Variants - (0xfe30 <= x && x <= 0xfe6b) || - // Halfwidth and Fullwidth Forms - (0xff01 <= x && x <= 0xff60) || - (0xffe0 <= x && x <= 0xffe6) || - // Kana Supplement - (0x1b000 <= x && x <= 0x1b001) || - // Enclosed Ideographic Supplement - (0x1f200 <= x && x <= 0x1f251) || - // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - (0x20000 <= x && x <= 0x3fffd) - ) - ) { - return true; + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); } +} - return false; -}; +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + get bodyUsed() { + return this[INTERNALS].disturbed; + }, -/***/ }), -/* 364 */ -/***/ (function(module) { + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, -"use strict"; + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, -module.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf('--'); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } }; +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); -/***/ }), -/* 365 */, -/* 366 */ -/***/ (function(module) { +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; -var twoify = function (n) { - if (n && !(n & (n - 1))) return n - var p = 1 - while (p < n) p <<= 1 - return p -} +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; -var Cyclist = function (size) { - if (!(this instanceof Cyclist)) return new Cyclist(size) - size = twoify(size) - this.mask = size - 1 - this.size = size - this.values = new Array(size) -} + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } -Cyclist.prototype.put = function (index, val) { - var pos = index & this.mask - this.values[pos] = val - return pos -} + this[INTERNALS].disturbed = true; -Cyclist.prototype.get = function (index) { - return this.values[index & this.mask] -} + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } -Cyclist.prototype.del = function (index) { - var pos = index & this.mask - var val = this.values[pos] - this.values[pos] = undefined - return val -} + let body = this.body; -module.exports = Cyclist + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } -/***/ }), -/* 367 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } -"use strict"; + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); -module.exports = __webpack_require__(100) + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } -/***/ }), -/* 368 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + accumBytes += chunk.length; + accum.push(chunk); + }); -"use strict"; + body.on('end', function () { + if (abort) { + return; + } + clearTimeout(resTimeout); -const figgyPudding = __webpack_require__(122) -const npa = __webpack_require__(482) -const npmFetch = __webpack_require__(789) -const semver = __webpack_require__(280) -const url = __webpack_require__(835) + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} -const UnpublishConfig = figgyPudding({ - force: { default: false }, - Promise: { default: () => Promise } -}) +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } -module.exports = unpublish -function unpublish (spec, opts) { - opts = UnpublishConfig(opts) - return new opts.Promise(resolve => resolve()).then(() => { - spec = npa(spec) - // NOTE: spec is used to pick the appropriate registry/auth combo. - opts = opts.concat({ spec }) - const pkgUri = spec.escapedName - return npmFetch.json(pkgUri, opts.concat({ - query: { write: true } - })).then(pkg => { - if (!spec.rawSpec || spec.rawSpec === '*') { - return npmFetch(`${pkgUri}/-rev/${pkg._rev}`, opts.concat({ - method: 'DELETE', - ignoreBody: true - })) - } else { - const version = spec.rawSpec - const allVersions = pkg.versions || {} - const versionPublic = allVersions[version] - let dist - if (versionPublic) { - dist = allVersions[version].dist - } - delete allVersions[version] - // if it was the only version, then delete the whole package. - if (!Object.keys(allVersions).length) { - return npmFetch(`${pkgUri}/-rev/${pkg._rev}`, opts.concat({ - method: 'DELETE', - ignoreBody: true - })) - } else if (versionPublic) { - const latestVer = pkg['dist-tags'].latest - Object.keys(pkg['dist-tags']).forEach(tag => { - if (pkg['dist-tags'][tag] === version) { - delete pkg['dist-tags'][tag] - } - }) + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; - if (latestVer === version) { - pkg['dist-tags'].latest = Object.keys( - allVersions - ).sort(semver.compareLoose).pop() - } + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } - delete pkg._revisions - delete pkg._attachments - // Update packument with removed versions - return npmFetch(`${pkgUri}/-rev/${pkg._rev}`, opts.concat({ - method: 'PUT', - body: pkg, - ignoreBody: true - })).then(() => { - // Remove the tarball itself - return npmFetch.json(pkgUri, opts.concat({ - query: { write: true } - })).then(({ _rev, _id }) => { - const tarballUrl = url.parse(dist.tarball).pathname.substr(1) - return npmFetch(`${tarballUrl}/-rev/${_rev}`, opts.concat({ - method: 'DELETE', - ignoreBody: true - })) - }) - }) - } - } - }, err => { - if (err.code !== 'E404') { - throw err - } - }) - }).then(() => true) + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = /= 2)) { - throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxiesLength, options); - } - // Validate proxies - options.proxies.forEach((proxy) => { - if (!isValidSocksProxy(proxy)) { - throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options); - } - }); - // Check timeout - if (options.timeout && !isValidTimeoutValue(options.timeout)) { - throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options); - } +function getTotalBytes(instance) { + const body = instance.body; + + + if (body === null) { + // body is null + return 0; + } else if (isBlob(body)) { + return body.size; + } else if (Buffer.isBuffer(body)) { + // body is buffer + return body.length; + } else if (body && typeof body.getLengthSync === 'function') { + // detect form data input from form-data module + if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x + body.hasKnownLength && body.hasKnownLength()) { + // 2.x + return body.getLengthSync(); + } + return null; + } else { + // body is stream + return null; + } } -exports.validateSocksClientChainOptions = validateSocksClientChainOptions; + /** - * Validates a SocksRemoteHost - * @param remoteHost { SocksRemoteHost } + * Write a Body to a Node.js WritableStream (e.g. http.Request) object. + * + * @param Body instance Instance of Body + * @return Void */ -function isValidSocksRemoteHost(remoteHost) { - return (remoteHost && - typeof remoteHost.host === 'string' && - typeof remoteHost.port === 'number' && - remoteHost.port >= 0 && - remoteHost.port <= 65535); +function writeToStream(dest, instance) { + const body = instance.body; + + + if (body === null) { + // body is null + dest.end(); + } else if (isBlob(body)) { + body.stream().pipe(dest); + } else if (Buffer.isBuffer(body)) { + // body is buffer + dest.write(body); + dest.end(); + } else { + // body is stream + body.pipe(dest); + } } + +// expose Promise +Body.Promise = global.Promise; + /** - * Validates a SocksProxy - * @param proxy { SocksProxy } + * headers.js + * + * Headers class offers convenient helpers */ -function isValidSocksProxy(proxy) { - return (proxy && - (typeof proxy.host === 'string' || typeof proxy.ipaddress === 'string') && - typeof proxy.port === 'number' && - proxy.port >= 0 && - proxy.port <= 65535 && - (proxy.type === 4 || proxy.type === 5)); + +const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/; +const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/; + +function validateName(name) { + name = `${name}`; + if (invalidTokenRegex.test(name) || name === '') { + throw new TypeError(`${name} is not a legal HTTP header name`); + } +} + +function validateValue(value) { + value = `${value}`; + if (invalidHeaderCharRegex.test(value)) { + throw new TypeError(`${value} is not a legal HTTP header value`); + } } + /** - * Validates a timeout value. - * @param value { Number } + * Find the key in the map object given a header name. + * + * Returns undefined if not found. + * + * @param String name Header name + * @return String|Undefined */ -function isValidTimeoutValue(value) { - return typeof value === 'number' && value > 0; +function find(map, name) { + name = name.toLowerCase(); + for (const key in map) { + if (key.toLowerCase() === name) { + return key; + } + } + return undefined; } -//# sourceMappingURL=helpers.js.map -/***/ }), -/* 373 */, -/* 374 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +const MAP = Symbol('map'); +class Headers { + /** + * Headers class + * + * @param Object headers Response headers + * @return Void + */ + constructor() { + let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; -"use strict"; + this[MAP] = Object.create(null); + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); -module.exports = __webpack_require__(990) + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + return; + } -/***/ }), -/* 375 */, -/* 376 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } -module.exports = rimraf -rimraf.sync = rimrafSync + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } -var assert = __webpack_require__(357) -var path = __webpack_require__(622) -var fs = __webpack_require__(747) -var glob = undefined -try { - glob = __webpack_require__(402) -} catch (_err) { - // treat glob as optional. -} -var _0666 = parseInt('666', 8) + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } -var defaultGlobOpts = { - nosort: true, - silent: true -} + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } -// for EMFILE handling -var timeout = 0 + return this[MAP][key].join(', '); + } -var isWindows = (process.platform === "win32") + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } -function defaults (options) { - var methods = [ - 'unlink', - 'chmod', - 'stat', - 'lstat', - 'rmdir', - 'readdir' - ] - methods.forEach(function(m) { - options[m] = options[m] || fs[m] - m = m + 'Sync' - options[m] = options[m] || fs[m] - }) + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } - options.maxBusyTries = options.maxBusyTries || 3 - options.emfileWait = options.emfileWait || 1000 - if (options.glob === false) { - options.disableGlob = true - } - if (options.disableGlob !== true && glob === undefined) { - throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') - } - options.disableGlob = options.disableGlob || false - options.glob = options.glob || defaultGlobOpts + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } } +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; -function rimraf (p, options, cb) { - if (typeof options === 'function') { - cb = options - options = {} - } +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert.equal(typeof cb, 'function', 'rimraf: callback function required') - assert(options, 'rimraf: invalid options argument provided') - assert.equal(typeof options, 'object', 'rimraf: options should be object') +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); - defaults(options) +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; - var busyTries = 0 - var errState = null - var n = 0 + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} - if (options.disableGlob || !glob.hasMagic(p)) - return afterGlob(null, [p]) +const INTERNAL = Symbol('internal'); - options.lstat(p, function (er, stat) { - if (!er) - return afterGlob(null, [p]) +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} - glob(p, options.glob, afterGlob) - }) +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } - function next (er) { - errState = errState || er - if (--n === 0) - cb(errState) - } + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } - function afterGlob (er, results) { - if (er) - return cb(er) + this[INTERNAL].index = index + 1; - n = results.length - if (n === 0) - return cb() + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); - results.forEach(function (p) { - rimraf_(p, options, function CB (er) { - if (er) { - if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && - busyTries < options.maxBusyTries) { - busyTries ++ - var time = busyTries * 100 - // try again, with the same exact callback as this one. - return setTimeout(function () { - rimraf_(p, options, CB) - }, time) - } +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); - // this one won't happen if graceful-fs is used. - if (er.code === "EMFILE" && timeout < options.emfileWait) { - return setTimeout(function () { - rimraf_(p, options, CB) - }, timeout ++) - } +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } - // already gone - if (er.code === "ENOENT") er = null - } + return obj; +} - timeout = 0 - next(er) - }) - }) - } +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; } -// Two possible strategies. -// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR -// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR -// -// Both result in an extra syscall when you guess wrong. However, there -// are likely far more normal files in the world than directories. This -// is based on the assumption that a the average number of files per -// directory is >= 1. -// -// If anyone ever complains about this, then I guess the strategy could -// be made configurable somehow. But until then, YAGNI. -function rimraf_ (p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') +const INTERNALS$1 = Symbol('Response internals'); - // sunos lets the root user unlink directories, which is... weird. - // so we have to lstat here and make sure it's not a dir. - options.lstat(p, function (er, st) { - if (er && er.code === "ENOENT") - return cb(null) +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; - // Windows can EPERM on stat. Life is suffering. - if (er && er.code === "EPERM" && isWindows) - fixWinEPERM(p, options, er, cb) +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (st && st.isDirectory()) - return rmdir(p, options, er, cb) + Body.call(this, body, opts); - options.unlink(p, function (er) { - if (er) { - if (er.code === "ENOENT") - return cb(null) - if (er.code === "EPERM") - return (isWindows) - ? fixWinEPERM(p, options, er, cb) - : rmdir(p, options, er, cb) - if (er.code === "EISDIR") - return rmdir(p, options, er, cb) - } - return cb(er) - }) - }) -} + const status = opts.status || 200; + const headers = new Headers(opts.headers); -function fixWinEPERM (p, options, er, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - if (er) - assert(er instanceof Error) + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } - options.chmod(p, _0666, function (er2) { - if (er2) - cb(er2.code === "ENOENT" ? null : er) - else - options.stat(p, function(er3, stats) { - if (er3) - cb(er3.code === "ENOENT" ? null : er) - else if (stats.isDirectory()) - rmdir(p, options, er, cb) - else - options.unlink(p, cb) - }) - }) -} + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } -function fixWinEPERMSync (p, options, er) { - assert(p) - assert(options) - if (er) - assert(er instanceof Error) + get url() { + return this[INTERNALS$1].url || ''; + } - try { - options.chmodSync(p, _0666) - } catch (er2) { - if (er2.code === "ENOENT") - return - else - throw er - } + get status() { + return this[INTERNALS$1].status; + } - try { - var stats = options.statSync(p) - } catch (er3) { - if (er3.code === "ENOENT") - return - else - throw er - } + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } - if (stats.isDirectory()) - rmdirSync(p, options, er) - else - options.unlinkSync(p) -} + get redirected() { + return this[INTERNALS$1].counter > 0; + } -function rmdir (p, options, originalEr, cb) { - assert(p) - assert(options) - if (originalEr) - assert(originalEr instanceof Error) - assert(typeof cb === 'function') + get statusText() { + return this[INTERNALS$1].statusText; + } - // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) - // if we guessed wrong, and it's not a directory, then - // raise the original error. - options.rmdir(p, function (er) { - if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) - rmkids(p, options, cb) - else if (er && er.code === "ENOTDIR") - cb(originalEr) - else - cb(er) - }) + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } } -function rmkids(p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') +Body.mixIn(Response.prototype); - options.readdir(p, function (er, files) { - if (er) - return cb(er) - var n = files.length - if (n === 0) - return options.rmdir(p, cb) - var errState - files.forEach(function (f) { - rimraf(path.join(p, f), options, function (er) { - if (errState) - return - if (er) - return cb(errState = er) - if (--n === 0) - options.rmdir(p, cb) - }) - }) - }) +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; } -// this looks simpler, and is strictly *faster*, but will -// tie up the JavaScript thread and fail on excessively -// deep directory trees. -function rimrafSync (p, options) { - options = options || {} - defaults(options) +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert(options, 'rimraf: missing options') - assert.equal(typeof options, 'object', 'rimraf: options should be object') +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parse_url(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parse_url(`${input}`); + } + input = {}; + } else { + parsedURL = parse_url(input.url); + } - var results + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); - if (options.disableGlob || !glob.hasMagic(p)) { - results = [p] - } else { - try { - options.lstatSync(p) - results = [p] - } catch (er) { - results = glob.sync(p, options.glob) - } - } + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } - if (!results.length) - return + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; - for (var i = 0; i < results.length; i++) { - var p = results[i] + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); - try { - var st = options.lstatSync(p) - } catch (er) { - if (er.code === "ENOENT") - return + const headers = new Headers(init.headers || input.headers || {}); - // Windows can EPERM on stat. Life is suffering. - if (er.code === "EPERM" && isWindows) - fixWinEPERMSync(p, options, er) - } + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } - try { - // sunos lets the root user unlink directories, which is... weird. - if (st && st.isDirectory()) - rmdirSync(p, options, null) - else - options.unlinkSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "EPERM") - return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) - if (er.code !== "EISDIR") - throw er + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; - rmdirSync(p, options, er) - } - } -} + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } -function rmdirSync (p, options, originalEr) { - assert(p) - assert(options) - if (originalEr) - assert(originalEr instanceof Error) + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; - try { - options.rmdirSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "ENOTDIR") - throw originalEr - if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") - rmkidsSync(p, options) - } -} + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } -function rmkidsSync (p, options) { - assert(p) - assert(options) - options.readdirSync(p).forEach(function (f) { - rimrafSync(path.join(p, f), options) - }) + get method() { + return this[INTERNALS$2].method; + } - // We only end up here once we got ENOTEMPTY at least once, and - // at this point, we are guaranteed to have removed all the kids. - // So, we know that it won't be ENOENT or ENOTDIR or anything else. - // try really hard to delete stuff on windows, because it has a - // PROFOUNDLY annoying habit of not closing handles promptly when - // files are deleted, resulting in spurious ENOTEMPTY errors. - var retries = isWindows ? 100 : 1 - var i = 0 - do { - var threw = true - try { - var ret = options.rmdirSync(p, options) - threw = false - return ret - } finally { - if (++i < retries && threw) - continue - } - } while (true) + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } } +Body.mixIn(Request.prototype); -/***/ }), -/* 377 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); -"use strict"; +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); -module.exports = function(Promise, INTERNAL) { -var util = __webpack_require__(248); -var errorObj = util.errorObj; -var isObject = util.isObject; +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); -function tryConvertToPromise(obj, context) { - if (isObject(obj)) { - if (obj instanceof Promise) return obj; - var then = getThen(obj); - if (then === errorObj) { - if (context) context._pushContext(); - var ret = Promise.reject(then.e); - if (context) context._popContext(); - return ret; - } else if (typeof then === "function") { - if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - obj._then( - ret._fulfill, - ret._reject, - undefined, - ret, - null - ); - return ret; - } - return doThenable(obj, then, context); - } - } - return obj; -} + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } -function doGetThen(obj) { - return obj.then; -} + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } -function getThen(obj) { - try { - return doGetThen(obj); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } -var hasProp = {}.hasOwnProperty; -function isAnyBluebirdPromise(obj) { - try { - return hasProp.call(obj, "_promise0"); - } catch (e) { - return false; - } + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + if (!headers.has('Connection') && !agent) { + headers.set('Connection', 'close'); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); } -function doThenable(x, then, context) { - var promise = new Promise(INTERNAL); - var ret = promise; - if (context) context._pushContext(); - promise._captureStackTrace(); - if (context) context._popContext(); - var synchronous = true; - var result = util.tryCatch(then).call(x, resolve, reject); - synchronous = false; +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ - if (promise && result === errorObj) { - promise._rejectCallback(result.e, true, true); - promise = null; - } +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); - function resolve(value) { - if (!promise) return; - promise._resolveCallback(value); - promise = null; - } + this.type = 'aborted'; + this.message = message; - function reject(reason) { - if (!promise) return; - promise._rejectCallback(reason, synchronous, true); - promise = null; - } - return ret; + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); } -return tryConvertToPromise; -}; +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; +const resolve_url = Url.resolve; -/***/ }), -/* 378 */, -/* 379 */, -/* 380 */, -/* 381 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { -"use strict"; + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + Body.Promise = fetch.Promise; -const Buffer = __webpack_require__(197) + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); -// XXX: This shares a lot in common with extract.js -// maybe some DRY opportunity here? + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; -// tar -t -const hlo = __webpack_require__(29) -const Parser = __webpack_require__(203) -const fs = __webpack_require__(747) -const fsm = __webpack_require__(827) -const path = __webpack_require__(622) + let response = null; -const t = module.exports = (opt_, files, cb) => { - if (typeof opt_ === 'function') - cb = opt_, files = null, opt_ = {} - else if (Array.isArray(opt_)) - files = opt_, opt_ = {} + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + request.body.destroy(error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; - if (typeof files === 'function') - cb = files, files = null + if (signal && signal.aborted) { + abort(); + return; + } - if (!files) - files = [] - else - files = Array.from(files) + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; - const opt = hlo(opt_) + // send request + const req = send(options); + let reqTimeout; - if (opt.sync && typeof cb === 'function') - throw new TypeError('callback not supported for sync tar functions') + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } - if (!opt.file && typeof cb === 'function') - throw new TypeError('callback only supported with file option') + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } - if (files.length) - filesFilter(opt, files) + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } - if (!opt.noResume) - onentryFunction(opt) + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + finalize(); + }); - return opt.file && opt.sync ? listFileSync(opt) - : opt.file ? listFile(opt, cb) - : list(opt) -} + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + const locationURL = location === null ? null : resolve_url(request.url, location); + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } -const onentryFunction = opt => { - const onentry = opt.onentry - opt.onentry = onentry ? e => { - onentry(e) - e.resume() - } : e => e.resume() -} + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } -// construct a filter that limits the file entries listed -// include child entries if a dir is included -const filesFilter = (opt, files) => { - const map = new Map(files.map(f => [f.replace(/\/+$/, ''), true])) - const filter = opt.filter + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } - const mapHas = (file, r) => { - const root = r || path.parse(file).root || '.' - const ret = file === root ? false - : map.has(file) ? map.get(file) - : mapHas(path.dirname(file), root) + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + return; + } - map.set(file, ret) - return ret - } + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } - opt.filter = filter - ? (file, entry) => filter(file, entry) && mapHas(file.replace(/\/+$/, '')) - : file => mapHas(file.replace(/\/+$/, '')) + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); } +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; -const listFileSync = opt => { - const p = list(opt) - const file = opt.file - let threw = true - let fd - try { - const stat = fs.statSync(file) - const readSize = opt.maxReadSize || 16*1024*1024 - if (stat.size < readSize) { - p.end(fs.readFileSync(file)) - } else { - let pos = 0 - const buf = Buffer.allocUnsafe(readSize) - fd = fs.openSync(file, 'r') - while (pos < stat.size) { - let bytesRead = fs.readSync(fd, buf, 0, readSize, pos) - pos += bytesRead - p.write(buf.slice(0, bytesRead)) - } - p.end() +// expose Promise +fetch.Promise = global.Promise; + +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; + + +/***/ }), +/* 455 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +var path = __webpack_require__(622); +var parse = path.parse || __webpack_require__(905); + +var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) { + var prefix = '/'; + if ((/^([A-Za-z]:)/).test(absoluteStart)) { + prefix = ''; + } else if ((/^\\\\/).test(absoluteStart)) { + prefix = '\\\\'; } - threw = false - } finally { - if (threw && fd) - try { fs.closeSync(fd) } catch (er) {} - } -} -const listFile = (opt, cb) => { - const parse = new Parser(opt) - const readSize = opt.maxReadSize || 16*1024*1024 + var paths = [absoluteStart]; + var parsed = parse(absoluteStart); + while (parsed.dir !== paths[paths.length - 1]) { + paths.push(parsed.dir); + parsed = parse(parsed.dir); + } - const file = opt.file - const p = new Promise((resolve, reject) => { - parse.on('error', reject) - parse.on('end', resolve) + return paths.reduce(function (dirs, aPath) { + return dirs.concat(modules.map(function (moduleDir) { + return path.resolve(prefix, aPath, moduleDir); + })); + }, []); +}; - fs.stat(file, (er, stat) => { - if (er) - reject(er) - else { - const stream = new fsm.ReadStream(file, { - readSize: readSize, - size: stat.size - }) - stream.on('error', reject) - stream.pipe(parse) - } - }) - }) - return cb ? p.then(cb, cb) : p -} +module.exports = function nodeModulesPaths(start, opts, request) { + var modules = opts && opts.moduleDirectory + ? [].concat(opts.moduleDirectory) + : ['node_modules']; -const list = opt => new Parser(opt) + if (opts && typeof opts.paths === 'function') { + return opts.paths( + request, + start, + function () { return getNodeModulesDirs(start, modules); }, + opts + ); + } + + var dirs = getNodeModulesDirs(start, modules); + return opts && opts.paths ? dirs.concat(opts.paths) : dirs; +}; /***/ }), -/* 382 */ +/* 456 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +var stringWidth = __webpack_require__(66) -var iconvLite = __webpack_require__(841); - -// Expose to the world -module.exports.convert = convert; +module.exports = TemplateItem -/** - * Convert encoding of an UTF-8 string or a buffer - * - * @param {String|Buffer} str String to be converted - * @param {String} to Encoding to be converted to - * @param {String} [from='UTF-8'] Encoding to be converted from - * @return {Buffer} Encoded string - */ -function convert(str, to, from) { - from = checkEncoding(from || 'UTF-8'); - to = checkEncoding(to || 'UTF-8'); - str = str || ''; +function isPercent (num) { + if (typeof num !== 'string') return false + return num.slice(-1) === '%' +} - var result; +function percent (num) { + return Number(num.slice(0, -1)) / 100 +} - if (from !== 'UTF-8' && typeof str === 'string') { - str = Buffer.from(str, 'binary'); - } +function TemplateItem (values, outputLength) { + this.overallOutputLength = outputLength + this.finished = false + this.type = null + this.value = null + this.length = null + this.maxLength = null + this.minLength = null + this.kerning = null + this.align = 'left' + this.padLeft = 0 + this.padRight = 0 + this.index = null + this.first = null + this.last = null + if (typeof values === 'string') { + this.value = values + } else { + for (var prop in values) this[prop] = values[prop] + } + // Realize percents + if (isPercent(this.length)) { + this.length = Math.round(this.overallOutputLength * percent(this.length)) + } + if (isPercent(this.minLength)) { + this.minLength = Math.round(this.overallOutputLength * percent(this.minLength)) + } + if (isPercent(this.maxLength)) { + this.maxLength = Math.round(this.overallOutputLength * percent(this.maxLength)) + } + return this +} - if (from === to) { - if (typeof str === 'string') { - result = Buffer.from(str); - } else { - result = str; - } - } else { - try { - result = convertIconvLite(str, to, from); - } catch (E) { - console.error(E); - result = str; - } - } +TemplateItem.prototype = {} - if (typeof result === 'string') { - result = Buffer.from(result, 'utf-8'); - } +TemplateItem.prototype.getBaseLength = function () { + var length = this.length + if (length == null && typeof this.value === 'string' && this.maxLength == null && this.minLength == null) { + length = stringWidth(this.value) + } + return length +} - return result; +TemplateItem.prototype.getLength = function () { + var length = this.getBaseLength() + if (length == null) return null + return length + this.padLeft + this.padRight } -/** - * Convert encoding of astring with iconv-lite - * - * @param {String|Buffer} str String to be converted - * @param {String} to Encoding to be converted to - * @param {String} [from='UTF-8'] Encoding to be converted from - * @return {Buffer} Encoded string - */ -function convertIconvLite(str, to, from) { - if (to === 'UTF-8') { - return iconvLite.decode(str, from); - } else if (from === 'UTF-8') { - return iconvLite.encode(str, to); - } else { - return iconvLite.encode(iconvLite.decode(str, from), to); - } +TemplateItem.prototype.getMaxLength = function () { + if (this.maxLength == null) return null + return this.maxLength + this.padLeft + this.padRight } -/** - * Converts charset name if needed - * - * @param {String} name Character set - * @return {String} Character set name - */ -function checkEncoding(name) { - return (name || '') - .toString() - .trim() - .replace(/^latin[\-_]?(\d+)$/i, 'ISO-8859-$1') - .replace(/^win(?:dows)?[\-_]?(\d+)$/i, 'WINDOWS-$1') - .replace(/^utf[\-_]?(\d+)$/i, 'UTF-$1') - .replace(/^ks_c_5601\-1987$/i, 'CP949') - .replace(/^us[\-_]?ascii$/i, 'ASCII') - .toUpperCase(); +TemplateItem.prototype.getMinLength = function () { + if (this.minLength == null) return null + return this.minLength + this.padLeft + this.padRight } + /***/ }), -/* 383 */, -/* 384 */ -/***/ (function(module) { +/* 457 */ +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -module.exports.isObjectProto = isObjectProto -function isObjectProto (obj) { - return obj === Object.prototype -} +const Fetcher = __webpack_require__(404) +const fetchRegistry = __webpack_require__(446) -const _null = {} -const _undefined = {} -const Bool = Boolean -const Num = Number -const Str = String -const boolCache = { - true: new Bool(true), - false: new Bool(false) -} -const numCache = {} -const strCache = {} +const fetchRemote = module.exports = Object.create(null) -/* - * Returns a useful dispatch object for value using a process similar to - * the ToObject operation specified in http://es5.github.com/#x9.9 - */ -module.exports.dispatchableObject = dispatchableObject -function dispatchableObject (value) { - // To shut up jshint, which doesn't let me turn off this warning. - const Obj = Object - if (value === null) { return _null } - if (value === undefined) { return _undefined } - switch (typeof value) { - case 'object': return value - case 'boolean': return boolCache[value] - case 'number': return numCache[value] || (numCache[value] = new Num(value)) - case 'string': return strCache[value] || (strCache[value] = new Str(value)) - default: return new Obj(value) +Fetcher.impl(fetchRemote, { + packument (spec, opts) { + return fetchRegistry.packument(spec.subSpec, opts) + }, + + manifest (spec, opts) { + return fetchRegistry.manifest(spec.subSpec, opts) + }, + + tarball (spec, opts) { + return fetchRegistry.tarball(spec.subSpec, opts) + }, + + fromManifest (manifest, spec, opts) { + return fetchRegistry.fromManifest(manifest, spec.subSpec, opts) } -} +}) /***/ }), -/* 385 */, -/* 386 */ +/* 458 */ /***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, WriterState, XMLStreamWriter, XMLWriterBase, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + NodeType = __webpack_require__(683); + + XMLWriterBase = __webpack_require__(423); + + WriterState = __webpack_require__(541); + + module.exports = XMLStreamWriter = (function(superClass) { + extend(XMLStreamWriter, superClass); + + function XMLStreamWriter(stream, options) { + this.stream = stream; + XMLStreamWriter.__super__.constructor.call(this, options); + } + + XMLStreamWriter.prototype.endline = function(node, options, level) { + if (node.isLastRootNode && options.state === WriterState.CloseTag) { + return ''; + } else { + return XMLStreamWriter.__super__.endline.call(this, node, options, level); + } + }; + + XMLStreamWriter.prototype.document = function(doc, options) { + var child, i, j, k, len, len1, ref, ref1, results; + ref = doc.children; + for (i = j = 0, len = ref.length; j < len; i = ++j) { + child = ref[i]; + child.isLastRootNode = i === doc.children.length - 1; + } + options = this.filterOptions(options); + ref1 = doc.children; + results = []; + for (k = 0, len1 = ref1.length; k < len1; k++) { + child = ref1[k]; + results.push(this.writeChildNode(child, options, 0)); + } + return results; + }; + XMLStreamWriter.prototype.attribute = function(att, options, level) { + return this.stream.write(XMLStreamWriter.__super__.attribute.call(this, att, options, level)); + }; -var stringify = __webpack_require__(897); -var parse = __webpack_require__(755); -var formats = __webpack_require__(13); + XMLStreamWriter.prototype.cdata = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.cdata.call(this, node, options, level)); + }; -module.exports = { - formats: formats, - parse: parse, - stringify: stringify -}; + XMLStreamWriter.prototype.comment = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.comment.call(this, node, options, level)); + }; + XMLStreamWriter.prototype.declaration = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.declaration.call(this, node, options, level)); + }; -/***/ }), -/* 387 */ -/***/ (function(module) { + XMLStreamWriter.prototype.docType = function(node, options, level) { + var child, j, len, ref; + level || (level = 0); + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + this.stream.write(this.indent(node, options, level)); + this.stream.write(' 0) { + this.stream.write(' ['); + this.stream.write(this.endline(node, options, level)); + options.state = WriterState.InsideTag; + ref = node.children; + for (j = 0, len = ref.length; j < len; j++) { + child = ref[j]; + this.writeChildNode(child, options, level + 1); + } + options.state = WriterState.CloseTag; + this.stream.write(']'); + } + options.state = WriterState.CloseTag; + this.stream.write(options.spaceBeforeSlash + '>'); + this.stream.write(this.endline(node, options, level)); + options.state = WriterState.None; + return this.closeNode(node, options, level); + }; -module.exports = {"name":"node-gyp","description":"Node.js native addon build tool","license":"MIT","keywords":["native","addon","module","c","c++","bindings","gyp"],"version":"5.1.1","installVersion":9,"author":"Nathan Rajlich (http://tootallnate.net)","repository":{"type":"git","url":"git://github.com/nodejs/node-gyp.git"},"preferGlobal":true,"bin":"./bin/node-gyp.js","main":"./lib/node-gyp.js","dependencies":{"env-paths":"^2.2.0","glob":"^7.1.4","graceful-fs":"^4.2.2","mkdirp":"^0.5.1","nopt":"^4.0.1","npmlog":"^4.1.2","request":"^2.88.0","rimraf":"^2.6.3","semver":"^5.7.1","tar":"^4.4.12","which":"^1.3.1"},"engines":{"node":">= 6.0.0"},"devDependencies":{"bindings":"^1.5.0","nan":"^2.14.0","require-inject":"^1.4.4","standard":"^14.3.1","tap":"~12.7.0"},"scripts":{"lint":"standard */*.js test/**/*.js","test":"npm run lint && tap --timeout=120 test/test-*"}}; + XMLStreamWriter.prototype.element = function(node, options, level) { + var att, child, childNodeCount, firstChildNode, j, len, name, prettySuppressed, ref, ref1; + level || (level = 0); + this.openNode(node, options, level); + options.state = WriterState.OpenTag; + this.stream.write(this.indent(node, options, level) + '<' + node.name); + ref = node.attribs; + for (name in ref) { + if (!hasProp.call(ref, name)) continue; + att = ref[name]; + this.attribute(att, options, level); + } + childNodeCount = node.children.length; + firstChildNode = childNodeCount === 0 ? null : node.children[0]; + if (childNodeCount === 0 || node.children.every(function(e) { + return (e.type === NodeType.Text || e.type === NodeType.Raw) && e.value === ''; + })) { + if (options.allowEmpty) { + this.stream.write('>'); + options.state = WriterState.CloseTag; + this.stream.write(''); + } else { + options.state = WriterState.CloseTag; + this.stream.write(options.spaceBeforeSlash + '/>'); + } + } else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && (firstChildNode.value != null)) { + this.stream.write('>'); + options.state = WriterState.InsideTag; + options.suppressPrettyCount++; + prettySuppressed = true; + this.writeChildNode(firstChildNode, options, level + 1); + options.suppressPrettyCount--; + prettySuppressed = false; + options.state = WriterState.CloseTag; + this.stream.write(''); + } else { + this.stream.write('>' + this.endline(node, options, level)); + options.state = WriterState.InsideTag; + ref1 = node.children; + for (j = 0, len = ref1.length; j < len; j++) { + child = ref1[j]; + this.writeChildNode(child, options, level + 1); + } + options.state = WriterState.CloseTag; + this.stream.write(this.indent(node, options, level) + ''); + } + this.stream.write(this.endline(node, options, level)); + options.state = WriterState.None; + return this.closeNode(node, options, level); + }; -/***/ }), -/* 388 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + XMLStreamWriter.prototype.processingInstruction = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.processingInstruction.call(this, node, options, level)); + }; -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ + XMLStreamWriter.prototype.raw = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.raw.call(this, node, options, level)); + }; -if (typeof process === 'undefined' || process.type === 'renderer') { - module.exports = __webpack_require__(592); -} else { - module.exports = __webpack_require__(161); -} + XMLStreamWriter.prototype.text = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.text.call(this, node, options, level)); + }; + XMLStreamWriter.prototype.dtdAttList = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.dtdAttList.call(this, node, options, level)); + }; -/***/ }), -/* 389 */, -/* 390 */, -/* 391 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + XMLStreamWriter.prototype.dtdElement = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.dtdElement.call(this, node, options, level)); + }; -var current = (process.versions && process.versions.node && process.versions.node.split('.')) || []; + XMLStreamWriter.prototype.dtdEntity = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.dtdEntity.call(this, node, options, level)); + }; -function specifierIncluded(specifier) { - var parts = specifier.split(' '); - var op = parts.length > 1 ? parts[0] : '='; - var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); + XMLStreamWriter.prototype.dtdNotation = function(node, options, level) { + return this.stream.write(XMLStreamWriter.__super__.dtdNotation.call(this, node, options, level)); + }; - for (var i = 0; i < 3; ++i) { - var cur = Number(current[i] || 0); - var ver = Number(versionParts[i] || 0); - if (cur === ver) { - continue; // eslint-disable-line no-restricted-syntax, no-continue - } - if (op === '<') { - return cur < ver; - } else if (op === '>=') { - return cur >= ver; - } else { - return false; - } - } - return op === '>='; -} + return XMLStreamWriter; -function matchesRange(range) { - var specifiers = range.split(/ ?&& ?/); - if (specifiers.length === 0) { return false; } - for (var i = 0; i < specifiers.length; ++i) { - if (!specifierIncluded(specifiers[i])) { return false; } - } - return true; -} + })(XMLWriterBase); -function versionIncluded(specifierValue) { - if (typeof specifierValue === 'boolean') { return specifierValue; } - if (specifierValue && typeof specifierValue === 'object') { - for (var i = 0; i < specifierValue.length; ++i) { - if (matchesRange(specifierValue[i])) { return true; } - } - return false; - } - return matchesRange(specifierValue); -} +}).call(this); -var data = __webpack_require__(529); -var core = {}; -for (var mod in data) { // eslint-disable-line no-restricted-syntax - if (Object.prototype.hasOwnProperty.call(data, mod)) { - core[mod] = versionIncluded(data[mod]); - } -} -module.exports = core; +/***/ }), +/* 459 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(__webpack_require__(765), exports); +__exportStar(__webpack_require__(560), exports); +__exportStar(__webpack_require__(53), exports); +//# sourceMappingURL=index.js.map /***/ }), -/* 392 */, -/* 393 */ +/* 460 */ /***/ (function(module) { -module.exports = [["0","\u0000",127],["a140"," ,、。.‧;:?!︰…‥﹐﹑﹒·﹔﹕﹖﹗|–︱—︳╴︴﹏()︵︶{}︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"],["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′#&*※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡+-×÷±√<>=≦≧≠∞≒≡﹢",4,"~∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣/"],["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"],["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳0",9,"Ⅰ",9,"〡",8,"十卄卅A",25,"a",21],["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10],["a3a1","ㄐ",25,"˙ˉˊˇˋ"],["a3e1","€"],["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"],["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"],["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"],["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"],["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"],["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"],["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"],["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"],["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"],["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"],["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"],["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"],["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"],["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"],["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"],["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"],["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"],["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"],["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"],["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"],["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"],["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"],["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"],["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"],["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"],["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"],["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"],["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"],["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"],["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"],["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"],["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"],["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"],["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"],["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"],["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"],["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"],["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"],["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"],["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"],["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"],["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"],["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"],["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"],["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"],["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"],["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"],["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"],["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"],["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"],["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"],["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"],["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"],["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"],["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"],["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"],["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"],["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"],["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"],["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"],["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"],["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"],["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"],["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"],["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"],["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"],["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"],["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"],["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"],["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"],["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"],["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"],["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"],["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"],["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"],["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"],["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"],["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"],["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"],["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"],["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"],["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"],["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"],["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"],["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"],["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"],["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"],["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"],["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"],["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"],["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"],["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"],["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"],["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"],["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"],["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"],["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"],["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"],["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"],["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"],["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"],["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"],["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"],["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"],["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"],["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"],["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"],["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"],["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"],["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"],["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"],["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"],["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"],["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"],["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"],["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"],["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"],["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"],["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"],["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"],["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"],["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"],["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"],["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"],["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"],["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"],["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"],["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"],["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"],["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"],["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"],["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"],["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"],["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"],["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"],["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"],["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"],["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"],["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"],["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"],["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"],["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"],["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"],["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"],["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"],["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"],["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"],["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"],["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"],["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"],["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"],["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"],["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"],["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"],["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"],["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"],["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"],["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"],["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"],["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"],["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"],["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"],["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"],["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"],["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"],["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"],["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"]]; +// generated by genversion +module.exports = '4.0.0' + /***/ }), -/* 394 */, -/* 395 */, -/* 396 */ -/***/ (function(module) { +/* 461 */ +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -module.exports = function (Yallist) { - Yallist.prototype[Symbol.iterator] = function* () { - for (let walker = this.head; walker; walker = walker.next) { - yield walker.value - } - } + +const BB = __webpack_require__(489) + +module.exports = function (child, hasExitCode = false) { + return BB.fromNode(function (cb) { + child.on('error', cb) + child.on(hasExitCode ? 'close' : 'end', function (exitCode) { + if (exitCode === undefined || exitCode === 0) { + cb() + } else { + let err = new Error('exited with error code: ' + exitCode) + cb(err) + } + }) + }) } /***/ }), -/* 397 */, -/* 398 */, -/* 399 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 462 */ +/***/ (function(module) { "use strict"; -module.exports = RunQueue +// this exists so we can replace it during testing +module.exports = setInterval -var validate = __webpack_require__(904) -function RunQueue (opts) { - validate('Z|O', [opts]) - if (!opts) opts = {} - this.finished = false - this.inflight = 0 - this.maxConcurrency = opts.maxConcurrency || 1 - this.queued = 0 - this.queue = [] - this.currentPrio = null - this.currentQueue = null - this.Promise = opts.Promise || global.Promise - this.deferred = {} -} +/***/ }), +/* 463 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -RunQueue.prototype = {} +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLDTDElement, XMLNode, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; -RunQueue.prototype.run = function () { - if (arguments.length !== 0) throw new Error('RunQueue.run takes no arguments') - var self = this - var deferred = this.deferred - if (!deferred.promise) { - deferred.promise = new this.Promise(function (resolve, reject) { - deferred.resolve = resolve - deferred.reject = reject - self._runQueue() - }) - } - return deferred.promise -} + XMLNode = __webpack_require__(257); -RunQueue.prototype._runQueue = function () { - var self = this + NodeType = __webpack_require__(683); - while ((this.inflight < this.maxConcurrency) && this.queued) { - if (!this.currentQueue || this.currentQueue.length === 0) { - // wait till the current priority is entirely processed before - // starting a new one - if (this.inflight) return - var prios = Object.keys(this.queue) - for (var ii = 0; ii < prios.length; ++ii) { - var prioQueue = this.queue[prios[ii]] - if (prioQueue.length) { - this.currentQueue = prioQueue - this.currentPrio = prios[ii] - break - } + module.exports = XMLDTDElement = (function(superClass) { + extend(XMLDTDElement, superClass); + + function XMLDTDElement(parent, name, value) { + XMLDTDElement.__super__.constructor.call(this, parent); + if (name == null) { + throw new Error("Missing DTD element name. " + this.debugInfo()); + } + if (!value) { + value = '(#PCDATA)'; + } + if (Array.isArray(value)) { + value = '(' + value.join(',') + ')'; } + this.name = this.stringify.name(name); + this.type = NodeType.ElementDeclaration; + this.value = this.stringify.dtdElementValue(value); } - --this.queued - ++this.inflight - var next = this.currentQueue.shift() - var args = next.args || [] + XMLDTDElement.prototype.toString = function(options) { + return this.options.writer.dtdElement(this, this.options.writer.filterOptions(options)); + }; - // we explicitly construct a promise here so that queue items can throw - // or immediately return to resolve - var queueEntry = new this.Promise(function (resolve) { - resolve(next.cmd.apply(null, args)) - }) + return XMLDTDElement; - queueEntry.then(function () { - --self.inflight - if (self.finished) return - if (self.queued <= 0 && self.inflight <= 0) { - self.finished = true - self.deferred.resolve() - } - self._runQueue() - }, function (err) { - self.finished = true - self.deferred.reject(err) - }) - } -} + })(XMLNode); -RunQueue.prototype.add = function (prio, cmd, args) { - if (this.finished) throw new Error("Can't add to a finished queue. Create a new queue.") - if (Math.abs(Math.floor(prio)) !== prio) throw new Error('Priorities must be a positive integer value.') - validate('NFA|NFZ', [prio, cmd, args]) - prio = Number(prio) - if (!this.queue[prio]) this.queue[prio] = [] - ++this.queued - this.queue[prio].push({cmd: cmd, args: args}) - // if this priority is higher than the one we're currently processing, - // switch back to processing its queue. - if (this.currentPrio > prio) { - this.currentQueue = this.queue[prio] - this.currentPrio = prio - } -} +}).call(this); /***/ }), -/* 400 */ -/***/ (function(module, exports, __webpack_require__) { +/* 464 */, +/* 465 */ +/***/ (function(__unusedmodule, __unusedexports, __webpack_require__) { -var Stream = __webpack_require__(794) +"use strict"; -// through -// -// a stream that does nothing but re-emit the input. -// useful for aggregating a series of changing but not ending streams into one stream) +const url = __webpack_require__(835); +const https = __webpack_require__(211); -exports = module.exports = through -through.through = through +/** + * This currently needs to be applied to all Node.js versions + * in order to determine if the `req` is an HTTP or HTTPS request. + * + * There is currently no PR attempting to move this property upstream. + */ +const patchMarker = "__agent_base_https_request_patched__"; +if (!https.request[patchMarker]) { + https.request = (function(request) { + return function(_options, cb) { + let options; + if (typeof _options === 'string') { + options = url.parse(_options); + } else { + options = Object.assign({}, _options); + } + if (null == options.port) { + options.port = 443; + } + options.secureEndpoint = true; + return request.call(https, options, cb); + }; + })(https.request); + https.request[patchMarker] = true; +} -//create a readable writable stream. +/** + * This is needed for Node.js >= 9.0.0 to make sure `https.get()` uses the + * patched `https.request()`. + * + * Ref: https://github.com/nodejs/node/commit/5118f31 + */ +https.get = function (_url, _options, cb) { + let options; + if (typeof _url === 'string' && _options && typeof _options !== 'function') { + options = Object.assign({}, url.parse(_url), _options); + } else if (!_options && !cb) { + options = _url; + } else if (!cb) { + options = _url; + cb = _options; + } -function through (write, end, opts) { - write = write || function (data) { this.queue(data) } - end = end || function () { this.queue(null) } + const req = https.request(options, cb); + req.end(); + return req; +}; - var ended = false, destroyed = false, buffer = [], _ended = false - var stream = new Stream() - stream.readable = stream.writable = true - stream.paused = false -// stream.autoPause = !(opts && opts.autoPause === false) - stream.autoDestroy = !(opts && opts.autoDestroy === false) +/***/ }), +/* 466 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - stream.write = function (data) { - write.call(this, data) - return !stream.paused - } +;(function (sax) { // wrapper for non-node envs + sax.parser = function (strict, opt) { return new SAXParser(strict, opt) } + sax.SAXParser = SAXParser + sax.SAXStream = SAXStream + sax.createStream = createStream + + // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns. + // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)), + // since that's the earliest that a buffer overrun could occur. This way, checks are + // as rare as required, but as often as necessary to ensure never crossing this bound. + // Furthermore, buffers are only tested at most once per write(), so passing a very + // large string into write() might have undesirable effects, but this is manageable by + // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme + // edge case, result in creating at most one complete copy of the string passed in. + // Set to Infinity to have unlimited buffers. + sax.MAX_BUFFER_LENGTH = 64 * 1024 + + var buffers = [ + 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype', + 'procInstName', 'procInstBody', 'entity', 'attribName', + 'attribValue', 'cdata', 'script' + ] - function drain() { - while(buffer.length && !stream.paused) { - var data = buffer.shift() - if(null === data) - return stream.emit('end') - else - stream.emit('data', data) - } - } + sax.EVENTS = [ + 'text', + 'processinginstruction', + 'sgmldeclaration', + 'doctype', + 'comment', + 'opentagstart', + 'attribute', + 'opentag', + 'closetag', + 'opencdata', + 'cdata', + 'closecdata', + 'error', + 'end', + 'ready', + 'script', + 'opennamespace', + 'closenamespace' + ] - stream.queue = stream.push = function (data) { -// console.error(ended) - if(_ended) return stream - if(data === null) _ended = true - buffer.push(data) - drain() - return stream - } + function SAXParser (strict, opt) { + if (!(this instanceof SAXParser)) { + return new SAXParser(strict, opt) + } + + var parser = this + clearBuffers(parser) + parser.q = parser.c = '' + parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH + parser.opt = opt || {} + parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags + parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase' + parser.tags = [] + parser.closed = parser.closedRoot = parser.sawRoot = false + parser.tag = parser.error = null + parser.strict = !!strict + parser.noscript = !!(strict || parser.opt.noscript) + parser.state = S.BEGIN + parser.strictEntities = parser.opt.strictEntities + parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES) + parser.attribList = [] + + // namespaces form a prototype chain. + // it always points at the current tag, + // which protos to its parent tag. + if (parser.opt.xmlns) { + parser.ns = Object.create(rootNS) + } + + // mostly just for error reporting + parser.trackPosition = parser.opt.position !== false + if (parser.trackPosition) { + parser.position = parser.line = parser.column = 0 + } + emit(parser, 'onready') + } + + if (!Object.create) { + Object.create = function (o) { + function F () {} + F.prototype = o + var newf = new F() + return newf + } + } + + if (!Object.keys) { + Object.keys = function (o) { + var a = [] + for (var i in o) if (o.hasOwnProperty(i)) a.push(i) + return a + } + } + + function checkBufferLength (parser) { + var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10) + var maxActual = 0 + for (var i = 0, l = buffers.length; i < l; i++) { + var len = parser[buffers[i]].length + if (len > maxAllowed) { + // Text/cdata nodes can get big, and since they're buffered, + // we can get here under normal conditions. + // Avoid issues by emitting the text node now, + // so at least it won't get any bigger. + switch (buffers[i]) { + case 'textNode': + closeText(parser) + break - //this will be registered as the first 'end' listener - //must call destroy next tick, to make sure we're after any - //stream piped from here. - //this is only a problem if end is not emitted synchronously. - //a nicer way to do this is to make sure this is the last listener for 'end' + case 'cdata': + emitNode(parser, 'oncdata', parser.cdata) + parser.cdata = '' + break - stream.on('end', function () { - stream.readable = false - if(!stream.writable && stream.autoDestroy) - process.nextTick(function () { - stream.destroy() - }) - }) + case 'script': + emitNode(parser, 'onscript', parser.script) + parser.script = '' + break - function _end () { - stream.writable = false - end.call(stream) - if(!stream.readable && stream.autoDestroy) - stream.destroy() + default: + error(parser, 'Max buffer length exceeded: ' + buffers[i]) + } + } + maxActual = Math.max(maxActual, len) + } + // schedule the next check for the earliest possible buffer overrun. + var m = sax.MAX_BUFFER_LENGTH - maxActual + parser.bufferCheckPosition = m + parser.position } - stream.end = function (data) { - if(ended) return - ended = true - if(arguments.length) stream.write(data) - _end() // will emit or queue - return stream + function clearBuffers (parser) { + for (var i = 0, l = buffers.length; i < l; i++) { + parser[buffers[i]] = '' + } } - stream.destroy = function () { - if(destroyed) return - destroyed = true - ended = true - buffer.length = 0 - stream.writable = stream.readable = false - stream.emit('close') - return stream + function flushBuffers (parser) { + closeText(parser) + if (parser.cdata !== '') { + emitNode(parser, 'oncdata', parser.cdata) + parser.cdata = '' + } + if (parser.script !== '') { + emitNode(parser, 'onscript', parser.script) + parser.script = '' + } } - stream.pause = function () { - if(stream.paused) return - stream.paused = true - return stream + SAXParser.prototype = { + end: function () { end(this) }, + write: write, + resume: function () { this.error = null; return this }, + close: function () { return this.write(null) }, + flush: function () { flushBuffers(this) } } - stream.resume = function () { - if(stream.paused) { - stream.paused = false - stream.emit('resume') - } - drain() - //may have become paused again, - //as drain emits 'data'. - if(!stream.paused) - stream.emit('drain') - return stream + var Stream + try { + Stream = __webpack_require__(794).Stream + } catch (ex) { + Stream = function () {} } - return stream -} - - - -/***/ }), -/* 401 */ -/***/ (function(module, exports, __webpack_require__) { - -// info about each config option. - -var debug = process.env.DEBUG_NOPT || process.env.NOPT_DEBUG - ? function () { console.error.apply(console, arguments) } - : function () {} - -var url = __webpack_require__(835) - , path = __webpack_require__(622) - , Stream = __webpack_require__(794).Stream - , abbrev = __webpack_require__(916) - , osenv = __webpack_require__(580) -module.exports = exports = nopt -exports.clean = clean + var streamWraps = sax.EVENTS.filter(function (ev) { + return ev !== 'error' && ev !== 'end' + }) -exports.typeDefs = - { String : { type: String, validate: validateString } - , Boolean : { type: Boolean, validate: validateBoolean } - , url : { type: url, validate: validateUrl } - , Number : { type: Number, validate: validateNumber } - , path : { type: path, validate: validatePath } - , Stream : { type: Stream, validate: validateStream } - , Date : { type: Date, validate: validateDate } + function createStream (strict, opt) { + return new SAXStream(strict, opt) } -function nopt (types, shorthands, args, slice) { - args = args || process.argv - types = types || {} - shorthands = shorthands || {} - if (typeof slice !== "number") slice = 2 - - debug(types, shorthands, args, slice) - - args = args.slice(slice) - var data = {} - , key - , argv = { - remain: [], - cooked: args, - original: args.slice(0) - } - - parse(args, data, argv.remain, types, shorthands) - // now data is full - clean(data, types, exports.typeDefs) - data.argv = argv - Object.defineProperty(data.argv, 'toString', { value: function () { - return this.original.map(JSON.stringify).join(" ") - }, enumerable: false }) - return data -} - -function clean (data, types, typeDefs) { - typeDefs = typeDefs || exports.typeDefs - var remove = {} - , typeDefault = [false, true, null, String, Array] + function SAXStream (strict, opt) { + if (!(this instanceof SAXStream)) { + return new SAXStream(strict, opt) + } - Object.keys(data).forEach(function (k) { - if (k === "argv") return - var val = data[k] - , isArray = Array.isArray(val) - , type = types[k] - if (!isArray) val = [val] - if (!type) type = typeDefault - if (type === Array) type = typeDefault.concat(Array) - if (!Array.isArray(type)) type = [type] + Stream.apply(this) - debug("val=%j", val) - debug("types=", type) - val = val.map(function (val) { - // if it's an unknown value, then parse false/true/null/numbers/dates - if (typeof val === "string") { - debug("string %j", val) - val = val.trim() - if ((val === "null" && ~type.indexOf(null)) - || (val === "true" && - (~type.indexOf(true) || ~type.indexOf(Boolean))) - || (val === "false" && - (~type.indexOf(false) || ~type.indexOf(Boolean)))) { - val = JSON.parse(val) - debug("jsonable %j", val) - } else if (~type.indexOf(Number) && !isNaN(val)) { - debug("convert to number", val) - val = +val - } else if (~type.indexOf(Date) && !isNaN(Date.parse(val))) { - debug("convert to date", val) - val = new Date(val) - } - } + this._parser = new SAXParser(strict, opt) + this.writable = true + this.readable = true - if (!types.hasOwnProperty(k)) { - return val - } + var me = this - // allow `--no-blah` to set 'blah' to null if null is allowed - if (val === false && ~type.indexOf(null) && - !(~type.indexOf(false) || ~type.indexOf(Boolean))) { - val = null - } + this._parser.onend = function () { + me.emit('end') + } - var d = {} - d[k] = val - debug("prevalidated val", d, val, types[k]) - if (!validate(d, k, val, types[k], typeDefs)) { - if (exports.invalidHandler) { - exports.invalidHandler(k, val, types[k], data) - } else if (exports.invalidHandler !== false) { - debug("invalid: "+k+"="+val, types[k]) - } - return remove - } - debug("validated val", d, val, types[k]) - return d[k] - }).filter(function (val) { return val !== remove }) + this._parser.onerror = function (er) { + me.emit('error', er) - // if we allow Array specifically, then an empty array is how we - // express 'no value here', not null. Allow it. - if (!val.length && type.indexOf(Array) === -1) { - debug('VAL HAS NO LENGTH, DELETE IT', val, k, type.indexOf(Array)) - delete data[k] + // if didn't throw, then means error was handled. + // go ahead and clear error, so we can write again. + me._parser.error = null } - else if (isArray) { - debug(isArray, data[k], val) - data[k] = val - } else data[k] = val[0] - debug("k=%s val=%j", k, val, data[k]) + this._decoder = null + + streamWraps.forEach(function (ev) { + Object.defineProperty(me, 'on' + ev, { + get: function () { + return me._parser['on' + ev] + }, + set: function (h) { + if (!h) { + me.removeAllListeners(ev) + me._parser['on' + ev] = h + return h + } + me.on(ev, h) + }, + enumerable: true, + configurable: false + }) + }) + } + + SAXStream.prototype = Object.create(Stream.prototype, { + constructor: { + value: SAXStream + } }) -} -function validateString (data, k, val) { - data[k] = String(val) -} + SAXStream.prototype.write = function (data) { + if (typeof Buffer === 'function' && + typeof Buffer.isBuffer === 'function' && + Buffer.isBuffer(data)) { + if (!this._decoder) { + var SD = __webpack_require__(304).StringDecoder + this._decoder = new SD('utf8') + } + data = this._decoder.write(data) + } -function validatePath (data, k, val) { - if (val === true) return false - if (val === null) return true + this._parser.write(data.toString()) + this.emit('data', data) + return true + } - val = String(val) + SAXStream.prototype.end = function (chunk) { + if (chunk && chunk.length) { + this.write(chunk) + } + this._parser.end() + return true + } - var isWin = process.platform === 'win32' - , homePattern = isWin ? /^~(\/|\\)/ : /^~\// - , home = osenv.home() + SAXStream.prototype.on = function (ev, handler) { + var me = this + if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) { + me._parser['on' + ev] = function () { + var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments) + args.splice(0, 0, ev) + me.emit.apply(me, args) + } + } - if (home && val.match(homePattern)) { - data[k] = path.resolve(home, val.substr(2)) - } else { - data[k] = path.resolve(val) + return Stream.prototype.on.call(me, ev, handler) + } + + // this really needs to be replaced with character classes. + // XML allows all manner of ridiculous numbers and digits. + var CDATA = '[CDATA[' + var DOCTYPE = 'DOCTYPE' + var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace' + var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/' + var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE } + + // http://www.w3.org/TR/REC-xml/#NT-NameStartChar + // This implementation works on strings, a single character at a time + // as such, it cannot ever support astral-plane characters (10000-EFFFF) + // without a significant breaking change to either this parser, or the + // JavaScript language. Implementation of an emoji-capable xml parser + // is left as an exercise for the reader. + var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ + + var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ + + var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ + var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ + + function isWhitespace (c) { + return c === ' ' || c === '\n' || c === '\r' || c === '\t' + } + + function isQuote (c) { + return c === '"' || c === '\'' + } + + function isAttribEnd (c) { + return c === '>' || isWhitespace(c) + } + + function isMatch (regex, c) { + return regex.test(c) + } + + function notMatch (regex, c) { + return !isMatch(regex, c) + } + + var S = 0 + sax.STATE = { + BEGIN: S++, // leading byte order mark or whitespace + BEGIN_WHITESPACE: S++, // leading whitespace + TEXT: S++, // general stuff + TEXT_ENTITY: S++, // & and such. + OPEN_WAKA: S++, // < + SGML_DECL: S++, // + SCRIPT: S++, //