diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index 1fb0b587..00000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,6 +0,0 @@ -version: 2 -updates: - - package-ecosystem: npm - directory: / - schedule: - interval: daily diff --git a/.github/workflows/workflow.yml b/.github/workflows/workflow.yml index b63710b8..b2465ae2 100644 --- a/.github/workflows/workflow.yml +++ b/.github/workflows/workflow.yml @@ -35,6 +35,11 @@ jobs: - name: Checkout code uses: actions/checkout@v3 + - name: Use pnpm + uses: pnpm/action-setup@v2.2.2 + with: + version: latest + - name: Use Node.js 16.x uses: actions/setup-node@v2 with: @@ -42,25 +47,25 @@ jobs: - name: Install npm packages if: runner.os == 'Linux' - run: yarn --frozen-lockfile + run: pnpm install --frozen-lockfile - name: Check formatting if: runner.os == 'Linux' - run: yarn fmt:check + run: pnpm fmt:check - name: Check lint if: runner.os == 'Linux' - run: yarn lint + run: pnpm lint - name: Check type if: runner.os == 'Linux' - run: yarn typecheck + run: pnpm typecheck - name: Ensure dist directory is up-to-date if: runner.os == 'Linux' shell: bash run: | - yarn build + pnpm build if [ "$(git status dist lint-doc lint-fmt lint-opam --porcelain | wc -l)" -gt "0" ]; then echo "Detected uncommitted changes after build. See status below:" git diff diff --git a/.prettierignore b/.prettierignore index d4f74c4a..f75bc530 100644 --- a/.prettierignore +++ b/.prettierignore @@ -3,3 +3,4 @@ /lint-doc/* /lint-fmt/* /lint-opam/* +pnpm-lock.yaml diff --git a/dist/LICENSE.txt b/dist/LICENSE.txt index 6c984c6f..0a50fbb6 100644 --- a/dist/LICENSE.txt +++ b/dist/LICENSE.txt @@ -257,6 +257,31 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +@azure/core-util +MIT +The MIT License (MIT) + +Copyright (c) 2020 Microsoft + +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. + + @azure/logger MIT The MIT License (MIT) diff --git a/dist/index.js b/dist/index.js index a3255ee9..53228e98 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,7 +1,7 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ 27799: +/***/ 38949: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -23,11 +23,11 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(42186)); +const core = __importStar(__nccwpck_require__(65681)); const path = __importStar(__nccwpck_require__(71017)); -const utils = __importStar(__nccwpck_require__(91518)); -const cacheHttpClient = __importStar(__nccwpck_require__(98245)); -const tar_1 = __nccwpck_require__(56490); +const utils = __importStar(__nccwpck_require__(41641)); +const cacheHttpClient = __importStar(__nccwpck_require__(82289)); +const tar_1 = __nccwpck_require__(99405); class ValidationError extends Error { constructor(message) { super(message); @@ -218,7 +218,7 @@ exports.saveCache = saveCache; /***/ }), -/***/ 98245: +/***/ 82289: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -240,17 +240,17 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(42186)); -const http_client_1 = __nccwpck_require__(96255); -const auth_1 = __nccwpck_require__(35526); +const core = __importStar(__nccwpck_require__(65681)); +const http_client_1 = __nccwpck_require__(9706); +const auth_1 = __nccwpck_require__(98336); const crypto = __importStar(__nccwpck_require__(6113)); const fs = __importStar(__nccwpck_require__(57147)); const url_1 = __nccwpck_require__(57310); -const utils = __importStar(__nccwpck_require__(91518)); -const constants_1 = __nccwpck_require__(88840); -const downloadUtils_1 = __nccwpck_require__(55500); -const options_1 = __nccwpck_require__(76215); -const requestUtils_1 = __nccwpck_require__(13981); +const utils = __importStar(__nccwpck_require__(41641)); +const constants_1 = __nccwpck_require__(3247); +const downloadUtils_1 = __nccwpck_require__(13262); +const options_1 = __nccwpck_require__(44620); +const requestUtils_1 = __nccwpck_require__(67584); const versionSalt = '1.0'; function getCacheApiUrl(resource) { const baseUrl = process.env['ACTIONS_CACHE_URL'] || ''; @@ -438,7 +438,7 @@ exports.saveCache = saveCache; /***/ }), -/***/ 91518: +/***/ 41641: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -467,16 +467,16 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(42186)); -const exec = __importStar(__nccwpck_require__(71514)); -const glob = __importStar(__nccwpck_require__(31597)); -const io = __importStar(__nccwpck_require__(47351)); +const core = __importStar(__nccwpck_require__(65681)); +const exec = __importStar(__nccwpck_require__(15082)); +const glob = __importStar(__nccwpck_require__(59215)); +const io = __importStar(__nccwpck_require__(50157)); const fs = __importStar(__nccwpck_require__(57147)); const path = __importStar(__nccwpck_require__(71017)); -const semver = __importStar(__nccwpck_require__(3771)); +const semver = __importStar(__nccwpck_require__(71494)); const util = __importStar(__nccwpck_require__(73837)); -const uuid_1 = __nccwpck_require__(94138); -const constants_1 = __nccwpck_require__(88840); +const uuid_1 = __nccwpck_require__(57046); +const constants_1 = __nccwpck_require__(3247); // 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* () { @@ -626,7 +626,7 @@ exports.isGhes = isGhes; /***/ }), -/***/ 88840: +/***/ 3247: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -657,7 +657,7 @@ exports.SocketTimeout = 5000; /***/ }), -/***/ 55500: +/***/ 13262: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -679,17 +679,17 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(42186)); -const http_client_1 = __nccwpck_require__(96255); -const storage_blob_1 = __nccwpck_require__(84100); +const core = __importStar(__nccwpck_require__(65681)); +const http_client_1 = __nccwpck_require__(9706); +const storage_blob_1 = __nccwpck_require__(36835); const buffer = __importStar(__nccwpck_require__(14300)); const fs = __importStar(__nccwpck_require__(57147)); const stream = __importStar(__nccwpck_require__(12781)); const util = __importStar(__nccwpck_require__(73837)); -const utils = __importStar(__nccwpck_require__(91518)); -const constants_1 = __nccwpck_require__(88840); -const requestUtils_1 = __nccwpck_require__(13981); -const abort_controller_1 = __nccwpck_require__(52557); +const utils = __importStar(__nccwpck_require__(41641)); +const constants_1 = __nccwpck_require__(3247); +const requestUtils_1 = __nccwpck_require__(67584); +const abort_controller_1 = __nccwpck_require__(97675); /** * Pipes the body of a HTTP response to a stream * @@ -915,7 +915,7 @@ const promiseWithTimeout = (timeoutMs, promise) => __awaiter(void 0, void 0, voi /***/ }), -/***/ 13981: +/***/ 67584: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -937,9 +937,9 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(42186)); -const http_client_1 = __nccwpck_require__(96255); -const constants_1 = __nccwpck_require__(88840); +const core = __importStar(__nccwpck_require__(65681)); +const http_client_1 = __nccwpck_require__(9706); +const constants_1 = __nccwpck_require__(3247); function isSuccessStatusCode(statusCode) { if (!statusCode) { return false; @@ -1042,7 +1042,7 @@ exports.retryHttpClientResponse = retryHttpClientResponse; /***/ }), -/***/ 56490: +/***/ 99405: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1064,12 +1064,12 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const exec_1 = __nccwpck_require__(71514); -const io = __importStar(__nccwpck_require__(47351)); +const exec_1 = __nccwpck_require__(15082); +const io = __importStar(__nccwpck_require__(50157)); const fs_1 = __nccwpck_require__(57147); const path = __importStar(__nccwpck_require__(71017)); -const utils = __importStar(__nccwpck_require__(91518)); -const constants_1 = __nccwpck_require__(88840); +const utils = __importStar(__nccwpck_require__(41641)); +const constants_1 = __nccwpck_require__(3247); const IS_WINDOWS = process.platform === 'win32'; function getTarPath(args, compressionMethod) { return __awaiter(this, void 0, void 0, function* () { @@ -1211,7 +1211,7 @@ exports.createTar = createTar; /***/ }), -/***/ 76215: +/***/ 44620: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1224,7 +1224,7 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(42186)); +const core = __importStar(__nccwpck_require__(65681)); /** * Returns a copy of the upload options with defaults filled in. * @@ -1292,40 +1292,7 @@ exports.getDownloadOptions = getDownloadOptions; /***/ }), -/***/ 31597: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.create = void 0; -const internal_globber_1 = __nccwpck_require__(27341); -/** - * 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 - -/***/ }), - -/***/ 99350: +/***/ 11346: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1350,39 +1317,81 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOptions = void 0; -const core = __importStar(__nccwpck_require__(42186)); +exports.issue = exports.issueCommand = void 0; +const os = __importStar(__nccwpck_require__(22037)); +const utils_1 = __nccwpck_require__(79754); /** - * Returns a copy with defaults filled in. + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value */ -function getOptions(copy) { - const result = { - followSymbolicLinks: true, - implicitDescendants: true, - omitBrokenSymbolicLinks: true - }; - if (copy) { - if (typeof copy.followSymbolicLinks === 'boolean') { - result.followSymbolicLinks = copy.followSymbolicLinks; - core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); - } - if (typeof copy.implicitDescendants === 'boolean') { - result.implicitDescendants = copy.implicitDescendants; - core.debug(`implicitDescendants '${result.implicitDescendants}'`); +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'; } - if (typeof copy.omitBrokenSymbolicLinks === 'boolean') { - result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; - core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); + 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; } - return result; } -exports.getOptions = getOptions; -//# sourceMappingURL=internal-glob-options-helper.js.map +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 /***/ }), -/***/ 27341: +/***/ 65681: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1415,450 +1424,323 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge 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 })); -exports.DefaultGlobber = void 0; -const core = __importStar(__nccwpck_require__(42186)); -const fs = __importStar(__nccwpck_require__(57147)); -const globOptionsHelper = __importStar(__nccwpck_require__(99350)); +exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; +const command_1 = __nccwpck_require__(11346); +const file_command_1 = __nccwpck_require__(91753); +const utils_1 = __nccwpck_require__(79754); +const os = __importStar(__nccwpck_require__(22037)); const path = __importStar(__nccwpck_require__(71017)); -const patternHelper = __importStar(__nccwpck_require__(95186)); -const internal_match_kind_1 = __nccwpck_require__(80836); -const internal_pattern_1 = __nccwpck_require__(35343); -const internal_search_state_1 = __nccwpck_require__(28530); -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, true, 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); - } - } - }); - } +const uuid_1 = __nccwpck_require__(37066); +const oidc_utils_1 = __nccwpck_require__(94892); +/** + * The code to exit an action + */ +var ExitCode; +(function (ExitCode) { /** - * Constructs a DefaultGlobber + * A code indicating that the action was successful */ - 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; - }); + ExitCode[ExitCode["Success"] = 0] = "Success"; + /** + * A code indicating that the action was a failure + */ + ExitCode[ExitCode["Failure"] = 1] = "Failure"; +})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); +//----------------------------------------------------------------------- +// Variables +//----------------------------------------------------------------------- +/** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function exportVariable(name, val) { + const convertedVal = utils_1.toCommandValue(val); + process.env[name] = convertedVal; + const filePath = process.env['GITHUB_ENV'] || ''; + if (filePath) { + const delimiter = `ghadelimiter_${uuid_1.v4()}`; + // These should realistically never happen, but just in case someone finds a way to exploit uuid generation let's not allow keys or values that contain the delimiter. + if (name.includes(delimiter)) { + throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); + } + if (convertedVal.includes(delimiter)) { + throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); + } + const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; + file_command_1.issueCommand('ENV', commandValue); } - 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; - }); + else { + command_1.issueCommand('set-env', { name }, convertedVal); } } -exports.DefaultGlobber = DefaultGlobber; -//# sourceMappingURL=internal-globber.js.map - -/***/ }), - -/***/ 80836: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MatchKind = void 0; +exports.exportVariable = exportVariable; /** - * Indicates whether a pattern matches a path + * Registers a secret which will get masked from logs + * @param secret value of the secret */ -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 - -/***/ }), - -/***/ 20022: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.safeTrimTrailingSeparator = exports.normalizeSeparators = exports.hasRoot = exports.hasAbsoluteRoot = exports.ensureAbsoluteRoot = exports.dirname = void 0; -const path = __importStar(__nccwpck_require__(71017)); -const assert_1 = __importDefault(__nccwpck_require__(39491)); -const IS_WINDOWS = process.platform === 'win32'; +function setSecret(secret) { + command_1.issueCommand('add-mask', {}, secret); +} +exports.setSecret = setSecret; /** - * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths. - * - * For example, on Linux/macOS: - * - `/ => /` - * - `/hello => /` - * - * For example, on Windows: - * - `C:\ => C:\` - * - `C:\hello => C:\` - * - `C: => C:` - * - `C:hello => C:` - * - `\ => \` - * - `\hello => \` - * - `\\hello => \\hello` - * - `\\hello\world => \\hello\world` + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath */ -function dirname(p) { - // Normalize slashes and trim unnecessary trailing slash - p = safeTrimTrailingSeparator(p); - // Windows UNC root, e.g. \\hello or \\hello\world - if (IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) { - return p; +function addPath(inputPath) { + const filePath = process.env['GITHUB_PATH'] || ''; + if (filePath) { + file_command_1.issueCommand('PATH', inputPath); } - // Get dirname - let result = path.dirname(p); - // Trim trailing slash for Windows UNC root, e.g. \\hello\world\ - if (IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) { - result = safeTrimTrailingSeparator(result); + else { + command_1.issueCommand('add-path', {}, inputPath); } - return result; + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } -exports.dirname = dirname; +exports.addPath = addPath; /** - * Roots the path if not already rooted. On Windows, relative roots like `\` - * or `C:` are expanded based on the current working directory. + * Gets the value of an input. + * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. + * Returns an empty string if the value is not defined. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string */ -function ensureAbsoluteRoot(root, itemPath) { - assert_1.default(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); - assert_1.default(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); - // Already rooted - if (hasAbsoluteRoot(itemPath)) { - return itemPath; - } - // Windows - if (IS_WINDOWS) { - // Check for itemPath like C: or C:foo - if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) { - let cwd = process.cwd(); - assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); - // Drive letter matches cwd? Expand to cwd - if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) { - // Drive only, e.g. C: - if (itemPath.length === 2) { - // Preserve specified drive letter case (upper or lower) - return `${itemPath[0]}:\\${cwd.substr(3)}`; - } - // Drive + path, e.g. C:foo - else { - if (!cwd.endsWith('\\')) { - cwd += '\\'; - } - // Preserve specified drive letter case (upper or lower) - return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`; - } - } - // Different drive - else { - return `${itemPath[0]}:\\${itemPath.substr(2)}`; - } - } - // Check for itemPath like \ or \foo - else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) { - const cwd = process.cwd(); - assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); - return `${cwd[0]}:\\${itemPath.substr(1)}`; - } +function getInput(name, options) { + const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; + if (options && options.required && !val) { + throw new Error(`Input required and not supplied: ${name}`); } - assert_1.default(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); - // Otherwise ensure root ends with a separator - if (root.endsWith('/') || (IS_WINDOWS && root.endsWith('\\'))) { - // Intentionally empty + if (options && options.trimWhitespace === false) { + return val; } - else { - // Append separator - root += path.sep; - } - return root + itemPath; + return val.trim(); } -exports.ensureAbsoluteRoot = ensureAbsoluteRoot; +exports.getInput = getInput; /** - * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: - * `\\hello\share` and `C:\hello` (and using alternate separator). + * Gets the values of an multiline input. Each value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string[] + * */ -function hasAbsoluteRoot(itemPath) { - assert_1.default(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); - // Normalize separators - itemPath = normalizeSeparators(itemPath); - // Windows - if (IS_WINDOWS) { - // E.g. \\hello\share or C:\hello - return itemPath.startsWith('\\\\') || /^[A-Z]:\\/i.test(itemPath); - } - // E.g. /hello - return itemPath.startsWith('/'); +function getMultilineInput(name, options) { + const inputs = getInput(name, options) + .split('\n') + .filter(x => x !== ''); + return inputs; } -exports.hasAbsoluteRoot = hasAbsoluteRoot; +exports.getMultilineInput = getMultilineInput; /** - * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: - * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator). + * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. + * Support boolean input list: `true | True | TRUE | false | False | FALSE` . + * The return value is also in boolean type. + * ref: https://yaml.org/spec/1.2/spec.html#id2804923 + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns boolean */ -function hasRoot(itemPath) { - assert_1.default(itemPath, `isRooted parameter 'itemPath' must not be empty`); - // Normalize separators - itemPath = normalizeSeparators(itemPath); - // Windows - if (IS_WINDOWS) { - // E.g. \ or \hello or \\hello - // E.g. C: or C:\hello - return itemPath.startsWith('\\') || /^[A-Z]:/i.test(itemPath); - } - // E.g. /hello - return itemPath.startsWith('/'); +function getBooleanInput(name, options) { + const trueValue = ['true', 'True', 'TRUE']; + const falseValue = ['false', 'False', 'FALSE']; + const val = getInput(name, options); + if (trueValue.includes(val)) + return true; + if (falseValue.includes(val)) + return false; + throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + + `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); } -exports.hasRoot = hasRoot; +exports.getBooleanInput = getBooleanInput; /** - * Removes redundant slashes and converts `/` to `\` on Windows + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ -function normalizeSeparators(p) { - p = p || ''; - // Windows - if (IS_WINDOWS) { - // Convert slashes on Windows - p = p.replace(/\//g, '\\'); - // Remove redundant slashes - const isUnc = /^\\\\+[^\\]/.test(p); // e.g. \\hello - return (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\'); // preserve leading \\ for UNC - } - // Remove redundant slashes - return p.replace(/\/\/+/g, '/'); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setOutput(name, value) { + process.stdout.write(os.EOL); + command_1.issueCommand('set-output', { name }, value); } -exports.normalizeSeparators = normalizeSeparators; +exports.setOutput = setOutput; /** - * Normalizes the path separators and trims the trailing separator (when safe). - * For example, `/foo/ => /foo` but `/ => /` + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * */ -function safeTrimTrailingSeparator(p) { - // Short-circuit if empty - if (!p) { - return ''; - } - // Normalize separators - p = normalizeSeparators(p); - // No trailing slash - if (!p.endsWith(path.sep)) { - return p; - } - // Check '/' on Linux/macOS and '\' on Windows - if (p === path.sep) { - return p; - } - // On Windows check if drive root. E.g. C:\ - if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) { - return p; - } - // Otherwise trim trailing slash - return p.substr(0, p.length - 1); +function setCommandEcho(enabled) { + command_1.issue('echo', enabled ? 'on' : 'off'); } -exports.safeTrimTrailingSeparator = safeTrimTrailingSeparator; -//# sourceMappingURL=internal-path-helper.js.map +exports.setCommandEcho = setCommandEcho; +//----------------------------------------------------------------------- +// Results +//----------------------------------------------------------------------- +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); +} +exports.setFailed = setFailed; +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; +} +exports.isDebug = isDebug; +/** + * Writes debug message to user log + * @param message debug message + */ +function debug(message) { + command_1.issueCommand('debug', {}, message); +} +exports.debug = debug; +/** + * Adds an error issue + * @param message error issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function error(message, properties = {}) { + command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +exports.error = error; +/** + * Adds a warning issue + * @param message warning issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function warning(message, properties = {}) { + command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +exports.warning = warning; +/** + * Adds a notice issue + * @param message notice issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function notice(message, properties = {}) { + command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +exports.notice = notice; +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + os.EOL); +} +exports.info = info; +/** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ +function startGroup(name) { + command_1.issue('group', name); +} +exports.startGroup = startGroup; +/** + * End an output group. + */ +function endGroup() { + command_1.issue('endgroup'); +} +exports.endGroup = endGroup; +/** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ +function group(name, fn) { + return __awaiter(this, void 0, void 0, function* () { + startGroup(name); + let result; + try { + result = yield fn(); + } + finally { + endGroup(); + } + return result; + }); +} +exports.group = group; +//----------------------------------------------------------------------- +// Wrapper action state +//----------------------------------------------------------------------- +/** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @param name name of the state to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function saveState(name, value) { + command_1.issueCommand('save-state', { name }, value); +} +exports.saveState = saveState; +/** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ +function getState(name) { + return process.env[`STATE_${name}`] || ''; +} +exports.getState = getState; +function getIDToken(aud) { + return __awaiter(this, void 0, void 0, function* () { + return yield oidc_utils_1.OidcClient.getIDToken(aud); + }); +} +exports.getIDToken = getIDToken; +/** + * Summary exports + */ +var summary_1 = __nccwpck_require__(25957); +Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); +/** + * @deprecated use core.summary + */ +var summary_2 = __nccwpck_require__(25957); +Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); +/** + * Path exports + */ +var path_utils_1 = __nccwpck_require__(50891); +Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); +Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); +Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); +//# sourceMappingURL=core.js.map /***/ }), -/***/ 19413: +/***/ 91753: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +// For internal use, subject to change. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); @@ -1878,103 +1760,115 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.issueCommand = void 0; +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +const fs = __importStar(__nccwpck_require__(57147)); +const os = __importStar(__nccwpck_require__(22037)); +const utils_1 = __nccwpck_require__(79754); +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 + +/***/ }), + +/***/ 94892: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Path = void 0; -const path = __importStar(__nccwpck_require__(71017)); -const pathHelper = __importStar(__nccwpck_require__(20022)); -const assert_1 = __importDefault(__nccwpck_require__(39491)); -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_1.default(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); - } +exports.OidcClient = void 0; +const http_client_1 = __nccwpck_require__(9706); +const auth_1 = __nccwpck_require__(98336); +const core_1 = __nccwpck_require__(65681); +class OidcClient { + static createHttpClient(allowRetry = true, maxRetry = 10) { + const requestOptions = { + allowRetries: allowRetry, + maxRetries: maxRetry + }; + return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); + } + static getRequestToken() { + const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; + if (!token) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); } - // Array - else { - // Must not be empty - assert_1.default(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_1.default(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_1.default(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_1.default(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); - this.segments.push(segment); - } - } + return token; + } + static getIDTokenUrl() { + const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; + if (!runtimeUrl) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); } + return runtimeUrl; } - /** - * 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; + static getCall(id_token_url) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const httpclient = OidcClient.createHttpClient(); + const res = yield httpclient + .getJson(id_token_url) + .catch(error => { + throw new Error(`Failed to get ID Token. \n + Error Code : ${error.statusCode}\n + Error Message: ${error.result.message}`); + }); + const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; + if (!id_token) { + throw new Error('Response json body do not have ID Token field'); } - else { - result += path.sep; + return id_token; + }); + } + static getIDToken(audience) { + return __awaiter(this, void 0, void 0, function* () { + try { + // New ID Token is requested from action service + let id_token_url = OidcClient.getIDTokenUrl(); + if (audience) { + const encodedAudience = encodeURIComponent(audience); + id_token_url = `${id_token_url}&audience=${encodedAudience}`; + } + core_1.debug(`ID token url is ${id_token_url}`); + const id_token = yield OidcClient.getCall(id_token_url); + core_1.setSecret(id_token); + return id_token; } - result += this.segments[i]; - } - return result; + catch (error) { + throw new Error(`Error message: ${error.message}`); + } + }); } } -exports.Path = Path; -//# sourceMappingURL=internal-path.js.map +exports.OidcClient = OidcClient; +//# sourceMappingURL=oidc-utils.js.map /***/ }), -/***/ 95186: +/***/ 50891: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1999,18207 +1893,12474 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.partialMatch = exports.match = exports.getSearchPaths = void 0; -const pathHelper = __importStar(__nccwpck_require__(20022)); -const internal_match_kind_1 = __nccwpck_require__(80836); -const IS_WINDOWS = process.platform === 'win32'; +exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; +const path = __importStar(__nccwpck_require__(71017)); /** - * Given an array of patterns, returns an array of paths to search. - * Duplicates and paths under other included paths are filtered out. + * toPosixPath converts the given path to the posix form. On Windows, \\ will be + * replaced with /. + * + * @param pth. Path to transform. + * @return string Posix path. */ -function getSearchPaths(patterns) { - // Ignore negate patterns - patterns = patterns.filter(x => !x.negate); - // Create a map of all search paths - const searchPathMap = {}; - for (const pattern of patterns) { - const key = IS_WINDOWS - ? pattern.searchPath.toUpperCase() - : pattern.searchPath; - searchPathMap[key] = 'candidate'; - } - const result = []; - for (const pattern of patterns) { - // Check if already included - const key = IS_WINDOWS - ? pattern.searchPath.toUpperCase() - : pattern.searchPath; - if (searchPathMap[key] === 'included') { - continue; - } - // Check for an ancestor search path - let foundAncestor = false; - let tempKey = key; - let parent = pathHelper.dirname(tempKey); - while (parent !== tempKey) { - if (searchPathMap[parent]) { - foundAncestor = true; - break; - } - tempKey = parent; - parent = pathHelper.dirname(tempKey); - } - // Include the search pattern in the result - if (!foundAncestor) { - result.push(pattern.searchPath); - searchPathMap[key] = 'included'; - } - } - return result; +function toPosixPath(pth) { + return pth.replace(/[\\]/g, '/'); } -exports.getSearchPaths = getSearchPaths; +exports.toPosixPath = toPosixPath; /** - * Matches the patterns against the path + * toWin32Path converts the given path to the win32 form. On Linux, / will be + * replaced with \\. + * + * @param pth. Path to transform. + * @return string Win32 path. */ -function match(patterns, itemPath) { - let result = internal_match_kind_1.MatchKind.None; - for (const pattern of patterns) { - if (pattern.negate) { - result &= ~pattern.match(itemPath); - } - else { - result |= pattern.match(itemPath); - } - } - return result; +function toWin32Path(pth) { + return pth.replace(/[/]/g, '\\'); } -exports.match = match; +exports.toWin32Path = toWin32Path; /** - * Checks whether to descend further into the directory + * toPlatformPath converts the given path to a platform-specific path. It does + * this by replacing instances of / and \ with the platform-specific path + * separator. + * + * @param pth The path to platformize. + * @return string The platform-specific path. */ -function partialMatch(patterns, itemPath) { - return patterns.some(x => !x.negate && x.partialMatch(itemPath)); +function toPlatformPath(pth) { + return pth.replace(/[/\\]/g, path.sep); } -exports.partialMatch = partialMatch; -//# sourceMappingURL=internal-pattern-helper.js.map +exports.toPlatformPath = toPlatformPath; +//# sourceMappingURL=path-utils.js.map /***/ }), -/***/ 35343: +/***/ 25957: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; +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.Pattern = void 0; -const os = __importStar(__nccwpck_require__(22037)); -const path = __importStar(__nccwpck_require__(71017)); -const pathHelper = __importStar(__nccwpck_require__(20022)); -const assert_1 = __importDefault(__nccwpck_require__(39491)); -const minimatch_1 = __nccwpck_require__(83973); -const internal_match_kind_1 = __nccwpck_require__(80836); -const internal_path_1 = __nccwpck_require__(19413); -const IS_WINDOWS = process.platform === 'win32'; -class Pattern { - constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) { - /** - * Indicates whether matches should be excluded from the result set - */ - this.negate = false; - // Pattern overload - let pattern; - if (typeof patternOrNegate === 'string') { - pattern = patternOrNegate.trim(); - } - // Segments overload - else { - // Convert to pattern - segments = segments || []; - assert_1.default(segments.length, `Parameter 'segments' must not empty`); - const root = Pattern.getLiteral(segments[0]); - assert_1.default(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); - pattern = new internal_path_1.Path(segments).toString().trim(); - if (patternOrNegate) { - pattern = `!${pattern}`; - } - } - // Negate - while (pattern.startsWith('!')) { - this.negate = !this.negate; - pattern = pattern.substr(1).trim(); - } - // Normalize slashes and ensures absolute root - pattern = Pattern.fixupPattern(pattern, homedir); - // Segments - this.segments = new internal_path_1.Path(pattern).segments; - // Trailing slash indicates the pattern should only match directories, not regular files - this.trailingSeparator = pathHelper - .normalizeSeparators(pattern) - .endsWith(path.sep); - pattern = pathHelper.safeTrimTrailingSeparator(pattern); - // Search path (literal path prior to the first glob segment) - let foundGlob = false; - const searchSegments = this.segments - .map(x => Pattern.getLiteral(x)) - .filter(x => !foundGlob && !(foundGlob = x === '')); - this.searchPath = new internal_path_1.Path(searchSegments).toString(); - // Root RegExp (required when determining partial match) - this.rootRegExp = new RegExp(Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? 'i' : ''); - this.isImplicitPattern = isImplicitPattern; - // Create minimatch - const minimatchOptions = { - dot: true, - nobrace: true, - nocase: IS_WINDOWS, - nocomment: true, - noext: true, - nonegate: true - }; - pattern = IS_WINDOWS ? pattern.replace(/\\/g, '/') : pattern; - this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions); +exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; +const os_1 = __nccwpck_require__(22037); +const fs_1 = __nccwpck_require__(57147); +const { access, appendFile, writeFile } = fs_1.promises; +exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; +exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; +class Summary { + constructor() { + this._buffer = ''; } /** - * Matches the pattern against the specified path + * Finds the summary file path from the environment, rejects if env var is not found or file does not exist + * Also checks r/w permissions. + * + * @returns step summary file path */ - match(itemPath) { - // Last segment is globstar? - if (this.segments[this.segments.length - 1] === '**') { - // Normalize slashes - itemPath = pathHelper.normalizeSeparators(itemPath); - // Append a trailing slash. Otherwise Minimatch will not match the directory immediately - // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns - // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk. - if (!itemPath.endsWith(path.sep) && this.isImplicitPattern === false) { - // Note, this is safe because the constructor ensures the pattern has an absolute root. - // For example, formats like C: and C:foo on Windows are resolved to an absolute root. - itemPath = `${itemPath}${path.sep}`; + filePath() { + return __awaiter(this, void 0, void 0, function* () { + if (this._filePath) { + return this._filePath; } - } - else { - // Normalize slashes and trim unnecessary trailing slash - itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); - } - // Match - if (this.minimatch.match(itemPath)) { - return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All; - } - return internal_match_kind_1.MatchKind.None; + const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; + if (!pathFromEnv) { + throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); + } + try { + yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); + } + catch (_a) { + throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + } + this._filePath = pathFromEnv; + return this._filePath; + }); } /** - * Indicates whether the pattern may match descendants of the specified path + * Wraps content in an HTML tag, adding any HTML attributes + * + * @param {string} tag HTML tag to wrap + * @param {string | null} content content within the tag + * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add + * + * @returns {string} content wrapped in HTML element */ - partialMatch(itemPath) { - // Normalize slashes and trim unnecessary trailing slash - itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); - // matchOne does not handle root path correctly - if (pathHelper.dirname(itemPath) === itemPath) { - return this.rootRegExp.test(itemPath); + wrap(tag, content, attrs = {}) { + const htmlAttrs = Object.entries(attrs) + .map(([key, value]) => ` ${key}="${value}"`) + .join(''); + if (!content) { + return `<${tag}${htmlAttrs}>`; } - return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true); + return `<${tag}${htmlAttrs}>${content}`; } /** - * Escapes glob patterns within a path + * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. + * + * @param {SummaryWriteOptions} [options] (optional) options for write operation + * + * @returns {Promise} summary instance */ - static globEscape(s) { - return (IS_WINDOWS ? s : s.replace(/\\/g, '\\\\')) // escape '\' on Linux/macOS - .replace(/(\[)(?=[^/]+\])/g, '[[]') // escape '[' when ']' follows within the path segment - .replace(/\?/g, '[?]') // escape '?' - .replace(/\*/g, '[*]'); // escape '*' + write(options) { + return __awaiter(this, void 0, void 0, function* () { + const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); + const filePath = yield this.filePath(); + const writeFunc = overwrite ? writeFile : appendFile; + yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); + return this.emptyBuffer(); + }); } /** - * Normalizes slashes and ensures absolute root + * Clears the summary buffer and wipes the summary file + * + * @returns {Summary} summary instance */ - static fixupPattern(pattern, homedir) { - // Empty - assert_1.default(pattern, 'pattern cannot be empty'); - // Must not contain `.` segment, unless first segment - // Must not contain `..` segment - const literalSegments = new internal_path_1.Path(pattern).segments.map(x => Pattern.getLiteral(x)); - assert_1.default(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); - // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r - assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); - // Normalize slashes - pattern = pathHelper.normalizeSeparators(pattern); - // Replace leading `.` segment - if (pattern === '.' || pattern.startsWith(`.${path.sep}`)) { - pattern = Pattern.globEscape(process.cwd()) + pattern.substr(1); - } - // Replace leading `~` segment - else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) { - homedir = homedir || os.homedir(); - assert_1.default(homedir, 'Unable to determine HOME directory'); - assert_1.default(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); - pattern = Pattern.globEscape(homedir) + pattern.substr(1); - } - // Replace relative drive root, e.g. pattern is C: or C:foo - else if (IS_WINDOWS && - (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) { - let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', pattern.substr(0, 2)); - if (pattern.length > 2 && !root.endsWith('\\')) { - root += '\\'; - } - pattern = Pattern.globEscape(root) + pattern.substr(2); - } - // Replace relative root, e.g. pattern is \ or \foo - else if (IS_WINDOWS && (pattern === '\\' || pattern.match(/^\\[^\\]/))) { - let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', '\\'); - if (!root.endsWith('\\')) { - root += '\\'; - } - pattern = Pattern.globEscape(root) + pattern.substr(1); - } - // Otherwise ensure absolute root - else { - pattern = pathHelper.ensureAbsoluteRoot(Pattern.globEscape(process.cwd()), pattern); - } - return pathHelper.normalizeSeparators(pattern); + clear() { + return __awaiter(this, void 0, void 0, function* () { + return this.emptyBuffer().write({ overwrite: true }); + }); } /** - * Attempts to unescape a pattern segment to create a literal path segment. - * Otherwise returns empty string. + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer */ - static getLiteral(segment) { - let literal = ''; - for (let i = 0; i < segment.length; i++) { - const c = segment[i]; - // Escape - if (c === '\\' && !IS_WINDOWS && i + 1 < segment.length) { - literal += segment[++i]; - continue; - } - // Wildcard - else if (c === '*' || c === '?') { - return ''; - } - // Character set - else if (c === '[' && i + 1 < segment.length) { - let set = ''; - let closed = -1; - for (let i2 = i + 1; i2 < segment.length; i2++) { - const c2 = segment[i2]; - // Escape - if (c2 === '\\' && !IS_WINDOWS && i2 + 1 < segment.length) { - set += segment[++i2]; - continue; - } - // Closed - else if (c2 === ']') { - closed = i2; - break; - } - // Otherwise - else { - set += c2; - } - } - // Closed? - if (closed >= 0) { - // Cannot convert - if (set.length > 1) { - return ''; - } - // Convert to literal - if (set) { - literal += set; - i = closed; - continue; - } + stringify() { + return this._buffer; + } + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer() { + return this._buffer.length === 0; + } + /** + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance + */ + emptyBuffer() { + this._buffer = ''; + return this; + } + /** + * Adds raw text to the summary buffer + * + * @param {string} text content to add + * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) + * + * @returns {Summary} summary instance + */ + addRaw(text, addEOL = false) { + this._buffer += text; + return addEOL ? this.addEOL() : this; + } + /** + * Adds the operating system-specific end-of-line marker to the buffer + * + * @returns {Summary} summary instance + */ + addEOL() { + return this.addRaw(os_1.EOL); + } + /** + * Adds an HTML codeblock to the summary buffer + * + * @param {string} code content to render within fenced code block + * @param {string} lang (optional) language to syntax highlight code + * + * @returns {Summary} summary instance + */ + addCodeBlock(code, lang) { + const attrs = Object.assign({}, (lang && { lang })); + const element = this.wrap('pre', this.wrap('code', code), attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML list to the summary buffer + * + * @param {string[]} items list of items to render + * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) + * + * @returns {Summary} summary instance + */ + addList(items, ordered = false) { + const tag = ordered ? 'ol' : 'ul'; + const listItems = items.map(item => this.wrap('li', item)).join(''); + const element = this.wrap(tag, listItems); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML table to the summary buffer + * + * @param {SummaryTableCell[]} rows table rows + * + * @returns {Summary} summary instance + */ + addTable(rows) { + const tableBody = rows + .map(row => { + const cells = row + .map(cell => { + if (typeof cell === 'string') { + return this.wrap('td', cell); } - // Otherwise fall thru - } - // Append - literal += c; - } - return literal; + const { header, data, colspan, rowspan } = cell; + const tag = header ? 'th' : 'td'; + const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); + return this.wrap(tag, data, attrs); + }) + .join(''); + return this.wrap('tr', cells); + }) + .join(''); + const element = this.wrap('table', tableBody); + return this.addRaw(element).addEOL(); } /** - * Escapes regexp special characters - * https://javascript.info/regexp-escaping + * Adds a collapsable HTML details element to the summary buffer + * + * @param {string} label text for the closed state + * @param {string} content collapsable content + * + * @returns {Summary} summary instance */ - static regExpEscape(s) { - return s.replace(/[[\\^$.|?*+()]/g, '\\$&'); + addDetails(label, content) { + const element = this.wrap('details', this.wrap('summary', label) + content); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML image tag to the summary buffer + * + * @param {string} src path to the image you to embed + * @param {string} alt text description of the image + * @param {SummaryImageOptions} options (optional) addition image attributes + * + * @returns {Summary} summary instance + */ + addImage(src, alt, options) { + const { width, height } = options || {}; + const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); + const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML section heading element + * + * @param {string} text heading text + * @param {number | string} [level=1] (optional) the heading level, default: 1 + * + * @returns {Summary} summary instance + */ + addHeading(text, level) { + const tag = `h${level}`; + const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) + ? tag + : 'h1'; + const element = this.wrap(allowedTag, text); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML thematic break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addSeparator() { + const element = this.wrap('hr', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML line break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addBreak() { + const element = this.wrap('br', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML blockquote to the summary buffer + * + * @param {string} text quote text + * @param {string} cite (optional) citation url + * + * @returns {Summary} summary instance + */ + addQuote(text, cite) { + const attrs = Object.assign({}, (cite && { cite })); + const element = this.wrap('blockquote', text, attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML anchor tag to the summary buffer + * + * @param {string} text link text/content + * @param {string} href hyperlink + * + * @returns {Summary} summary instance + */ + addLink(text, href) { + const element = this.wrap('a', text, { href }); + return this.addRaw(element).addEOL(); } } -exports.Pattern = Pattern; -//# sourceMappingURL=internal-pattern.js.map +const _summary = new Summary(); +/** + * @deprecated use `core.summary` + */ +exports.markdownSummary = _summary; +exports.summary = _summary; +//# sourceMappingURL=summary.js.map /***/ }), -/***/ 28530: +/***/ 79754: /***/ ((__unused_webpack_module, exports) => { "use strict"; +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SearchState = void 0; -class SearchState { - constructor(path, level) { - this.path = path; - this.level = level; +exports.toCommandProperties = exports.toCommandValue = void 0; +/** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; } + else if (typeof input === 'string' || input instanceof String) { + return input; + } + return JSON.stringify(input); } -exports.SearchState = SearchState; -//# sourceMappingURL=internal-search-state.js.map - -/***/ }), - -/***/ 3771: -/***/ ((module, exports) => { - -exports = module.exports = SemVer - -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 () {} -} - -// 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 MAX_LENGTH = 256 -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 - -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16 - -// The actual regexps go on exports.re -var re = exports.re = [] -var src = exports.src = [] -var t = exports.tokens = {} -var R = 0 - -function tok (n) { - t[n] = R++ +exports.toCommandValue = toCommandValue; +/** + * + * @param annotationProperties + * @returns The command properties to send with the actual annotation command + * See IssueCommandProperties: /~https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 + */ +function toCommandProperties(annotationProperties) { + if (!Object.keys(annotationProperties).length) { + return {}; + } + return { + title: annotationProperties.title, + file: annotationProperties.file, + line: annotationProperties.startLine, + endLine: annotationProperties.endLine, + col: annotationProperties.startColumn, + endColumn: annotationProperties.endColumn + }; } +exports.toCommandProperties = toCommandProperties; +//# sourceMappingURL=utils.js.map -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. - -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. - -tok('NUMERICIDENTIFIER') -src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*' -tok('NUMERICIDENTIFIERLOOSE') -src[t.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. - -tok('NONNUMERICIDENTIFIER') -src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' - -// ## Main Version -// Three dot-separated numeric identifiers. - -tok('MAINVERSION') -src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + - '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + - '(' + src[t.NUMERICIDENTIFIER] + ')' - -tok('MAINVERSIONLOOSE') -src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')' - -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. - -tok('PRERELEASEIDENTIFIER') -src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + - '|' + src[t.NONNUMERICIDENTIFIER] + ')' - -tok('PRERELEASEIDENTIFIERLOOSE') -src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + - '|' + src[t.NONNUMERICIDENTIFIER] + ')' - -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. - -tok('PRERELEASE') -src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + - '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))' - -tok('PRERELEASELOOSE') -src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))' - -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. - -tok('BUILDIDENTIFIER') -src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+' - -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. - -tok('BUILD') -src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + - '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))' - -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. - -// 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. - -tok('FULL') -tok('FULLPLAIN') -src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + - src[t.PRERELEASE] + '?' + - src[t.BUILD] + '?' - -src[t.FULL] = '^' + src[t.FULLPLAIN] + '$' - -// 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. -tok('LOOSEPLAIN') -src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + - src[t.PRERELEASELOOSE] + '?' + - src[t.BUILD] + '?' - -tok('LOOSE') -src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$' - -tok('GTLT') -src[t.GTLT] = '((?:<|>)?=?)' - -// 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. -tok('XRANGEIDENTIFIERLOOSE') -src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' -tok('XRANGEIDENTIFIER') -src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*' - -tok('XRANGEPLAIN') -src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + - '(?:' + src[t.PRERELEASE] + ')?' + - src[t.BUILD] + '?' + - ')?)?' - -tok('XRANGEPLAINLOOSE') -src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[t.PRERELEASELOOSE] + ')?' + - src[t.BUILD] + '?' + - ')?)?' - -tok('XRANGE') -src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$' -tok('XRANGELOOSE') -src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$' - -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -tok('COERCE') -src[t.COERCE] = '(^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])' -tok('COERCERTL') -re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g') - -// Tilde ranges. -// Meaning is "reasonably at or greater than" -tok('LONETILDE') -src[t.LONETILDE] = '(?:~>?)' - -tok('TILDETRIM') -src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+' -re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g') -var tildeTrimReplace = '$1~' - -tok('TILDE') -src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$' -tok('TILDELOOSE') -src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$' - -// Caret ranges. -// Meaning is "at least and backwards compatible with" -tok('LONECARET') -src[t.LONECARET] = '(?:\\^)' - -tok('CARETTRIM') -src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+' -re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g') -var caretTrimReplace = '$1^' - -tok('CARET') -src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$' -tok('CARETLOOSE') -src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$' - -// A simple gt/lt/eq thing, or just "" to indicate "any version" -tok('COMPARATORLOOSE') -src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$' -tok('COMPARATOR') -src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$' - -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -tok('COMPARATORTRIM') -src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + - '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')' - -// this one has to use the /g flag -re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g') -var comparatorTrimReplace = '$1$2$3' - -// 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. -tok('HYPHENRANGE') -src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[t.XRANGEPLAIN] + ')' + - '\\s*$' +/***/ }), -tok('HYPHENRANGELOOSE') -src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[t.XRANGEPLAINLOOSE] + ')' + - '\\s*$' +/***/ 15082: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -// Star ranges basically just allow anything at all. -tok('STAR') -src[t.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]) - } +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.getExecOutput = exports.exec = void 0; +const string_decoder_1 = __nccwpck_require__(71576); +const tr = __importStar(__nccwpck_require__(61668)); +/** + * Exec a command. + * Output will be streamed to the live console. + * Returns promise with return code + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code + */ +function exec(commandLine, args, options) { + return __awaiter(this, void 0, void 0, function* () { + const commandArgs = tr.argStringToArray(commandLine); + if (commandArgs.length === 0) { + throw new Error(`Parameter 'commandLine' cannot be null or empty.`); + } + // Path to tool to execute should be first arg + const toolPath = commandArgs[0]; + args = commandArgs.slice(1).concat(args || []); + const runner = new tr.ToolRunner(toolPath, args, options); + return runner.exec(); + }); } - -exports.parse = parse -function parse (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (version instanceof SemVer) { - return version - } - - if (typeof version !== 'string') { - return null - } - - if (version.length > MAX_LENGTH) { - return null - } - - var r = options.loose ? re[t.LOOSE] : re[t.FULL] - if (!r.test(version)) { - return null - } - - try { - return new SemVer(version, options) - } catch (er) { - return null - } +exports.exec = exec; +/** + * Exec a command and get the output. + * Output will be streamed to the live console. + * Returns promise with the exit code and collected stdout and stderr + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code, stdout, and stderr + */ +function getExecOutput(commandLine, args, options) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + let stdout = ''; + let stderr = ''; + //Using string decoder covers the case where a mult-byte character is split + const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); + const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); + const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; + const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; + const stdErrListener = (data) => { + stderr += stderrDecoder.write(data); + if (originalStdErrListener) { + originalStdErrListener(data); + } + }; + const stdOutListener = (data) => { + stdout += stdoutDecoder.write(data); + if (originalStdoutListener) { + originalStdoutListener(data); + } + }; + const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); + const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); + //flush any remaining characters + stdout += stdoutDecoder.end(); + stderr += stderrDecoder.end(); + return { + exitCode, + stdout, + stderr + }; + }); } +exports.getExecOutput = getExecOutput; +//# sourceMappingURL=exec.js.map -exports.valid = valid -function valid (version, options) { - var v = parse(version, options) - return v ? v.version : null -} +/***/ }), -exports.clean = clean -function clean (version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} +/***/ 61668: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -exports.SemVer = SemVer +"use strict"; -function SemVer (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false +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.argStringToArray = exports.ToolRunner = void 0; +const os = __importStar(__nccwpck_require__(22037)); +const events = __importStar(__nccwpck_require__(82361)); +const child = __importStar(__nccwpck_require__(32081)); +const path = __importStar(__nccwpck_require__(71017)); +const io = __importStar(__nccwpck_require__(50157)); +const ioUtil = __importStar(__nccwpck_require__(74498)); +const timers_1 = __nccwpck_require__(39512); +/* eslint-disable @typescript-eslint/unbound-method */ +const IS_WINDOWS = process.platform === 'win32'; +/* + * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. + */ +class ToolRunner extends events.EventEmitter { + constructor(toolPath, args, options) { + super(); + if (!toolPath) { + throw new Error("Parameter 'toolPath' cannot be null or empty."); + } + this.toolPath = toolPath; + this.args = args || []; + this.options = options || {}; } - } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version - } else { - version = version.version + _debug(message) { + if (this.options.listeners && this.options.listeners.debug) { + this.options.listeners.debug(message); + } } - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version) - } - - if (version.length > MAX_LENGTH) { - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') - } - - if (!(this instanceof SemVer)) { - return new SemVer(version, options) - } - - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose - - var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) - - if (!m) { - throw new TypeError('Invalid Version: ' + version) - } - - this.raw = version - - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // 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 + _getCommandString(options, noPrefix) { + const toolPath = this._getSpawnFileName(); + const args = this._getSpawnArgs(options); + let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool + if (IS_WINDOWS) { + // Windows + cmd file + if (this._isCmdFile()) { + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; + } + } + // Windows + verbatim + else if (options.windowsVerbatimArguments) { + cmd += `"${toolPath}"`; + for (const a of args) { + cmd += ` ${a}`; + } + } + // Windows (regular) + else { + cmd += this._windowsQuoteCmdArg(toolPath); + for (const a of args) { + cmd += ` ${this._windowsQuoteCmdArg(a)}`; + } + } } - } - return id - }) - } - - this.build = m[5] ? m[5].split('.') : [] - this.format() -} - -SemVer.prototype.format = function () { - this.version = this.major + '.' + this.minor + '.' + this.patch - if (this.prerelease.length) { - this.version += '-' + this.prerelease.join('.') - } - return this.version -} - -SemVer.prototype.toString = function () { - return this.version -} - -SemVer.prototype.compare = function (other) { - 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) - } - - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) -} - -SemVer.prototype.comparePre = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - // 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) -} - -SemVer.prototype.compareBuild = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - var i = 0 - do { - var a = this.build[i] - var b = other.build[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) + else { + // OSX/Linux - this can likely be improved with some form of quoting. + // creating processes on Unix is fundamentally different than Windows. + // on Unix, execvp() takes an arg array. + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; + } + } + return cmd; } - } 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 - - 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 - } + _processLineBuffer(data, strBuffer, onLine) { + try { + let s = strBuffer + data.toString(); + let n = s.indexOf(os.EOL); + while (n > -1) { + const line = s.substring(0, n); + onLine(line); + // the rest of the string ... + s = s.substring(n + os.EOL.length); + n = s.indexOf(os.EOL); + } + return s; } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0) + catch (err) { + // streaming lines to console is best effort. Don't fail a build. + this._debug(`error processing line. Failed with error ${err}`); + return ''; } - } - 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] + } + _getSpawnFileName() { + if (IS_WINDOWS) { + if (this._isCmdFile()) { + return process.env['COMSPEC'] || 'cmd.exe'; + } } - } - break - - default: - throw new Error('invalid increment argument: ' + release) - } - this.format() - this.raw = this.version - return this -} - -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.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' + return this.toolPath; } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key + _getSpawnArgs(options) { + if (IS_WINDOWS) { + if (this._isCmdFile()) { + let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; + for (const a of this.args) { + argline += ' '; + argline += options.windowsVerbatimArguments + ? a + : this._windowsQuoteCmdArg(a); + } + argline += '"'; + return [argline]; + } } - } + return this.args; } - return defaultResult // may be undefined - } -} - -exports.compareIdentifiers = compareIdentifiers - -var numeric = /^[0-9]+$/ -function compareIdentifiers (a, b) { - var anum = numeric.test(a) - var bnum = numeric.test(b) - - if (anum && bnum) { - a = +a - b = +b - } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} - -exports.rcompareIdentifiers = rcompareIdentifiers -function rcompareIdentifiers (a, b) { - return compareIdentifiers(b, a) -} - -exports.major = major -function major (a, loose) { - return new SemVer(a, loose).major -} - -exports.minor = minor -function minor (a, loose) { - return new SemVer(a, loose).minor -} - -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)) -} - -exports.compareLoose = compareLoose -function compareLoose (a, b) { - return compare(a, b, true) -} - -exports.compareBuild = compareBuild -function compareBuild (a, b, loose) { - var versionA = new SemVer(a, loose) - var versionB = new SemVer(b, loose) - return versionA.compare(versionB) || versionA.compareBuild(versionB) -} - -exports.rcompare = rcompare -function rcompare (a, b, loose) { - return compare(b, a, loose) -} - -exports.sort = sort -function sort (list, loose) { - return list.sort(function (a, b) { - return exports.compareBuild(a, b, loose) - }) -} - -exports.rsort = rsort -function rsort (list, loose) { - return list.sort(function (a, b) { - return exports.compareBuild(b, a, loose) - }) -} - -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 -} - -exports.eq = eq -function eq (a, b, loose) { - return compare(a, b, loose) === 0 -} - -exports.neq = neq -function neq (a, b, loose) { - return compare(a, b, loose) !== 0 -} - -exports.gte = gte -function gte (a, b, loose) { - return compare(a, b, loose) >= 0 -} - -exports.lte = lte -function lte (a, b, loose) { - return compare(a, b, loose) <= 0 -} - -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 - - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt(a, b, loose) - - case '>=': - return gte(a, b, loose) - - case '<': - return lt(a, b, loose) - - case '<=': - return lte(a, b, loose) - - default: - throw new TypeError('Invalid operator: ' + op) - } -} - -exports.Comparator = Comparator -function Comparator (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false + _endsWith(str, end) { + return str.endsWith(end); } - } - - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value + _isCmdFile() { + const upperToolPath = this.toolPath.toUpperCase(); + return (this._endsWith(upperToolPath, '.CMD') || + this._endsWith(upperToolPath, '.BAT')); } - } - - 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[t.COMPARATORLOOSE] : re[t.COMPARATOR] - var m = comp.match(r) - - if (!m) { - throw new TypeError('Invalid comparator: ' + comp) - } - - this.operator = m[1] !== undefined ? m[1] : '' - if (this.operator === '=') { - this.operator = '' - } - - // 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) - } -} - -Comparator.prototype.toString = function () { - return this.value -} - -Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.options.loose) - - if (this.semver === ANY || version === ANY) { - return true - } - - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } - - return cmp(version, this.operator, this.semver, this.options) -} - -Comparator.prototype.intersects = function (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - var rangeTmp - - if (this.operator === '') { - if (this.value === '') { - return true - } - rangeTmp = new Range(comp.value, options) - return satisfies(this.value, rangeTmp, options) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - rangeTmp = new Range(this.value, options) - return satisfies(comp.semver, rangeTmp, options) - } - - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>') - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<') - var sameSemVer = this.semver.version === comp.semver.version - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<=') - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')) - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')) - - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan -} - -exports.Range = Range -function Range (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range - } else { - return new Range(range.raw, options) - } - } - - if (range instanceof Comparator) { - return new Range(range.value, options) - } - - if (!(this instanceof Range)) { - return new Range(range, options) - } - - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease - - // 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 - }) - - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range) - } - - this.format() -} - -Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim() - }).join('||').trim() - return this.range -} - -Range.prototype.toString = function () { - return this.range -} - -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[t.HYPHENRANGELOOSE] : re[t.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[t.COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[t.COMPARATORTRIM]) - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[t.TILDETRIM], tildeTrimReplace) - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[t.CARETTRIM], caretTrimReplace) - - // normalize spaces - range = range.split(/\s+/).join(' ') - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.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) - - 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 ( - isSatisfiable(thisComparators, options) && - range.set.some(function (rangeComparators) { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every(function (thisComparator) { - return rangeComparators.every(function (rangeComparator) { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) -} - -// take a set of comparators and determine whether there -// exists a version which can satisfy it -function isSatisfiable (comparators, options) { - var result = true - var remainingComparators = comparators.slice() - var testComparator = remainingComparators.pop() - - while (result && remainingComparators.length) { - result = remainingComparators.every(function (otherComparator) { - return testComparator.intersects(otherComparator, options) - }) - - testComparator = remainingComparators.pop() - } - - return result -} - -// 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 -} - -function isX (id) { - return !id || id.toLowerCase() === 'x' || id === '*' -} - -// ~, ~> --> * (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(' ') -} - -function replaceTilde (comp, options) { - var r = options.loose ? re[t.TILDELOOSE] : re[t.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' - } - - debug('tilde return', ret) - return ret - }) -} - -// ^ --> * (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 replaceCaret (comp, options) { - debug('caret', comp, options) - var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] - return comp.replace(r, function (_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr) - var ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - if (M === '0') { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else { - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' - } - } 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' - } - } - - debug('caret return', ret) - return ret - }) -} - -function replaceXRanges (comp, options) { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map(function (comp) { - return replaceXRange(comp, options) - }).join(' ') -} - -function replaceXRange (comp, options) { - comp = comp.trim() - var r = options.loose ? re[t.XRANGELOOSE] : re[t.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 = '' - } - - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : '' - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.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 - - 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 + pr - } else if (xm) { - ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr - } else if (xp) { - ret = '>=' + M + '.' + m + '.0' + pr + - ' <' + M + '.' + (+m + 1) + '.0' + pr - } - - debug('xRange return', ret) - - return ret - }) -} - -// 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[t.STAR], '') -} - -// This function is passed to string.replace(re[t.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 (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = '<' + (+tM + 1) + '.0.0' - } else if (isX(tp)) { - to = '<' + tM + '.' + (+tm + 1) + '.0' - } else if (tpr) { - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr - } else { - to = '<=' + to - } - - return (from + ' ' + to).trim() -} - -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function (version) { - if (!version) { - return false - } - - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } - - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false -} - -function testSet (set, version, options) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } - - 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 - } - } - } - - // 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 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) - } - } - }) - 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) - - var minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } - - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } - - minver = null - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] - - 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) - } - }) - } - - if (minver && range.test(minver)) { - return minver - } - - return null -} - -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) -} - -exports.outside = outside -function outside (version, range, hilo, options) { - version = new SemVer(version, options) - range = new Range(range, options) - - 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 ">"') - } - - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] - - var high = null - var low = null - - comparators.forEach(function (comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - - // 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 -} - -exports.prerelease = prerelease -function prerelease (version, options) { - var parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} - -exports.intersects = intersects -function intersects (r1, r2, options) { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) -} - -exports.coerce = coerce -function coerce (version, options) { - if (version instanceof SemVer) { - return version - } - - if (typeof version === 'number') { - version = String(version) - } - - if (typeof version !== 'string') { - return null - } - - options = options || {} - - var match = null - if (!options.rtl) { - match = version.match(re[t.COERCE]) - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - var next - while ((next = re[t.COERCERTL].exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next - } - re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length - } - // leave it in a clean state - re[t.COERCERTL].lastIndex = -1 - } - - if (match === null) { - return null - } - - return parse(match[2] + - '.' + (match[3] || '0') + - '.' + (match[4] || '0'), options) -} - - -/***/ }), - -/***/ 94138: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var v1 = __nccwpck_require__(61610); -var v4 = __nccwpck_require__(8373); - -var uuid = v4; -uuid.v1 = v1; -uuid.v4 = v4; - -module.exports = uuid; - - -/***/ }), - -/***/ 65694: -/***/ ((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; - - -/***/ }), - -/***/ 34069: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// Unique ID creation requires a high quality random # generator. In node.js -// this is pretty straight-forward - we use the crypto API. - -var crypto = __nccwpck_require__(6113); - -module.exports = function nodeRNG() { - return crypto.randomBytes(16); -}; - - -/***/ }), - -/***/ 61610: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var rng = __nccwpck_require__(34069); -var bytesToUuid = __nccwpck_require__(65694); - -// **`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; - - -/***/ }), - -/***/ 8373: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var rng = __nccwpck_require__(34069); -var bytesToUuid = __nccwpck_require__(65694); - -function v4(options, buf, offset) { - var i = buf && offset || 0; - - if (typeof(options) == 'string') { - buf = options === 'binary' ? new Array(16) : null; - options = null; - } - options = options || {}; - - var rnds = options.random || (options.rng || rng)(); - - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = (rnds[6] & 0x0f) | 0x40; - rnds[8] = (rnds[8] & 0x3f) | 0x80; - - // Copy bytes to buffer, if provided - if (buf) { - for (var ii = 0; ii < 16; ++ii) { - buf[i + ii] = rnds[ii]; - } - } - - return buf || bytesToUuid(rnds); -} - -module.exports = v4; - - -/***/ }), - -/***/ 87351: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issue = exports.issueCommand = void 0; -const os = __importStar(__nccwpck_require__(22037)); -const utils_1 = __nccwpck_require__(5278); -/** - * 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 - -/***/ }), - -/***/ 42186: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; -const command_1 = __nccwpck_require__(87351); -const file_command_1 = __nccwpck_require__(717); -const utils_1 = __nccwpck_require__(5278); -const os = __importStar(__nccwpck_require__(22037)); -const path = __importStar(__nccwpck_require__(71017)); -const uuid_1 = __nccwpck_require__(75840); -const oidc_utils_1 = __nccwpck_require__(98041); -/** - * The code to exit an action - */ -var ExitCode; -(function (ExitCode) { - /** - * A code indicating that the action was successful - */ - ExitCode[ExitCode["Success"] = 0] = "Success"; - /** - * A code indicating that the action was a failure - */ - ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); -//----------------------------------------------------------------------- -// Variables -//----------------------------------------------------------------------- -/** - * Sets env variable for this action and future actions in the job - * @param name the name of the variable to set - * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function exportVariable(name, val) { - const convertedVal = utils_1.toCommandValue(val); - process.env[name] = convertedVal; - const filePath = process.env['GITHUB_ENV'] || ''; - if (filePath) { - const delimiter = `ghadelimiter_${uuid_1.v4()}`; - // These should realistically never happen, but just in case someone finds a way to exploit uuid generation let's not allow keys or values that contain the delimiter. - if (name.includes(delimiter)) { - throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); - } - if (convertedVal.includes(delimiter)) { - throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); - } - const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; - file_command_1.issueCommand('ENV', commandValue); - } - else { - command_1.issueCommand('set-env', { name }, convertedVal); - } -} -exports.exportVariable = exportVariable; -/** - * Registers a secret which will get masked from logs - * @param secret value of the secret - */ -function setSecret(secret) { - command_1.issueCommand('add-mask', {}, secret); -} -exports.setSecret = setSecret; -/** - * Prepends inputPath to the PATH (for this action and future actions) - * @param inputPath - */ -function addPath(inputPath) { - const filePath = process.env['GITHUB_PATH'] || ''; - if (filePath) { - file_command_1.issueCommand('PATH', inputPath); - } - else { - command_1.issueCommand('add-path', {}, inputPath); - } - process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; -} -exports.addPath = addPath; -/** - * Gets the value of an input. - * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. - * Returns an empty string if the value is not defined. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string - */ -function getInput(name, options) { - const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; - if (options && options.required && !val) { - throw new Error(`Input required and not supplied: ${name}`); - } - if (options && options.trimWhitespace === false) { - return val; - } - return val.trim(); -} -exports.getInput = getInput; -/** - * Gets the values of an multiline input. Each value is also trimmed. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string[] - * - */ -function getMultilineInput(name, options) { - const inputs = getInput(name, options) - .split('\n') - .filter(x => x !== ''); - return inputs; -} -exports.getMultilineInput = getMultilineInput; -/** - * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. - * Support boolean input list: `true | True | TRUE | false | False | FALSE` . - * The return value is also in boolean type. - * ref: https://yaml.org/spec/1.2/spec.html#id2804923 - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns boolean - */ -function getBooleanInput(name, options) { - const trueValue = ['true', 'True', 'TRUE']; - const falseValue = ['false', 'False', 'FALSE']; - const val = getInput(name, options); - if (trueValue.includes(val)) - return true; - if (falseValue.includes(val)) - return false; - throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + - `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); -} -exports.getBooleanInput = getBooleanInput; -/** - * Sets the value of an output. - * - * @param name name of the output to set - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setOutput(name, value) { - process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, value); -} -exports.setOutput = setOutput; -/** - * Enables or disables the echoing of commands into stdout for the rest of the step. - * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. - * - */ -function setCommandEcho(enabled) { - command_1.issue('echo', enabled ? 'on' : 'off'); -} -exports.setCommandEcho = setCommandEcho; -//----------------------------------------------------------------------- -// Results -//----------------------------------------------------------------------- -/** - * Sets the action status to failed. - * When the action exits it will be with an exit code of 1 - * @param message add error issue message - */ -function setFailed(message) { - process.exitCode = ExitCode.Failure; - error(message); -} -exports.setFailed = setFailed; -//----------------------------------------------------------------------- -// Logging Commands -//----------------------------------------------------------------------- -/** - * Gets whether Actions Step Debug is on or not - */ -function isDebug() { - return process.env['RUNNER_DEBUG'] === '1'; -} -exports.isDebug = isDebug; -/** - * Writes debug message to user log - * @param message debug message - */ -function debug(message) { - command_1.issueCommand('debug', {}, message); -} -exports.debug = debug; -/** - * Adds an error issue - * @param message error issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function error(message, properties = {}) { - command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); -} -exports.error = error; -/** - * Adds a warning issue - * @param message warning issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function warning(message, properties = {}) { - command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); -} -exports.warning = warning; -/** - * Adds a notice issue - * @param message notice issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function notice(message, properties = {}) { - command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); -} -exports.notice = notice; -/** - * Writes info to log with console.log. - * @param message info message - */ -function info(message) { - process.stdout.write(message + os.EOL); -} -exports.info = info; -/** - * Begin an output group. - * - * Output until the next `groupEnd` will be foldable in this group - * - * @param name The name of the output group - */ -function startGroup(name) { - command_1.issue('group', name); -} -exports.startGroup = startGroup; -/** - * End an output group. - */ -function endGroup() { - command_1.issue('endgroup'); -} -exports.endGroup = endGroup; -/** - * Wrap an asynchronous function call in a group. - * - * Returns the same type as the function itself. - * - * @param name The name of the group - * @param fn The function to wrap in the group - */ -function group(name, fn) { - return __awaiter(this, void 0, void 0, function* () { - startGroup(name); - let result; - try { - result = yield fn(); - } - finally { - endGroup(); - } - return result; - }); -} -exports.group = group; -//----------------------------------------------------------------------- -// Wrapper action state -//----------------------------------------------------------------------- -/** - * Saves state for current action, the state can only be retrieved by this action's post job execution. - * - * @param name name of the state to store - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function saveState(name, value) { - command_1.issueCommand('save-state', { name }, value); -} -exports.saveState = saveState; -/** - * Gets the value of an state set by this action's main execution. - * - * @param name name of the state to get - * @returns string - */ -function getState(name) { - return process.env[`STATE_${name}`] || ''; -} -exports.getState = getState; -function getIDToken(aud) { - return __awaiter(this, void 0, void 0, function* () { - return yield oidc_utils_1.OidcClient.getIDToken(aud); - }); -} -exports.getIDToken = getIDToken; -/** - * Summary exports - */ -var summary_1 = __nccwpck_require__(81327); -Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); -/** - * @deprecated use core.summary - */ -var summary_2 = __nccwpck_require__(81327); -Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); -/** - * Path exports - */ -var path_utils_1 = __nccwpck_require__(2981); -Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); -Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); -Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); -//# sourceMappingURL=core.js.map - -/***/ }), - -/***/ 717: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -// For internal use, subject to change. -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issueCommand = void 0; -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -const fs = __importStar(__nccwpck_require__(57147)); -const os = __importStar(__nccwpck_require__(22037)); -const utils_1 = __nccwpck_require__(5278); -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 - -/***/ }), - -/***/ 98041: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(96255); -const auth_1 = __nccwpck_require__(35526); -const core_1 = __nccwpck_require__(42186); -class OidcClient { - static createHttpClient(allowRetry = true, maxRetry = 10) { - const requestOptions = { - allowRetries: allowRetry, - maxRetries: maxRetry - }; - return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); - } - static getRequestToken() { - const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; - if (!token) { - throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); - } - return token; - } - static getIDTokenUrl() { - const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; - if (!runtimeUrl) { - throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); - } - return runtimeUrl; - } - static getCall(id_token_url) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const httpclient = OidcClient.createHttpClient(); - const res = yield httpclient - .getJson(id_token_url) - .catch(error => { - throw new Error(`Failed to get ID Token. \n - Error Code : ${error.statusCode}\n - Error Message: ${error.result.message}`); - }); - const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; - if (!id_token) { - throw new Error('Response json body do not have ID Token field'); - } - return id_token; - }); - } - static getIDToken(audience) { - return __awaiter(this, void 0, void 0, function* () { - try { - // New ID Token is requested from action service - let id_token_url = OidcClient.getIDTokenUrl(); - if (audience) { - const encodedAudience = encodeURIComponent(audience); - id_token_url = `${id_token_url}&audience=${encodedAudience}`; - } - core_1.debug(`ID token url is ${id_token_url}`); - const id_token = yield OidcClient.getCall(id_token_url); - core_1.setSecret(id_token); - return id_token; - } - catch (error) { - throw new Error(`Error message: ${error.message}`); - } - }); - } -} -exports.OidcClient = OidcClient; -//# sourceMappingURL=oidc-utils.js.map - -/***/ }), - -/***/ 2981: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; -const path = __importStar(__nccwpck_require__(71017)); -/** - * toPosixPath converts the given path to the posix form. On Windows, \\ will be - * replaced with /. - * - * @param pth. Path to transform. - * @return string Posix path. - */ -function toPosixPath(pth) { - return pth.replace(/[\\]/g, '/'); -} -exports.toPosixPath = toPosixPath; -/** - * toWin32Path converts the given path to the win32 form. On Linux, / will be - * replaced with \\. - * - * @param pth. Path to transform. - * @return string Win32 path. - */ -function toWin32Path(pth) { - return pth.replace(/[/]/g, '\\'); -} -exports.toWin32Path = toWin32Path; -/** - * toPlatformPath converts the given path to a platform-specific path. It does - * this by replacing instances of / and \ with the platform-specific path - * separator. - * - * @param pth The path to platformize. - * @return string The platform-specific path. - */ -function toPlatformPath(pth) { - return pth.replace(/[/\\]/g, path.sep); -} -exports.toPlatformPath = toPlatformPath; -//# sourceMappingURL=path-utils.js.map - -/***/ }), - -/***/ 81327: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; -const os_1 = __nccwpck_require__(22037); -const fs_1 = __nccwpck_require__(57147); -const { access, appendFile, writeFile } = fs_1.promises; -exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; -exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; -class Summary { - constructor() { - this._buffer = ''; - } - /** - * Finds the summary file path from the environment, rejects if env var is not found or file does not exist - * Also checks r/w permissions. - * - * @returns step summary file path - */ - filePath() { - return __awaiter(this, void 0, void 0, function* () { - if (this._filePath) { - return this._filePath; - } - const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; - if (!pathFromEnv) { - throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); - } - try { - yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); - } - catch (_a) { - throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); - } - this._filePath = pathFromEnv; - return this._filePath; - }); - } - /** - * Wraps content in an HTML tag, adding any HTML attributes - * - * @param {string} tag HTML tag to wrap - * @param {string | null} content content within the tag - * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add - * - * @returns {string} content wrapped in HTML element - */ - wrap(tag, content, attrs = {}) { - const htmlAttrs = Object.entries(attrs) - .map(([key, value]) => ` ${key}="${value}"`) - .join(''); - if (!content) { - return `<${tag}${htmlAttrs}>`; - } - return `<${tag}${htmlAttrs}>${content}`; - } - /** - * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. - * - * @param {SummaryWriteOptions} [options] (optional) options for write operation - * - * @returns {Promise} summary instance - */ - write(options) { - return __awaiter(this, void 0, void 0, function* () { - const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); - const filePath = yield this.filePath(); - const writeFunc = overwrite ? writeFile : appendFile; - yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); - return this.emptyBuffer(); - }); - } - /** - * Clears the summary buffer and wipes the summary file - * - * @returns {Summary} summary instance - */ - clear() { - return __awaiter(this, void 0, void 0, function* () { - return this.emptyBuffer().write({ overwrite: true }); - }); - } - /** - * Returns the current summary buffer as a string - * - * @returns {string} string of summary buffer - */ - stringify() { - return this._buffer; - } - /** - * If the summary buffer is empty - * - * @returns {boolen} true if the buffer is empty - */ - isEmptyBuffer() { - return this._buffer.length === 0; - } - /** - * Resets the summary buffer without writing to summary file - * - * @returns {Summary} summary instance - */ - emptyBuffer() { - this._buffer = ''; - return this; - } - /** - * Adds raw text to the summary buffer - * - * @param {string} text content to add - * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) - * - * @returns {Summary} summary instance - */ - addRaw(text, addEOL = false) { - this._buffer += text; - return addEOL ? this.addEOL() : this; - } - /** - * Adds the operating system-specific end-of-line marker to the buffer - * - * @returns {Summary} summary instance - */ - addEOL() { - return this.addRaw(os_1.EOL); - } - /** - * Adds an HTML codeblock to the summary buffer - * - * @param {string} code content to render within fenced code block - * @param {string} lang (optional) language to syntax highlight code - * - * @returns {Summary} summary instance - */ - addCodeBlock(code, lang) { - const attrs = Object.assign({}, (lang && { lang })); - const element = this.wrap('pre', this.wrap('code', code), attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML list to the summary buffer - * - * @param {string[]} items list of items to render - * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) - * - * @returns {Summary} summary instance - */ - addList(items, ordered = false) { - const tag = ordered ? 'ol' : 'ul'; - const listItems = items.map(item => this.wrap('li', item)).join(''); - const element = this.wrap(tag, listItems); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML table to the summary buffer - * - * @param {SummaryTableCell[]} rows table rows - * - * @returns {Summary} summary instance - */ - addTable(rows) { - const tableBody = rows - .map(row => { - const cells = row - .map(cell => { - if (typeof cell === 'string') { - return this.wrap('td', cell); - } - const { header, data, colspan, rowspan } = cell; - const tag = header ? 'th' : 'td'; - const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); - return this.wrap(tag, data, attrs); - }) - .join(''); - return this.wrap('tr', cells); - }) - .join(''); - const element = this.wrap('table', tableBody); - return this.addRaw(element).addEOL(); - } - /** - * Adds a collapsable HTML details element to the summary buffer - * - * @param {string} label text for the closed state - * @param {string} content collapsable content - * - * @returns {Summary} summary instance - */ - addDetails(label, content) { - const element = this.wrap('details', this.wrap('summary', label) + content); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML image tag to the summary buffer - * - * @param {string} src path to the image you to embed - * @param {string} alt text description of the image - * @param {SummaryImageOptions} options (optional) addition image attributes - * - * @returns {Summary} summary instance - */ - addImage(src, alt, options) { - const { width, height } = options || {}; - const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); - const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML section heading element - * - * @param {string} text heading text - * @param {number | string} [level=1] (optional) the heading level, default: 1 - * - * @returns {Summary} summary instance - */ - addHeading(text, level) { - const tag = `h${level}`; - const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) - ? tag - : 'h1'; - const element = this.wrap(allowedTag, text); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML thematic break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addSeparator() { - const element = this.wrap('hr', null); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML line break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addBreak() { - const element = this.wrap('br', null); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML blockquote to the summary buffer - * - * @param {string} text quote text - * @param {string} cite (optional) citation url - * - * @returns {Summary} summary instance - */ - addQuote(text, cite) { - const attrs = Object.assign({}, (cite && { cite })); - const element = this.wrap('blockquote', text, attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML anchor tag to the summary buffer - * - * @param {string} text link text/content - * @param {string} href hyperlink - * - * @returns {Summary} summary instance - */ - addLink(text, href) { - const element = this.wrap('a', text, { href }); - return this.addRaw(element).addEOL(); - } -} -const _summary = new Summary(); -/** - * @deprecated use `core.summary` - */ -exports.markdownSummary = _summary; -exports.summary = _summary; -//# sourceMappingURL=summary.js.map - -/***/ }), - -/***/ 5278: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toCommandProperties = exports.toCommandValue = void 0; -/** - * Sanitizes an input into a string so it can be passed into issueCommand safely - * @param input input to sanitize into a string - */ -function toCommandValue(input) { - if (input === null || input === undefined) { - return ''; - } - else if (typeof input === 'string' || input instanceof String) { - return input; - } - return JSON.stringify(input); -} -exports.toCommandValue = toCommandValue; -/** - * - * @param annotationProperties - * @returns The command properties to send with the actual annotation command - * See IssueCommandProperties: /~https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 - */ -function toCommandProperties(annotationProperties) { - if (!Object.keys(annotationProperties).length) { - return {}; - } - return { - title: annotationProperties.title, - file: annotationProperties.file, - line: annotationProperties.startLine, - endLine: annotationProperties.endLine, - col: annotationProperties.startColumn, - endColumn: annotationProperties.endColumn - }; -} -exports.toCommandProperties = toCommandProperties; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 71514: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getExecOutput = exports.exec = void 0; -const string_decoder_1 = __nccwpck_require__(71576); -const tr = __importStar(__nccwpck_require__(88159)); -/** - * Exec a command. - * Output will be streamed to the live console. - * Returns promise with return code - * - * @param commandLine command to execute (can include additional args). Must be correctly escaped. - * @param args optional arguments for tool. Escaping is handled by the lib. - * @param options optional exec options. See ExecOptions - * @returns Promise exit code - */ -function exec(commandLine, args, options) { - return __awaiter(this, void 0, void 0, function* () { - const commandArgs = tr.argStringToArray(commandLine); - if (commandArgs.length === 0) { - throw new Error(`Parameter 'commandLine' cannot be null or empty.`); - } - // Path to tool to execute should be first arg - const toolPath = commandArgs[0]; - args = commandArgs.slice(1).concat(args || []); - const runner = new tr.ToolRunner(toolPath, args, options); - return runner.exec(); - }); -} -exports.exec = exec; -/** - * Exec a command and get the output. - * Output will be streamed to the live console. - * Returns promise with the exit code and collected stdout and stderr - * - * @param commandLine command to execute (can include additional args). Must be correctly escaped. - * @param args optional arguments for tool. Escaping is handled by the lib. - * @param options optional exec options. See ExecOptions - * @returns Promise exit code, stdout, and stderr - */ -function getExecOutput(commandLine, args, options) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - let stdout = ''; - let stderr = ''; - //Using string decoder covers the case where a mult-byte character is split - const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); - const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); - const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; - const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; - const stdErrListener = (data) => { - stderr += stderrDecoder.write(data); - if (originalStdErrListener) { - originalStdErrListener(data); - } - }; - const stdOutListener = (data) => { - stdout += stdoutDecoder.write(data); - if (originalStdoutListener) { - originalStdoutListener(data); - } - }; - const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); - const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); - //flush any remaining characters - stdout += stdoutDecoder.end(); - stderr += stderrDecoder.end(); - return { - exitCode, - stdout, - stderr - }; - }); -} -exports.getExecOutput = getExecOutput; -//# sourceMappingURL=exec.js.map - -/***/ }), - -/***/ 88159: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.argStringToArray = exports.ToolRunner = void 0; -const os = __importStar(__nccwpck_require__(22037)); -const events = __importStar(__nccwpck_require__(82361)); -const child = __importStar(__nccwpck_require__(32081)); -const path = __importStar(__nccwpck_require__(71017)); -const io = __importStar(__nccwpck_require__(47351)); -const ioUtil = __importStar(__nccwpck_require__(81962)); -const timers_1 = __nccwpck_require__(39512); -/* eslint-disable @typescript-eslint/unbound-method */ -const IS_WINDOWS = process.platform === 'win32'; -/* - * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. - */ -class ToolRunner extends events.EventEmitter { - constructor(toolPath, args, options) { - super(); - if (!toolPath) { - throw new Error("Parameter 'toolPath' cannot be null or empty."); - } - this.toolPath = toolPath; - this.args = args || []; - this.options = options || {}; - } - _debug(message) { - if (this.options.listeners && this.options.listeners.debug) { - this.options.listeners.debug(message); - } - } - _getCommandString(options, noPrefix) { - const toolPath = this._getSpawnFileName(); - const args = this._getSpawnArgs(options); - let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool - if (IS_WINDOWS) { - // Windows + cmd file - if (this._isCmdFile()) { - cmd += toolPath; - for (const a of args) { - cmd += ` ${a}`; - } - } - // Windows + verbatim - else if (options.windowsVerbatimArguments) { - cmd += `"${toolPath}"`; - for (const a of args) { - cmd += ` ${a}`; - } - } - // Windows (regular) - else { - cmd += this._windowsQuoteCmdArg(toolPath); - for (const a of args) { - cmd += ` ${this._windowsQuoteCmdArg(a)}`; - } - } - } - else { - // OSX/Linux - this can likely be improved with some form of quoting. - // creating processes on Unix is fundamentally different than Windows. - // on Unix, execvp() takes an arg array. - cmd += toolPath; - for (const a of args) { - cmd += ` ${a}`; - } - } - return cmd; - } - _processLineBuffer(data, strBuffer, onLine) { - try { - let s = strBuffer + data.toString(); - let n = s.indexOf(os.EOL); - while (n > -1) { - const line = s.substring(0, n); - onLine(line); - // the rest of the string ... - s = s.substring(n + os.EOL.length); - n = s.indexOf(os.EOL); - } - return s; - } - catch (err) { - // streaming lines to console is best effort. Don't fail a build. - this._debug(`error processing line. Failed with error ${err}`); - return ''; - } - } - _getSpawnFileName() { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - return process.env['COMSPEC'] || 'cmd.exe'; - } - } - return this.toolPath; - } - _getSpawnArgs(options) { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; - for (const a of this.args) { - argline += ' '; - argline += options.windowsVerbatimArguments - ? a - : this._windowsQuoteCmdArg(a); - } - argline += '"'; - return [argline]; - } - } - return this.args; - } - _endsWith(str, end) { - return str.endsWith(end); - } - _isCmdFile() { - const upperToolPath = this.toolPath.toUpperCase(); - return (this._endsWith(upperToolPath, '.CMD') || - this._endsWith(upperToolPath, '.BAT')); - } - _windowsQuoteCmdArg(arg) { - // for .exe, apply the normal quoting rules that libuv applies - if (!this._isCmdFile()) { - return this._uvQuoteCmdArg(arg); - } - // otherwise apply quoting rules specific to the cmd.exe command line parser. - // the libuv rules are generic and are not designed specifically for cmd.exe - // command line parser. - // - // for a detailed description of the cmd.exe command line parser, refer to - // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 - // need quotes for empty arg - if (!arg) { - return '""'; - } - // determine whether the arg needs to be quoted - const cmdSpecialChars = [ - ' ', - '\t', - '&', - '(', - ')', - '[', - ']', - '{', - '}', - '^', - '=', - ';', - '!', - "'", - '+', - ',', - '`', - '~', - '|', - '<', - '>', - '"' - ]; - let needsQuotes = false; - for (const char of arg) { - if (cmdSpecialChars.some(x => x === char)) { - needsQuotes = true; - break; - } - } - // short-circuit if quotes not needed - if (!needsQuotes) { - return arg; - } - // the following quoting rules are very similar to the rules that by libuv applies. - // - // 1) wrap the string in quotes - // - // 2) double-up quotes - i.e. " => "" - // - // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately - // doesn't work well with a cmd.exe command line. - // - // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. - // for example, the command line: - // foo.exe "myarg:""my val""" - // is parsed by a .NET console app into an arg array: - // [ "myarg:\"my val\"" ] - // which is the same end result when applying libuv quoting rules. although the actual - // command line from libuv quoting rules would look like: - // foo.exe "myarg:\"my val\"" - // - // 3) double-up slashes that precede a quote, - // e.g. hello \world => "hello \world" - // hello\"world => "hello\\""world" - // hello\\"world => "hello\\\\""world" - // hello world\ => "hello world\\" - // - // technically this is not required for a cmd.exe command line, or the batch argument parser. - // the reasons for including this as a .cmd quoting rule are: - // - // a) this is optimized for the scenario where the argument is passed from the .cmd file to an - // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. - // - // b) it's what we've been doing previously (by deferring to node default behavior) and we - // haven't heard any complaints about that aspect. - // - // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be - // escaped when used on the command line directly - even though within a .cmd file % can be escaped - // by using %%. - // - // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts - // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. - // - // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would - // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the - // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args - // to an external program. - // - // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. - // % can be escaped within a .cmd file. - let reverse = '"'; - let quoteHit = true; - for (let i = arg.length; i > 0; i--) { - // walk the string in reverse - reverse += arg[i - 1]; - if (quoteHit && arg[i - 1] === '\\') { - reverse += '\\'; // double the slash - } - else if (arg[i - 1] === '"') { - quoteHit = true; - reverse += '"'; // double the quote - } - else { - quoteHit = false; - } - } - reverse += '"'; - return reverse - .split('') - .reverse() - .join(''); - } - _uvQuoteCmdArg(arg) { - // Tool runner wraps child_process.spawn() and needs to apply the same quoting as - // Node in certain cases where the undocumented spawn option windowsVerbatimArguments - // is used. - // - // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, - // see /~https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), - // pasting copyright notice from Node within this function: - // - // Copyright Joyent, Inc. and other Node contributors. All rights reserved. - // - // 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. - if (!arg) { - // Need double quotation for empty argument - return '""'; - } - if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { - // No quotation needed - return arg; - } - if (!arg.includes('"') && !arg.includes('\\')) { - // No embedded double quotes or backslashes, so I can just wrap - // quote marks around the whole thing. - return `"${arg}"`; - } - // Expected input/output: - // input : hello"world - // output: "hello\"world" - // input : hello""world - // output: "hello\"\"world" - // input : hello\world - // output: hello\world - // input : hello\\world - // output: hello\\world - // input : hello\"world - // output: "hello\\\"world" - // input : hello\\"world - // output: "hello\\\\\"world" - // input : hello world\ - // output: "hello world\\" - note the comment in libuv actually reads "hello world\" - // but it appears the comment is wrong, it should be "hello world\\" - let reverse = '"'; - let quoteHit = true; - for (let i = arg.length; i > 0; i--) { - // walk the string in reverse - reverse += arg[i - 1]; - if (quoteHit && arg[i - 1] === '\\') { - reverse += '\\'; - } - else if (arg[i - 1] === '"') { - quoteHit = true; - reverse += '\\'; - } - else { - quoteHit = false; - } - } - reverse += '"'; - return reverse - .split('') - .reverse() - .join(''); - } - _cloneExecOptions(options) { - options = options || {}; - const result = { - cwd: options.cwd || process.cwd(), - env: options.env || process.env, - silent: options.silent || false, - windowsVerbatimArguments: options.windowsVerbatimArguments || false, - failOnStdErr: options.failOnStdErr || false, - ignoreReturnCode: options.ignoreReturnCode || false, - delay: options.delay || 10000 - }; - result.outStream = options.outStream || process.stdout; - result.errStream = options.errStream || process.stderr; - return result; - } - _getSpawnOptions(options, toolPath) { - options = options || {}; - const result = {}; - result.cwd = options.cwd; - result.env = options.env; - result['windowsVerbatimArguments'] = - options.windowsVerbatimArguments || this._isCmdFile(); - if (options.windowsVerbatimArguments) { - result.argv0 = `"${toolPath}"`; - } - return result; - } - /** - * Exec a tool. - * Output will be streamed to the live console. - * Returns promise with return code - * - * @param tool path to tool to exec - * @param options optional exec options. See ExecOptions - * @returns number - */ - exec() { - return __awaiter(this, void 0, void 0, function* () { - // root the tool path if it is unrooted and contains relative pathing - if (!ioUtil.isRooted(this.toolPath) && - (this.toolPath.includes('/') || - (IS_WINDOWS && this.toolPath.includes('\\')))) { - // prefer options.cwd if it is specified, however options.cwd may also need to be rooted - this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); - } - // if the tool is only a file name, then resolve it from the PATH - // otherwise verify it exists (add extension on Windows if necessary) - this.toolPath = yield io.which(this.toolPath, true); - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - this._debug(`exec tool: ${this.toolPath}`); - this._debug('arguments:'); - for (const arg of this.args) { - this._debug(` ${arg}`); - } - const optionsNonNull = this._cloneExecOptions(this.options); - if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); - } - const state = new ExecState(optionsNonNull, this.toolPath); - state.on('debug', (message) => { - this._debug(message); - }); - if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { - return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); - } - const fileName = this._getSpawnFileName(); - const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); - let stdbuffer = ''; - if (cp.stdout) { - cp.stdout.on('data', (data) => { - if (this.options.listeners && this.options.listeners.stdout) { - this.options.listeners.stdout(data); - } - if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(data); - } - stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { - if (this.options.listeners && this.options.listeners.stdline) { - this.options.listeners.stdline(line); - } - }); - }); - } - let errbuffer = ''; - if (cp.stderr) { - cp.stderr.on('data', (data) => { - state.processStderr = true; - if (this.options.listeners && this.options.listeners.stderr) { - this.options.listeners.stderr(data); - } - if (!optionsNonNull.silent && - optionsNonNull.errStream && - optionsNonNull.outStream) { - const s = optionsNonNull.failOnStdErr - ? optionsNonNull.errStream - : optionsNonNull.outStream; - s.write(data); - } - errbuffer = this._processLineBuffer(data, errbuffer, (line) => { - if (this.options.listeners && this.options.listeners.errline) { - this.options.listeners.errline(line); - } - }); - }); - } - cp.on('error', (err) => { - state.processError = err.message; - state.processExited = true; - state.processClosed = true; - state.CheckComplete(); - }); - cp.on('exit', (code) => { - state.processExitCode = code; - state.processExited = true; - this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); - state.CheckComplete(); - }); - cp.on('close', (code) => { - state.processExitCode = code; - state.processExited = true; - state.processClosed = true; - this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); - state.CheckComplete(); - }); - state.on('done', (error, exitCode) => { - if (stdbuffer.length > 0) { - this.emit('stdline', stdbuffer); - } - if (errbuffer.length > 0) { - this.emit('errline', errbuffer); - } - cp.removeAllListeners(); - if (error) { - reject(error); - } - else { - resolve(exitCode); - } - }); - if (this.options.input) { - if (!cp.stdin) { - throw new Error('child process missing stdin'); - } - cp.stdin.end(this.options.input); - } - })); - }); - } -} -exports.ToolRunner = ToolRunner; -/** - * Convert an arg string to an array of args. Handles escaping - * - * @param argString string of arguments - * @returns string[] array of arguments - */ -function argStringToArray(argString) { - const args = []; - let inQuotes = false; - let escaped = false; - let arg = ''; - function append(c) { - // we only escape double quotes. - if (escaped && c !== '"') { - arg += '\\'; - } - arg += c; - escaped = false; - } - for (let i = 0; i < argString.length; i++) { - const c = argString.charAt(i); - if (c === '"') { - if (!escaped) { - inQuotes = !inQuotes; - } - else { - append(c); - } - continue; - } - if (c === '\\' && escaped) { - append(c); - continue; - } - if (c === '\\' && inQuotes) { - escaped = true; - continue; - } - if (c === ' ' && !inQuotes) { - if (arg.length > 0) { - args.push(arg); - arg = ''; - } - continue; - } - append(c); - } - if (arg.length > 0) { - args.push(arg.trim()); - } - return args; -} -exports.argStringToArray = argStringToArray; -class ExecState extends events.EventEmitter { - constructor(options, toolPath) { - super(); - this.processClosed = false; // tracks whether the process has exited and stdio is closed - this.processError = ''; - this.processExitCode = 0; - this.processExited = false; // tracks whether the process has exited - this.processStderr = false; // tracks whether stderr was written to - this.delay = 10000; // 10 seconds - this.done = false; - this.timeout = null; - if (!toolPath) { - throw new Error('toolPath must not be empty'); - } - this.options = options; - this.toolPath = toolPath; - if (options.delay) { - this.delay = options.delay; - } - } - CheckComplete() { - if (this.done) { - return; - } - if (this.processClosed) { - this._setResult(); - } - else if (this.processExited) { - this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); - } - } - _debug(message) { - this.emit('debug', message); - } - _setResult() { - // determine whether there is an error - let error; - if (this.processExited) { - if (this.processError) { - error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); - } - else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { - error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); - } - else if (this.processStderr && this.options.failOnStdErr) { - error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); - } - } - // clear the timeout - if (this.timeout) { - clearTimeout(this.timeout); - this.timeout = null; - } - this.done = true; - this.emit('done', error, this.processExitCode); - } - static HandleTimeout(state) { - if (state.done) { - return; - } - if (!state.processClosed && state.processExited) { - const message = `The STDIO streams did not close within ${state.delay / - 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; - state._debug(message); - } - state._setResult(); - } -} -//# sourceMappingURL=toolrunner.js.map - -/***/ }), - -/***/ 74087: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Context = void 0; -const fs_1 = __nccwpck_require__(57147); -const os_1 = __nccwpck_require__(22037); -class Context { - /** - * Hydrate the context from the environment - */ - constructor() { - var _a, _b, _c; - this.payload = {}; - if (process.env.GITHUB_EVENT_PATH) { - if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) { - this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); - } - else { - const path = process.env.GITHUB_EVENT_PATH; - process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); - } - } - this.eventName = process.env.GITHUB_EVENT_NAME; - this.sha = process.env.GITHUB_SHA; - this.ref = process.env.GITHUB_REF; - this.workflow = process.env.GITHUB_WORKFLOW; - this.action = process.env.GITHUB_ACTION; - this.actor = process.env.GITHUB_ACTOR; - this.job = process.env.GITHUB_JOB; - this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); - this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); - this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; - this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; - this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; - } - get issue() { - const payload = this.payload; - return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); - } - get repo() { - if (process.env.GITHUB_REPOSITORY) { - const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); - return { owner, repo }; - } - if (this.payload.repository) { - return { - owner: this.payload.repository.owner.login, - repo: this.payload.repository.name - }; - } - throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); - } -} -exports.Context = Context; -//# sourceMappingURL=context.js.map - -/***/ }), - -/***/ 95438: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOctokit = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(74087)); -const utils_1 = __nccwpck_require__(73030); -exports.context = new Context.Context(); -/** - * Returns a hydrated octokit ready to use for GitHub Actions - * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set - */ -function getOctokit(token, options) { - return new utils_1.GitHub(utils_1.getOctokitOptions(token, options)); -} -exports.getOctokit = getOctokit; -//# sourceMappingURL=github.js.map - -/***/ }), - -/***/ 47914: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0; -const httpClient = __importStar(__nccwpck_require__(96255)); -function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error('Parameter token or opts.auth is required'); - } - else if (token && options.auth) { - throw new Error('Parameters token and opts.auth may not both be specified'); - } - return typeof options.auth === 'string' ? options.auth : `token ${token}`; -} -exports.getAuthString = getAuthString; -function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); -} -exports.getProxyAgent = getProxyAgent; -function getApiBaseUrl() { - return process.env['GITHUB_API_URL'] || 'https://api.github.com'; -} -exports.getApiBaseUrl = getApiBaseUrl; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 73030: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOctokitOptions = exports.GitHub = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(74087)); -const Utils = __importStar(__nccwpck_require__(47914)); -// octokit + plugins -const core_1 = __nccwpck_require__(76762); -const plugin_rest_endpoint_methods_1 = __nccwpck_require__(83044); -const plugin_paginate_rest_1 = __nccwpck_require__(64193); -exports.context = new Context.Context(); -const baseUrl = Utils.getApiBaseUrl(); -const defaults = { - baseUrl, - request: { - agent: Utils.getProxyAgent(baseUrl) - } -}; -exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(defaults); -/** - * Convience function to correctly format Octokit Options to pass into the constructor. - * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set - */ -function getOctokitOptions(token, options) { - const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller - // Auth - const auth = Utils.getAuthString(token, opts); - if (auth) { - opts.auth = auth; - } - return opts; -} -exports.getOctokitOptions = getOctokitOptions; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 28090: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.hashFiles = exports.create = void 0; -const internal_globber_1 = __nccwpck_require__(28298); -const internal_hash_files_1 = __nccwpck_require__(2448); -/** - * 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; -/** - * Computes the sha256 hash of a glob - * - * @param patterns Patterns separated by newlines - * @param options Glob options - */ -function hashFiles(patterns, options, verbose = false) { - return __awaiter(this, void 0, void 0, function* () { - let followSymbolicLinks = true; - if (options && typeof options.followSymbolicLinks === 'boolean') { - followSymbolicLinks = options.followSymbolicLinks; - } - const globber = yield create(patterns, { followSymbolicLinks }); - return internal_hash_files_1.hashFiles(globber, verbose); - }); -} -exports.hashFiles = hashFiles; -//# sourceMappingURL=glob.js.map - -/***/ }), - -/***/ 51026: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOptions = void 0; -const core = __importStar(__nccwpck_require__(42186)); -/** - * Returns a copy with defaults filled in. - */ -function getOptions(copy) { - const result = { - followSymbolicLinks: true, - implicitDescendants: true, - matchDirectories: true, - omitBrokenSymbolicLinks: true - }; - if (copy) { - if (typeof copy.followSymbolicLinks === 'boolean') { - result.followSymbolicLinks = copy.followSymbolicLinks; - core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); - } - if (typeof copy.implicitDescendants === 'boolean') { - result.implicitDescendants = copy.implicitDescendants; - core.debug(`implicitDescendants '${result.implicitDescendants}'`); - } - if (typeof copy.matchDirectories === 'boolean') { - result.matchDirectories = copy.matchDirectories; - core.debug(`matchDirectories '${result.matchDirectories}'`); - } - if (typeof copy.omitBrokenSymbolicLinks === 'boolean') { - result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; - core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); - } - } - return result; -} -exports.getOptions = getOptions; -//# sourceMappingURL=internal-glob-options-helper.js.map - -/***/ }), - -/***/ 28298: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -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 })); -exports.DefaultGlobber = void 0; -const core = __importStar(__nccwpck_require__(42186)); -const fs = __importStar(__nccwpck_require__(57147)); -const globOptionsHelper = __importStar(__nccwpck_require__(51026)); -const path = __importStar(__nccwpck_require__(71017)); -const patternHelper = __importStar(__nccwpck_require__(29005)); -const internal_match_kind_1 = __nccwpck_require__(81063); -const internal_pattern_1 = __nccwpck_require__(64536); -const internal_search_state_1 = __nccwpck_require__(89117); -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, true, 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 && options.matchDirectories) { - 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 - -/***/ }), - -/***/ 2448: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -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); } -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.hashFiles = void 0; -const crypto = __importStar(__nccwpck_require__(6113)); -const core = __importStar(__nccwpck_require__(42186)); -const fs = __importStar(__nccwpck_require__(57147)); -const stream = __importStar(__nccwpck_require__(12781)); -const util = __importStar(__nccwpck_require__(73837)); -const path = __importStar(__nccwpck_require__(71017)); -function hashFiles(globber, verbose = false) { - var e_1, _a; - var _b; - return __awaiter(this, void 0, void 0, function* () { - const writeDelegate = verbose ? core.info : core.debug; - let hasMatch = false; - const githubWorkspace = (_b = process.env['GITHUB_WORKSPACE']) !== null && _b !== void 0 ? _b : process.cwd(); - const result = crypto.createHash('sha256'); - let count = 0; - try { - for (var _c = __asyncValues(globber.globGenerator()), _d; _d = yield _c.next(), !_d.done;) { - const file = _d.value; - writeDelegate(file); - if (!file.startsWith(`${githubWorkspace}${path.sep}`)) { - writeDelegate(`Ignore '${file}' since it is not under GITHUB_WORKSPACE.`); - continue; - } - if (fs.statSync(file).isDirectory()) { - writeDelegate(`Skip directory '${file}'.`); - continue; - } - const hash = crypto.createHash('sha256'); - const pipeline = util.promisify(stream.pipeline); - yield pipeline(fs.createReadStream(file), hash); - result.write(hash.digest()); - count++; - if (!hasMatch) { - hasMatch = true; - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_d && !_d.done && (_a = _c.return)) yield _a.call(_c); - } - finally { if (e_1) throw e_1.error; } - } - result.end(); - if (hasMatch) { - writeDelegate(`Found ${count} files to hash.`); - return result.digest('hex'); - } - else { - writeDelegate(`No matches found for glob`); - return ''; - } - }); -} -exports.hashFiles = hashFiles; -//# sourceMappingURL=internal-hash-files.js.map - -/***/ }), - -/***/ 81063: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MatchKind = void 0; -/** - * 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 - -/***/ }), - -/***/ 1849: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.safeTrimTrailingSeparator = exports.normalizeSeparators = exports.hasRoot = exports.hasAbsoluteRoot = exports.ensureAbsoluteRoot = exports.dirname = void 0; -const path = __importStar(__nccwpck_require__(71017)); -const assert_1 = __importDefault(__nccwpck_require__(39491)); -const IS_WINDOWS = process.platform === 'win32'; -/** - * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths. - * - * For example, on Linux/macOS: - * - `/ => /` - * - `/hello => /` - * - * For example, on Windows: - * - `C:\ => C:\` - * - `C:\hello => C:\` - * - `C: => C:` - * - `C:hello => C:` - * - `\ => \` - * - `\hello => \` - * - `\\hello => \\hello` - * - `\\hello\world => \\hello\world` - */ -function dirname(p) { - // Normalize slashes and trim unnecessary trailing slash - p = safeTrimTrailingSeparator(p); - // Windows UNC root, e.g. \\hello or \\hello\world - if (IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) { - return p; - } - // Get dirname - let result = path.dirname(p); - // Trim trailing slash for Windows UNC root, e.g. \\hello\world\ - if (IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) { - result = safeTrimTrailingSeparator(result); - } - return result; -} -exports.dirname = dirname; -/** - * Roots the path if not already rooted. On Windows, relative roots like `\` - * or `C:` are expanded based on the current working directory. - */ -function ensureAbsoluteRoot(root, itemPath) { - assert_1.default(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); - assert_1.default(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); - // Already rooted - if (hasAbsoluteRoot(itemPath)) { - return itemPath; - } - // Windows - if (IS_WINDOWS) { - // Check for itemPath like C: or C:foo - if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) { - let cwd = process.cwd(); - assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); - // Drive letter matches cwd? Expand to cwd - if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) { - // Drive only, e.g. C: - if (itemPath.length === 2) { - // Preserve specified drive letter case (upper or lower) - return `${itemPath[0]}:\\${cwd.substr(3)}`; - } - // Drive + path, e.g. C:foo - else { - if (!cwd.endsWith('\\')) { - cwd += '\\'; - } - // Preserve specified drive letter case (upper or lower) - return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`; - } - } - // Different drive - else { - return `${itemPath[0]}:\\${itemPath.substr(2)}`; - } - } - // Check for itemPath like \ or \foo - else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) { - const cwd = process.cwd(); - assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); - return `${cwd[0]}:\\${itemPath.substr(1)}`; - } - } - assert_1.default(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); - // Otherwise ensure root ends with a separator - if (root.endsWith('/') || (IS_WINDOWS && root.endsWith('\\'))) { - // Intentionally empty - } - else { - // Append separator - root += path.sep; - } - return root + itemPath; -} -exports.ensureAbsoluteRoot = ensureAbsoluteRoot; -/** - * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: - * `\\hello\share` and `C:\hello` (and using alternate separator). - */ -function hasAbsoluteRoot(itemPath) { - assert_1.default(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); - // Normalize separators - itemPath = normalizeSeparators(itemPath); - // Windows - if (IS_WINDOWS) { - // E.g. \\hello\share or C:\hello - return itemPath.startsWith('\\\\') || /^[A-Z]:\\/i.test(itemPath); - } - // E.g. /hello - return itemPath.startsWith('/'); -} -exports.hasAbsoluteRoot = hasAbsoluteRoot; -/** - * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: - * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator). - */ -function hasRoot(itemPath) { - assert_1.default(itemPath, `isRooted parameter 'itemPath' must not be empty`); - // Normalize separators - itemPath = normalizeSeparators(itemPath); - // Windows - if (IS_WINDOWS) { - // E.g. \ or \hello or \\hello - // E.g. C: or C:\hello - return itemPath.startsWith('\\') || /^[A-Z]:/i.test(itemPath); - } - // E.g. /hello - return itemPath.startsWith('/'); -} -exports.hasRoot = hasRoot; -/** - * Removes redundant slashes and converts `/` to `\` on Windows - */ -function normalizeSeparators(p) { - p = p || ''; - // Windows - if (IS_WINDOWS) { - // Convert slashes on Windows - p = p.replace(/\//g, '\\'); - // Remove redundant slashes - const isUnc = /^\\\\+[^\\]/.test(p); // e.g. \\hello - return (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\'); // preserve leading \\ for UNC - } - // Remove redundant slashes - return p.replace(/\/\/+/g, '/'); -} -exports.normalizeSeparators = normalizeSeparators; -/** - * Normalizes the path separators and trims the trailing separator (when safe). - * For example, `/foo/ => /foo` but `/ => /` - */ -function safeTrimTrailingSeparator(p) { - // Short-circuit if empty - if (!p) { - return ''; - } - // Normalize separators - p = normalizeSeparators(p); - // No trailing slash - if (!p.endsWith(path.sep)) { - return p; - } - // Check '/' on Linux/macOS and '\' on Windows - if (p === path.sep) { - return p; - } - // On Windows check if drive root. E.g. C:\ - if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) { - return p; - } - // Otherwise trim trailing slash - return p.substr(0, p.length - 1); -} -exports.safeTrimTrailingSeparator = safeTrimTrailingSeparator; -//# sourceMappingURL=internal-path-helper.js.map - -/***/ }), - -/***/ 96836: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Path = void 0; -const path = __importStar(__nccwpck_require__(71017)); -const pathHelper = __importStar(__nccwpck_require__(1849)); -const assert_1 = __importDefault(__nccwpck_require__(39491)); -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_1.default(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_1.default(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_1.default(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_1.default(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_1.default(!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 - -/***/ }), - -/***/ 29005: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.partialMatch = exports.match = exports.getSearchPaths = void 0; -const pathHelper = __importStar(__nccwpck_require__(1849)); -const internal_match_kind_1 = __nccwpck_require__(81063); -const IS_WINDOWS = process.platform === 'win32'; -/** - * Given an array of patterns, returns an array of paths to search. - * Duplicates and paths under other included paths are filtered out. - */ -function getSearchPaths(patterns) { - // Ignore negate patterns - patterns = patterns.filter(x => !x.negate); - // Create a map of all search paths - const searchPathMap = {}; - for (const pattern of patterns) { - const key = IS_WINDOWS - ? pattern.searchPath.toUpperCase() - : pattern.searchPath; - searchPathMap[key] = 'candidate'; - } - const result = []; - for (const pattern of patterns) { - // Check if already included - const key = IS_WINDOWS - ? pattern.searchPath.toUpperCase() - : pattern.searchPath; - if (searchPathMap[key] === 'included') { - continue; - } - // Check for an ancestor search path - let foundAncestor = false; - let tempKey = key; - let parent = pathHelper.dirname(tempKey); - while (parent !== tempKey) { - if (searchPathMap[parent]) { - foundAncestor = true; - break; - } - tempKey = parent; - parent = pathHelper.dirname(tempKey); - } - // Include the search pattern in the result - if (!foundAncestor) { - result.push(pattern.searchPath); - searchPathMap[key] = 'included'; - } - } - return result; -} -exports.getSearchPaths = getSearchPaths; -/** - * Matches the patterns against the path - */ -function match(patterns, itemPath) { - let result = internal_match_kind_1.MatchKind.None; - for (const pattern of patterns) { - if (pattern.negate) { - result &= ~pattern.match(itemPath); - } - else { - result |= pattern.match(itemPath); - } - } - return result; -} -exports.match = match; -/** - * Checks whether to descend further into the directory - */ -function partialMatch(patterns, itemPath) { - return patterns.some(x => !x.negate && x.partialMatch(itemPath)); -} -exports.partialMatch = partialMatch; -//# sourceMappingURL=internal-pattern-helper.js.map - -/***/ }), - -/***/ 64536: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Pattern = void 0; -const os = __importStar(__nccwpck_require__(22037)); -const path = __importStar(__nccwpck_require__(71017)); -const pathHelper = __importStar(__nccwpck_require__(1849)); -const assert_1 = __importDefault(__nccwpck_require__(39491)); -const minimatch_1 = __nccwpck_require__(83973); -const internal_match_kind_1 = __nccwpck_require__(81063); -const internal_path_1 = __nccwpck_require__(96836); -const IS_WINDOWS = process.platform === 'win32'; -class Pattern { - constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) { - /** - * Indicates whether matches should be excluded from the result set - */ - this.negate = false; - // Pattern overload - let pattern; - if (typeof patternOrNegate === 'string') { - pattern = patternOrNegate.trim(); - } - // Segments overload - else { - // Convert to pattern - segments = segments || []; - assert_1.default(segments.length, `Parameter 'segments' must not empty`); - const root = Pattern.getLiteral(segments[0]); - assert_1.default(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); - pattern = new internal_path_1.Path(segments).toString().trim(); - if (patternOrNegate) { - pattern = `!${pattern}`; - } - } - // Negate - while (pattern.startsWith('!')) { - this.negate = !this.negate; - pattern = pattern.substr(1).trim(); - } - // Normalize slashes and ensures absolute root - pattern = Pattern.fixupPattern(pattern, homedir); - // Segments - this.segments = new internal_path_1.Path(pattern).segments; - // Trailing slash indicates the pattern should only match directories, not regular files - this.trailingSeparator = pathHelper - .normalizeSeparators(pattern) - .endsWith(path.sep); - pattern = pathHelper.safeTrimTrailingSeparator(pattern); - // Search path (literal path prior to the first glob segment) - let foundGlob = false; - const searchSegments = this.segments - .map(x => Pattern.getLiteral(x)) - .filter(x => !foundGlob && !(foundGlob = x === '')); - this.searchPath = new internal_path_1.Path(searchSegments).toString(); - // Root RegExp (required when determining partial match) - this.rootRegExp = new RegExp(Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? 'i' : ''); - this.isImplicitPattern = isImplicitPattern; - // Create minimatch - const minimatchOptions = { - dot: true, - nobrace: true, - nocase: IS_WINDOWS, - nocomment: true, - noext: true, - nonegate: true - }; - pattern = IS_WINDOWS ? pattern.replace(/\\/g, '/') : pattern; - this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions); - } - /** - * Matches the pattern against the specified path - */ - match(itemPath) { - // Last segment is globstar? - if (this.segments[this.segments.length - 1] === '**') { - // Normalize slashes - itemPath = pathHelper.normalizeSeparators(itemPath); - // Append a trailing slash. Otherwise Minimatch will not match the directory immediately - // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns - // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk. - if (!itemPath.endsWith(path.sep) && this.isImplicitPattern === false) { - // Note, this is safe because the constructor ensures the pattern has an absolute root. - // For example, formats like C: and C:foo on Windows are resolved to an absolute root. - itemPath = `${itemPath}${path.sep}`; - } - } - else { - // Normalize slashes and trim unnecessary trailing slash - itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); - } - // Match - if (this.minimatch.match(itemPath)) { - return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All; - } - return internal_match_kind_1.MatchKind.None; - } - /** - * Indicates whether the pattern may match descendants of the specified path - */ - partialMatch(itemPath) { - // Normalize slashes and trim unnecessary trailing slash - itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); - // matchOne does not handle root path correctly - if (pathHelper.dirname(itemPath) === itemPath) { - return this.rootRegExp.test(itemPath); - } - return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true); - } - /** - * Escapes glob patterns within a path - */ - static globEscape(s) { - return (IS_WINDOWS ? s : s.replace(/\\/g, '\\\\')) // escape '\' on Linux/macOS - .replace(/(\[)(?=[^/]+\])/g, '[[]') // escape '[' when ']' follows within the path segment - .replace(/\?/g, '[?]') // escape '?' - .replace(/\*/g, '[*]'); // escape '*' - } - /** - * Normalizes slashes and ensures absolute root - */ - static fixupPattern(pattern, homedir) { - // Empty - assert_1.default(pattern, 'pattern cannot be empty'); - // Must not contain `.` segment, unless first segment - // Must not contain `..` segment - const literalSegments = new internal_path_1.Path(pattern).segments.map(x => Pattern.getLiteral(x)); - assert_1.default(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); - // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r - assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); - // Normalize slashes - pattern = pathHelper.normalizeSeparators(pattern); - // Replace leading `.` segment - if (pattern === '.' || pattern.startsWith(`.${path.sep}`)) { - pattern = Pattern.globEscape(process.cwd()) + pattern.substr(1); - } - // Replace leading `~` segment - else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) { - homedir = homedir || os.homedir(); - assert_1.default(homedir, 'Unable to determine HOME directory'); - assert_1.default(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); - pattern = Pattern.globEscape(homedir) + pattern.substr(1); - } - // Replace relative drive root, e.g. pattern is C: or C:foo - else if (IS_WINDOWS && - (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) { - let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', pattern.substr(0, 2)); - if (pattern.length > 2 && !root.endsWith('\\')) { - root += '\\'; - } - pattern = Pattern.globEscape(root) + pattern.substr(2); - } - // Replace relative root, e.g. pattern is \ or \foo - else if (IS_WINDOWS && (pattern === '\\' || pattern.match(/^\\[^\\]/))) { - let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', '\\'); - if (!root.endsWith('\\')) { - root += '\\'; - } - pattern = Pattern.globEscape(root) + pattern.substr(1); - } - // Otherwise ensure absolute root - else { - pattern = pathHelper.ensureAbsoluteRoot(Pattern.globEscape(process.cwd()), pattern); - } - return pathHelper.normalizeSeparators(pattern); - } - /** - * Attempts to unescape a pattern segment to create a literal path segment. - * Otherwise returns empty string. - */ - static getLiteral(segment) { - let literal = ''; - for (let i = 0; i < segment.length; i++) { - const c = segment[i]; - // Escape - if (c === '\\' && !IS_WINDOWS && i + 1 < segment.length) { - literal += segment[++i]; - continue; - } - // Wildcard - else if (c === '*' || c === '?') { - return ''; - } - // Character set - else if (c === '[' && i + 1 < segment.length) { - let set = ''; - let closed = -1; - for (let i2 = i + 1; i2 < segment.length; i2++) { - const c2 = segment[i2]; - // Escape - if (c2 === '\\' && !IS_WINDOWS && i2 + 1 < segment.length) { - set += segment[++i2]; - continue; - } - // Closed - else if (c2 === ']') { - closed = i2; - break; - } - // Otherwise - else { - set += c2; - } - } - // Closed? - if (closed >= 0) { - // Cannot convert - if (set.length > 1) { - return ''; - } - // Convert to literal - if (set) { - literal += set; - i = closed; - continue; - } - } - // Otherwise fall thru - } - // Append - literal += c; - } - return literal; - } - /** - * Escapes regexp special characters - * https://javascript.info/regexp-escaping - */ - static regExpEscape(s) { - return s.replace(/[[\\^$.|?*+()]/g, '\\$&'); - } -} -exports.Pattern = Pattern; -//# sourceMappingURL=internal-pattern.js.map - -/***/ }), - -/***/ 89117: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SearchState = void 0; -class SearchState { - constructor(path, level) { - this.path = path; - this.level = level; - } -} -exports.SearchState = SearchState; -//# sourceMappingURL=internal-search-state.js.map - -/***/ }), - -/***/ 35526: -/***/ (function(__unused_webpack_module, exports) { - -"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.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; -class BasicCredentialHandler { - constructor(username, password) { - this.username = username; - this.password = password; - } - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } -} -exports.BasicCredentialHandler = BasicCredentialHandler; -class BearerCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Bearer ${this.token}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } -} -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) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } -} -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; -//# sourceMappingURL=auth.js.map - -/***/ }), - -/***/ 96255: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -/* eslint-disable @typescript-eslint/no-explicit-any */ -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.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; -const http = __importStar(__nccwpck_require__(13685)); -const https = __importStar(__nccwpck_require__(95687)); -const pm = __importStar(__nccwpck_require__(19835)); -const tunnel = __importStar(__nccwpck_require__(74294)); -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); -/** - * Returns the proxy URL, depending upon the supplied url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ -function getProxyUrl(serverUrl) { - const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; -} -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; -const ExponentialBackoffCeiling = 10; -const ExponentialBackoffTimeSlice = 5; -class HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = 'HttpClientError'; - this.statusCode = statusCode; - Object.setPrototypeOf(this, HttpClientError.prototype); - } -} -exports.HttpClientError = HttpClientError; -class HttpClientResponse { - constructor(message) { - this.message = message; - } - readBody() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - })); - }); - } -} -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - const parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; -} -exports.isHttps = isHttps; -class HttpClient { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = userAgent; - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; - } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; - } - } - } - options(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - }); - } - get(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - }); - } - del(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - }); - } - post(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - }); - } - patch(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); - }); - } - put(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - }); - } - head(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - }); - } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request(verb, requestUrl, stream, additionalHeaders); - }); - } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - getJson(requestUrl, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - const res = yield this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - postJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - putJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - patchJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - request(verb, requestUrl, data, headers) { - return __awaiter(this, void 0, void 0, function* () { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - const parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - do { - response = yield this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (const handler of this.handlers) { - if (handler.canHandleAuthentication(response)) { - authenticationHandler = handler; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); - } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. - return response; - } - } - let redirectsRemaining = this._maxRedirects; - while (response.message.statusCode && - HttpRedirectCodes.includes(response.message.statusCode) && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - const parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol === 'https:' && - parsedUrl.protocol !== parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); - } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - yield response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (const header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } - } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = yield this.requestRaw(info, data); - redirectsRemaining--; - } - if (!response.message.statusCode || - !HttpResponseRetryCodes.includes(response.message.statusCode)) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - yield response.readBody(); - yield this._performExponentialBackoff(numTries); - } - } while (numTries < maxTries); - return response; - }); - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); - } - this._disposed = true; - } - /** - * Raw request. - * @param info - * @param data - */ - requestRaw(info, data) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - function callbackForResult(err, res) { - if (err) { - reject(err); - } - else if (!res) { - // If `err` is not passed, then `res` must be passed. - reject(new Error('Unknown error')); - } - else { - resolve(res); - } - } - this.requestRawWithCallback(info, data, callbackForResult); - }); - }); - } - /** - * Raw request with callback. - * @param info - * @param data - * @param onResult - */ - requestRawWithCallback(info, data, onResult) { - if (typeof data === 'string') { - if (!info.options.headers) { - info.options.headers = {}; - } - info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); - } - let callbackCalled = false; - function handleResult(err, res) { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } - } - const req = info.httpModule.request(info.options, (msg) => { - const res = new HttpClientResponse(msg); - handleResult(undefined, res); - }); - let socket; - req.on('socket', sock => { - socket = sock; - }); - // If we ever get disconnected, we want the socket to timeout eventually - req.setTimeout(this._socketTimeout || 3 * 60000, () => { - if (socket) { - socket.end(); - } - handleResult(new Error(`Request timeout: ${info.options.path}`)); - }); - req.on('error', function (err) { - // err has statusCode property - // res should have headers - handleResult(err); - }); - if (data && typeof data === 'string') { - req.write(data, 'utf8'); - } - if (data && typeof data !== 'string') { - data.on('close', function () { - req.end(); - }); - data.pipe(req); - } - else { - req.end(); - } - } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - const parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); - } - _prepareRequest(method, requestUrl, headers) { - const info = {}; - info.parsedUrl = requestUrl; - const usingSsl = info.parsedUrl.protocol === 'https:'; - info.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info.options = {}; - info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port - ? parseInt(info.parsedUrl.port) - : defaultPort; - info.options.path = - (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); - info.options.method = method; - info.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info.options.headers['user-agent'] = this.userAgent; - } - info.options.agent = this._getAgent(info.parsedUrl); - // gives handlers an opportunity to participate - if (this.handlers) { - for (const handler of this.handlers) { - handler.prepareRequest(info.options); - } - } - return info; - } - _mergeHeaders(headers) { - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); - } - return lowercaseKeys(headers || {}); - } - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; - } - return additionalHeaders[header] || clientHeader || _default; - } - _getAgent(parsedUrl) { - let agent; - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (this._keepAlive && !useProxy) { - agent = this._agent; - } - // if agent is already assigned use that agent. - if (agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - let maxSockets = 100; - if (this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. - if (proxyUrl && proxyUrl.hostname) { - const agentOptions = { - maxSockets, - keepAlive: this._keepAlive, - proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - })), { host: proxyUrl.hostname, port: proxyUrl.port }) - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === 'https:'; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } - else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { - const options = { keepAlive: this._keepAlive, maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); - } - return agent; - } - _performExponentialBackoff(retryNumber) { - return __awaiter(this, void 0, void 0, function* () { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - }); - } - _processResponse(res, options) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - const statusCode = res.message.statusCode || 0; - const response = { - statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode === HttpCodes.NotFound) { - resolve(response); - } - // get the result from the body - function dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - const a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - let obj; - let contents; - try { - contents = yield res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, dateTimeDeserializer); - } - else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } - catch (err) { - // 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})`; - } - const err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } - else { - resolve(response); - } - })); - }); - } -} -exports.HttpClient = HttpClient; -const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 19835: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.checkBypass = exports.getProxyUrl = void 0; -function getProxyUrl(reqUrl) { - const usingSsl = reqUrl.protocol === 'https:'; - if (checkBypass(reqUrl)) { - return undefined; - } - const proxyVar = (() => { - if (usingSsl) { - return process.env['https_proxy'] || process.env['HTTPS_PROXY']; - } - else { - return process.env['http_proxy'] || process.env['HTTP_PROXY']; - } - })(); - if (proxyVar) { - return new URL(proxyVar); - } - else { - return undefined; - } -} -exports.getProxyUrl = getProxyUrl; -function checkBypass(reqUrl) { - if (!reqUrl.hostname) { - return false; - } - const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; - if (!noProxy) { - return false; - } - // Determine the request port - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); - } - else if (reqUrl.protocol === 'http:') { - reqPort = 80; - } - else if (reqUrl.protocol === 'https:') { - reqPort = 443; - } - // Format the request hostname and hostname with port - const upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === 'number') { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); - } - // Compare request host against noproxy - for (const upperNoProxyItem of noProxy - .split(',') - .map(x => x.trim().toUpperCase()) - .filter(x => x)) { - if (upperReqHosts.some(x => x === upperNoProxyItem)) { - return true; - } - } - return false; -} -exports.checkBypass = checkBypass; -//# sourceMappingURL=proxy.js.map - -/***/ }), - -/***/ 81962: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var _a; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rename = exports.readlink = exports.readdir = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; -const fs = __importStar(__nccwpck_require__(57147)); -const path = __importStar(__nccwpck_require__(71017)); -_a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; -exports.IS_WINDOWS = process.platform === 'win32'; -function exists(fsPath) { - return __awaiter(this, void 0, void 0, function* () { - try { - yield exports.stat(fsPath); - } - catch (err) { - if (err.code === 'ENOENT') { - return false; - } - throw err; - } - return true; - }); -} -exports.exists = exists; -function isDirectory(fsPath, useStat = false) { - return __awaiter(this, void 0, void 0, function* () { - const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); - return stats.isDirectory(); - }); -} -exports.isDirectory = isDirectory; -/** - * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: - * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). - */ -function isRooted(p) { - p = normalizeSeparators(p); - if (!p) { - throw new Error('isRooted() parameter "p" cannot be empty'); - } - if (exports.IS_WINDOWS) { - return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello - ); // e.g. C: or C:\hello - } - return p.startsWith('/'); -} -exports.isRooted = isRooted; -/** - * Best effort attempt to determine whether a file exists and is executable. - * @param filePath file path to check - * @param extensions additional file extensions to try - * @return if file exists and is executable, returns the file path. otherwise empty string. - */ -function tryGetExecutablePath(filePath, extensions) { - return __awaiter(this, void 0, void 0, function* () { - let stats = undefined; - try { - // test file exists - stats = yield exports.stat(filePath); - } - catch (err) { - if (err.code !== 'ENOENT') { - // eslint-disable-next-line no-console - console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); - } - } - if (stats && stats.isFile()) { - if (exports.IS_WINDOWS) { - // on Windows, test for valid extension - const upperExt = path.extname(filePath).toUpperCase(); - if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { - return filePath; - } - } - else { - if (isUnixExecutable(stats)) { - return filePath; - } - } - } - // try each extension - const originalFilePath = filePath; - for (const extension of extensions) { - filePath = originalFilePath + extension; - stats = undefined; - try { - stats = yield exports.stat(filePath); - } - catch (err) { - if (err.code !== 'ENOENT') { - // eslint-disable-next-line no-console - console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); - } - } - if (stats && stats.isFile()) { - if (exports.IS_WINDOWS) { - // preserve the case of the actual file (since an extension was appended) - try { - const directory = path.dirname(filePath); - const upperName = path.basename(filePath).toUpperCase(); - for (const actualName of yield exports.readdir(directory)) { - if (upperName === actualName.toUpperCase()) { - filePath = path.join(directory, actualName); - break; - } - } - } - catch (err) { - // eslint-disable-next-line no-console - console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); - } - return filePath; - } - else { - if (isUnixExecutable(stats)) { - return filePath; - } - } - } - } - return ''; - }); -} -exports.tryGetExecutablePath = tryGetExecutablePath; -function normalizeSeparators(p) { - p = p || ''; - if (exports.IS_WINDOWS) { - // convert slashes on Windows - p = p.replace(/\//g, '\\'); - // remove redundant slashes - return p.replace(/\\\\+/g, '\\'); - } - // remove redundant slashes - return p.replace(/\/\/+/g, '/'); -} -// on Mac/Linux, test the execute bit -// R W X R W X R W X -// 256 128 64 32 16 8 4 2 1 -function isUnixExecutable(stats) { - return ((stats.mode & 1) > 0 || - ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || - ((stats.mode & 64) > 0 && stats.uid === process.getuid())); -} -// Get the path of cmd.exe in windows -function getCmdPath() { - var _a; - return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; -} -exports.getCmdPath = getCmdPath; -//# sourceMappingURL=io-util.js.map - -/***/ }), - -/***/ 47351: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; -const assert_1 = __nccwpck_require__(39491); -const childProcess = __importStar(__nccwpck_require__(32081)); -const path = __importStar(__nccwpck_require__(71017)); -const util_1 = __nccwpck_require__(73837); -const ioUtil = __importStar(__nccwpck_require__(81962)); -const exec = util_1.promisify(childProcess.exec); -const execFile = util_1.promisify(childProcess.execFile); -/** - * Copies a file or folder. - * Based off of shelljs - /~https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js - * - * @param source source path - * @param dest destination path - * @param options optional. See CopyOptions. - */ -function cp(source, dest, options = {}) { - return __awaiter(this, void 0, void 0, function* () { - const { force, recursive, copySourceDirectory } = readCopyOptions(options); - const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; - // Dest is an existing file, but not forcing - if (destStat && destStat.isFile() && !force) { - return; - } - // If dest is an existing directory, should copy inside. - const newDest = destStat && destStat.isDirectory() && copySourceDirectory - ? path.join(dest, path.basename(source)) - : dest; - if (!(yield ioUtil.exists(source))) { - throw new Error(`no such file or directory: ${source}`); - } - const sourceStat = yield ioUtil.stat(source); - if (sourceStat.isDirectory()) { - if (!recursive) { - throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); - } - else { - yield cpDirRecursive(source, newDest, 0, force); - } - } - else { - if (path.relative(source, newDest) === '') { - // a file cannot be copied to itself - throw new Error(`'${newDest}' and '${source}' are the same file`); - } - yield copyFile(source, newDest, force); - } - }); -} -exports.cp = cp; -/** - * Moves a path. - * - * @param source source path - * @param dest destination path - * @param options optional. See MoveOptions. - */ -function mv(source, dest, options = {}) { - return __awaiter(this, void 0, void 0, function* () { - if (yield ioUtil.exists(dest)) { - let destExists = true; - if (yield ioUtil.isDirectory(dest)) { - // If dest is directory copy src into dest - dest = path.join(dest, path.basename(source)); - destExists = yield ioUtil.exists(dest); - } - if (destExists) { - if (options.force == null || options.force) { - yield rmRF(dest); - } - else { - throw new Error('Destination already exists'); - } - } - } - yield mkdirP(path.dirname(dest)); - yield ioUtil.rename(source, dest); - }); -} -exports.mv = mv; -/** - * Remove a path recursively with force - * - * @param inputPath path to remove - */ -function rmRF(inputPath) { - return __awaiter(this, void 0, void 0, function* () { - if (ioUtil.IS_WINDOWS) { - // Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another - // program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del. - // Check for invalid characters - // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file - if (/[*"<>|]/.test(inputPath)) { - throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); - } - try { - const cmdPath = ioUtil.getCmdPath(); - if (yield ioUtil.isDirectory(inputPath, true)) { - yield exec(`${cmdPath} /s /c "rd /s /q "%inputPath%""`, { - env: { inputPath } - }); - } - else { - yield exec(`${cmdPath} /s /c "del /f /a "%inputPath%""`, { - env: { inputPath } - }); - } - } - catch (err) { - // if you try to delete a file that doesn't exist, desired result is achieved - // other errors are valid - if (err.code !== 'ENOENT') - throw err; - } - // Shelling out fails to remove a symlink folder with missing source, this unlink catches that - try { - yield ioUtil.unlink(inputPath); - } - catch (err) { - // if you try to delete a file that doesn't exist, desired result is achieved - // other errors are valid - if (err.code !== 'ENOENT') - throw err; - } - } - else { - let isDir = false; - try { - isDir = yield ioUtil.isDirectory(inputPath); - } - catch (err) { - // if you try to delete a file that doesn't exist, desired result is achieved - // other errors are valid - if (err.code !== 'ENOENT') - throw err; - return; - } - if (isDir) { - yield execFile(`rm`, [`-rf`, `${inputPath}`]); - } - else { - yield ioUtil.unlink(inputPath); - } - } - }); -} -exports.rmRF = rmRF; -/** - * Make a directory. Creates the full path with folders in between - * Will throw if it fails - * - * @param fsPath path to create - * @returns Promise - */ -function mkdirP(fsPath) { - return __awaiter(this, void 0, void 0, function* () { - assert_1.ok(fsPath, 'a path argument must be provided'); - yield ioUtil.mkdir(fsPath, { recursive: true }); - }); -} -exports.mkdirP = mkdirP; -/** - * Returns path of a tool had the tool actually been invoked. Resolves via paths. - * If you check and the tool does not exist, it will throw. - * - * @param tool name of the tool - * @param check whether to check if tool exists - * @returns Promise path to tool - */ -function which(tool, check) { - return __awaiter(this, void 0, void 0, function* () { - if (!tool) { - throw new Error("parameter 'tool' is required"); - } - // recursive when check=true - if (check) { - const result = yield which(tool, false); - if (!result) { - if (ioUtil.IS_WINDOWS) { - throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); - } - else { - throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); - } - } - return result; - } - const matches = yield findInPath(tool); - if (matches && matches.length > 0) { - return matches[0]; - } - return ''; - }); -} -exports.which = which; -/** - * Returns a list of all occurrences of the given tool on the system path. - * - * @returns Promise the paths of the tool - */ -function findInPath(tool) { - return __awaiter(this, void 0, void 0, function* () { - if (!tool) { - throw new Error("parameter 'tool' is required"); - } - // build the list of extensions to try - const extensions = []; - if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) { - for (const extension of process.env['PATHEXT'].split(path.delimiter)) { - if (extension) { - extensions.push(extension); - } - } - } - // if it's rooted, return it if exists. otherwise return empty. - if (ioUtil.isRooted(tool)) { - const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); - if (filePath) { - return [filePath]; - } - return []; - } - // if any path separators, return empty - if (tool.includes(path.sep)) { - return []; - } - // build the list of directories - // - // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, - // it feels like we should not do this. Checking the current directory seems like more of a use - // case of a shell, and the which() function exposed by the toolkit should strive for consistency - // across platforms. - const directories = []; - if (process.env.PATH) { - for (const p of process.env.PATH.split(path.delimiter)) { - if (p) { - directories.push(p); - } - } - } - // find all matches - const matches = []; - for (const directory of directories) { - const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); - if (filePath) { - matches.push(filePath); - } - } - return matches; - }); -} -exports.findInPath = findInPath; -function readCopyOptions(options) { - const force = options.force == null ? true : options.force; - const recursive = Boolean(options.recursive); - const copySourceDirectory = options.copySourceDirectory == null - ? true - : Boolean(options.copySourceDirectory); - return { force, recursive, copySourceDirectory }; -} -function cpDirRecursive(sourceDir, destDir, currentDepth, force) { - return __awaiter(this, void 0, void 0, function* () { - // Ensure there is not a run away recursive copy - if (currentDepth >= 255) - return; - currentDepth++; - yield mkdirP(destDir); - const files = yield ioUtil.readdir(sourceDir); - for (const fileName of files) { - const srcFile = `${sourceDir}/${fileName}`; - const destFile = `${destDir}/${fileName}`; - const srcFileStat = yield ioUtil.lstat(srcFile); - if (srcFileStat.isDirectory()) { - // Recurse - yield cpDirRecursive(srcFile, destFile, currentDepth, force); - } - else { - yield copyFile(srcFile, destFile, force); - } - } - // Change the mode for the newly created directory - yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); - }); -} -// Buffered file copy -function copyFile(srcFile, destFile, force) { - return __awaiter(this, void 0, void 0, function* () { - if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { - // unlink/re-link it - try { - yield ioUtil.lstat(destFile); - yield ioUtil.unlink(destFile); - } - catch (e) { - // Try to override file permission - if (e.code === 'EPERM') { - yield ioUtil.chmod(destFile, '0666'); - yield ioUtil.unlink(destFile); - } - // other errors = it doesn't exist, no work to do - } - // Copy over symlink - const symlinkFull = yield ioUtil.readlink(srcFile); - yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); - } - else if (!(yield ioUtil.exists(destFile)) || force) { - yield ioUtil.copyFile(srcFile, destFile); - } - }); -} -//# sourceMappingURL=io.js.map - -/***/ }), - -/***/ 32473: -/***/ (function(module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports._readLinuxVersionFile = exports._getOsVersion = exports._findMatch = void 0; -const semver = __importStar(__nccwpck_require__(70562)); -const core_1 = __nccwpck_require__(42186); -// needs to be require for core node modules to be mocked -/* eslint @typescript-eslint/no-require-imports: 0 */ -const os = __nccwpck_require__(22037); -const cp = __nccwpck_require__(32081); -const fs = __nccwpck_require__(57147); -function _findMatch(versionSpec, stable, candidates, archFilter) { - return __awaiter(this, void 0, void 0, function* () { - const platFilter = os.platform(); - let result; - let match; - let file; - for (const candidate of candidates) { - const version = candidate.version; - core_1.debug(`check ${version} satisfies ${versionSpec}`); - if (semver.satisfies(version, versionSpec) && - (!stable || candidate.stable === stable)) { - file = candidate.files.find(item => { - core_1.debug(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); - let chk = item.arch === archFilter && item.platform === platFilter; - if (chk && item.platform_version) { - const osVersion = module.exports._getOsVersion(); - if (osVersion === item.platform_version) { - chk = true; - } - else { - chk = semver.satisfies(osVersion, item.platform_version); - } - } - return chk; - }); - if (file) { - core_1.debug(`matched ${candidate.version}`); - match = candidate; - break; - } - } - } - if (match && file) { - // clone since we're mutating the file list to be only the file that matches - result = Object.assign({}, match); - result.files = [file]; - } - return result; - }); -} -exports._findMatch = _findMatch; -function _getOsVersion() { - // TODO: add windows and other linux, arm variants - // right now filtering on version is only an ubuntu and macos scenario for tools we build for hosted (python) - const plat = os.platform(); - let version = ''; - if (plat === 'darwin') { - version = cp.execSync('sw_vers -productVersion').toString(); - } - else if (plat === 'linux') { - // lsb_release process not in some containers, readfile - // Run cat /etc/lsb-release - // DISTRIB_ID=Ubuntu - // DISTRIB_RELEASE=18.04 - // DISTRIB_CODENAME=bionic - // DISTRIB_DESCRIPTION="Ubuntu 18.04.4 LTS" - const lsbContents = module.exports._readLinuxVersionFile(); - if (lsbContents) { - const lines = lsbContents.split('\n'); - for (const line of lines) { - const parts = line.split('='); - if (parts.length === 2 && - (parts[0].trim() === 'VERSION_ID' || - parts[0].trim() === 'DISTRIB_RELEASE')) { - version = parts[1] - .trim() - .replace(/^"/, '') - .replace(/"$/, ''); - break; - } - } - } - } - return version; -} -exports._getOsVersion = _getOsVersion; -function _readLinuxVersionFile() { - const lsbReleaseFile = '/etc/lsb-release'; - const osReleaseFile = '/etc/os-release'; - let contents = ''; - if (fs.existsSync(lsbReleaseFile)) { - contents = fs.readFileSync(lsbReleaseFile).toString(); - } - else if (fs.existsSync(osReleaseFile)) { - contents = fs.readFileSync(osReleaseFile).toString(); - } - return contents; -} -exports._readLinuxVersionFile = _readLinuxVersionFile; -//# sourceMappingURL=manifest.js.map - -/***/ }), - -/***/ 38279: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RetryHelper = void 0; -const core = __importStar(__nccwpck_require__(42186)); -/** - * Internal class for retries - */ -class RetryHelper { - constructor(maxAttempts, minSeconds, maxSeconds) { - if (maxAttempts < 1) { - throw new Error('max attempts should be greater than or equal to 1'); - } - this.maxAttempts = maxAttempts; - this.minSeconds = Math.floor(minSeconds); - this.maxSeconds = Math.floor(maxSeconds); - if (this.minSeconds > this.maxSeconds) { - throw new Error('min seconds should be less than or equal to max seconds'); - } - } - execute(action, isRetryable) { - return __awaiter(this, void 0, void 0, function* () { - let attempt = 1; - while (attempt < this.maxAttempts) { - // Try - try { - return yield action(); - } - catch (err) { - if (isRetryable && !isRetryable(err)) { - throw err; - } - core.info(err.message); - } - // Sleep - const seconds = this.getSleepAmount(); - core.info(`Waiting ${seconds} seconds before trying again`); - yield this.sleep(seconds); - attempt++; - } - // Last attempt - return yield action(); - }); - } - getSleepAmount() { - return (Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + - this.minSeconds); - } - sleep(seconds) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise(resolve => setTimeout(resolve, seconds * 1000)); - }); - } -} -exports.RetryHelper = RetryHelper; -//# sourceMappingURL=retry-helper.js.map - -/***/ }), - -/***/ 27784: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.evaluateVersions = exports.isExplicitVersion = exports.findFromManifest = exports.getManifestFromRepo = exports.findAllVersions = exports.find = exports.cacheFile = exports.cacheDir = exports.extractZip = exports.extractXar = exports.extractTar = exports.extract7z = exports.downloadTool = exports.HTTPError = void 0; -const core = __importStar(__nccwpck_require__(42186)); -const io = __importStar(__nccwpck_require__(47351)); -const fs = __importStar(__nccwpck_require__(57147)); -const mm = __importStar(__nccwpck_require__(32473)); -const os = __importStar(__nccwpck_require__(22037)); -const path = __importStar(__nccwpck_require__(71017)); -const httpm = __importStar(__nccwpck_require__(96255)); -const semver = __importStar(__nccwpck_require__(70562)); -const stream = __importStar(__nccwpck_require__(12781)); -const util = __importStar(__nccwpck_require__(73837)); -const assert_1 = __nccwpck_require__(39491); -const v4_1 = __importDefault(__nccwpck_require__(17468)); -const exec_1 = __nccwpck_require__(71514); -const retry_helper_1 = __nccwpck_require__(38279); -class HTTPError extends Error { - constructor(httpStatusCode) { - super(`Unexpected HTTP response: ${httpStatusCode}`); - this.httpStatusCode = httpStatusCode; - Object.setPrototypeOf(this, new.target.prototype); - } -} -exports.HTTPError = HTTPError; -const IS_WINDOWS = process.platform === 'win32'; -const IS_MAC = process.platform === 'darwin'; -const userAgent = 'actions/tool-cache'; -/** - * Download a tool from an url and stream it into a file - * - * @param url url of tool to download - * @param dest path to download tool - * @param auth authorization header - * @param headers other headers - * @returns path to downloaded tool - */ -function downloadTool(url, dest, auth, headers) { - return __awaiter(this, void 0, void 0, function* () { - dest = dest || path.join(_getTempDirectory(), v4_1.default()); - yield io.mkdirP(path.dirname(dest)); - core.debug(`Downloading ${url}`); - core.debug(`Destination ${dest}`); - const maxAttempts = 3; - const minSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS', 10); - const maxSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS', 20); - const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); - return yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { - return yield downloadToolAttempt(url, dest || '', auth, headers); - }), (err) => { - if (err instanceof HTTPError && err.httpStatusCode) { - // Don't retry anything less than 500, except 408 Request Timeout and 429 Too Many Requests - if (err.httpStatusCode < 500 && - err.httpStatusCode !== 408 && - err.httpStatusCode !== 429) { - return false; - } - } - // Otherwise retry - return true; - }); - }); -} -exports.downloadTool = downloadTool; -function downloadToolAttempt(url, dest, auth, headers) { - return __awaiter(this, void 0, void 0, function* () { - if (fs.existsSync(dest)) { - throw new Error(`Destination file path ${dest} already exists`); - } - // Get the response headers - const http = new httpm.HttpClient(userAgent, [], { - allowRetries: false - }); - if (auth) { - core.debug('set auth'); - if (headers === undefined) { - headers = {}; - } - headers.authorization = auth; - } - const response = yield http.get(url, headers); - if (response.message.statusCode !== 200) { - const err = new HTTPError(response.message.statusCode); - core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); - throw err; - } - // Download the response body - const pipeline = util.promisify(stream.pipeline); - const responseMessageFactory = _getGlobal('TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY', () => response.message); - const readStream = responseMessageFactory(); - let succeeded = false; - try { - yield pipeline(readStream, fs.createWriteStream(dest)); - core.debug('download complete'); - succeeded = true; - return dest; - } - finally { - // Error, delete dest before retry - if (!succeeded) { - core.debug('download failed'); - try { - yield io.rmRF(dest); - } - catch (err) { - core.debug(`Failed to delete '${dest}'. ${err.message}`); - } - } - } - }); -} -/** - * Extract a .7z file - * - * @param file path to the .7z file - * @param dest destination directory. Optional. - * @param _7zPath path to 7zr.exe. Optional, for long path support. Most .7z archives do not have this - * problem. If your .7z archive contains very long paths, you can pass the path to 7zr.exe which will - * gracefully handle long paths. By default 7zdec.exe is used because it is a very small program and is - * bundled with the tool lib. However it does not support long paths. 7zr.exe is the reduced command line - * interface, it is smaller than the full command line interface, and it does support long paths. At the - * time of this writing, it is freely available from the LZMA SDK that is available on the 7zip website. - * Be sure to check the current license agreement. If 7zr.exe is bundled with your action, then the path - * to 7zr.exe can be pass to this function. - * @returns path to the destination directory - */ -function extract7z(file, dest, _7zPath) { - return __awaiter(this, void 0, void 0, function* () { - assert_1.ok(IS_WINDOWS, 'extract7z() not supported on current OS'); - assert_1.ok(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - const originalCwd = process.cwd(); - process.chdir(dest); - if (_7zPath) { - try { - const logLevel = core.isDebug() ? '-bb1' : '-bb0'; - const args = [ - 'x', - logLevel, - '-bd', - '-sccUTF-8', - file - ]; - const options = { - silent: true - }; - yield exec_1.exec(`"${_7zPath}"`, args, options); - } - finally { - process.chdir(originalCwd); - } - } - else { - const escapedScript = path - .join(__dirname, '..', 'scripts', 'Invoke-7zdec.ps1') - .replace(/'/g, "''") - .replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); - const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ''); - const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; - const args = [ - '-NoLogo', - '-Sta', - '-NoProfile', - '-NonInteractive', - '-ExecutionPolicy', - 'Unrestricted', - '-Command', - command - ]; - const options = { - silent: true - }; - try { - const powershellPath = yield io.which('powershell', true); - yield exec_1.exec(`"${powershellPath}"`, args, options); - } - finally { - process.chdir(originalCwd); - } - } - return dest; - }); -} -exports.extract7z = extract7z; -/** - * Extract a compressed tar archive - * - * @param file path to the tar - * @param dest destination directory. Optional. - * @param flags flags for the tar command to use for extraction. Defaults to 'xz' (extracting gzipped tars). Optional. - * @returns path to the destination directory - */ -function extractTar(file, dest, flags = 'xz') { - return __awaiter(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); - } - // Create dest - dest = yield _createExtractFolder(dest); - // Determine whether GNU tar - core.debug('Checking tar --version'); - let versionOutput = ''; - yield exec_1.exec('tar --version', [], { - ignoreReturnCode: true, - silent: true, - listeners: { - stdout: (data) => (versionOutput += data.toString()), - stderr: (data) => (versionOutput += data.toString()) - } - }); - core.debug(versionOutput.trim()); - const isGnuTar = versionOutput.toUpperCase().includes('GNU TAR'); - // Initialize args - let args; - if (flags instanceof Array) { - args = flags; - } - else { - args = [flags]; - } - if (core.isDebug() && !flags.includes('v')) { - args.push('-v'); - } - let destArg = dest; - let fileArg = file; - if (IS_WINDOWS && isGnuTar) { - args.push('--force-local'); - destArg = dest.replace(/\\/g, '/'); - // Technically only the dest needs to have `/` but for aesthetic consistency - // convert slashes in the file arg too. - fileArg = file.replace(/\\/g, '/'); - } - if (isGnuTar) { - // Suppress warnings when using GNU tar to extract archives created by BSD tar - args.push('--warning=no-unknown-keyword'); - args.push('--overwrite'); - } - args.push('-C', destArg, '-f', fileArg); - yield exec_1.exec(`tar`, args); - return dest; - }); -} -exports.extractTar = extractTar; -/** - * Extract a xar compatible archive - * - * @param file path to the archive - * @param dest destination directory. Optional. - * @param flags flags for the xar. Optional. - * @returns path to the destination directory - */ -function extractXar(file, dest, flags = []) { - return __awaiter(this, void 0, void 0, function* () { - assert_1.ok(IS_MAC, 'extractXar() not supported on current OS'); - assert_1.ok(file, 'parameter "file" is required'); - dest = yield _createExtractFolder(dest); - let args; - if (flags instanceof Array) { - args = flags; - } - else { - args = [flags]; - } - args.push('-x', '-C', dest, '-f', file); - if (core.isDebug()) { - args.push('-v'); - } - const xarPath = yield io.which('xar', true); - yield exec_1.exec(`"${xarPath}"`, _unique(args)); - return dest; - }); -} -exports.extractXar = extractXar; -/** - * Extract a zip - * - * @param file path to the zip - * @param dest destination directory. Optional. - * @returns path to the destination directory - */ -function extractZip(file, dest) { - return __awaiter(this, void 0, void 0, function* () { - if (!file) { - throw new Error("parameter 'file' is required"); - } - dest = yield _createExtractFolder(dest); - if (IS_WINDOWS) { - yield extractZipWin(file, dest); - } - else { - yield extractZipNix(file, dest); - } - return dest; - }); -} -exports.extractZip = extractZip; -function extractZipWin(file, dest) { - return __awaiter(this, void 0, void 0, function* () { - // build the powershell command - const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines - const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ''); - const pwshPath = yield io.which('pwsh', false); - //To match the file overwrite behavior on nix systems, we use the overwrite = true flag for ExtractToDirectory - //and the -Force flag for Expand-Archive as a fallback - if (pwshPath) { - //attempt to use pwsh with ExtractToDirectory, if this fails attempt Expand-Archive - const pwshCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, - `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, - `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` - ].join(' '); - const args = [ - '-NoLogo', - '-NoProfile', - '-NonInteractive', - '-ExecutionPolicy', - 'Unrestricted', - '-Command', - pwshCommand - ]; - core.debug(`Using pwsh at path: ${pwshPath}`); - yield exec_1.exec(`"${pwshPath}"`, args); - } - else { - const powershellCommand = [ - `$ErrorActionPreference = 'Stop' ;`, - `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, - `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, - `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` - ].join(' '); - const args = [ - '-NoLogo', - '-Sta', - '-NoProfile', - '-NonInteractive', - '-ExecutionPolicy', - 'Unrestricted', - '-Command', - powershellCommand - ]; - const powershellPath = yield io.which('powershell', true); - core.debug(`Using powershell at path: ${powershellPath}`); - yield exec_1.exec(`"${powershellPath}"`, args); - } - }); -} -function extractZipNix(file, dest) { - return __awaiter(this, void 0, void 0, function* () { - const unzipPath = yield io.which('unzip', true); - const args = [file]; - if (!core.isDebug()) { - args.unshift('-q'); - } - args.unshift('-o'); //overwrite with -o, otherwise a prompt is shown which freezes the run - yield exec_1.exec(`"${unzipPath}"`, args, { cwd: dest }); - }); -} -/** - * Caches a directory and installs it into the tool cacheDir - * - * @param sourceDir the directory to cache into tools - * @param tool tool name - * @param version version of the tool. semver format - * @param arch architecture of the tool. Optional. Defaults to machine architecture - */ -function cacheDir(sourceDir, tool, version, arch) { - return __awaiter(this, void 0, void 0, function* () { - version = semver.clean(version) || version; - arch = arch || os.arch(); - core.debug(`Caching tool ${tool} ${version} ${arch}`); - core.debug(`source dir: ${sourceDir}`); - if (!fs.statSync(sourceDir).isDirectory()) { - throw new Error('sourceDir is not a directory'); - } - // Create the tool dir - const destPath = yield _createToolPath(tool, version, arch); - // copy each child item. do not move. move can fail on Windows - // due to anti-virus software having an open handle on a file. - for (const itemName of fs.readdirSync(sourceDir)) { - const s = path.join(sourceDir, itemName); - yield io.cp(s, destPath, { recursive: true }); - } - // write .complete - _completeToolPath(tool, version, arch); - return destPath; - }); -} -exports.cacheDir = cacheDir; -/** - * Caches a downloaded file (GUID) and installs it - * into the tool cache with a given targetName - * - * @param sourceFile the file to cache into tools. Typically a result of downloadTool which is a guid. - * @param targetFile the name of the file name in the tools directory - * @param tool tool name - * @param version version of the tool. semver format - * @param arch architecture of the tool. Optional. Defaults to machine architecture - */ -function cacheFile(sourceFile, targetFile, tool, version, arch) { - return __awaiter(this, void 0, void 0, function* () { - version = semver.clean(version) || version; - arch = arch || os.arch(); - core.debug(`Caching tool ${tool} ${version} ${arch}`); - core.debug(`source file: ${sourceFile}`); - if (!fs.statSync(sourceFile).isFile()) { - throw new Error('sourceFile is not a file'); - } - // create the tool dir - const destFolder = yield _createToolPath(tool, version, arch); - // copy instead of move. move can fail on Windows due to - // anti-virus software having an open handle on a file. - const destPath = path.join(destFolder, targetFile); - core.debug(`destination file ${destPath}`); - yield io.cp(sourceFile, destPath); - // write .complete - _completeToolPath(tool, version, arch); - return destFolder; - }); -} -exports.cacheFile = cacheFile; -/** - * Finds the path to a tool version in the local installed tool cache - * - * @param toolName name of the tool - * @param versionSpec version of the tool - * @param arch optional arch. defaults to arch of computer - */ -function find(toolName, versionSpec, arch) { - if (!toolName) { - throw new Error('toolName parameter is required'); - } - if (!versionSpec) { - throw new Error('versionSpec parameter is required'); - } - arch = arch || os.arch(); - // attempt to resolve an explicit version - if (!isExplicitVersion(versionSpec)) { - const localVersions = findAllVersions(toolName, arch); - const match = evaluateVersions(localVersions, versionSpec); - versionSpec = match; - } - // check for the explicit version in the cache - let toolPath = ''; - if (versionSpec) { - versionSpec = semver.clean(versionSpec) || ''; - const cachePath = path.join(_getCacheDirectory(), toolName, versionSpec, arch); - core.debug(`checking cache: ${cachePath}`); - if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) { - core.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); - toolPath = cachePath; - } - else { - core.debug('not found'); - } - } - return toolPath; -} -exports.find = find; -/** - * Finds the paths to all versions of a tool that are installed in the local tool cache - * - * @param toolName name of the tool - * @param arch optional arch. defaults to arch of computer - */ -function findAllVersions(toolName, arch) { - const versions = []; - arch = arch || os.arch(); - const toolPath = path.join(_getCacheDirectory(), toolName); - if (fs.existsSync(toolPath)) { - const children = fs.readdirSync(toolPath); - for (const child of children) { - if (isExplicitVersion(child)) { - const fullPath = path.join(toolPath, child, arch || ''); - if (fs.existsSync(fullPath) && fs.existsSync(`${fullPath}.complete`)) { - versions.push(child); - } - } - } - } - return versions; -} -exports.findAllVersions = findAllVersions; -function getManifestFromRepo(owner, repo, auth, branch = 'master') { - return __awaiter(this, void 0, void 0, function* () { - let releases = []; - const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; - const http = new httpm.HttpClient('tool-cache'); - const headers = {}; - if (auth) { - core.debug('set auth'); - headers.authorization = auth; - } - const response = yield http.getJson(treeUrl, headers); - if (!response.result) { - return releases; - } - let manifestUrl = ''; - for (const item of response.result.tree) { - if (item.path === 'versions-manifest.json') { - manifestUrl = item.url; - break; - } - } - headers['accept'] = 'application/vnd.github.VERSION.raw'; - let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); - if (versionsRaw) { - // shouldn't be needed but protects against invalid json saved with BOM - versionsRaw = versionsRaw.replace(/^\uFEFF/, ''); - try { - releases = JSON.parse(versionsRaw); - } - catch (_a) { - core.debug('Invalid json'); - } - } - return releases; - }); -} -exports.getManifestFromRepo = getManifestFromRepo; -function findFromManifest(versionSpec, stable, manifest, archFilter = os.arch()) { - return __awaiter(this, void 0, void 0, function* () { - // wrap the internal impl - const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); - return match; - }); -} -exports.findFromManifest = findFromManifest; -function _createExtractFolder(dest) { - return __awaiter(this, void 0, void 0, function* () { - if (!dest) { - // create a temp dir - dest = path.join(_getTempDirectory(), v4_1.default()); - } - yield io.mkdirP(dest); - return dest; - }); -} -function _createToolPath(tool, version, arch) { - return __awaiter(this, void 0, void 0, function* () { - const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || ''); - core.debug(`destination ${folderPath}`); - const markerPath = `${folderPath}.complete`; - yield io.rmRF(folderPath); - yield io.rmRF(markerPath); - yield io.mkdirP(folderPath); - return folderPath; - }); -} -function _completeToolPath(tool, version, arch) { - const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || ''); - const markerPath = `${folderPath}.complete`; - fs.writeFileSync(markerPath, ''); - core.debug('finished caching tool'); -} -/** - * Check if version string is explicit - * - * @param versionSpec version string to check - */ -function isExplicitVersion(versionSpec) { - const c = semver.clean(versionSpec) || ''; - core.debug(`isExplicit: ${c}`); - const valid = semver.valid(c) != null; - core.debug(`explicit? ${valid}`); - return valid; -} -exports.isExplicitVersion = isExplicitVersion; -/** - * Get the highest satisfiying semantic version in `versions` which satisfies `versionSpec` - * - * @param versions array of versions to evaluate - * @param versionSpec semantic version spec to satisfy - */ -function evaluateVersions(versions, versionSpec) { - let version = ''; - core.debug(`evaluating ${versions.length} versions`); - versions = versions.sort((a, b) => { - if (semver.gt(a, b)) { - return 1; - } - return -1; - }); - for (let i = versions.length - 1; i >= 0; i--) { - const potential = versions[i]; - const satisfied = semver.satisfies(potential, versionSpec); - if (satisfied) { - version = potential; - break; - } - } - if (version) { - core.debug(`matched: ${version}`); - } - else { - core.debug('match not found'); - } - return version; -} -exports.evaluateVersions = evaluateVersions; -/** - * Gets RUNNER_TOOL_CACHE - */ -function _getCacheDirectory() { - const cacheDirectory = process.env['RUNNER_TOOL_CACHE'] || ''; - assert_1.ok(cacheDirectory, 'Expected RUNNER_TOOL_CACHE to be defined'); - return cacheDirectory; -} -/** - * Gets RUNNER_TEMP - */ -function _getTempDirectory() { - const tempDirectory = process.env['RUNNER_TEMP'] || ''; - assert_1.ok(tempDirectory, 'Expected RUNNER_TEMP to be defined'); - return tempDirectory; -} -/** - * Gets a global variable - */ -function _getGlobal(key, defaultValue) { - /* eslint-disable @typescript-eslint/no-explicit-any */ - const value = global[key]; - /* eslint-enable @typescript-eslint/no-explicit-any */ - return value !== undefined ? value : defaultValue; -} -/** - * Returns an array of unique values. - * @param values Values to make unique. - */ -function _unique(values) { - return Array.from(new Set(values)); -} -//# sourceMappingURL=tool-cache.js.map - -/***/ }), - -/***/ 70562: -/***/ ((module, exports) => { - -exports = module.exports = SemVer - -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 () {} -} - -// 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 MAX_LENGTH = 256 -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 - -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16 - -// The actual regexps go on exports.re -var re = exports.re = [] -var src = exports.src = [] -var t = exports.tokens = {} -var R = 0 - -function tok (n) { - t[n] = R++ -} - -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. - -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. - -tok('NUMERICIDENTIFIER') -src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*' -tok('NUMERICIDENTIFIERLOOSE') -src[t.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. - -tok('NONNUMERICIDENTIFIER') -src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' - -// ## Main Version -// Three dot-separated numeric identifiers. - -tok('MAINVERSION') -src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + - '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + - '(' + src[t.NUMERICIDENTIFIER] + ')' - -tok('MAINVERSIONLOOSE') -src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')' - -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. - -tok('PRERELEASEIDENTIFIER') -src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + - '|' + src[t.NONNUMERICIDENTIFIER] + ')' - -tok('PRERELEASEIDENTIFIERLOOSE') -src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + - '|' + src[t.NONNUMERICIDENTIFIER] + ')' - -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. - -tok('PRERELEASE') -src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + - '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))' - -tok('PRERELEASELOOSE') -src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))' - -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. - -tok('BUILDIDENTIFIER') -src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+' - -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. - -tok('BUILD') -src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + - '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))' - -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. - -// 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. - -tok('FULL') -tok('FULLPLAIN') -src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + - src[t.PRERELEASE] + '?' + - src[t.BUILD] + '?' - -src[t.FULL] = '^' + src[t.FULLPLAIN] + '$' - -// 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. -tok('LOOSEPLAIN') -src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + - src[t.PRERELEASELOOSE] + '?' + - src[t.BUILD] + '?' - -tok('LOOSE') -src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$' - -tok('GTLT') -src[t.GTLT] = '((?:<|>)?=?)' - -// 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. -tok('XRANGEIDENTIFIERLOOSE') -src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' -tok('XRANGEIDENTIFIER') -src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*' - -tok('XRANGEPLAIN') -src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + - '(?:' + src[t.PRERELEASE] + ')?' + - src[t.BUILD] + '?' + - ')?)?' - -tok('XRANGEPLAINLOOSE') -src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[t.PRERELEASELOOSE] + ')?' + - src[t.BUILD] + '?' + - ')?)?' - -tok('XRANGE') -src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$' -tok('XRANGELOOSE') -src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$' - -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -tok('COERCE') -src[t.COERCE] = '(^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])' -tok('COERCERTL') -re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g') - -// Tilde ranges. -// Meaning is "reasonably at or greater than" -tok('LONETILDE') -src[t.LONETILDE] = '(?:~>?)' - -tok('TILDETRIM') -src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+' -re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g') -var tildeTrimReplace = '$1~' - -tok('TILDE') -src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$' -tok('TILDELOOSE') -src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$' - -// Caret ranges. -// Meaning is "at least and backwards compatible with" -tok('LONECARET') -src[t.LONECARET] = '(?:\\^)' - -tok('CARETTRIM') -src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+' -re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g') -var caretTrimReplace = '$1^' - -tok('CARET') -src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$' -tok('CARETLOOSE') -src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$' - -// A simple gt/lt/eq thing, or just "" to indicate "any version" -tok('COMPARATORLOOSE') -src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$' -tok('COMPARATOR') -src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$' - -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -tok('COMPARATORTRIM') -src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + - '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')' - -// this one has to use the /g flag -re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g') -var comparatorTrimReplace = '$1$2$3' - -// 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. -tok('HYPHENRANGE') -src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[t.XRANGEPLAIN] + ')' + - '\\s*$' - -tok('HYPHENRANGELOOSE') -src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[t.XRANGEPLAINLOOSE] + ')' + - '\\s*$' - -// Star ranges basically just allow anything at all. -tok('STAR') -src[t.STAR] = '(<|>)?=?\\s*\\*' - -// 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]) - } -} - -exports.parse = parse -function parse (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (version instanceof SemVer) { - return version - } - - if (typeof version !== 'string') { - return null - } - - if (version.length > MAX_LENGTH) { - return null - } - - var r = options.loose ? re[t.LOOSE] : re[t.FULL] - if (!r.test(version)) { - return null - } - - try { - return new SemVer(version, options) - } catch (er) { - return null - } -} - -exports.valid = valid -function valid (version, options) { - var v = parse(version, options) - return v ? v.version : null -} - -exports.clean = clean -function clean (version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} - -exports.SemVer = SemVer - -function SemVer (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version - } else { - version = version.version - } - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version) - } - - if (version.length > MAX_LENGTH) { - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') - } - - if (!(this instanceof SemVer)) { - return new SemVer(version, options) - } - - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose - - var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) - - if (!m) { - throw new TypeError('Invalid Version: ' + version) - } - - this.raw = version - - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // 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 - }) - } - - this.build = m[5] ? m[5].split('.') : [] - this.format() -} - -SemVer.prototype.format = function () { - this.version = this.major + '.' + this.minor + '.' + this.patch - if (this.prerelease.length) { - this.version += '-' + this.prerelease.join('.') - } - return this.version -} - -SemVer.prototype.toString = function () { - return this.version -} - -SemVer.prototype.compare = function (other) { - 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) - } - - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) -} - -SemVer.prototype.comparePre = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - // 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) -} - -SemVer.prototype.compareBuild = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - var i = 0 - do { - var a = this.build[i] - var b = other.build[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 - - 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] + _windowsQuoteCmdArg(arg) { + // for .exe, apply the normal quoting rules that libuv applies + if (!this._isCmdFile()) { + return this._uvQuoteCmdArg(arg); } - } - break - - default: - throw new Error('invalid increment argument: ' + release) - } - this.format() - this.raw = this.version - return this -} - -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.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 + // otherwise apply quoting rules specific to the cmd.exe command line parser. + // the libuv rules are generic and are not designed specifically for cmd.exe + // command line parser. + // + // for a detailed description of the cmd.exe command line parser, refer to + // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 + // need quotes for empty arg + if (!arg) { + return '""'; } - } - } - return defaultResult // may be undefined - } -} - -exports.compareIdentifiers = compareIdentifiers - -var numeric = /^[0-9]+$/ -function compareIdentifiers (a, b) { - var anum = numeric.test(a) - var bnum = numeric.test(b) - - if (anum && bnum) { - a = +a - b = +b - } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} - -exports.rcompareIdentifiers = rcompareIdentifiers -function rcompareIdentifiers (a, b) { - return compareIdentifiers(b, a) -} - -exports.major = major -function major (a, loose) { - return new SemVer(a, loose).major -} - -exports.minor = minor -function minor (a, loose) { - return new SemVer(a, loose).minor -} - -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)) -} - -exports.compareLoose = compareLoose -function compareLoose (a, b) { - return compare(a, b, true) -} - -exports.compareBuild = compareBuild -function compareBuild (a, b, loose) { - var versionA = new SemVer(a, loose) - var versionB = new SemVer(b, loose) - return versionA.compare(versionB) || versionA.compareBuild(versionB) -} - -exports.rcompare = rcompare -function rcompare (a, b, loose) { - return compare(b, a, loose) -} - -exports.sort = sort -function sort (list, loose) { - return list.sort(function (a, b) { - return exports.compareBuild(a, b, loose) - }) -} - -exports.rsort = rsort -function rsort (list, loose) { - return list.sort(function (a, b) { - return exports.compareBuild(b, a, loose) - }) -} - -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 -} - -exports.eq = eq -function eq (a, b, loose) { - return compare(a, b, loose) === 0 -} - -exports.neq = neq -function neq (a, b, loose) { - return compare(a, b, loose) !== 0 -} - -exports.gte = gte -function gte (a, b, loose) { - return compare(a, b, loose) >= 0 -} - -exports.lte = lte -function lte (a, b, loose) { - return compare(a, b, loose) <= 0 -} - -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 - - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt(a, b, loose) - - case '>=': - return gte(a, b, loose) - - case '<': - return lt(a, b, loose) - - case '<=': - return lte(a, b, loose) - - default: - throw new TypeError('Invalid operator: ' + op) - } -} - -exports.Comparator = Comparator -function Comparator (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value - } - } - - if (!(this instanceof Comparator)) { - return new Comparator(comp, options) - } - - 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[t.COMPARATORLOOSE] : re[t.COMPARATOR] - var m = comp.match(r) - - if (!m) { - throw new TypeError('Invalid comparator: ' + comp) - } - - this.operator = m[1] !== undefined ? m[1] : '' - if (this.operator === '=') { - this.operator = '' - } - - // 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) - } -} - -Comparator.prototype.toString = function () { - return this.value -} - -Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.options.loose) - - if (this.semver === ANY || version === ANY) { - return true - } - - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } - - return cmp(version, this.operator, this.semver, this.options) -} - -Comparator.prototype.intersects = function (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - var rangeTmp - - if (this.operator === '') { - if (this.value === '') { - return true + // determine whether the arg needs to be quoted + const cmdSpecialChars = [ + ' ', + '\t', + '&', + '(', + ')', + '[', + ']', + '{', + '}', + '^', + '=', + ';', + '!', + "'", + '+', + ',', + '`', + '~', + '|', + '<', + '>', + '"' + ]; + let needsQuotes = false; + for (const char of arg) { + if (cmdSpecialChars.some(x => x === char)) { + needsQuotes = true; + break; + } + } + // short-circuit if quotes not needed + if (!needsQuotes) { + return arg; + } + // the following quoting rules are very similar to the rules that by libuv applies. + // + // 1) wrap the string in quotes + // + // 2) double-up quotes - i.e. " => "" + // + // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately + // doesn't work well with a cmd.exe command line. + // + // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. + // for example, the command line: + // foo.exe "myarg:""my val""" + // is parsed by a .NET console app into an arg array: + // [ "myarg:\"my val\"" ] + // which is the same end result when applying libuv quoting rules. although the actual + // command line from libuv quoting rules would look like: + // foo.exe "myarg:\"my val\"" + // + // 3) double-up slashes that precede a quote, + // e.g. hello \world => "hello \world" + // hello\"world => "hello\\""world" + // hello\\"world => "hello\\\\""world" + // hello world\ => "hello world\\" + // + // technically this is not required for a cmd.exe command line, or the batch argument parser. + // the reasons for including this as a .cmd quoting rule are: + // + // a) this is optimized for the scenario where the argument is passed from the .cmd file to an + // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. + // + // b) it's what we've been doing previously (by deferring to node default behavior) and we + // haven't heard any complaints about that aspect. + // + // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be + // escaped when used on the command line directly - even though within a .cmd file % can be escaped + // by using %%. + // + // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts + // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. + // + // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would + // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the + // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args + // to an external program. + // + // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. + // % can be escaped within a .cmd file. + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + // walk the string in reverse + reverse += arg[i - 1]; + if (quoteHit && arg[i - 1] === '\\') { + reverse += '\\'; // double the slash + } + else if (arg[i - 1] === '"') { + quoteHit = true; + reverse += '"'; // double the quote + } + else { + quoteHit = false; + } + } + reverse += '"'; + return reverse + .split('') + .reverse() + .join(''); } - rangeTmp = new Range(comp.value, options) - return satisfies(this.value, rangeTmp, options) - } else if (comp.operator === '') { - if (comp.value === '') { - return true + _uvQuoteCmdArg(arg) { + // Tool runner wraps child_process.spawn() and needs to apply the same quoting as + // Node in certain cases where the undocumented spawn option windowsVerbatimArguments + // is used. + // + // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, + // see /~https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), + // pasting copyright notice from Node within this function: + // + // Copyright Joyent, Inc. and other Node contributors. All rights reserved. + // + // 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. + if (!arg) { + // Need double quotation for empty argument + return '""'; + } + if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { + // No quotation needed + return arg; + } + if (!arg.includes('"') && !arg.includes('\\')) { + // No embedded double quotes or backslashes, so I can just wrap + // quote marks around the whole thing. + return `"${arg}"`; + } + // Expected input/output: + // input : hello"world + // output: "hello\"world" + // input : hello""world + // output: "hello\"\"world" + // input : hello\world + // output: hello\world + // input : hello\\world + // output: hello\\world + // input : hello\"world + // output: "hello\\\"world" + // input : hello\\"world + // output: "hello\\\\\"world" + // input : hello world\ + // output: "hello world\\" - note the comment in libuv actually reads "hello world\" + // but it appears the comment is wrong, it should be "hello world\\" + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + // walk the string in reverse + reverse += arg[i - 1]; + if (quoteHit && arg[i - 1] === '\\') { + reverse += '\\'; + } + else if (arg[i - 1] === '"') { + quoteHit = true; + reverse += '\\'; + } + else { + quoteHit = false; + } + } + reverse += '"'; + return reverse + .split('') + .reverse() + .join(''); } - rangeTmp = new Range(this.value, options) - return satisfies(comp.semver, rangeTmp, options) - } - - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>') - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<') - var sameSemVer = this.semver.version === comp.semver.version - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<=') - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')) - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')) - - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan -} - -exports.Range = Range -function Range (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false + _cloneExecOptions(options) { + options = options || {}; + const result = { + cwd: options.cwd || process.cwd(), + env: options.env || process.env, + silent: options.silent || false, + windowsVerbatimArguments: options.windowsVerbatimArguments || false, + failOnStdErr: options.failOnStdErr || false, + ignoreReturnCode: options.ignoreReturnCode || false, + delay: options.delay || 10000 + }; + result.outStream = options.outStream || process.stdout; + result.errStream = options.errStream || process.stderr; + return result; } - } - - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range - } else { - return new Range(range.raw, options) + _getSpawnOptions(options, toolPath) { + options = options || {}; + const result = {}; + result.cwd = options.cwd; + result.env = options.env; + result['windowsVerbatimArguments'] = + options.windowsVerbatimArguments || this._isCmdFile(); + if (options.windowsVerbatimArguments) { + result.argv0 = `"${toolPath}"`; + } + return result; } - } - - if (range instanceof Comparator) { - return new Range(range.value, options) - } - - if (!(this instanceof Range)) { - return new Range(range, options) - } - - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease - - // 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 - }) - - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range) - } - - this.format() -} - -Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim() - }).join('||').trim() - return this.range -} - -Range.prototype.toString = function () { - return this.range -} - -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[t.HYPHENRANGELOOSE] : re[t.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[t.COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[t.COMPARATORTRIM]) - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[t.TILDETRIM], tildeTrimReplace) - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[t.CARETTRIM], caretTrimReplace) - - // normalize spaces - range = range.split(/\s+/).join(' ') - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.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) - - 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 ( - isSatisfiable(thisComparators, options) && - range.set.some(function (rangeComparators) { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every(function (thisComparator) { - return rangeComparators.every(function (rangeComparator) { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) -} - -// take a set of comparators and determine whether there -// exists a version which can satisfy it -function isSatisfiable (comparators, options) { - var result = true - var remainingComparators = comparators.slice() - var testComparator = remainingComparators.pop() - - while (result && remainingComparators.length) { - result = remainingComparators.every(function (otherComparator) { - return testComparator.intersects(otherComparator, options) - }) - - testComparator = remainingComparators.pop() - } - - return result -} - -// 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 -} - -function isX (id) { - return !id || id.toLowerCase() === 'x' || id === '*' -} - -// ~, ~> --> * (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(' ') -} - -function replaceTilde (comp, options) { - var r = options.loose ? re[t.TILDELOOSE] : re[t.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' + /** + * Exec a tool. + * Output will be streamed to the live console. + * Returns promise with return code + * + * @param tool path to tool to exec + * @param options optional exec options. See ExecOptions + * @returns number + */ + exec() { + return __awaiter(this, void 0, void 0, function* () { + // root the tool path if it is unrooted and contains relative pathing + if (!ioUtil.isRooted(this.toolPath) && + (this.toolPath.includes('/') || + (IS_WINDOWS && this.toolPath.includes('\\')))) { + // prefer options.cwd if it is specified, however options.cwd may also need to be rooted + this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); + } + // if the tool is only a file name, then resolve it from the PATH + // otherwise verify it exists (add extension on Windows if necessary) + this.toolPath = yield io.which(this.toolPath, true); + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + this._debug(`exec tool: ${this.toolPath}`); + this._debug('arguments:'); + for (const arg of this.args) { + this._debug(` ${arg}`); + } + const optionsNonNull = this._cloneExecOptions(this.options); + if (!optionsNonNull.silent && optionsNonNull.outStream) { + optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); + } + const state = new ExecState(optionsNonNull, this.toolPath); + state.on('debug', (message) => { + this._debug(message); + }); + if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { + return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); + } + const fileName = this._getSpawnFileName(); + const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); + let stdbuffer = ''; + if (cp.stdout) { + cp.stdout.on('data', (data) => { + if (this.options.listeners && this.options.listeners.stdout) { + this.options.listeners.stdout(data); + } + if (!optionsNonNull.silent && optionsNonNull.outStream) { + optionsNonNull.outStream.write(data); + } + stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { + if (this.options.listeners && this.options.listeners.stdline) { + this.options.listeners.stdline(line); + } + }); + }); + } + let errbuffer = ''; + if (cp.stderr) { + cp.stderr.on('data', (data) => { + state.processStderr = true; + if (this.options.listeners && this.options.listeners.stderr) { + this.options.listeners.stderr(data); + } + if (!optionsNonNull.silent && + optionsNonNull.errStream && + optionsNonNull.outStream) { + const s = optionsNonNull.failOnStdErr + ? optionsNonNull.errStream + : optionsNonNull.outStream; + s.write(data); + } + errbuffer = this._processLineBuffer(data, errbuffer, (line) => { + if (this.options.listeners && this.options.listeners.errline) { + this.options.listeners.errline(line); + } + }); + }); + } + cp.on('error', (err) => { + state.processError = err.message; + state.processExited = true; + state.processClosed = true; + state.CheckComplete(); + }); + cp.on('exit', (code) => { + state.processExitCode = code; + state.processExited = true; + this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); + state.CheckComplete(); + }); + cp.on('close', (code) => { + state.processExitCode = code; + state.processExited = true; + state.processClosed = true; + this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); + state.CheckComplete(); + }); + state.on('done', (error, exitCode) => { + if (stdbuffer.length > 0) { + this.emit('stdline', stdbuffer); + } + if (errbuffer.length > 0) { + this.emit('errline', errbuffer); + } + cp.removeAllListeners(); + if (error) { + reject(error); + } + else { + resolve(exitCode); + } + }); + if (this.options.input) { + if (!cp.stdin) { + throw new Error('child process missing stdin'); + } + cp.stdin.end(this.options.input); + } + })); + }); } - - debug('tilde return', ret) - return ret - }) -} - -// ^ --> * (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 replaceCaret (comp, options) { - debug('caret', comp, options) - var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] - return comp.replace(r, function (_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr) - var ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - if (M === '0') { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else { - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' - } - } 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' +exports.ToolRunner = ToolRunner; +/** + * Convert an arg string to an array of args. Handles escaping + * + * @param argString string of arguments + * @returns string[] array of arguments + */ +function argStringToArray(argString) { + const args = []; + let inQuotes = false; + let escaped = false; + let arg = ''; + function append(c) { + // we only escape double quotes. + if (escaped && c !== '"') { + arg += '\\'; } - } 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' + arg += c; + escaped = false; + } + for (let i = 0; i < argString.length; i++) { + const c = argString.charAt(i); + if (c === '"') { + if (!escaped) { + inQuotes = !inQuotes; + } + else { + append(c); + } + continue; } - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0' - } + if (c === '\\' && escaped) { + append(c); + continue; + } + if (c === '\\' && inQuotes) { + escaped = true; + continue; + } + if (c === ' ' && !inQuotes) { + if (arg.length > 0) { + args.push(arg); + arg = ''; + } + continue; + } + append(c); } - - debug('caret return', ret) - return ret - }) -} - -function replaceXRanges (comp, options) { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map(function (comp) { - return replaceXRange(comp, options) - }).join(' ') -} - -function replaceXRange (comp, options) { - comp = comp.trim() - var r = options.loose ? re[t.XRANGELOOSE] : re[t.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 = '' + if (arg.length > 0) { + args.push(arg.trim()); } - - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : '' - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.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 - - 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 + return args; +} +exports.argStringToArray = argStringToArray; +class ExecState extends events.EventEmitter { + constructor(options, toolPath) { + super(); + this.processClosed = false; // tracks whether the process has exited and stdio is closed + this.processError = ''; + this.processExitCode = 0; + this.processExited = false; // tracks whether the process has exited + this.processStderr = false; // tracks whether stderr was written to + this.delay = 10000; // 10 seconds + this.done = false; + this.timeout = null; + if (!toolPath) { + throw new Error('toolPath must not be empty'); } - } 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 + this.options = options; + this.toolPath = toolPath; + if (options.delay) { + this.delay = options.delay; } - } - - ret = gtlt + M + '.' + m + '.' + p + pr - } else if (xm) { - ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr - } else if (xp) { - ret = '>=' + M + '.' + m + '.0' + pr + - ' <' + M + '.' + (+m + 1) + '.0' + pr } - - debug('xRange return', ret) - - return ret - }) -} - -// 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[t.STAR], '') -} - -// This function is passed to string.replace(re[t.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 (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = '<' + (+tM + 1) + '.0.0' - } else if (isX(tp)) { - to = '<' + tM + '.' + (+tm + 1) + '.0' - } else if (tpr) { - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr - } else { - to = '<=' + to - } - - return (from + ' ' + to).trim() -} - -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function (version) { - if (!version) { - return false - } - - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false + CheckComplete() { + if (this.done) { + return; + } + if (this.processClosed) { + this._setResult(); + } + else if (this.processExited) { + this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); + } } - } - - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true + _debug(message) { + this.emit('debug', message); } - } - return false -} - -function testSet (set, version, options) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false + _setResult() { + // determine whether there is an error + let error; + if (this.processExited) { + if (this.processError) { + error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); + } + else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { + error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); + } + else if (this.processStderr && this.options.failOnStdErr) { + error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); + } + } + // clear the timeout + if (this.timeout) { + clearTimeout(this.timeout); + this.timeout = null; + } + this.done = true; + this.emit('done', error, this.processExitCode); } - } - - 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 + static HandleTimeout(state) { + if (state.done) { + return; } - } + if (!state.processClosed && state.processExited) { + const message = `The STDIO streams did not close within ${state.delay / + 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; + state._debug(message); + } + state._setResult(); } +} +//# sourceMappingURL=toolrunner.js.map - // Version has a -pre, but it's not one of the ones we like. - return false - } +/***/ }), - return true -} +/***/ 45908: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -exports.satisfies = satisfies -function satisfies (version, range, options) { - try { - range = new Range(range, options) - } catch (er) { - return false - } - return range.test(version) -} +"use strict"; -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) - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Context = void 0; +const fs_1 = __nccwpck_require__(57147); +const os_1 = __nccwpck_require__(22037); +class Context { + /** + * Hydrate the context from the environment + */ + constructor() { + var _a, _b, _c; + this.payload = {}; + if (process.env.GITHUB_EVENT_PATH) { + if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) { + this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); + } + else { + const path = process.env.GITHUB_EVENT_PATH; + process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); + } + } + this.eventName = process.env.GITHUB_EVENT_NAME; + this.sha = process.env.GITHUB_SHA; + this.ref = process.env.GITHUB_REF; + this.workflow = process.env.GITHUB_WORKFLOW; + this.action = process.env.GITHUB_ACTION; + this.actor = process.env.GITHUB_ACTOR; + this.job = process.env.GITHUB_JOB; + this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); + this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); + this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; + this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; + this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; } - }) - 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) - } + get issue() { + const payload = this.payload; + return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); + } + get repo() { + if (process.env.GITHUB_REPOSITORY) { + const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); + return { owner, repo }; + } + if (this.payload.repository) { + return { + owner: this.payload.repository.owner.login, + repo: this.payload.repository.name + }; + } + throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); } - }) - return min -} - -exports.minVersion = minVersion -function minVersion (range, loose) { - range = new Range(range, loose) - - var minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } - - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } - - minver = null - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] - - 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) - } - }) - } - - if (minver && range.test(minver)) { - return minver - } - - return null } +exports.Context = Context; +//# sourceMappingURL=context.js.map -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) -} +/***/ 51340: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -// 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) +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOctokit = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(45908)); +const utils_1 = __nccwpck_require__(24778); +exports.context = new Context.Context(); +/** + * Returns a hydrated octokit ready to use for GitHub Actions + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokit(token, options) { + return new utils_1.GitHub(utils_1.getOctokitOptions(token, options)); } +exports.getOctokit = getOctokit; +//# sourceMappingURL=github.js.map -exports.outside = outside -function outside (version, range, hilo, options) { - version = new SemVer(version, options) - range = new Range(range, options) +/***/ }), - 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 ">"') - } +/***/ 14716: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false - } +"use strict"; - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0; +const httpClient = __importStar(__nccwpck_require__(9706)); +function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error('Parameter token or opts.auth is required'); + } + else if (token && options.auth) { + throw new Error('Parameters token and opts.auth may not both be specified'); + } + return typeof options.auth === 'string' ? options.auth : `token ${token}`; +} +exports.getAuthString = getAuthString; +function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); +} +exports.getProxyAgent = getProxyAgent; +function getApiBaseUrl() { + return process.env['GITHUB_API_URL'] || 'https://api.github.com'; +} +exports.getApiBaseUrl = getApiBaseUrl; +//# sourceMappingURL=utils.js.map - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] +/***/ }), - var high = null - var low = null +/***/ 24778: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - 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 - } - }) +"use strict"; - // 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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOctokitOptions = exports.GitHub = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(45908)); +const Utils = __importStar(__nccwpck_require__(14716)); +// octokit + plugins +const core_1 = __nccwpck_require__(33520); +const plugin_rest_endpoint_methods_1 = __nccwpck_require__(55628); +const plugin_paginate_rest_1 = __nccwpck_require__(38810); +exports.context = new Context.Context(); +const baseUrl = Utils.getApiBaseUrl(); +const defaults = { + baseUrl, + request: { + agent: Utils.getProxyAgent(baseUrl) } - - // 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 +}; +exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(defaults); +/** + * Convience function to correctly format Octokit Options to pass into the constructor. + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokitOptions(token, options) { + const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller + // Auth + const auth = Utils.getAuthString(token, opts); + if (auth) { + opts.auth = auth; } - } - return true + return opts; } +exports.getOctokitOptions = getOctokitOptions; +//# sourceMappingURL=utils.js.map -exports.prerelease = prerelease -function prerelease (version, options) { - var parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} +/***/ }), -exports.intersects = intersects -function intersects (r1, r2, options) { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) +/***/ 59215: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.create = void 0; +const internal_globber_1 = __nccwpck_require__(84827); +/** + * 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 -exports.coerce = coerce -function coerce (version, options) { - if (version instanceof SemVer) { - return version - } +/***/ }), - if (typeof version === 'number') { - version = String(version) - } +/***/ 89430: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - if (typeof version !== 'string') { - return null - } +"use strict"; - options = options || {} +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOptions = void 0; +const core = __importStar(__nccwpck_require__(65681)); +/** + * Returns a copy with defaults filled in. + */ +function getOptions(copy) { + const result = { + followSymbolicLinks: true, + implicitDescendants: true, + omitBrokenSymbolicLinks: true + }; + if (copy) { + if (typeof copy.followSymbolicLinks === 'boolean') { + result.followSymbolicLinks = copy.followSymbolicLinks; + core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); + } + if (typeof copy.implicitDescendants === 'boolean') { + result.implicitDescendants = copy.implicitDescendants; + core.debug(`implicitDescendants '${result.implicitDescendants}'`); + } + if (typeof copy.omitBrokenSymbolicLinks === 'boolean') { + result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; + core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); + } + } + return result; +} +exports.getOptions = getOptions; +//# sourceMappingURL=internal-glob-options-helper.js.map - var match = null - if (!options.rtl) { - match = version.match(re[t.COERCE]) - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - var next - while ((next = re[t.COERCERTL].exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next - } - re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length +/***/ }), + +/***/ 84827: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +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 })); +exports.DefaultGlobber = void 0; +const core = __importStar(__nccwpck_require__(65681)); +const fs = __importStar(__nccwpck_require__(57147)); +const globOptionsHelper = __importStar(__nccwpck_require__(89430)); +const path = __importStar(__nccwpck_require__(71017)); +const patternHelper = __importStar(__nccwpck_require__(33963)); +const internal_match_kind_1 = __nccwpck_require__(68261); +const internal_pattern_1 = __nccwpck_require__(76821); +const internal_search_state_1 = __nccwpck_require__(41455); +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, true, 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; + }); } - // leave it in a clean state - re[t.COERCERTL].lastIndex = -1 - } - - if (match === null) { - return null - } - - return parse(match[2] + - '.' + (match[3] || '0') + - '.' + (match[4] || '0'), options) } - +exports.DefaultGlobber = DefaultGlobber; +//# sourceMappingURL=internal-globber.js.map /***/ }), -/***/ 7701: -/***/ ((module) => { +/***/ 68261: +/***/ ((__unused_webpack_module, exports) => { +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MatchKind = void 0; /** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + * Indicates whether a pattern matches a path */ -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; - - -/***/ }), - -/***/ 37269: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// Unique ID creation requires a high quality random # generator. In node.js -// this is pretty straight-forward - we use the crypto API. - -var crypto = __nccwpck_require__(6113); - -module.exports = function nodeRNG() { - return crypto.randomBytes(16); -}; - - -/***/ }), - -/***/ 17468: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var rng = __nccwpck_require__(37269); -var bytesToUuid = __nccwpck_require__(7701); - -function v4(options, buf, offset) { - var i = buf && offset || 0; - - if (typeof(options) == 'string') { - buf = options === 'binary' ? new Array(16) : null; - options = null; - } - options = options || {}; - - var rnds = options.random || (options.rng || rng)(); - - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = (rnds[6] & 0x0f) | 0x40; - rnds[8] = (rnds[8] & 0x3f) | 0x80; - - // Copy bytes to buffer, if provided - if (buf) { - for (var ii = 0; ii < 16; ++ii) { - buf[i + ii] = rnds[ii]; - } - } - - return buf || bytesToUuid(rnds); -} - -module.exports = v4; - +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 /***/ }), -/***/ 52557: -/***/ ((__unused_webpack_module, exports) => { +/***/ 19202: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/// -const listenersMap = new WeakMap(); -const 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 - * ```ts - * await doAsyncWork(AbortSignal.none); - * ``` - */ -class AbortSignal { - constructor() { - /** - * onabort event listener. - */ - this.onabort = null; - listenersMap.set(this, []); - abortedMap.set(this, false); - } - /** - * Status of whether aborted or not. - * - * @readonly - */ - get aborted() { - if (!abortedMap.has(this)) { - throw new TypeError("Expected `this` to be an instance of AbortSignal."); - } - return abortedMap.get(this); - } - /** - * Creates a new AbortSignal instance that will never be aborted. - * - * @readonly - */ - static get none() { - return new AbortSignal(); - } - /** - * Added new "abort" event listener, only support "abort" event. - * - * @param _type - Only support "abort" event - * @param listener - The listener to be added - */ - addEventListener( - // tslint:disable-next-line:variable-name - _type, listener) { - if (!listenersMap.has(this)) { - throw new TypeError("Expected `this` to be an instance of AbortSignal."); - } - const listeners = listenersMap.get(this); - listeners.push(listener); - } - /** - * Remove "abort" event listener, only support "abort" event. - * - * @param _type - Only support "abort" event - * @param listener - The listener to be removed - */ - removeEventListener( - // tslint:disable-next-line:variable-name - _type, listener) { - if (!listenersMap.has(this)) { - throw new TypeError("Expected `this` to be an instance of AbortSignal."); - } - const listeners = listenersMap.get(this); - const index = listeners.indexOf(listener); - if (index > -1) { - listeners.splice(index, 1); - } - } - /** - * Dispatches a synthetic event to the AbortSignal. - */ - dispatchEvent(_event) { - throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes."); - } -} +exports.safeTrimTrailingSeparator = exports.normalizeSeparators = exports.hasRoot = exports.hasAbsoluteRoot = exports.ensureAbsoluteRoot = exports.dirname = void 0; +const path = __importStar(__nccwpck_require__(71017)); +const assert_1 = __importDefault(__nccwpck_require__(39491)); +const IS_WINDOWS = process.platform === 'win32'; /** - * 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. + * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths. * - * - If there is a timeout, the timer will be cancelled. - * - If aborted is true, nothing will happen. + * For example, on Linux/macOS: + * - `/ => /` + * - `/hello => /` * - * @internal + * For example, on Windows: + * - `C:\ => C:\` + * - `C:\hello => C:\` + * - `C: => C:` + * - `C:hello => C:` + * - `\ => \` + * - `\hello => \` + * - `\\hello => \\hello` + * - `\\hello\world => \\hello\world` */ -// eslint-disable-next-line @azure/azure-sdk/ts-use-interface-parameters -function abortSignal(signal) { - if (signal.aborted) { - return; - } - if (signal.onabort) { - signal.onabort.call(signal); +function dirname(p) { + // Normalize slashes and trim unnecessary trailing slash + p = safeTrimTrailingSeparator(p); + // Windows UNC root, e.g. \\hello or \\hello\world + if (IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) { + return p; } - const listeners = listenersMap.get(signal); - if (listeners) { - // Create a copy of listeners so mutations to the array - // (e.g. via removeListener calls) don't affect the listeners - // we invoke. - listeners.slice().forEach((listener) => { - listener.call(signal, { type: "abort" }); - }); + // Get dirname + let result = path.dirname(p); + // Trim trailing slash for Windows UNC root, e.g. \\hello\world\ + if (IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) { + result = safeTrimTrailingSeparator(result); } - abortedMap.set(signal, true); + return result; } - -// Copyright (c) Microsoft Corporation. +exports.dirname = dirname; /** - * 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 - * ```ts - * const controller = new AbortController(); - * controller.abort(); - * try { - * doAsyncWork(controller.signal) - * } catch (e) { - * if (e.name === 'AbortError') { - * // handle abort error here. - * } - * } - * ``` + * Roots the path if not already rooted. On Windows, relative roots like `\` + * or `C:` are expanded based on the current working directory. */ -class AbortError extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; +function ensureAbsoluteRoot(root, itemPath) { + assert_1.default(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); + assert_1.default(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); + // Already rooted + if (hasAbsoluteRoot(itemPath)) { + return itemPath; } -} -/** - * 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 - * ```ts - * const controller = new AbortController(); - * const signal = controller.signal; - * doAsyncWork(signal); - * button.addEventListener('click', () => controller.abort()); - * ``` - * - * @example - * Share aborter cross multiple operations in 30s - * ```ts - * // 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 - * ```ts - * // 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)); - * ``` - */ -class AbortController { - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types - constructor(parentSignals) { - this._signal = new AbortSignal(); - if (!parentSignals) { - return; - } - // coerce parentSignals into an array - if (!Array.isArray(parentSignals)) { - // eslint-disable-next-line prefer-rest-params - parentSignals = arguments; - } - for (const parentSignal of parentSignals) { - // if the parent signal has already had abort() called, - // then call abort on this signal as well. - if (parentSignal.aborted) { - this.abort(); + // Windows + if (IS_WINDOWS) { + // Check for itemPath like C: or C:foo + if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) { + let cwd = process.cwd(); + assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + // Drive letter matches cwd? Expand to cwd + if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) { + // Drive only, e.g. C: + if (itemPath.length === 2) { + // Preserve specified drive letter case (upper or lower) + return `${itemPath[0]}:\\${cwd.substr(3)}`; + } + // Drive + path, e.g. C:foo + else { + if (!cwd.endsWith('\\')) { + cwd += '\\'; + } + // Preserve specified drive letter case (upper or lower) + return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`; + } } + // Different drive else { - // when the parent signal aborts, this signal should as well. - parentSignal.addEventListener("abort", () => { - this.abort(); - }); + return `${itemPath[0]}:\\${itemPath.substr(2)}`; } } - } - /** - * The AbortSignal associated with this controller that will signal aborted - * when the abort method is called on this controller. - * - * @readonly - */ - get signal() { - return this._signal; - } - /** - * Signal that any operations passed this controller's associated abort signal - * to cancel any remaining work and throw an `AbortError`. - */ - abort() { - abortSignal(this._signal); - } - /** - * Creates a new AbortSignal instance that will abort after the provided ms. - * @param ms - Elapsed time in milliseconds to trigger an abort. - */ - static timeout(ms) { - const signal = new AbortSignal(); - const 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; - } -} - -exports.AbortController = AbortController; -exports.AbortError = AbortError; -exports.AbortSignal = AbortSignal; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 39645: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * A static-key-based credential that supports updating - * the underlying key value. - */ -class AzureKeyCredential { - /** - * Create an instance of an AzureKeyCredential for use - * with a service client. - * - * @param key - The initial value of the key to use in authentication - */ - constructor(key) { - if (!key) { - throw new Error("key must be a non-empty string"); + // Check for itemPath like \ or \foo + else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) { + const cwd = process.cwd(); + assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + return `${cwd[0]}:\\${itemPath.substr(1)}`; } - this._key = key; - } - /** - * The value of the key to be used in authentication - */ - get key() { - return this._key; } - /** - * Change the value of the key. - * - * Updates will take effect upon the next request after - * updating the key value. - * - * @param newKey - The new key value to be used - */ - update(newKey) { - this._key = newKey; + assert_1.default(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); + // Otherwise ensure root ends with a separator + if (root.endsWith('/') || (IS_WINDOWS && root.endsWith('\\'))) { + // Intentionally empty + } + else { + // Append separator + root += path.sep; } + return root + itemPath; } - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +exports.ensureAbsoluteRoot = ensureAbsoluteRoot; /** - * Helper TypeGuard that checks if something is defined or not. - * @param thing - Anything - * @internal + * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: + * `\\hello\share` and `C:\hello` (and using alternate separator). */ -function isDefined(thing) { - return typeof thing !== "undefined" && thing !== null; +function hasAbsoluteRoot(itemPath) { + assert_1.default(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); + // Normalize separators + itemPath = normalizeSeparators(itemPath); + // Windows + if (IS_WINDOWS) { + // E.g. \\hello\share or C:\hello + return itemPath.startsWith('\\\\') || /^[A-Z]:\\/i.test(itemPath); + } + // E.g. /hello + return itemPath.startsWith('/'); } +exports.hasAbsoluteRoot = hasAbsoluteRoot; /** - * Helper TypeGuard that checks if the input is an object with the specified properties. - * Note: The properties may be inherited. - * @param thing - Anything. - * @param properties - The name of the properties that should appear in the object. - * @internal + * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: + * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator). */ -function isObjectWithProperties(thing, properties) { - if (!isDefined(thing) || typeof thing !== "object") { - return false; - } - for (const property of properties) { - if (!objectHasProperty(thing, property)) { - return false; - } +function hasRoot(itemPath) { + assert_1.default(itemPath, `isRooted parameter 'itemPath' must not be empty`); + // Normalize separators + itemPath = normalizeSeparators(itemPath); + // Windows + if (IS_WINDOWS) { + // E.g. \ or \hello or \\hello + // E.g. C: or C:\hello + return itemPath.startsWith('\\') || /^[A-Z]:/i.test(itemPath); } - return true; + // E.g. /hello + return itemPath.startsWith('/'); } +exports.hasRoot = hasRoot; /** - * Helper TypeGuard that checks if the input is an object with the specified property. - * Note: The property may be inherited. - * @param thing - Any object. - * @param property - The name of the property that should appear in the object. - * @internal + * Removes redundant slashes and converts `/` to `\` on Windows */ -function objectHasProperty(thing, property) { - return typeof thing === "object" && property in thing; +function normalizeSeparators(p) { + p = p || ''; + // Windows + if (IS_WINDOWS) { + // Convert slashes on Windows + p = p.replace(/\//g, '\\'); + // Remove redundant slashes + const isUnc = /^\\\\+[^\\]/.test(p); // e.g. \\hello + return (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\'); // preserve leading \\ for UNC + } + // Remove redundant slashes + return p.replace(/\/\/+/g, '/'); } - -// Copyright (c) Microsoft Corporation. +exports.normalizeSeparators = normalizeSeparators; /** - * A static name/key-based credential that supports updating - * the underlying name and key values. + * Normalizes the path separators and trims the trailing separator (when safe). + * For example, `/foo/ => /foo` but `/ => /` */ -class AzureNamedKeyCredential { - /** - * Create an instance of an AzureNamedKeyCredential for use - * with a service client. - * - * @param name - The initial value of the name to use in authentication. - * @param key - The initial value of the key to use in authentication. - */ - constructor(name, key) { - if (!name || !key) { - throw new TypeError("name and key must be non-empty strings"); - } - this._name = name; - this._key = key; +function safeTrimTrailingSeparator(p) { + // Short-circuit if empty + if (!p) { + return ''; } - /** - * The value of the key to be used in authentication. - */ - get key() { - return this._key; + // Normalize separators + p = normalizeSeparators(p); + // No trailing slash + if (!p.endsWith(path.sep)) { + return p; } - /** - * The value of the name to be used in authentication. - */ - get name() { - return this._name; + // Check '/' on Linux/macOS and '\' on Windows + if (p === path.sep) { + return p; } - /** - * Change the value of the key. - * - * Updates will take effect upon the next request after - * updating the key value. - * - * @param newName - The new name value to be used. - * @param newKey - The new key value to be used. - */ - update(newName, newKey) { - if (!newName || !newKey) { - throw new TypeError("newName and newKey must be non-empty strings"); - } - this._name = newName; - this._key = newKey; + // On Windows check if drive root. E.g. C:\ + if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) { + return p; } + // Otherwise trim trailing slash + return p.substr(0, p.length - 1); } -/** - * Tests an object to determine whether it implements NamedKeyCredential. - * - * @param credential - The assumed NamedKeyCredential to be tested. - */ -function isNamedKeyCredential(credential) { - return (isObjectWithProperties(credential, ["name", "key"]) && - typeof credential.key === "string" && - typeof credential.name === "string"); -} +exports.safeTrimTrailingSeparator = safeTrimTrailingSeparator; +//# sourceMappingURL=internal-path-helper.js.map -// Copyright (c) Microsoft Corporation. +/***/ }), + +/***/ 10124: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Path = void 0; +const path = __importStar(__nccwpck_require__(71017)); +const pathHelper = __importStar(__nccwpck_require__(19202)); +const assert_1 = __importDefault(__nccwpck_require__(39491)); +const IS_WINDOWS = process.platform === 'win32'; /** - * A static-signature-based credential that supports updating - * the underlying signature value. + * Helper class for parsing paths into segments */ -class AzureSASCredential { +class Path { /** - * Create an instance of an AzureSASCredential for use - * with a service client. - * - * @param signature - The initial value of the shared access signature to use in authentication + * Constructs a Path + * @param itemPath Path or array of segments */ - constructor(signature) { - if (!signature) { - throw new Error("shared access signature must be a non-empty string"); + constructor(itemPath) { + this.segments = []; + // String + if (typeof itemPath === 'string') { + assert_1.default(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_1.default(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_1.default(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_1.default(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_1.default(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); + this.segments.push(segment); + } + } } - this._signature = signature; - } - /** - * The value of the shared access signature to be used in authentication - */ - get signature() { - return this._signature; } /** - * Change the value of the signature. - * - * Updates will take effect upon the next request after - * updating the signature value. - * - * @param newSignature - The new shared access signature value to be used + * Converts the path to it's string representation */ - update(newSignature) { - if (!newSignature) { - throw new Error("shared access signature must be a non-empty string"); + 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]; } - this._signature = newSignature; + return result; } } -/** - * Tests an object to determine whether it implements SASCredential. - * - * @param credential - The assumed SASCredential to be tested. - */ -function isSASCredential(credential) { - return (isObjectWithProperties(credential, ["signature"]) && typeof credential.signature === "string"); -} - -// 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. - const castCredential = credential; - return (castCredential && - typeof castCredential.getToken === "function" && - (castCredential.signRequest === undefined || castCredential.getToken.length > 0)); -} - -exports.AzureKeyCredential = AzureKeyCredential; -exports.AzureNamedKeyCredential = AzureNamedKeyCredential; -exports.AzureSASCredential = AzureSASCredential; -exports.isNamedKeyCredential = isNamedKeyCredential; -exports.isSASCredential = isSASCredential; -exports.isTokenCredential = isTokenCredential; -//# sourceMappingURL=index.js.map - +exports.Path = Path; +//# sourceMappingURL=internal-path.js.map /***/ }), -/***/ 24607: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 33963: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); - -var uuid = __nccwpck_require__(75840); -var util = __nccwpck_require__(73837); -var tslib = __nccwpck_require__(4351); -var xml2js = __nccwpck_require__(66189); -var abortController = __nccwpck_require__(52557); -var logger$1 = __nccwpck_require__(3233); -var coreAuth = __nccwpck_require__(39645); -var os = __nccwpck_require__(22037); -var http = __nccwpck_require__(13685); -var https = __nccwpck_require__(95687); -var tough = __nccwpck_require__(18165); -var tunnel = __nccwpck_require__(74294); -var stream = __nccwpck_require__(12781); -var FormData = __nccwpck_require__(46279); -var node_fetch = __nccwpck_require__(80467); -var coreTracing = __nccwpck_require__(94175); - -function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } - -function _interopNamespace(e) { - if (e && e.__esModule) return e; - var n = Object.create(null); - if (e) { - Object.keys(e).forEach(function (k) { - if (k !== 'default') { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: function () { return e[k]; } - }); +exports.partialMatch = exports.match = exports.getSearchPaths = void 0; +const pathHelper = __importStar(__nccwpck_require__(19202)); +const internal_match_kind_1 = __nccwpck_require__(68261); +const IS_WINDOWS = process.platform === 'win32'; +/** + * Given an array of patterns, returns an array of paths to search. + * Duplicates and paths under other included paths are filtered out. + */ +function getSearchPaths(patterns) { + // Ignore negate patterns + patterns = patterns.filter(x => !x.negate); + // Create a map of all search paths + const searchPathMap = {}; + for (const pattern of patterns) { + const key = IS_WINDOWS + ? pattern.searchPath.toUpperCase() + : pattern.searchPath; + searchPathMap[key] = 'candidate'; + } + const result = []; + for (const pattern of patterns) { + // Check if already included + const key = IS_WINDOWS + ? pattern.searchPath.toUpperCase() + : pattern.searchPath; + if (searchPathMap[key] === 'included') { + continue; + } + // Check for an ancestor search path + let foundAncestor = false; + let tempKey = key; + let parent = pathHelper.dirname(tempKey); + while (parent !== tempKey) { + if (searchPathMap[parent]) { + foundAncestor = true; + break; } - }); + tempKey = parent; + parent = pathHelper.dirname(tempKey); + } + // Include the search pattern in the result + if (!foundAncestor) { + result.push(pattern.searchPath); + searchPathMap[key] = 'included'; + } } - n["default"] = e; - return Object.freeze(n); + return result; } - -var xml2js__namespace = /*#__PURE__*/_interopNamespace(xml2js); -var os__namespace = /*#__PURE__*/_interopNamespace(os); -var http__namespace = /*#__PURE__*/_interopNamespace(http); -var https__namespace = /*#__PURE__*/_interopNamespace(https); -var tough__namespace = /*#__PURE__*/_interopNamespace(tough); -var tunnel__namespace = /*#__PURE__*/_interopNamespace(tunnel); -var FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData); -var node_fetch__default = /*#__PURE__*/_interopDefaultLegacy(node_fetch); - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +exports.getSearchPaths = getSearchPaths; /** - * A collection of HttpHeaders that can be sent with a HTTP request. + * Matches the patterns against the path */ -function getHeaderKey(headerName) { - return headerName.toLowerCase(); -} -function isHttpHeadersLike(object) { - if (object && typeof object === "object") { - const castObject = object; - if (typeof castObject.rawHeaders === "function" && - typeof castObject.clone === "function" && - typeof castObject.get === "function" && - typeof castObject.set === "function" && - typeof castObject.contains === "function" && - typeof castObject.remove === "function" && - typeof castObject.headersArray === "function" && - typeof castObject.headerValues === "function" && - typeof castObject.headerNames === "function" && - typeof castObject.toJson === "function") { - return true; +function match(patterns, itemPath) { + let result = internal_match_kind_1.MatchKind.None; + for (const pattern of patterns) { + if (pattern.negate) { + result &= ~pattern.match(itemPath); + } + else { + result |= pattern.match(itemPath); } } - return false; + return result; } +exports.match = match; /** - * A collection of HTTP header key/value pairs. + * Checks whether to descend further into the directory */ -class HttpHeaders { - constructor(rawHeaders) { - this._headersMap = {}; - if (rawHeaders) { - for (const headerName in rawHeaders) { - this.set(headerName, rawHeaders[headerName]); +function partialMatch(patterns, itemPath) { + return patterns.some(x => !x.negate && x.partialMatch(itemPath)); +} +exports.partialMatch = partialMatch; +//# sourceMappingURL=internal-pattern-helper.js.map + +/***/ }), + +/***/ 76821: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Pattern = void 0; +const os = __importStar(__nccwpck_require__(22037)); +const path = __importStar(__nccwpck_require__(71017)); +const pathHelper = __importStar(__nccwpck_require__(19202)); +const assert_1 = __importDefault(__nccwpck_require__(39491)); +const minimatch_1 = __nccwpck_require__(67586); +const internal_match_kind_1 = __nccwpck_require__(68261); +const internal_path_1 = __nccwpck_require__(10124); +const IS_WINDOWS = process.platform === 'win32'; +class Pattern { + constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) { + /** + * Indicates whether matches should be excluded from the result set + */ + this.negate = false; + // Pattern overload + let pattern; + if (typeof patternOrNegate === 'string') { + pattern = patternOrNegate.trim(); + } + // Segments overload + else { + // Convert to pattern + segments = segments || []; + assert_1.default(segments.length, `Parameter 'segments' must not empty`); + const root = Pattern.getLiteral(segments[0]); + assert_1.default(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); + pattern = new internal_path_1.Path(segments).toString().trim(); + if (patternOrNegate) { + pattern = `!${pattern}`; } } - } - /** - * Set a header in this collection with the provided name and value. The name is - * case-insensitive. - * @param headerName - The name of the header to set. This value is case-insensitive. - * @param headerValue - The value of the header to set. - */ - set(headerName, headerValue) { - this._headersMap[getHeaderKey(headerName)] = { - name: headerName, - value: headerValue.toString(), + // Negate + while (pattern.startsWith('!')) { + this.negate = !this.negate; + pattern = pattern.substr(1).trim(); + } + // Normalize slashes and ensures absolute root + pattern = Pattern.fixupPattern(pattern, homedir); + // Segments + this.segments = new internal_path_1.Path(pattern).segments; + // Trailing slash indicates the pattern should only match directories, not regular files + this.trailingSeparator = pathHelper + .normalizeSeparators(pattern) + .endsWith(path.sep); + pattern = pathHelper.safeTrimTrailingSeparator(pattern); + // Search path (literal path prior to the first glob segment) + let foundGlob = false; + const searchSegments = this.segments + .map(x => Pattern.getLiteral(x)) + .filter(x => !foundGlob && !(foundGlob = x === '')); + this.searchPath = new internal_path_1.Path(searchSegments).toString(); + // Root RegExp (required when determining partial match) + this.rootRegExp = new RegExp(Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? 'i' : ''); + this.isImplicitPattern = isImplicitPattern; + // Create minimatch + const minimatchOptions = { + dot: true, + nobrace: true, + nocase: IS_WINDOWS, + nocomment: true, + noext: true, + nonegate: true }; + pattern = IS_WINDOWS ? pattern.replace(/\\/g, '/') : pattern; + this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions); } /** - * Get the header value for the provided header name, or undefined if no header exists in this - * collection with the provided name. - * @param headerName - The name of the header. - */ - get(headerName) { - const header = this._headersMap[getHeaderKey(headerName)]; - return !header ? undefined : header.value; - } - /** - * Get whether or not this header collection contains a header entry for the provided header name. + * Matches the pattern against the specified path */ - contains(headerName) { - return !!this._headersMap[getHeaderKey(headerName)]; + match(itemPath) { + // Last segment is globstar? + if (this.segments[this.segments.length - 1] === '**') { + // Normalize slashes + itemPath = pathHelper.normalizeSeparators(itemPath); + // Append a trailing slash. Otherwise Minimatch will not match the directory immediately + // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns + // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk. + if (!itemPath.endsWith(path.sep) && this.isImplicitPattern === false) { + // Note, this is safe because the constructor ensures the pattern has an absolute root. + // For example, formats like C: and C:foo on Windows are resolved to an absolute root. + itemPath = `${itemPath}${path.sep}`; + } + } + else { + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + } + // Match + if (this.minimatch.match(itemPath)) { + return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All; + } + return internal_match_kind_1.MatchKind.None; } /** - * Remove the header with the provided headerName. Return whether or not the header existed and - * was removed. - * @param headerName - The name of the header to remove. + * Indicates whether the pattern may match descendants of the specified path */ - remove(headerName) { - const result = this.contains(headerName); - delete this._headersMap[getHeaderKey(headerName)]; - return result; + partialMatch(itemPath) { + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + // matchOne does not handle root path correctly + if (pathHelper.dirname(itemPath) === itemPath) { + return this.rootRegExp.test(itemPath); + } + return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true); } /** - * Get the headers that are contained this collection as an object. + * Escapes glob patterns within a path */ - rawHeaders() { - return this.toJson({ preserveCase: true }); + static globEscape(s) { + return (IS_WINDOWS ? s : s.replace(/\\/g, '\\\\')) // escape '\' on Linux/macOS + .replace(/(\[)(?=[^/]+\])/g, '[[]') // escape '[' when ']' follows within the path segment + .replace(/\?/g, '[?]') // escape '?' + .replace(/\*/g, '[*]'); // escape '*' } /** - * Get the headers that are contained in this collection as an array. + * Normalizes slashes and ensures absolute root */ - headersArray() { - const headers = []; - for (const headerKey in this._headersMap) { - headers.push(this._headersMap[headerKey]); + static fixupPattern(pattern, homedir) { + // Empty + assert_1.default(pattern, 'pattern cannot be empty'); + // Must not contain `.` segment, unless first segment + // Must not contain `..` segment + const literalSegments = new internal_path_1.Path(pattern).segments.map(x => Pattern.getLiteral(x)); + assert_1.default(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); + // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r + assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); + // Normalize slashes + pattern = pathHelper.normalizeSeparators(pattern); + // Replace leading `.` segment + if (pattern === '.' || pattern.startsWith(`.${path.sep}`)) { + pattern = Pattern.globEscape(process.cwd()) + pattern.substr(1); } - return headers; - } - /** - * Get the header names that are contained in this collection. - */ - headerNames() { - const headerNames = []; - const headers = this.headersArray(); - for (let i = 0; i < headers.length; ++i) { - headerNames.push(headers[i].name); + // Replace leading `~` segment + else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) { + homedir = homedir || os.homedir(); + assert_1.default(homedir, 'Unable to determine HOME directory'); + assert_1.default(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); + pattern = Pattern.globEscape(homedir) + pattern.substr(1); } - return headerNames; - } - /** - * Get the header values that are contained in this collection. - */ - headerValues() { - const headerValues = []; - const headers = this.headersArray(); - for (let i = 0; i < headers.length; ++i) { - headerValues.push(headers[i].value); + // Replace relative drive root, e.g. pattern is C: or C:foo + else if (IS_WINDOWS && + (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) { + let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', pattern.substr(0, 2)); + if (pattern.length > 2 && !root.endsWith('\\')) { + root += '\\'; + } + pattern = Pattern.globEscape(root) + pattern.substr(2); } - return headerValues; - } - /** - * Get the JSON object representation of this HTTP header collection. - */ - toJson(options = {}) { - const result = {}; - if (options.preserveCase) { - for (const headerKey in this._headersMap) { - const header = this._headersMap[headerKey]; - result[header.name] = header.value; + // Replace relative root, e.g. pattern is \ or \foo + else if (IS_WINDOWS && (pattern === '\\' || pattern.match(/^\\[^\\]/))) { + let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', '\\'); + if (!root.endsWith('\\')) { + root += '\\'; } + pattern = Pattern.globEscape(root) + pattern.substr(1); } + // Otherwise ensure absolute root else { - for (const headerKey in this._headersMap) { - const header = this._headersMap[headerKey]; - result[getHeaderKey(header.name)] = header.value; - } + pattern = pathHelper.ensureAbsoluteRoot(Pattern.globEscape(process.cwd()), pattern); } - return result; + return pathHelper.normalizeSeparators(pattern); } /** - * Get the string representation of this HTTP header collection. + * Attempts to unescape a pattern segment to create a literal path segment. + * Otherwise returns empty string. */ - toString() { - return JSON.stringify(this.toJson({ preserveCase: true })); + static getLiteral(segment) { + let literal = ''; + for (let i = 0; i < segment.length; i++) { + const c = segment[i]; + // Escape + if (c === '\\' && !IS_WINDOWS && i + 1 < segment.length) { + literal += segment[++i]; + continue; + } + // Wildcard + else if (c === '*' || c === '?') { + return ''; + } + // Character set + else if (c === '[' && i + 1 < segment.length) { + let set = ''; + let closed = -1; + for (let i2 = i + 1; i2 < segment.length; i2++) { + const c2 = segment[i2]; + // Escape + if (c2 === '\\' && !IS_WINDOWS && i2 + 1 < segment.length) { + set += segment[++i2]; + continue; + } + // Closed + else if (c2 === ']') { + closed = i2; + break; + } + // Otherwise + else { + set += c2; + } + } + // Closed? + if (closed >= 0) { + // Cannot convert + if (set.length > 1) { + return ''; + } + // Convert to literal + if (set) { + literal += set; + i = closed; + continue; + } + } + // Otherwise fall thru + } + // Append + literal += c; + } + return literal; } /** - * Create a deep clone/copy of this HttpHeaders collection. + * Escapes regexp special characters + * https://javascript.info/regexp-escaping */ - clone() { - const resultPreservingCasing = {}; - for (const headerKey in this._headersMap) { - const header = this._headersMap[headerKey]; - resultPreservingCasing[header.name] = header.value; - } - return new HttpHeaders(resultPreservingCasing); + static regExpEscape(s) { + return s.replace(/[[\\^$.|?*+()]/g, '\\$&'); } } +exports.Pattern = Pattern; +//# sourceMappingURL=internal-pattern.js.map -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * Encodes a string in base64 format. - * @param value - The string to encode - */ -function encodeString(value) { - return Buffer.from(value).toString("base64"); -} -/** - * Encodes a byte array in base64 format. - * @param value - The Uint8Aray to encode - */ -function encodeByteArray(value) { - // Buffer.from accepts | -- the TypeScript definition is off here - // https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length - const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer); - return bufferValue.toString("base64"); -} -/** - * Decodes a base64 string into a byte array. - * @param value - The base64 string to decode - */ -function decodeString(value) { - return Buffer.from(value, "base64"); -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * A set of constants used internally when processing requests. - */ -const Constants = { - /** - * The core-http version - */ - coreHttpVersion: "2.2.6", - /** - * Specifies HTTP. - */ - HTTP: "http:", - /** - * Specifies HTTPS. - */ - HTTPS: "https:", - /** - * Specifies HTTP Proxy. - */ - HTTP_PROXY: "HTTP_PROXY", - /** - * Specifies HTTPS Proxy. - */ - HTTPS_PROXY: "HTTPS_PROXY", - /** - * Specifies NO Proxy. - */ - NO_PROXY: "NO_PROXY", - /** - * Specifies ALL Proxy. - */ - ALL_PROXY: "ALL_PROXY", - HttpConstants: { - /** - * Http Verbs - */ - HttpVerbs: { - PUT: "PUT", - GET: "GET", - DELETE: "DELETE", - POST: "POST", - MERGE: "MERGE", - HEAD: "HEAD", - PATCH: "PATCH", - }, - StatusCodes: { - TooManyRequests: 429, - ServiceUnavailable: 503, - }, - }, - /** - * Defines constants for use with HTTP headers. - */ - HeaderConstants: { - /** - * The Authorization header. - */ - AUTHORIZATION: "authorization", - AUTHORIZATION_SCHEME: "Bearer", - /** - * The Retry-After response-header field can be used with a 503 (Service - * Unavailable) or 349 (Too Many Requests) responses to indicate how long - * the service is expected to be unavailable to the requesting client. - */ - RETRY_AFTER: "Retry-After", - /** - * The UserAgent header. - */ - USER_AGENT: "User-Agent", - }, -}; +/***/ }), -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * Default key used to access the XML attributes. - */ -const XML_ATTRKEY = "$"; -/** - * Default key used to access the XML value content. - */ -const XML_CHARKEY = "_"; +/***/ 41455: +/***/ ((__unused_webpack_module, exports) => { -// Copyright (c) Microsoft Corporation. -const validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i; -/** - * A constant that indicates whether the environment is node.js or browser based. - */ -const isNode = typeof process !== "undefined" && - !!process.version && - !!process.versions && - !!process.versions.node; -/** - * Encodes an URI. - * - * @param uri - The URI to be encoded. - * @returns The encoded URI. - */ -function encodeUri(uri) { - return encodeURIComponent(uri) - .replace(/!/g, "%21") - .replace(/"/g, "%27") - .replace(/\(/g, "%28") - .replace(/\)/g, "%29") - .replace(/\*/g, "%2A"); -} -/** - * Returns a stripped version of the Http Response which only contains body, - * headers and the status. - * - * @param response - The Http Response - * @returns The stripped version of Http Response. - */ -function stripResponse(response) { - const strippedResponse = {}; - strippedResponse.body = response.bodyAsText; - strippedResponse.headers = response.headers; - strippedResponse.status = response.status; - return strippedResponse; -} -/** - * Returns a stripped version of the Http Request that does not contain the - * Authorization header. - * - * @param request - The Http Request object - * @returns The stripped version of Http Request. - */ -function stripRequest(request) { - const strippedRequest = request.clone(); - if (strippedRequest.headers) { - strippedRequest.headers.remove("authorization"); - } - return strippedRequest; -} -/** - * Validates the given uuid as a string - * - * @param uuid - The uuid as a string that needs to be validated - * @returns True if the uuid is valid; false otherwise. - */ -function isValidUuid(uuid) { - return validUuidRegex.test(uuid); -} -/** - * Generated UUID - * - * @returns RFC4122 v4 UUID. - */ -function generateUuid() { - return uuid.v4(); -} -/** - * Executes an array of promises sequentially. Inspiration of this method is here: - * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises! - * - * @param promiseFactories - An array of promise factories(A function that return a promise) - * @param kickstart - Input to the first promise that is used to kickstart the promise chain. - * If not provided then the promise chain starts with undefined. - * @returns A chain of resolved or rejected promises - */ -function executePromisesSequentially(promiseFactories, kickstart) { - let result = Promise.resolve(kickstart); - promiseFactories.forEach((promiseFactory) => { - result = result.then(promiseFactory); - }); - return result; -} -/** - * Converts a Promise to a callback. - * @param promise - The Promise to be converted to a callback - * @returns A function that takes the callback `(cb: Function) => void` - * @deprecated generated code should instead depend on responseToBody - */ -// eslint-disable-next-line @typescript-eslint/ban-types -function promiseToCallback(promise) { - if (typeof promise.then !== "function") { - throw new Error("The provided input is not a Promise."); - } - // eslint-disable-next-line @typescript-eslint/ban-types - return (cb) => { - promise - .then((data) => { - // eslint-disable-next-line promise/no-callback-in-promise - return cb(undefined, data); - }) - .catch((err) => { - // eslint-disable-next-line promise/no-callback-in-promise - cb(err); - }); - }; -} -/** - * Converts a Promise to a service callback. - * @param promise - The Promise of HttpOperationResponse to be converted to a service callback - * @returns A function that takes the service callback (cb: ServiceCallback): void - */ -function promiseToServiceCallback(promise) { - if (typeof promise.then !== "function") { - throw new Error("The provided input is not a Promise."); - } - return (cb) => { - promise - .then((data) => { - return process.nextTick(cb, undefined, data.parsedBody, data.request, data); - }) - .catch((err) => { - process.nextTick(cb, err); - }); - }; -} -function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { - if (!Array.isArray(obj)) { - obj = [obj]; - } - if (!xmlNamespaceKey || !xmlNamespace) { - return { [elementName]: obj }; +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SearchState = void 0; +class SearchState { + constructor(path, level) { + this.path = path; + this.level = level; } - const result = { [elementName]: obj }; - result[XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace }; - return result; } -/** - * Applies the properties on the prototype of sourceCtors to the prototype of targetCtor - * @param targetCtor - The target object on which the properties need to be applied. - * @param sourceCtors - An array of source objects from which the properties need to be taken. - */ -function applyMixins(targetCtorParam, sourceCtors) { - const castTargetCtorParam = targetCtorParam; - sourceCtors.forEach((sourceCtor) => { - Object.getOwnPropertyNames(sourceCtor.prototype).forEach((name) => { - castTargetCtorParam.prototype[name] = sourceCtor.prototype[name]; - }); +exports.SearchState = SearchState; +//# sourceMappingURL=internal-search-state.js.map + +/***/ }), + +/***/ 21770: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); -} -const validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.hashFiles = exports.create = void 0; +const internal_globber_1 = __nccwpck_require__(6769); +const internal_hash_files_1 = __nccwpck_require__(82561); /** - * Indicates whether the given string is in ISO 8601 format. - * @param value - The value to be validated for ISO 8601 duration format. - * @returns `true` if valid, `false` otherwise. + * Constructs a globber + * + * @param patterns Patterns separated by newlines + * @param options Glob options */ -function isDuration(value) { - return validateISODuration.test(value); +function create(patterns, options) { + return __awaiter(this, void 0, void 0, function* () { + return yield internal_globber_1.DefaultGlobber.create(patterns, options); + }); } +exports.create = create; /** - * Replace all of the instances of searchValue in value with the provided replaceValue. - * @param value - The value to search and replace in. - * @param searchValue - The value to search for in the value argument. - * @param replaceValue - The value to replace searchValue with in the value argument. - * @returns The value where each instance of searchValue was replaced with replacedValue. + * Computes the sha256 hash of a glob + * + * @param patterns Patterns separated by newlines + * @param options Glob options */ -function replaceAll(value, searchValue, replaceValue) { - return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || ""); +function hashFiles(patterns, options, verbose = false) { + return __awaiter(this, void 0, void 0, function* () { + let followSymbolicLinks = true; + if (options && typeof options.followSymbolicLinks === 'boolean') { + followSymbolicLinks = options.followSymbolicLinks; + } + const globber = yield create(patterns, { followSymbolicLinks }); + return internal_hash_files_1.hashFiles(globber, verbose); + }); } +exports.hashFiles = hashFiles; +//# sourceMappingURL=glob.js.map + +/***/ }), + +/***/ 82607: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOptions = void 0; +const core = __importStar(__nccwpck_require__(65681)); /** - * Determines whether the given entity is a basic/primitive type - * (string, number, boolean, null, undefined). - * @param value - Any entity - * @returns true is it is primitive type, false otherwise. + * Returns a copy with defaults filled in. */ -function isPrimitiveType(value) { - return (typeof value !== "object" && typeof value !== "function") || value === null; -} -function getEnvironmentValue(name) { - if (process.env[name]) { - return process.env[name]; - } - else if (process.env[name.toLowerCase()]) { - return process.env[name.toLowerCase()]; +function getOptions(copy) { + const result = { + followSymbolicLinks: true, + implicitDescendants: true, + matchDirectories: true, + omitBrokenSymbolicLinks: true + }; + if (copy) { + if (typeof copy.followSymbolicLinks === 'boolean') { + result.followSymbolicLinks = copy.followSymbolicLinks; + core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); + } + if (typeof copy.implicitDescendants === 'boolean') { + result.implicitDescendants = copy.implicitDescendants; + core.debug(`implicitDescendants '${result.implicitDescendants}'`); + } + if (typeof copy.matchDirectories === 'boolean') { + result.matchDirectories = copy.matchDirectories; + core.debug(`matchDirectories '${result.matchDirectories}'`); + } + if (typeof copy.omitBrokenSymbolicLinks === 'boolean') { + result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; + core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); + } } - return undefined; -} -/** - * @internal - * @returns true when input is an object type that is not null, Array, RegExp, or Date. - */ -function isObject(input) { - return (typeof input === "object" && - input !== null && - !Array.isArray(input) && - !(input instanceof RegExp) && - !(input instanceof Date)); + return result; } +exports.getOptions = getOptions; +//# sourceMappingURL=internal-glob-options-helper.js.map -// Copyright (c) Microsoft Corporation. -// This file contains utility code to serialize and deserialize network operations according to `OperationSpec` objects generated by AutoRest.TypeScript from OpenAPI specifications. -/** - * Used to map raw response objects to final shapes. - * Helps packing and unpacking Dates and other encoded types that are not intrinsic to JSON. - * Also allows pulling values from headers, as well as inserting default values and constants. - */ -class Serializer { - constructor( - /** - * The provided model mapper. - */ - modelMappers = {}, - /** - * Whether the contents are XML or not. - */ - isXML) { - this.modelMappers = modelMappers; - this.isXML = isXML; +/***/ }), + +/***/ 6769: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +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 })); +exports.DefaultGlobber = void 0; +const core = __importStar(__nccwpck_require__(65681)); +const fs = __importStar(__nccwpck_require__(57147)); +const globOptionsHelper = __importStar(__nccwpck_require__(82607)); +const path = __importStar(__nccwpck_require__(71017)); +const patternHelper = __importStar(__nccwpck_require__(23299)); +const internal_match_kind_1 = __nccwpck_require__(65378); +const internal_pattern_1 = __nccwpck_require__(23425); +const internal_search_state_1 = __nccwpck_require__(86646); +const IS_WINDOWS = process.platform === 'win32'; +class DefaultGlobber { + constructor(options) { + this.patterns = []; + this.searchPaths = []; + this.options = globOptionsHelper.getOptions(options); } - /** - * Validates constraints, if any. This function will throw if the provided value does not respect those constraints. - * @param mapper - The definition of data models. - * @param value - The value. - * @param objectName - Name of the object. Used in the error messages. - * @deprecated Removing the constraints validation on client side. - */ - validateConstraints(mapper, value, objectName) { - const failValidation = (constraintName, constraintValue) => { - throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`); - }; - if (mapper.constraints && value != undefined) { - const valueAsNumber = value; - const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints; - if (ExclusiveMaximum != undefined && valueAsNumber >= ExclusiveMaximum) { - failValidation("ExclusiveMaximum", ExclusiveMaximum); - } - if (ExclusiveMinimum != undefined && valueAsNumber <= ExclusiveMinimum) { - failValidation("ExclusiveMinimum", ExclusiveMinimum); - } - if (InclusiveMaximum != undefined && valueAsNumber > InclusiveMaximum) { - failValidation("InclusiveMaximum", InclusiveMaximum); - } - if (InclusiveMinimum != undefined && valueAsNumber < InclusiveMinimum) { - failValidation("InclusiveMinimum", InclusiveMinimum); - } - const valueAsArray = value; - if (MaxItems != undefined && valueAsArray.length > MaxItems) { - failValidation("MaxItems", MaxItems); - } - if (MaxLength != undefined && valueAsArray.length > MaxLength) { - failValidation("MaxLength", MaxLength); - } - if (MinItems != undefined && valueAsArray.length < MinItems) { - failValidation("MinItems", MinItems); - } - if (MinLength != undefined && valueAsArray.length < MinLength) { - failValidation("MinLength", MinLength); - } - if (MultipleOf != undefined && valueAsNumber % MultipleOf !== 0) { - failValidation("MultipleOf", MultipleOf); - } - if (Pattern) { - const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern; - if (typeof value !== "string" || value.match(pattern) === null) { - failValidation("Pattern", Pattern); + 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); } } - if (UniqueItems && - valueAsArray.some((item, i, ar) => ar.indexOf(item) !== i)) { - failValidation("UniqueItems", UniqueItems); + 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; + }); } - /** - * Serialize the given object based on its metadata defined in the mapper. - * - * @param mapper - The mapper which defines the metadata of the serializable object. - * @param object - A valid Javascript object to be serialized. - * @param objectName - Name of the serialized object. - * @param options - additional options to deserialization. - * @returns A valid serialized Javascript object. - */ - serialize(mapper, object, objectName, options = {}) { - var _a, _b, _c; - const updatedOptions = { - rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", - includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, - }; - let payload = {}; - const mapperType = mapper.type.name; - if (!objectName) { - objectName = mapper.serializedName; - } - if (mapperType.match(/^Sequence$/i) !== null) { - payload = []; - } - if (mapper.isConstant) { - object = mapper.defaultValue; - } - // This table of allowed values should help explain - // the mapper.required and mapper.nullable properties. - // X means "neither undefined or null are allowed". - // || required - // || true | false - // nullable || ========================== - // true || null | undefined/null - // false || X | undefined - // undefined || X | undefined/null - const { required, nullable } = mapper; - if (required && nullable && object === undefined) { - throw new Error(`${objectName} cannot be undefined.`); - } - if (required && !nullable && object == undefined) { - throw new Error(`${objectName} cannot be null or undefined.`); - } - if (!required && nullable === false && object === null) { - throw new Error(`${objectName} cannot be null.`); - } - if (object == undefined) { - payload = object; - } - else { - if (mapperType.match(/^any$/i) !== null) { - payload = object; - } - else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) { - payload = serializeBasicTypes(mapperType, objectName, object); - } - else if (mapperType.match(/^Enum$/i) !== null) { - const enumMapper = mapper; - payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object); - } - else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) { - payload = serializeDateTypes(mapperType, object, objectName); - } - else if (mapperType.match(/^ByteArray$/i) !== null) { - payload = serializeByteArrayType(objectName, object); - } - else if (mapperType.match(/^Base64Url$/i) !== null) { - payload = serializeBase64UrlType(objectName, object); - } - else if (mapperType.match(/^Sequence$/i) !== null) { - payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + 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, true, pattern.segments.concat('**'))); + } } - else if (mapperType.match(/^Dictionary$/i) !== null) { - payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + // 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)); } - else if (mapperType.match(/^Composite$/i) !== null) { - payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + // 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 && options.matchDirectories) { + 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); + } } - } - return payload; + }); } /** - * Deserialize the given object based on its metadata defined in the mapper. - * - * @param mapper - The mapper which defines the metadata of the serializable object. - * @param responseBody - A valid Javascript entity to be deserialized. - * @param objectName - Name of the deserialized object. - * @param options - Controls behavior of XML parser and builder. - * @returns A valid deserialized Javascript object. + * Constructs a DefaultGlobber */ - deserialize(mapper, responseBody, objectName, options = {}) { - var _a, _b, _c; - const updatedOptions = { - rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", - includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, - }; - if (responseBody == undefined) { - if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) { - // Edge case for empty XML non-wrapped lists. xml2js can't distinguish - // between the list being empty versus being missing, - // so let's do the more user-friendly thing and return an empty list. - responseBody = []; - } - // specifically check for undefined as default value can be a falsey value `0, "", false, null` - if (mapper.defaultValue !== undefined) { - responseBody = mapper.defaultValue; - } - return responseBody; - } - let payload; - const mapperType = mapper.type.name; - if (!objectName) { - objectName = mapper.serializedName; - } - if (mapperType.match(/^Composite$/i) !== null) { - payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions); - } - else { - if (this.isXML) { - const xmlCharKey = updatedOptions.xmlCharKey; - const castResponseBody = responseBody; - /** - * If the mapper specifies this as a non-composite type value but the responseBody contains - * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties, - * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property. - */ - if (castResponseBody[XML_ATTRKEY] != undefined && - castResponseBody[xmlCharKey] != undefined) { - responseBody = castResponseBody[xmlCharKey]; - } - } - if (mapperType.match(/^Number$/i) !== null) { - payload = parseFloat(responseBody); - if (isNaN(payload)) { - payload = responseBody; - } + 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'); } - else if (mapperType.match(/^Boolean$/i) !== null) { - if (responseBody === "true") { - payload = true; - } - else if (responseBody === "false") { - payload = false; + const lines = patterns.split('\n').map(x => x.trim()); + for (const line of lines) { + // Empty or comment + if (!line || line.startsWith('#')) { + continue; } + // Pattern else { - payload = responseBody; + result.patterns.push(new internal_pattern_1.Pattern(line)); } } - else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) { - payload = responseBody; - } - else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) { - payload = new Date(responseBody); - } - else if (mapperType.match(/^UnixTime$/i) !== null) { - payload = unixTimeToDate(responseBody); - } - else if (mapperType.match(/^ByteArray$/i) !== null) { - payload = decodeString(responseBody); - } - else if (mapperType.match(/^Base64Url$/i) !== null) { - payload = base64UrlToByteArray(responseBody); + 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 if (mapperType.match(/^Sequence$/i) !== null) { - payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions); + else { + // Use `lstat` (not following symlinks) + stats = yield fs.promises.lstat(item.path); } - else if (mapperType.match(/^Dictionary$/i) !== null) { - payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions); + // 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); } - } - if (mapper.isConstant) { - payload = mapper.defaultValue; - } - return payload; - } -} -function trimEnd(str, ch) { - let len = str.length; - while (len - 1 >= 0 && str[len - 1] === ch) { - --len; - } - return str.substr(0, len); -} -function bufferToBase64Url(buffer) { - if (!buffer) { - return undefined; - } - if (!(buffer instanceof Uint8Array)) { - throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`); - } - // Uint8Array to Base64. - const str = encodeByteArray(buffer); - // Base64 to Base64Url. - return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_"); -} -function base64UrlToByteArray(str) { - if (!str) { - return undefined; - } - if (str && typeof str.valueOf() !== "string") { - throw new Error("Please provide an input of type string for converting to Uint8Array"); + return stats; + }); } - // Base64Url to Base64. - str = str.replace(/-/g, "+").replace(/_/g, "/"); - // Base64 to Uint8Array. - return decodeString(str); } -function splitSerializeName(prop) { - const classes = []; - let partialclass = ""; - if (prop) { - const subwords = prop.split("."); - for (const item of subwords) { - if (item.charAt(item.length - 1) === "\\") { - partialclass += item.substr(0, item.length - 1) + "."; +exports.DefaultGlobber = DefaultGlobber; +//# sourceMappingURL=internal-globber.js.map + +/***/ }), + +/***/ 82561: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +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); } +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.hashFiles = void 0; +const crypto = __importStar(__nccwpck_require__(6113)); +const core = __importStar(__nccwpck_require__(65681)); +const fs = __importStar(__nccwpck_require__(57147)); +const stream = __importStar(__nccwpck_require__(12781)); +const util = __importStar(__nccwpck_require__(73837)); +const path = __importStar(__nccwpck_require__(71017)); +function hashFiles(globber, verbose = false) { + var e_1, _a; + var _b; + return __awaiter(this, void 0, void 0, function* () { + const writeDelegate = verbose ? core.info : core.debug; + let hasMatch = false; + const githubWorkspace = (_b = process.env['GITHUB_WORKSPACE']) !== null && _b !== void 0 ? _b : process.cwd(); + const result = crypto.createHash('sha256'); + let count = 0; + try { + for (var _c = __asyncValues(globber.globGenerator()), _d; _d = yield _c.next(), !_d.done;) { + const file = _d.value; + writeDelegate(file); + if (!file.startsWith(`${githubWorkspace}${path.sep}`)) { + writeDelegate(`Ignore '${file}' since it is not under GITHUB_WORKSPACE.`); + continue; + } + if (fs.statSync(file).isDirectory()) { + writeDelegate(`Skip directory '${file}'.`); + continue; + } + const hash = crypto.createHash('sha256'); + const pipeline = util.promisify(stream.pipeline); + yield pipeline(fs.createReadStream(file), hash); + result.write(hash.digest()); + count++; + if (!hasMatch) { + hasMatch = true; + } } - else { - partialclass += item; - classes.push(partialclass); - partialclass = ""; + } + 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 classes; + result.end(); + if (hasMatch) { + writeDelegate(`Found ${count} files to hash.`); + return result.digest('hex'); + } + else { + writeDelegate(`No matches found for glob`); + return ''; + } + }); } -function dateToUnixTime(d) { - if (!d) { - return undefined; +exports.hashFiles = hashFiles; +//# sourceMappingURL=internal-hash-files.js.map + +/***/ }), + +/***/ 65378: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MatchKind = void 0; +/** + * 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 + +/***/ }), + +/***/ 29844: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.safeTrimTrailingSeparator = exports.normalizeSeparators = exports.hasRoot = exports.hasAbsoluteRoot = exports.ensureAbsoluteRoot = exports.dirname = void 0; +const path = __importStar(__nccwpck_require__(71017)); +const assert_1 = __importDefault(__nccwpck_require__(39491)); +const IS_WINDOWS = process.platform === 'win32'; +/** + * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths. + * + * For example, on Linux/macOS: + * - `/ => /` + * - `/hello => /` + * + * For example, on Windows: + * - `C:\ => C:\` + * - `C:\hello => C:\` + * - `C: => C:` + * - `C:hello => C:` + * - `\ => \` + * - `\hello => \` + * - `\\hello => \\hello` + * - `\\hello\world => \\hello\world` + */ +function dirname(p) { + // Normalize slashes and trim unnecessary trailing slash + p = safeTrimTrailingSeparator(p); + // Windows UNC root, e.g. \\hello or \\hello\world + if (IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) { + return p; } - if (typeof d.valueOf() === "string") { - d = new Date(d); + // Get dirname + let result = path.dirname(p); + // Trim trailing slash for Windows UNC root, e.g. \\hello\world\ + if (IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) { + result = safeTrimTrailingSeparator(result); } - return Math.floor(d.getTime() / 1000); + return result; } -function unixTimeToDate(n) { - if (!n) { - return undefined; +exports.dirname = dirname; +/** + * Roots the path if not already rooted. On Windows, relative roots like `\` + * or `C:` are expanded based on the current working directory. + */ +function ensureAbsoluteRoot(root, itemPath) { + assert_1.default(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); + assert_1.default(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); + // Already rooted + if (hasAbsoluteRoot(itemPath)) { + return itemPath; } - return new Date(n * 1000); -} -function serializeBasicTypes(typeName, objectName, value) { - if (value !== null && value !== undefined) { - if (typeName.match(/^Number$/i) !== null) { - if (typeof value !== "number") { - throw new Error(`${objectName} with value ${value} must be of type number.`); - } - } - else if (typeName.match(/^String$/i) !== null) { - if (typeof value.valueOf() !== "string") { - throw new Error(`${objectName} with value "${value}" must be of type string.`); - } - } - else if (typeName.match(/^Uuid$/i) !== null) { - if (!(typeof value.valueOf() === "string" && isValidUuid(value))) { - throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`); + // Windows + if (IS_WINDOWS) { + // Check for itemPath like C: or C:foo + if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) { + let cwd = process.cwd(); + assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + // Drive letter matches cwd? Expand to cwd + if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) { + // Drive only, e.g. C: + if (itemPath.length === 2) { + // Preserve specified drive letter case (upper or lower) + return `${itemPath[0]}:\\${cwd.substr(3)}`; + } + // Drive + path, e.g. C:foo + else { + if (!cwd.endsWith('\\')) { + cwd += '\\'; + } + // Preserve specified drive letter case (upper or lower) + return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`; + } } - } - else if (typeName.match(/^Boolean$/i) !== null) { - if (typeof value !== "boolean") { - throw new Error(`${objectName} with value ${value} must be of type boolean.`); + // Different drive + else { + return `${itemPath[0]}:\\${itemPath.substr(2)}`; } } - else if (typeName.match(/^Stream$/i) !== null) { - const objectType = typeof value; - if (objectType !== "string" && - objectType !== "function" && - !(value instanceof ArrayBuffer) && - !ArrayBuffer.isView(value) && - !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob)) { - throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream.`); - } + // Check for itemPath like \ or \foo + else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) { + const cwd = process.cwd(); + assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + return `${cwd[0]}:\\${itemPath.substr(1)}`; } } - return value; -} -function serializeEnumType(objectName, allowedValues, value) { - if (!allowedValues) { - throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`); + assert_1.default(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); + // Otherwise ensure root ends with a separator + if (root.endsWith('/') || (IS_WINDOWS && root.endsWith('\\'))) { + // Intentionally empty } - const isPresent = allowedValues.some((item) => { - if (typeof item.valueOf() === "string") { - return item.toLowerCase() === value.toLowerCase(); - } - return item === value; - }); - if (!isPresent) { - throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`); + else { + // Append separator + root += path.sep; } - return value; + return root + itemPath; } -function serializeByteArrayType(objectName, value) { - let returnValue = ""; - if (value != undefined) { - if (!(value instanceof Uint8Array)) { - throw new Error(`${objectName} must be of type Uint8Array.`); - } - returnValue = encodeByteArray(value); +exports.ensureAbsoluteRoot = ensureAbsoluteRoot; +/** + * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: + * `\\hello\share` and `C:\hello` (and using alternate separator). + */ +function hasAbsoluteRoot(itemPath) { + assert_1.default(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); + // Normalize separators + itemPath = normalizeSeparators(itemPath); + // Windows + if (IS_WINDOWS) { + // E.g. \\hello\share or C:\hello + return itemPath.startsWith('\\\\') || /^[A-Z]:\\/i.test(itemPath); } - return returnValue; + // E.g. /hello + return itemPath.startsWith('/'); } -function serializeBase64UrlType(objectName, value) { - let returnValue = ""; - if (value != undefined) { - if (!(value instanceof Uint8Array)) { - throw new Error(`${objectName} must be of type Uint8Array.`); - } - returnValue = bufferToBase64Url(value) || ""; +exports.hasAbsoluteRoot = hasAbsoluteRoot; +/** + * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: + * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator). + */ +function hasRoot(itemPath) { + assert_1.default(itemPath, `isRooted parameter 'itemPath' must not be empty`); + // Normalize separators + itemPath = normalizeSeparators(itemPath); + // Windows + if (IS_WINDOWS) { + // E.g. \ or \hello or \\hello + // E.g. C: or C:\hello + return itemPath.startsWith('\\') || /^[A-Z]:/i.test(itemPath); } - return returnValue; + // E.g. /hello + return itemPath.startsWith('/'); } -function serializeDateTypes(typeName, value, objectName) { - if (value != undefined) { - if (typeName.match(/^Date$/i) !== null) { - if (!(value instanceof Date || - (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); - } - value = - value instanceof Date - ? value.toISOString().substring(0, 10) - : new Date(value).toISOString().substring(0, 10); - } - else if (typeName.match(/^DateTime$/i) !== null) { - if (!(value instanceof Date || - (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); - } - value = value instanceof Date ? value.toISOString() : new Date(value).toISOString(); - } - else if (typeName.match(/^DateTimeRfc1123$/i) !== null) { - if (!(value instanceof Date || - (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`); - } - value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString(); - } - else if (typeName.match(/^UnixTime$/i) !== null) { - if (!(value instanceof Date || - (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` + - `for it to be serialized in UnixTime/Epoch format.`); - } - value = dateToUnixTime(value); - } - else if (typeName.match(/^TimeSpan$/i) !== null) { - if (!isDuration(value)) { - throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`); - } - } +exports.hasRoot = hasRoot; +/** + * Removes redundant slashes and converts `/` to `\` on Windows + */ +function normalizeSeparators(p) { + p = p || ''; + // Windows + if (IS_WINDOWS) { + // Convert slashes on Windows + p = p.replace(/\//g, '\\'); + // Remove redundant slashes + const isUnc = /^\\\\+[^\\]/.test(p); // e.g. \\hello + return (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\'); // preserve leading \\ for UNC } - return value; + // Remove redundant slashes + return p.replace(/\/\/+/g, '/'); } -function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) { - if (!Array.isArray(object)) { - throw new Error(`${objectName} must be of type Array.`); +exports.normalizeSeparators = normalizeSeparators; +/** + * Normalizes the path separators and trims the trailing separator (when safe). + * For example, `/foo/ => /foo` but `/ => /` + */ +function safeTrimTrailingSeparator(p) { + // Short-circuit if empty + if (!p) { + return ''; } - const elementType = mapper.type.element; - if (!elementType || typeof elementType !== "object") { - throw new Error(`element" metadata for an Array must be defined in the ` + - `mapper and it must of type "object" in ${objectName}.`); + // Normalize separators + p = normalizeSeparators(p); + // No trailing slash + if (!p.endsWith(path.sep)) { + return p; } - const tempArray = []; - for (let i = 0; i < object.length; i++) { - const serializedValue = serializer.serialize(elementType, object[i], objectName, options); - if (isXml && elementType.xmlNamespace) { - const xmlnsKey = elementType.xmlNamespacePrefix - ? `xmlns:${elementType.xmlNamespacePrefix}` - : "xmlns"; - if (elementType.type.name === "Composite") { - tempArray[i] = Object.assign({}, serializedValue); - tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; + // Check '/' on Linux/macOS and '\' on Windows + if (p === path.sep) { + return p; + } + // On Windows check if drive root. E.g. C:\ + if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) { + return p; + } + // Otherwise trim trailing slash + return p.substr(0, p.length - 1); +} +exports.safeTrimTrailingSeparator = safeTrimTrailingSeparator; +//# sourceMappingURL=internal-path-helper.js.map + +/***/ }), + +/***/ 94166: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Path = void 0; +const path = __importStar(__nccwpck_require__(71017)); +const pathHelper = __importStar(__nccwpck_require__(29844)); +const assert_1 = __importDefault(__nccwpck_require__(39491)); +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_1.default(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 { - tempArray[i] = {}; - tempArray[i][options.xmlCharKey] = serializedValue; - tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; + // 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 { - tempArray[i] = serializedValue; + // Must not be empty + assert_1.default(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_1.default(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_1.default(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_1.default(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); + this.segments.push(segment); + } + } } } - return tempArray; -} -function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) { - if (typeof object !== "object") { - throw new Error(`${objectName} must be of type object.`); - } - const valueType = mapper.type.value; - if (!valueType || typeof valueType !== "object") { - throw new Error(`"value" metadata for a Dictionary must be defined in the ` + - `mapper and it must of type "object" in ${objectName}.`); - } - const tempDictionary = {}; - for (const key of Object.keys(object)) { - const serializedValue = serializer.serialize(valueType, object[key], objectName, options); - // If the element needs an XML namespace we need to add it within the $ property - tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options); - } - // Add the namespace to the root element if needed - if (isXml && mapper.xmlNamespace) { - const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; - const result = tempDictionary; - result[XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace }; + /** + * 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; } - return tempDictionary; } +exports.Path = Path; +//# sourceMappingURL=internal-path.js.map + +/***/ }), + +/***/ 23299: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.partialMatch = exports.match = exports.getSearchPaths = void 0; +const pathHelper = __importStar(__nccwpck_require__(29844)); +const internal_match_kind_1 = __nccwpck_require__(65378); +const IS_WINDOWS = process.platform === 'win32'; /** - * Resolves the additionalProperties property from a referenced mapper. - * @param serializer - The serializer containing the entire set of mappers. - * @param mapper - The composite mapper to resolve. - * @param objectName - Name of the object being serialized. + * Given an array of patterns, returns an array of paths to search. + * Duplicates and paths under other included paths are filtered out. */ -function resolveAdditionalProperties(serializer, mapper, objectName) { - const additionalProperties = mapper.type.additionalProperties; - if (!additionalProperties && mapper.type.className) { - const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); - return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties; +function getSearchPaths(patterns) { + // Ignore negate patterns + patterns = patterns.filter(x => !x.negate); + // Create a map of all search paths + const searchPathMap = {}; + for (const pattern of patterns) { + const key = IS_WINDOWS + ? pattern.searchPath.toUpperCase() + : pattern.searchPath; + searchPathMap[key] = 'candidate'; } - return additionalProperties; + const result = []; + for (const pattern of patterns) { + // Check if already included + const key = IS_WINDOWS + ? pattern.searchPath.toUpperCase() + : pattern.searchPath; + if (searchPathMap[key] === 'included') { + continue; + } + // Check for an ancestor search path + let foundAncestor = false; + let tempKey = key; + let parent = pathHelper.dirname(tempKey); + while (parent !== tempKey) { + if (searchPathMap[parent]) { + foundAncestor = true; + break; + } + tempKey = parent; + parent = pathHelper.dirname(tempKey); + } + // Include the search pattern in the result + if (!foundAncestor) { + result.push(pattern.searchPath); + searchPathMap[key] = 'included'; + } + } + return result; } +exports.getSearchPaths = getSearchPaths; /** - * Finds the mapper referenced by `className`. - * @param serializer - The serializer containing the entire set of mappers - * @param mapper - The composite mapper to resolve - * @param objectName - Name of the object being serialized + * Matches the patterns against the path */ -function resolveReferencedMapper(serializer, mapper, objectName) { - const className = mapper.type.className; - if (!className) { - throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`); +function match(patterns, itemPath) { + let result = internal_match_kind_1.MatchKind.None; + for (const pattern of patterns) { + if (pattern.negate) { + result &= ~pattern.match(itemPath); + } + else { + result |= pattern.match(itemPath); + } } - return serializer.modelMappers[className]; + return result; } +exports.match = match; /** - * Resolves a composite mapper's modelProperties. - * @param serializer - The serializer containing the entire set of mappers - * @param mapper - The composite mapper to resolve + * Checks whether to descend further into the directory */ -function resolveModelProperties(serializer, mapper, objectName) { - let modelProps = mapper.type.modelProperties; - if (!modelProps) { - const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); - if (!modelMapper) { - throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`); +function partialMatch(patterns, itemPath) { + return patterns.some(x => !x.negate && x.partialMatch(itemPath)); +} +exports.partialMatch = partialMatch; +//# sourceMappingURL=internal-pattern-helper.js.map + +/***/ }), + +/***/ 23425: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Pattern = void 0; +const os = __importStar(__nccwpck_require__(22037)); +const path = __importStar(__nccwpck_require__(71017)); +const pathHelper = __importStar(__nccwpck_require__(29844)); +const assert_1 = __importDefault(__nccwpck_require__(39491)); +const minimatch_1 = __nccwpck_require__(67586); +const internal_match_kind_1 = __nccwpck_require__(65378); +const internal_path_1 = __nccwpck_require__(94166); +const IS_WINDOWS = process.platform === 'win32'; +class Pattern { + constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) { + /** + * Indicates whether matches should be excluded from the result set + */ + this.negate = false; + // Pattern overload + let pattern; + if (typeof patternOrNegate === 'string') { + pattern = patternOrNegate.trim(); } - modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties; - if (!modelProps) { - throw new Error(`modelProperties cannot be null or undefined in the ` + - `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`); + // Segments overload + else { + // Convert to pattern + segments = segments || []; + assert_1.default(segments.length, `Parameter 'segments' must not empty`); + const root = Pattern.getLiteral(segments[0]); + assert_1.default(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); + pattern = new internal_path_1.Path(segments).toString().trim(); + if (patternOrNegate) { + pattern = `!${pattern}`; + } } + // Negate + while (pattern.startsWith('!')) { + this.negate = !this.negate; + pattern = pattern.substr(1).trim(); + } + // Normalize slashes and ensures absolute root + pattern = Pattern.fixupPattern(pattern, homedir); + // Segments + this.segments = new internal_path_1.Path(pattern).segments; + // Trailing slash indicates the pattern should only match directories, not regular files + this.trailingSeparator = pathHelper + .normalizeSeparators(pattern) + .endsWith(path.sep); + pattern = pathHelper.safeTrimTrailingSeparator(pattern); + // Search path (literal path prior to the first glob segment) + let foundGlob = false; + const searchSegments = this.segments + .map(x => Pattern.getLiteral(x)) + .filter(x => !foundGlob && !(foundGlob = x === '')); + this.searchPath = new internal_path_1.Path(searchSegments).toString(); + // Root RegExp (required when determining partial match) + this.rootRegExp = new RegExp(Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? 'i' : ''); + this.isImplicitPattern = isImplicitPattern; + // Create minimatch + const minimatchOptions = { + dot: true, + nobrace: true, + nocase: IS_WINDOWS, + nocomment: true, + noext: true, + nonegate: true + }; + pattern = IS_WINDOWS ? pattern.replace(/\\/g, '/') : pattern; + this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions); } - return modelProps; -} -function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) { - if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { - mapper = getPolymorphicMapper(serializer, mapper, object, "clientName"); - } - if (object != undefined) { - const payload = {}; - const modelProps = resolveModelProperties(serializer, mapper, objectName); - for (const key of Object.keys(modelProps)) { - const propertyMapper = modelProps[key]; - if (propertyMapper.readOnly) { - continue; - } - let propName; - let parentObject = payload; - if (serializer.isXML) { - if (propertyMapper.xmlIsWrapped) { - propName = propertyMapper.xmlName; - } - else { - propName = propertyMapper.xmlElementName || propertyMapper.xmlName; - } - } - else { - const paths = splitSerializeName(propertyMapper.serializedName); - propName = paths.pop(); - for (const pathName of paths) { - const childObject = parentObject[pathName]; - if (childObject == undefined && - (object[key] != undefined || propertyMapper.defaultValue !== undefined)) { - parentObject[pathName] = {}; - } - parentObject = parentObject[pathName]; - } - } - if (parentObject != undefined) { - if (isXml && mapper.xmlNamespace) { - const xmlnsKey = mapper.xmlNamespacePrefix - ? `xmlns:${mapper.xmlNamespacePrefix}` - : "xmlns"; - parentObject[XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace }); - } - const propertyObjectName = propertyMapper.serializedName !== "" - ? objectName + "." + propertyMapper.serializedName - : objectName; - let toSerialize = object[key]; - const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); - if (polymorphicDiscriminator && - polymorphicDiscriminator.clientName === key && - toSerialize == undefined) { - toSerialize = mapper.serializedName; - } - const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options); - if (serializedValue !== undefined && propName != undefined) { - const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options); - if (isXml && propertyMapper.xmlIsAttribute) { - // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js. - // This keeps things simple while preventing name collision - // with names in user documents. - parentObject[XML_ATTRKEY] = parentObject[XML_ATTRKEY] || {}; - parentObject[XML_ATTRKEY][propName] = serializedValue; - } - else if (isXml && propertyMapper.xmlIsWrapped) { - parentObject[propName] = { [propertyMapper.xmlElementName]: value }; - } - else { - parentObject[propName] = value; - } - } + /** + * Matches the pattern against the specified path + */ + match(itemPath) { + // Last segment is globstar? + if (this.segments[this.segments.length - 1] === '**') { + // Normalize slashes + itemPath = pathHelper.normalizeSeparators(itemPath); + // Append a trailing slash. Otherwise Minimatch will not match the directory immediately + // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns + // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk. + if (!itemPath.endsWith(path.sep) && this.isImplicitPattern === false) { + // Note, this is safe because the constructor ensures the pattern has an absolute root. + // For example, formats like C: and C:foo on Windows are resolved to an absolute root. + itemPath = `${itemPath}${path.sep}`; } } - const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName); - if (additionalPropertiesMapper) { - const propNames = Object.keys(modelProps); - for (const clientPropName in object) { - const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName); - if (isAdditionalProperty) { - payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options); - } - } + else { + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); } - return payload; - } - return object; -} -function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { - if (!isXml || !propertyMapper.xmlNamespace) { - return serializedValue; - } - const xmlnsKey = propertyMapper.xmlNamespacePrefix - ? `xmlns:${propertyMapper.xmlNamespacePrefix}` - : "xmlns"; - const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace }; - if (["Composite"].includes(propertyMapper.type.name)) { - if (serializedValue[XML_ATTRKEY]) { - return serializedValue; + // Match + if (this.minimatch.match(itemPath)) { + return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All; } - else { - const result = Object.assign({}, serializedValue); - result[XML_ATTRKEY] = xmlNamespace; - return result; + return internal_match_kind_1.MatchKind.None; + } + /** + * Indicates whether the pattern may match descendants of the specified path + */ + partialMatch(itemPath) { + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + // matchOne does not handle root path correctly + if (pathHelper.dirname(itemPath) === itemPath) { + return this.rootRegExp.test(itemPath); } + return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true); } - const result = {}; - result[options.xmlCharKey] = serializedValue; - result[XML_ATTRKEY] = xmlNamespace; - return result; -} -function isSpecialXmlProperty(propertyName, options) { - return [XML_ATTRKEY, options.xmlCharKey].includes(propertyName); -} -function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) { - var _a; - if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { - mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); + /** + * Escapes glob patterns within a path + */ + static globEscape(s) { + return (IS_WINDOWS ? s : s.replace(/\\/g, '\\\\')) // escape '\' on Linux/macOS + .replace(/(\[)(?=[^/]+\])/g, '[[]') // escape '[' when ']' follows within the path segment + .replace(/\?/g, '[?]') // escape '?' + .replace(/\*/g, '[*]'); // escape '*' } - const modelProps = resolveModelProperties(serializer, mapper, objectName); - let instance = {}; - const handledPropertyNames = []; - for (const key of Object.keys(modelProps)) { - const propertyMapper = modelProps[key]; - const paths = splitSerializeName(modelProps[key].serializedName); - handledPropertyNames.push(paths[0]); - const { serializedName, xmlName, xmlElementName } = propertyMapper; - let propertyObjectName = objectName; - if (serializedName !== "" && serializedName !== undefined) { - propertyObjectName = objectName + "." + serializedName; + /** + * Normalizes slashes and ensures absolute root + */ + static fixupPattern(pattern, homedir) { + // Empty + assert_1.default(pattern, 'pattern cannot be empty'); + // Must not contain `.` segment, unless first segment + // Must not contain `..` segment + const literalSegments = new internal_path_1.Path(pattern).segments.map(x => Pattern.getLiteral(x)); + assert_1.default(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); + // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r + assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); + // Normalize slashes + pattern = pathHelper.normalizeSeparators(pattern); + // Replace leading `.` segment + if (pattern === '.' || pattern.startsWith(`.${path.sep}`)) { + pattern = Pattern.globEscape(process.cwd()) + pattern.substr(1); } - const headerCollectionPrefix = propertyMapper.headerCollectionPrefix; - if (headerCollectionPrefix) { - const dictionary = {}; - for (const headerKey of Object.keys(responseBody)) { - if (headerKey.startsWith(headerCollectionPrefix)) { - dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options); - } - handledPropertyNames.push(headerKey); - } - instance[key] = dictionary; + // Replace leading `~` segment + else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) { + homedir = homedir || os.homedir(); + assert_1.default(homedir, 'Unable to determine HOME directory'); + assert_1.default(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); + pattern = Pattern.globEscape(homedir) + pattern.substr(1); } - else if (serializer.isXML) { - if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) { - instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options); + // Replace relative drive root, e.g. pattern is C: or C:foo + else if (IS_WINDOWS && + (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) { + let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', pattern.substr(0, 2)); + if (pattern.length > 2 && !root.endsWith('\\')) { + root += '\\'; } - else { - const propertyName = xmlElementName || xmlName || serializedName; - if (propertyMapper.xmlIsWrapped) { - /* a list of wrapped by - For the xml example below - - ... - ... - - the responseBody has - { - Cors: { - CorsRule: [{...}, {...}] - } - } - xmlName is "Cors" and xmlElementName is"CorsRule". - */ - const wrapped = responseBody[xmlName]; - const elementList = (_a = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _a !== void 0 ? _a : []; - instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options); - } - else { - const property = responseBody[propertyName]; - instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options); - } + pattern = Pattern.globEscape(root) + pattern.substr(2); + } + // Replace relative root, e.g. pattern is \ or \foo + else if (IS_WINDOWS && (pattern === '\\' || pattern.match(/^\\[^\\]/))) { + let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', '\\'); + if (!root.endsWith('\\')) { + root += '\\'; } + pattern = Pattern.globEscape(root) + pattern.substr(1); } + // Otherwise ensure absolute root else { - // deserialize the property if it is present in the provided responseBody instance - let propertyInstance; - let res = responseBody; - // traversing the object step by step. - for (const item of paths) { - if (!res) - break; - res = res[item]; + pattern = pathHelper.ensureAbsoluteRoot(Pattern.globEscape(process.cwd()), pattern); + } + return pathHelper.normalizeSeparators(pattern); + } + /** + * Attempts to unescape a pattern segment to create a literal path segment. + * Otherwise returns empty string. + */ + static getLiteral(segment) { + let literal = ''; + for (let i = 0; i < segment.length; i++) { + const c = segment[i]; + // Escape + if (c === '\\' && !IS_WINDOWS && i + 1 < segment.length) { + literal += segment[++i]; + continue; } - propertyInstance = res; - const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator; - // checking that the model property name (key)(ex: "fishtype") and the - // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype") - // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type") - // is a better approach. The generator is not consistent with escaping '\.' in the - // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator - // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However, - // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and - // the transformation of model property name (ex: "fishtype") is done consistently. - // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator. - if (polymorphicDiscriminator && - key === polymorphicDiscriminator.clientName && - propertyInstance == undefined) { - propertyInstance = mapper.serializedName; + // Wildcard + else if (c === '*' || c === '?') { + return ''; } - let serializedValue; - // paging - if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") { - propertyInstance = responseBody[key]; - const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); - // Copy over any properties that have already been added into the instance, where they do - // not exist on the newly de-serialized array - for (const [k, v] of Object.entries(instance)) { - if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) { - arrayInstance[k] = v; + // Character set + else if (c === '[' && i + 1 < segment.length) { + let set = ''; + let closed = -1; + for (let i2 = i + 1; i2 < segment.length; i2++) { + const c2 = segment[i2]; + // Escape + if (c2 === '\\' && !IS_WINDOWS && i2 + 1 < segment.length) { + set += segment[++i2]; + continue; + } + // Closed + else if (c2 === ']') { + closed = i2; + break; + } + // Otherwise + else { + set += c2; } } - instance = arrayInstance; - } - else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) { - serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); - instance[key] = serializedValue; - } - } - } - const additionalPropertiesMapper = mapper.type.additionalProperties; - if (additionalPropertiesMapper) { - const isAdditionalProperty = (responsePropName) => { - for (const clientPropName in modelProps) { - const paths = splitSerializeName(modelProps[clientPropName].serializedName); - if (paths[0] === responsePropName) { - return false; + // Closed? + if (closed >= 0) { + // Cannot convert + if (set.length > 1) { + return ''; + } + // Convert to literal + if (set) { + literal += set; + i = closed; + continue; + } } + // Otherwise fall thru } - return true; - }; - for (const responsePropName in responseBody) { - if (isAdditionalProperty(responsePropName)) { - instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options); - } + // Append + literal += c; } + return literal; } - else if (responseBody) { - for (const key of Object.keys(responseBody)) { - if (instance[key] === undefined && - !handledPropertyNames.includes(key) && - !isSpecialXmlProperty(key, options)) { - instance[key] = responseBody[key]; - } - } + /** + * Escapes regexp special characters + * https://javascript.info/regexp-escaping + */ + static regExpEscape(s) { + return s.replace(/[[\\^$.|?*+()]/g, '\\$&'); } - return instance; } -function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) { - const value = mapper.type.value; - if (!value || typeof value !== "object") { - throw new Error(`"value" metadata for a Dictionary must be defined in the ` + - `mapper and it must of type "object" in ${objectName}`); +exports.Pattern = Pattern; +//# sourceMappingURL=internal-pattern.js.map + +/***/ }), + +/***/ 86646: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SearchState = void 0; +class SearchState { + constructor(path, level) { + this.path = path; + this.level = level; } - if (responseBody) { - const tempDictionary = {}; - for (const key of Object.keys(responseBody)) { - tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options); +} +exports.SearchState = SearchState; +//# sourceMappingURL=internal-search-state.js.map + +/***/ }), + +/***/ 98336: +/***/ (function(__unused_webpack_module, exports) { + +"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.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; +class BasicCredentialHandler { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); } - return tempDictionary; + options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); } - return responseBody; } -function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) { - const element = mapper.type.element; - if (!element || typeof element !== "object") { - throw new Error(`element" metadata for an Array must be defined in the ` + - `mapper and it must of type "object" in ${objectName}`); +exports.BasicCredentialHandler = BasicCredentialHandler; +class BearerCredentialHandler { + constructor(token) { + this.token = token; } - if (responseBody) { - if (!Array.isArray(responseBody)) { - // xml2js will interpret a single element array as just the element, so force it to be an array - responseBody = [responseBody]; - } - const tempArray = []; - for (let i = 0; i < responseBody.length; i++) { - tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options); + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); } - return tempArray; + options.headers['Authorization'] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); } - return responseBody; } -function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) { - const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); - if (polymorphicDiscriminator) { - const discriminatorName = polymorphicDiscriminator[polymorphicPropertyName]; - if (discriminatorName != undefined) { - const discriminatorValue = object[discriminatorName]; - if (discriminatorValue != undefined) { - const typeName = mapper.type.uberParent || mapper.type.className; - const indexDiscriminator = discriminatorValue === typeName - ? discriminatorValue - : typeName + "." + discriminatorValue; - const polymorphicMapper = serializer.modelMappers.discriminators[indexDiscriminator]; - if (polymorphicMapper) { - mapper = polymorphicMapper; - } - } +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) { + if (!options.headers) { + throw Error('The request has no headers'); } + options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; +//# sourceMappingURL=auth.js.map + +/***/ }), + +/***/ 9706: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/* eslint-disable @typescript-eslint/no-explicit-any */ +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.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; +const http = __importStar(__nccwpck_require__(13685)); +const https = __importStar(__nccwpck_require__(95687)); +const pm = __importStar(__nccwpck_require__(80531)); +const tunnel = __importStar(__nccwpck_require__(68125)); +var HttpCodes; +(function (HttpCodes) { + HttpCodes[HttpCodes["OK"] = 200] = "OK"; + HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; + HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; + HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; + HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; + HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; + HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; + HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; + HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; + HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); +var Headers; +(function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; +})(Headers = exports.Headers || (exports.Headers = {})); +var MediaTypes; +(function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; +})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); +/** + * Returns the proxy URL, depending upon the supplied url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ +function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ''; +} +exports.getProxyUrl = getProxyUrl; +const HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +const HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; +const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; +const ExponentialBackoffCeiling = 10; +const ExponentialBackoffTimeSlice = 5; +class HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = 'HttpClientError'; + this.statusCode = statusCode; + Object.setPrototypeOf(this, HttpClientError.prototype); + } +} +exports.HttpClientError = HttpClientError; +class HttpClientResponse { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on('data', (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on('end', () => { + resolve(output.toString()); + }); + })); + }); } - return mapper; -} -function getPolymorphicDiscriminatorRecursively(serializer, mapper) { - return (mapper.type.polymorphicDiscriminator || - getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) || - getPolymorphicDiscriminatorSafely(serializer, mapper.type.className)); } -function getPolymorphicDiscriminatorSafely(serializer, typeName) { - return (typeName && - serializer.modelMappers[typeName] && - serializer.modelMappers[typeName].type.polymorphicDiscriminator); +exports.HttpClientResponse = HttpClientResponse; +function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === 'https:'; } -/** - * Utility function that serializes an object that might contain binary information into a plain object, array or a string. - */ -function serializeObject(toSerialize) { - const castToSerialize = toSerialize; - if (toSerialize == undefined) - return undefined; - if (toSerialize instanceof Uint8Array) { - toSerialize = encodeByteArray(toSerialize); - return toSerialize; +exports.isHttps = isHttps; +class HttpClient { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } } - else if (toSerialize instanceof Date) { - return toSerialize.toISOString(); + options(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + }); } - else if (Array.isArray(toSerialize)) { - const array = []; - for (let i = 0; i < toSerialize.length; i++) { - array.push(serializeObject(toSerialize[i])); - } - return array; + get(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('GET', requestUrl, null, additionalHeaders || {}); + }); } - else if (typeof toSerialize === "object") { - const dictionary = {}; - for (const property in toSerialize) { - dictionary[property] = serializeObject(castToSerialize[property]); - } - return dictionary; + del(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + }); } - return toSerialize; -} -/** - * Utility function to create a K:V from a list of strings - */ -function strEnum(o) { - const result = {}; - for (const key of o) { - result[key] = key; + post(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('POST', requestUrl, data, additionalHeaders || {}); + }); } - return result; -} -/** - * String enum containing the string types of property mappers. - */ -// eslint-disable-next-line @typescript-eslint/no-redeclare -const MapperType = strEnum([ - "Base64Url", - "Boolean", - "ByteArray", - "Composite", - "Date", - "DateTime", - "DateTimeRfc1123", - "Dictionary", - "Enum", - "Number", - "Object", - "Sequence", - "String", - "Stream", - "TimeSpan", - "UnixTime", -]); - -// Copyright (c) Microsoft Corporation. -function isWebResourceLike(object) { - if (object && typeof object === "object") { - const castObject = object; - if (typeof castObject.url === "string" && - typeof castObject.method === "string" && - typeof castObject.headers === "object" && - isHttpHeadersLike(castObject.headers) && - typeof castObject.validateRequestProperties === "function" && - typeof castObject.prepare === "function" && - typeof castObject.clone === "function") { - return true; - } + patch(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + }); } - return false; -} -/** - * Creates a new WebResource object. - * - * This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary - * properties to initiate a request. - */ -class WebResource { - constructor(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, decompressResponse, streamResponseStatusCodes) { - this.streamResponseBody = streamResponseBody; - this.streamResponseStatusCodes = streamResponseStatusCodes; - this.url = url || ""; - this.method = method || "GET"; - this.headers = isHttpHeadersLike(headers) ? headers : new HttpHeaders(headers); - this.body = body; - this.query = query; - this.formData = undefined; - this.withCredentials = withCredentials || false; - this.abortSignal = abortSignal; - this.timeout = timeout || 0; - this.onUploadProgress = onUploadProgress; - this.onDownloadProgress = onDownloadProgress; - this.proxySettings = proxySettings; - this.keepAlive = keepAlive; - this.decompressResponse = decompressResponse; - this.requestId = this.headers.get("x-ms-client-request-id") || generateUuid(); + put(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PUT', requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); } /** - * Validates that the required properties such as method, url, headers["Content-Type"], - * headers["accept-language"] are defined. It will throw an error if one of the above - * mentioned properties are not defined. + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise */ - validateRequestProperties() { - if (!this.method) { - throw new Error("WebResource.method is required."); - } - if (!this.url) { - throw new Error("WebResource.url is required."); - } + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } /** - * Prepares the request. - * @param options - Options to provide for preparing the request. - * @returns Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline. + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch */ - prepare(options) { - if (!options) { - throw new Error("options object is required"); - } - if (options.method === undefined || - options.method === null || - typeof options.method.valueOf() !== "string") { - throw new Error("options.method must be a string."); - } - if (options.url && options.pathTemplate) { - throw new Error("options.url and options.pathTemplate are mutually exclusive. Please provide exactly one of them."); - } - if ((options.pathTemplate === undefined || - options.pathTemplate === null || - typeof options.pathTemplate.valueOf() !== "string") && - (options.url === undefined || - options.url === null || - typeof options.url.valueOf() !== "string")) { - throw new Error("Please provide exactly one of options.pathTemplate or options.url."); - } - // set the url if it is provided. - if (options.url) { - if (typeof options.url !== "string") { - throw new Error('options.url must be of type "string".'); - } - this.url = options.url; - } - // set the method - if (options.method) { - const validMethods = ["GET", "PUT", "HEAD", "DELETE", "OPTIONS", "POST", "PATCH", "TRACE"]; - if (validMethods.indexOf(options.method.toUpperCase()) === -1) { - throw new Error('The provided method "' + - options.method + - '" is invalid. Supported HTTP methods are: ' + - JSON.stringify(validMethods)); - } - } - this.method = options.method.toUpperCase(); - // construct the url if path template is provided - if (options.pathTemplate) { - const { pathTemplate, pathParameters } = options; - if (typeof pathTemplate !== "string") { - throw new Error('options.pathTemplate must be of type "string".'); - } - if (!options.baseUrl) { - options.baseUrl = "https://management.azure.com"; + request(verb, requestUrl, data, headers) { + return __awaiter(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error('Client has already been disposed.'); } - const baseUrl = options.baseUrl; - let url = baseUrl + - (baseUrl.endsWith("/") ? "" : "/") + - (pathTemplate.startsWith("/") ? pathTemplate.slice(1) : pathTemplate); - const segments = url.match(/({[\w-]*\s*[\w-]*})/gi); - if (segments && segments.length) { - if (!pathParameters) { - throw new Error(`pathTemplate: ${pathTemplate} has been provided. Hence, options.pathParameters must also be provided.`); - } - segments.forEach(function (item) { - const pathParamName = item.slice(1, -1); - const pathParam = pathParameters[pathParamName]; - if (pathParam === null || - pathParam === undefined || - !(typeof pathParam === "string" || typeof pathParam === "object")) { - const stringifiedPathParameters = JSON.stringify(pathParameters, undefined, 2); - throw new Error(`pathTemplate: ${pathTemplate} contains the path parameter ${pathParamName}` + - ` however, it is not present in parameters: ${stringifiedPathParameters}.` + - `The value of the path parameter can either be a "string" of the form { ${pathParamName}: "some sample value" } or ` + - `it can be an "object" of the form { "${pathParamName}": { value: "some sample value", skipUrlEncoding: true } }.`); + const parsedUrl = new URL(requestUrl); + let info = this._prepareRequest(verb, parsedUrl, headers); + // Only perform retries on reads since writes may not be idempotent. + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) + ? this._maxRetries + 1 + : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info, data); + // Check if it's an authentication challenge + if (response && + response.message && + response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } } - if (typeof pathParam.valueOf() === "string") { - url = url.replace(item, encodeURIComponent(pathParam)); + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info, data); } - if (typeof pathParam.valueOf() === "object") { - if (!pathParam.value) { - throw new Error(`options.pathParameters[${pathParamName}] is of type "object" but it does not contain a "value" property.`); - } - if (pathParam.skipUrlEncoding) { - url = url.replace(item, pathParam.value); - } - else { - url = url.replace(item, encodeURIComponent(pathParam.value)); - } + else { + // We have received an unauthorized response but have no handlers to handle it. + // Let the response return to the caller. + return response; } - }); - } - this.url = url; - } - // append query parameters to the url if they are provided. They can be provided with pathTemplate or url option. - if (options.queryParameters) { - const queryParameters = options.queryParameters; - if (typeof queryParameters !== "object") { - throw new Error(`options.queryParameters must be of type object. It should be a JSON object ` + - `of "query-parameter-name" as the key and the "query-parameter-value" as the value. ` + - `The "query-parameter-value" may be fo type "string" or an "object" of the form { value: "query-parameter-value", skipUrlEncoding: true }.`); - } - // append question mark if it is not present in the url - if (this.url && this.url.indexOf("?") === -1) { - this.url += "?"; - } - // construct queryString - const queryParams = []; - // We need to populate this.query as a dictionary if the request is being used for Sway's validateRequest(). - this.query = {}; - for (const queryParamName in queryParameters) { - const queryParam = queryParameters[queryParamName]; - if (queryParam) { - if (typeof queryParam === "string") { - queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam)); - this.query[queryParamName] = encodeURIComponent(queryParam); + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && + HttpRedirectCodes.includes(response.message.statusCode) && + this._allowRedirects && + redirectsRemaining > 0) { + const redirectUrl = response.message.headers['location']; + if (!redirectUrl) { + // if there's no location to redirect to, we won't + break; } - else if (typeof queryParam === "object") { - if (!queryParam.value) { - throw new Error(`options.queryParameters[${queryParamName}] is of type "object" but it does not contain a "value" property.`); - } - if (queryParam.skipUrlEncoding) { - queryParams.push(queryParamName + "=" + queryParam.value); - this.query[queryParamName] = queryParam.value; - } - else { - queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam.value)); - this.query[queryParamName] = encodeURIComponent(queryParam.value); + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === 'https:' && + parsedUrl.protocol !== parsedRedirectUrl.protocol && + !this._allowRedirectDowngrade) { + throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); + } + // we need to finish reading the response before reassigning response + // which will leak the open socket. + yield response.readBody(); + // strip authorization header if redirected to a different hostname + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + // header names are case insensitive + if (header.toLowerCase() === 'authorization') { + delete headers[header]; + } } } + // let's make the request with the new redirectUrl + info = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info, data); + redirectsRemaining--; } - } // end-of-for - // append the queryString - this.url += queryParams.join("&"); - } - // add headers to the request if they are provided - if (options.headers) { - const headers = options.headers; - for (const headerName of Object.keys(options.headers)) { - this.headers.set(headerName, headers[headerName]); - } - } - // ensure accept-language is set correctly - if (!this.headers.get("accept-language")) { - this.headers.set("accept-language", "en-US"); - } - // ensure the request-id is set correctly - if (!this.headers.get("x-ms-client-request-id") && !options.disableClientRequestId) { - this.headers.set("x-ms-client-request-id", this.requestId); - } - // default - if (!this.headers.get("Content-Type")) { - this.headers.set("Content-Type", "application/json; charset=utf-8"); - } - // set the request body. request.js automatically sets the Content-Length request header, so we need not set it explicitly - this.body = options.body; - if (options.body !== undefined && options.body !== null) { - // body as a stream special case. set the body as-is and check for some special request headers specific to sending a stream. - if (options.bodyIsStream) { - if (!this.headers.get("Transfer-Encoding")) { - this.headers.set("Transfer-Encoding", "chunked"); - } - if (this.headers.get("Content-Type") !== "application/octet-stream") { - this.headers.set("Content-Type", "application/octet-stream"); - } - } - else { - if (options.serializationMapper) { - this.body = new Serializer(options.mappers).serialize(options.serializationMapper, options.body, "requestBody"); - } - if (!options.disableJsonStringifyOnBody) { - this.body = JSON.stringify(options.body); - } - } - } - if (options.spanOptions) { - this.spanOptions = options.spanOptions; - } - if (options.tracingContext) { - this.tracingContext = options.tracingContext; - } - this.abortSignal = options.abortSignal; - this.onDownloadProgress = options.onDownloadProgress; - this.onUploadProgress = options.onUploadProgress; - return this; - } - /** - * Clone this WebResource HTTP request object. - * @returns The clone of this WebResource HTTP request object. - */ - clone() { - const result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.decompressResponse, this.streamResponseStatusCodes); - if (this.formData) { - result.formData = this.formData; - } - if (this.operationSpec) { - result.operationSpec = this.operationSpec; - } - if (this.shouldDeserialize) { - result.shouldDeserialize = this.shouldDeserialize; - } - if (this.operationResponseGetter) { - result.operationResponseGetter = this.operationResponseGetter; - } - return result; - } -} - -// Copyright (c) Microsoft Corporation. -/** - * A class that handles the query portion of a URLBuilder. - */ -class URLQuery { - constructor() { - this._rawQuery = {}; - } - /** - * Get whether or not there any query parameters in this URLQuery. - */ - any() { - return Object.keys(this._rawQuery).length > 0; - } - /** - * Get the keys of the query string. - */ - keys() { - return Object.keys(this._rawQuery); + if (!response.message.statusCode || + !HttpResponseRetryCodes.includes(response.message.statusCode)) { + // If not a retry code, return immediately instead of retrying + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); } /** - * Set a query parameter with the provided name and value. If the parameterValue is undefined or - * empty, then this will attempt to remove an existing query parameter with the provided - * parameterName. + * Needs to be called if keepAlive is set to true in request options. */ - set(parameterName, parameterValue) { - const caseParameterValue = parameterValue; - if (parameterName) { - if (caseParameterValue !== undefined && caseParameterValue !== null) { - const newValue = Array.isArray(caseParameterValue) - ? caseParameterValue - : caseParameterValue.toString(); - this._rawQuery[parameterName] = newValue; - } - else { - delete this._rawQuery[parameterName]; - } + dispose() { + if (this._agent) { + this._agent.destroy(); } + this._disposed = true; } /** - * Get the value of the query parameter with the provided name. If no parameter exists with the - * provided parameter name, then undefined will be returned. - */ - get(parameterName) { - return parameterName ? this._rawQuery[parameterName] : undefined; - } - /** - * Get the string representation of this query. The return value will not start with a "?". + * Raw request. + * @param info + * @param data */ - toString() { - let result = ""; - for (const parameterName in this._rawQuery) { - if (result) { - result += "&"; - } - const parameterValue = this._rawQuery[parameterName]; - if (Array.isArray(parameterValue)) { - const parameterStrings = []; - for (const parameterValueElement of parameterValue) { - parameterStrings.push(`${parameterName}=${parameterValueElement}`); + requestRaw(info, data) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } + else if (!res) { + // If `err` is not passed, then `res` must be passed. + reject(new Error('Unknown error')); + } + else { + resolve(res); + } } - result += parameterStrings.join("&"); - } - else { - result += `${parameterName}=${parameterValue}`; - } - } - return result; + this.requestRawWithCallback(info, data, callbackForResult); + }); + }); } /** - * Parse a URLQuery from the provided text. + * Raw request with callback. + * @param info + * @param data + * @param onResult */ - static parse(text) { - const result = new URLQuery(); - if (text) { - if (text.startsWith("?")) { - text = text.substring(1); + requestRawWithCallback(info, data, onResult) { + if (typeof data === 'string') { + if (!info.options.headers) { + info.options.headers = {}; } - let currentState = "ParameterName"; - let parameterName = ""; - let parameterValue = ""; - for (let i = 0; i < text.length; ++i) { - const currentCharacter = text[i]; - switch (currentState) { - case "ParameterName": - switch (currentCharacter) { - case "=": - currentState = "ParameterValue"; - break; - case "&": - parameterName = ""; - parameterValue = ""; - break; - default: - parameterName += currentCharacter; - break; - } - break; - case "ParameterValue": - switch (currentCharacter) { - case "&": - result.set(parameterName, parameterValue); - parameterName = ""; - parameterValue = ""; - currentState = "ParameterName"; - break; - default: - parameterValue += currentCharacter; - break; - } - break; - default: - throw new Error("Unrecognized URLQuery parse state: " + currentState); - } + info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); } - if (currentState === "ParameterValue") { - result.set(parameterName, parameterValue); + } + const req = info.httpModule.request(info.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(undefined, res); + }); + let socket; + req.on('socket', sock => { + socket = sock; + }); + // If we ever get disconnected, we want the socket to timeout eventually + req.setTimeout(this._socketTimeout || 3 * 60000, () => { + if (socket) { + socket.end(); } + handleResult(new Error(`Request timeout: ${info.options.path}`)); + }); + req.on('error', function (err) { + // err has statusCode property + // res should have headers + handleResult(err); + }); + if (data && typeof data === 'string') { + req.write(data, 'utf8'); } - return result; - } -} -/** - * A class that handles creating, modifying, and parsing URLs. - */ -class URLBuilder { - /** - * Set the scheme/protocol for this URL. If the provided scheme contains other parts of a URL - * (such as a host, port, path, or query), those parts will be added to this URL as well. - */ - setScheme(scheme) { - if (!scheme) { - this._scheme = undefined; + if (data && typeof data !== 'string') { + data.on('close', function () { + req.end(); + }); + data.pipe(req); } else { - this.set(scheme, "SCHEME"); + req.end(); } } /** - * Get the scheme that has been set in this URL. + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ - getScheme() { - return this._scheme; + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - /** - * Set the host for this URL. If the provided host contains other parts of a URL (such as a - * port, path, or query), those parts will be added to this URL as well. - */ - setHost(host) { - if (!host) { - this._host = undefined; + _prepareRequest(method, requestUrl, headers) { + const info = {}; + info.parsedUrl = requestUrl; + const usingSsl = info.parsedUrl.protocol === 'https:'; + info.httpModule = usingSsl ? https : http; + const defaultPort = usingSsl ? 443 : 80; + info.options = {}; + info.options.host = info.parsedUrl.hostname; + info.options.port = info.parsedUrl.port + ? parseInt(info.parsedUrl.port) + : defaultPort; + info.options.path = + (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); + info.options.method = method; + info.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info.options.headers['user-agent'] = this.userAgent; } - else { - this.set(host, "SCHEME_OR_HOST"); + info.options.agent = this._getAgent(info.parsedUrl); + // gives handlers an opportunity to participate + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info.options); + } } + return info; } - /** - * Get the host that has been set in this URL. - */ - getHost() { - return this._host; - } - /** - * Set the port for this URL. If the provided port contains other parts of a URL (such as a - * path or query), those parts will be added to this URL as well. - */ - setPort(port) { - if (port === undefined || port === null || port === "") { - this._port = undefined; - } - else { - this.set(port.toString(), "PORT"); + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } + return lowercaseKeys(headers || {}); } - /** - * Get the port that has been set in this URL. - */ - getPort() { - return this._port; + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default; } - /** - * Set the path for this URL. If the provided path contains a query, then it will be added to - * this URL as well. - */ - setPath(path) { - if (!path) { - this._path = undefined; + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - else { - const schemeIndex = path.indexOf("://"); - if (schemeIndex !== -1) { - const schemeStart = path.lastIndexOf("/", schemeIndex); - // Make sure to only grab the URL part of the path before setting the state back to SCHEME - // this will handle cases such as "/a/b/c/https://microsoft.com" => "https://microsoft.com" - this.set(schemeStart === -1 ? path : path.substr(schemeStart + 1), "SCHEME"); + if (this._keepAlive && !useProxy) { + agent = this._agent; + } + // if agent is already assigned use that agent. + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + })), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === 'https:'; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { - this.set(path, "PATH"); - } - } - } - /** - * Append the provided path to this URL's existing path. If the provided path contains a query, - * then it will be added to this URL as well. - */ - appendPath(path) { - if (path) { - let currentPath = this.getPath(); - if (currentPath) { - if (!currentPath.endsWith("/")) { - currentPath += "/"; - } - if (path.startsWith("/")) { - path = path.substring(1); - } - path = currentPath + path; + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } - this.set(path, "PATH"); + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; } - } - /** - * Get the path that has been set in this URL. - */ - getPath() { - return this._path; - } - /** - * Set the query in this URL. - */ - setQuery(query) { - if (!query) { - this._query = undefined; + // if reusing agent across request and tunneling agent isn't assigned create a new agent + if (this._keepAlive && !agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https.Agent(options) : new http.Agent(options); + this._agent = agent; } - else { - this._query = URLQuery.parse(query); + // if not using private agent and tunnel agent isn't setup then use global agent + if (!agent) { + agent = usingSsl ? https.globalAgent : http.globalAgent; } - } - /** - * Set a query parameter with the provided name and value in this URL's query. If the provided - * query parameter value is undefined or empty, then the query parameter will be removed if it - * existed. - */ - setQueryParameter(queryParameterName, queryParameterValue) { - if (queryParameterName) { - if (!this._query) { - this._query = new URLQuery(); - } - this._query.set(queryParameterName, queryParameterValue); + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); } + return agent; } - /** - * Get the value of the query parameter with the provided query parameter name. If no query - * parameter exists with the provided name, then undefined will be returned. - */ - getQueryParameterValue(queryParameterName) { - return this._query ? this._query.get(queryParameterName) : undefined; - } - /** - * Get the query in this URL. - */ - getQuery() { - return this._query ? this._query.toString() : undefined; + _performExponentialBackoff(retryNumber) { + return __awaiter(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise(resolve => setTimeout(() => resolve(), ms)); + }); } - /** - * Set the parts of this URL by parsing the provided text using the provided startState. - */ - set(text, startState) { - const tokenizer = new URLTokenizer(text, startState); - while (tokenizer.next()) { - const token = tokenizer.current(); - let tokenPath; - if (token) { - switch (token.type) { - case "SCHEME": - this._scheme = token.text || undefined; - break; - case "HOST": - this._host = token.text || undefined; - break; - case "PORT": - this._port = token.text || undefined; - break; - case "PATH": - tokenPath = token.text || undefined; - if (!this._path || this._path === "/" || tokenPath !== "/") { - this._path = tokenPath; + _processResponse(res, options) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + // not found leads to null obj returned + if (statusCode === HttpCodes.NotFound) { + resolve(response); + } + // get the result from the body + function dateTimeDeserializer(key, value) { + if (typeof value === 'string') { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; } - break; - case "QUERY": - this._query = URLQuery.parse(token.text); - break; - default: - throw new Error(`Unrecognized URLTokenType: ${token.type}`); + } + return value; } - } - } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } + else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } + catch (err) { + // 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})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } + else { + resolve(response); + } + })); + }); } - /** - * Serializes the URL as a string. - * @returns the URL as a string. - */ - toString() { - let result = ""; - if (this._scheme) { - result += `${this._scheme}://`; - } - if (this._host) { - result += this._host; - } - if (this._port) { - result += `:${this._port}`; - } - if (this._path) { - if (!this._path.startsWith("/")) { - result += "/"; - } - result += this._path; - } - if (this._query && this._query.any()) { - result += `?${this._query.toString()}`; - } - return result; +} +exports.HttpClient = HttpClient; +const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 80531: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.checkBypass = exports.getProxyUrl = void 0; +function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === 'https:'; + if (checkBypass(reqUrl)) { + return undefined; } - /** - * If the provided searchValue is found in this URLBuilder, then replace it with the provided - * replaceValue. - */ - replaceAll(searchValue, replaceValue) { - if (searchValue) { - this.setScheme(replaceAll(this.getScheme(), searchValue, replaceValue)); - this.setHost(replaceAll(this.getHost(), searchValue, replaceValue)); - this.setPort(replaceAll(this.getPort(), searchValue, replaceValue)); - this.setPath(replaceAll(this.getPath(), searchValue, replaceValue)); - this.setQuery(replaceAll(this.getQuery(), searchValue, replaceValue)); + const proxyVar = (() => { + if (usingSsl) { + return process.env['https_proxy'] || process.env['HTTPS_PROXY']; } + else { + return process.env['http_proxy'] || process.env['HTTP_PROXY']; + } + })(); + if (proxyVar) { + return new URL(proxyVar); } - /** - * Parses a given string URL into a new {@link URLBuilder}. - */ - static parse(text) { - const result = new URLBuilder(); - result.set(text, "SCHEME_OR_HOST"); - return result; + else { + return undefined; } } -class URLToken { - constructor(text, type) { - this.text = text; - this.type = type; +exports.getProxyUrl = getProxyUrl; +function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - static scheme(text) { - return new URLToken(text, "SCHEME"); + const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; + if (!noProxy) { + return false; } - static host(text) { - return new URLToken(text, "HOST"); + // Determine the request port + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); } - static port(text) { - return new URLToken(text, "PORT"); + else if (reqUrl.protocol === 'http:') { + reqPort = 80; } - static path(text) { - return new URLToken(text, "PATH"); + else if (reqUrl.protocol === 'https:') { + reqPort = 443; } - static query(text) { - return new URLToken(text, "QUERY"); + // Format the request hostname and hostname with port + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === 'number') { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } + // Compare request host against noproxy + for (const upperNoProxyItem of noProxy + .split(',') + .map(x => x.trim().toUpperCase()) + .filter(x => x)) { + if (upperReqHosts.some(x => x === upperNoProxyItem)) { + return true; + } + } + return false; } -/** - * Get whether or not the provided character (single character string) is an alphanumeric (letter or - * digit) character. - */ -function isAlphaNumericCharacter(character) { - const characterCode = character.charCodeAt(0); - return ((48 /* '0' */ <= characterCode && characterCode <= 57) /* '9' */ || - (65 /* 'A' */ <= characterCode && characterCode <= 90) /* 'Z' */ || - (97 /* 'a' */ <= characterCode && characterCode <= 122) /* 'z' */); +exports.checkBypass = checkBypass; +//# sourceMappingURL=proxy.js.map + +/***/ }), + +/***/ 74498: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var _a; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rename = exports.readlink = exports.readdir = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const path = __importStar(__nccwpck_require__(71017)); +_a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; +exports.IS_WINDOWS = process.platform === 'win32'; +function exists(fsPath) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield exports.stat(fsPath); + } + catch (err) { + if (err.code === 'ENOENT') { + return false; + } + throw err; + } + return true; + }); +} +exports.exists = exists; +function isDirectory(fsPath, useStat = false) { + return __awaiter(this, void 0, void 0, function* () { + const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); + return stats.isDirectory(); + }); } +exports.isDirectory = isDirectory; /** - * A class that tokenizes URL strings. + * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: + * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). */ -class URLTokenizer { - constructor(_text, state) { - this._text = _text; - this._textLength = _text ? _text.length : 0; - this._currentState = state !== undefined && state !== null ? state : "SCHEME_OR_HOST"; - this._currentIndex = 0; +function isRooted(p) { + p = normalizeSeparators(p); + if (!p) { + throw new Error('isRooted() parameter "p" cannot be empty'); } - /** - * Get the current URLToken this URLTokenizer is pointing at, or undefined if the URLTokenizer - * hasn't started or has finished tokenizing. - */ - current() { - return this._currentToken; + if (exports.IS_WINDOWS) { + return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello + ); // e.g. C: or C:\hello } - /** - * Advance to the next URLToken and return whether or not a URLToken was found. - */ - next() { - if (!hasCurrentCharacter(this)) { - this._currentToken = undefined; + return p.startsWith('/'); +} +exports.isRooted = isRooted; +/** + * Best effort attempt to determine whether a file exists and is executable. + * @param filePath file path to check + * @param extensions additional file extensions to try + * @return if file exists and is executable, returns the file path. otherwise empty string. + */ +function tryGetExecutablePath(filePath, extensions) { + return __awaiter(this, void 0, void 0, function* () { + let stats = undefined; + try { + // test file exists + stats = yield exports.stat(filePath); } - else { - switch (this._currentState) { - case "SCHEME": - nextScheme(this); - break; - case "SCHEME_OR_HOST": - nextSchemeOrHost(this); - break; - case "HOST": - nextHost(this); - break; - case "PORT": - nextPort(this); - break; - case "PATH": - nextPath(this); - break; - case "QUERY": - nextQuery(this); - break; - default: - throw new Error(`Unrecognized URLTokenizerState: ${this._currentState}`); + catch (err) { + if (err.code !== 'ENOENT') { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } - return !!this._currentToken; - } + if (stats && stats.isFile()) { + if (exports.IS_WINDOWS) { + // on Windows, test for valid extension + const upperExt = path.extname(filePath).toUpperCase(); + if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { + return filePath; + } + } + else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + // try each extension + const originalFilePath = filePath; + for (const extension of extensions) { + filePath = originalFilePath + extension; + stats = undefined; + try { + stats = yield exports.stat(filePath); + } + catch (err) { + if (err.code !== 'ENOENT') { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + } + } + if (stats && stats.isFile()) { + if (exports.IS_WINDOWS) { + // preserve the case of the actual file (since an extension was appended) + try { + const directory = path.dirname(filePath); + const upperName = path.basename(filePath).toUpperCase(); + for (const actualName of yield exports.readdir(directory)) { + if (upperName === actualName.toUpperCase()) { + filePath = path.join(directory, actualName); + break; + } + } + } + catch (err) { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); + } + return filePath; + } + else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + } + return ''; + }); } -/** - * Read the remaining characters from this Tokenizer's character stream. - */ -function readRemaining(tokenizer) { - let result = ""; - if (tokenizer._currentIndex < tokenizer._textLength) { - result = tokenizer._text.substring(tokenizer._currentIndex); - tokenizer._currentIndex = tokenizer._textLength; +exports.tryGetExecutablePath = tryGetExecutablePath; +function normalizeSeparators(p) { + p = p || ''; + if (exports.IS_WINDOWS) { + // convert slashes on Windows + p = p.replace(/\//g, '\\'); + // remove redundant slashes + return p.replace(/\\\\+/g, '\\'); } - return result; + // remove redundant slashes + return p.replace(/\/\/+/g, '/'); +} +// on Mac/Linux, test the execute bit +// R W X R W X R W X +// 256 128 64 32 16 8 4 2 1 +function isUnixExecutable(stats) { + return ((stats.mode & 1) > 0 || + ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || + ((stats.mode & 64) > 0 && stats.uid === process.getuid())); +} +// Get the path of cmd.exe in windows +function getCmdPath() { + var _a; + return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; } +exports.getCmdPath = getCmdPath; +//# sourceMappingURL=io-util.js.map + +/***/ }), + +/***/ 50157: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; +const assert_1 = __nccwpck_require__(39491); +const childProcess = __importStar(__nccwpck_require__(32081)); +const path = __importStar(__nccwpck_require__(71017)); +const util_1 = __nccwpck_require__(73837); +const ioUtil = __importStar(__nccwpck_require__(74498)); +const exec = util_1.promisify(childProcess.exec); +const execFile = util_1.promisify(childProcess.execFile); /** - * Whether or not this URLTokenizer has a current character. + * Copies a file or folder. + * Based off of shelljs - /~https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js + * + * @param source source path + * @param dest destination path + * @param options optional. See CopyOptions. */ -function hasCurrentCharacter(tokenizer) { - return tokenizer._currentIndex < tokenizer._textLength; +function cp(source, dest, options = {}) { + return __awaiter(this, void 0, void 0, function* () { + const { force, recursive, copySourceDirectory } = readCopyOptions(options); + const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; + // Dest is an existing file, but not forcing + if (destStat && destStat.isFile() && !force) { + return; + } + // If dest is an existing directory, should copy inside. + const newDest = destStat && destStat.isDirectory() && copySourceDirectory + ? path.join(dest, path.basename(source)) + : dest; + if (!(yield ioUtil.exists(source))) { + throw new Error(`no such file or directory: ${source}`); + } + const sourceStat = yield ioUtil.stat(source); + if (sourceStat.isDirectory()) { + if (!recursive) { + throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); + } + else { + yield cpDirRecursive(source, newDest, 0, force); + } + } + else { + if (path.relative(source, newDest) === '') { + // a file cannot be copied to itself + throw new Error(`'${newDest}' and '${source}' are the same file`); + } + yield copyFile(source, newDest, force); + } + }); } +exports.cp = cp; /** - * Get the character in the text string at the current index. + * Moves a path. + * + * @param source source path + * @param dest destination path + * @param options optional. See MoveOptions. */ -function getCurrentCharacter(tokenizer) { - return tokenizer._text[tokenizer._currentIndex]; +function mv(source, dest, options = {}) { + return __awaiter(this, void 0, void 0, function* () { + if (yield ioUtil.exists(dest)) { + let destExists = true; + if (yield ioUtil.isDirectory(dest)) { + // If dest is directory copy src into dest + dest = path.join(dest, path.basename(source)); + destExists = yield ioUtil.exists(dest); + } + if (destExists) { + if (options.force == null || options.force) { + yield rmRF(dest); + } + else { + throw new Error('Destination already exists'); + } + } + } + yield mkdirP(path.dirname(dest)); + yield ioUtil.rename(source, dest); + }); } +exports.mv = mv; /** - * Advance to the character in text that is "step" characters ahead. If no step value is provided, - * then step will default to 1. + * Remove a path recursively with force + * + * @param inputPath path to remove */ -function nextCharacter(tokenizer, step) { - if (hasCurrentCharacter(tokenizer)) { - if (!step) { - step = 1; +function rmRF(inputPath) { + return __awaiter(this, void 0, void 0, function* () { + if (ioUtil.IS_WINDOWS) { + // Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another + // program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del. + // Check for invalid characters + // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file + if (/[*"<>|]/.test(inputPath)) { + throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); + } + try { + const cmdPath = ioUtil.getCmdPath(); + if (yield ioUtil.isDirectory(inputPath, true)) { + yield exec(`${cmdPath} /s /c "rd /s /q "%inputPath%""`, { + env: { inputPath } + }); + } + else { + yield exec(`${cmdPath} /s /c "del /f /a "%inputPath%""`, { + env: { inputPath } + }); + } + } + catch (err) { + // if you try to delete a file that doesn't exist, desired result is achieved + // other errors are valid + if (err.code !== 'ENOENT') + throw err; + } + // Shelling out fails to remove a symlink folder with missing source, this unlink catches that + try { + yield ioUtil.unlink(inputPath); + } + catch (err) { + // if you try to delete a file that doesn't exist, desired result is achieved + // other errors are valid + if (err.code !== 'ENOENT') + throw err; + } } - tokenizer._currentIndex += step; - } + else { + let isDir = false; + try { + isDir = yield ioUtil.isDirectory(inputPath); + } + catch (err) { + // if you try to delete a file that doesn't exist, desired result is achieved + // other errors are valid + if (err.code !== 'ENOENT') + throw err; + return; + } + if (isDir) { + yield execFile(`rm`, [`-rf`, `${inputPath}`]); + } + else { + yield ioUtil.unlink(inputPath); + } + } + }); } +exports.rmRF = rmRF; /** - * Starting with the current character, peek "charactersToPeek" number of characters ahead in this - * Tokenizer's stream of characters. + * Make a directory. Creates the full path with folders in between + * Will throw if it fails + * + * @param fsPath path to create + * @returns Promise */ -function peekCharacters(tokenizer, charactersToPeek) { - let endIndex = tokenizer._currentIndex + charactersToPeek; - if (tokenizer._textLength < endIndex) { - endIndex = tokenizer._textLength; - } - return tokenizer._text.substring(tokenizer._currentIndex, endIndex); +function mkdirP(fsPath) { + return __awaiter(this, void 0, void 0, function* () { + assert_1.ok(fsPath, 'a path argument must be provided'); + yield ioUtil.mkdir(fsPath, { recursive: true }); + }); } +exports.mkdirP = mkdirP; /** - * Read characters from this Tokenizer until the end of the stream or until the provided condition - * is false when provided the current character. + * Returns path of a tool had the tool actually been invoked. Resolves via paths. + * If you check and the tool does not exist, it will throw. + * + * @param tool name of the tool + * @param check whether to check if tool exists + * @returns Promise path to tool */ -function readWhile(tokenizer, condition) { - let result = ""; - while (hasCurrentCharacter(tokenizer)) { - const currentCharacter = getCurrentCharacter(tokenizer); - if (!condition(currentCharacter)) { - break; +function which(tool, check) { + return __awaiter(this, void 0, void 0, function* () { + if (!tool) { + throw new Error("parameter 'tool' is required"); } - else { - result += currentCharacter; - nextCharacter(tokenizer); + // recursive when check=true + if (check) { + const result = yield which(tool, false); + if (!result) { + if (ioUtil.IS_WINDOWS) { + throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); + } + else { + throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); + } + } + return result; } - } - return result; + const matches = yield findInPath(tool); + if (matches && matches.length > 0) { + return matches[0]; + } + return ''; + }); } +exports.which = which; /** - * Read characters from this Tokenizer until a non-alphanumeric character or the end of the - * character stream is reached. + * Returns a list of all occurrences of the given tool on the system path. + * + * @returns Promise the paths of the tool */ -function readWhileLetterOrDigit(tokenizer) { - return readWhile(tokenizer, (character) => isAlphaNumericCharacter(character)); +function findInPath(tool) { + return __awaiter(this, void 0, void 0, function* () { + if (!tool) { + throw new Error("parameter 'tool' is required"); + } + // build the list of extensions to try + const extensions = []; + if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) { + for (const extension of process.env['PATHEXT'].split(path.delimiter)) { + if (extension) { + extensions.push(extension); + } + } + } + // if it's rooted, return it if exists. otherwise return empty. + if (ioUtil.isRooted(tool)) { + const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); + if (filePath) { + return [filePath]; + } + return []; + } + // if any path separators, return empty + if (tool.includes(path.sep)) { + return []; + } + // build the list of directories + // + // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, + // it feels like we should not do this. Checking the current directory seems like more of a use + // case of a shell, and the which() function exposed by the toolkit should strive for consistency + // across platforms. + const directories = []; + if (process.env.PATH) { + for (const p of process.env.PATH.split(path.delimiter)) { + if (p) { + directories.push(p); + } + } + } + // find all matches + const matches = []; + for (const directory of directories) { + const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); + if (filePath) { + matches.push(filePath); + } + } + return matches; + }); } -/** - * Read characters from this Tokenizer until one of the provided terminating characters is read or - * the end of the character stream is reached. - */ -function readUntilCharacter(tokenizer, ...terminatingCharacters) { - return readWhile(tokenizer, (character) => terminatingCharacters.indexOf(character) === -1); +exports.findInPath = findInPath; +function readCopyOptions(options) { + const force = options.force == null ? true : options.force; + const recursive = Boolean(options.recursive); + const copySourceDirectory = options.copySourceDirectory == null + ? true + : Boolean(options.copySourceDirectory); + return { force, recursive, copySourceDirectory }; } -function nextScheme(tokenizer) { - const scheme = readWhileLetterOrDigit(tokenizer); - tokenizer._currentToken = URLToken.scheme(scheme); - if (!hasCurrentCharacter(tokenizer)) { - tokenizer._currentState = "DONE"; - } - else { - tokenizer._currentState = "HOST"; - } +function cpDirRecursive(sourceDir, destDir, currentDepth, force) { + return __awaiter(this, void 0, void 0, function* () { + // Ensure there is not a run away recursive copy + if (currentDepth >= 255) + return; + currentDepth++; + yield mkdirP(destDir); + const files = yield ioUtil.readdir(sourceDir); + for (const fileName of files) { + const srcFile = `${sourceDir}/${fileName}`; + const destFile = `${destDir}/${fileName}`; + const srcFileStat = yield ioUtil.lstat(srcFile); + if (srcFileStat.isDirectory()) { + // Recurse + yield cpDirRecursive(srcFile, destFile, currentDepth, force); + } + else { + yield copyFile(srcFile, destFile, force); + } + } + // Change the mode for the newly created directory + yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); + }); } -function nextSchemeOrHost(tokenizer) { - const schemeOrHost = readUntilCharacter(tokenizer, ":", "/", "?"); - if (!hasCurrentCharacter(tokenizer)) { - tokenizer._currentToken = URLToken.host(schemeOrHost); - tokenizer._currentState = "DONE"; - } - else if (getCurrentCharacter(tokenizer) === ":") { - if (peekCharacters(tokenizer, 3) === "://") { - tokenizer._currentToken = URLToken.scheme(schemeOrHost); - tokenizer._currentState = "HOST"; +// Buffered file copy +function copyFile(srcFile, destFile, force) { + return __awaiter(this, void 0, void 0, function* () { + if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { + // unlink/re-link it + try { + yield ioUtil.lstat(destFile); + yield ioUtil.unlink(destFile); + } + catch (e) { + // Try to override file permission + if (e.code === 'EPERM') { + yield ioUtil.chmod(destFile, '0666'); + yield ioUtil.unlink(destFile); + } + // other errors = it doesn't exist, no work to do + } + // Copy over symlink + const symlinkFull = yield ioUtil.readlink(srcFile); + yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); } - else { - tokenizer._currentToken = URLToken.host(schemeOrHost); - tokenizer._currentState = "PORT"; + else if (!(yield ioUtil.exists(destFile)) || force) { + yield ioUtil.copyFile(srcFile, destFile); } - } - else { - tokenizer._currentToken = URLToken.host(schemeOrHost); - if (getCurrentCharacter(tokenizer) === "/") { - tokenizer._currentState = "PATH"; + }); +} +//# sourceMappingURL=io.js.map + +/***/ }), + +/***/ 73937: +/***/ (function(module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports._readLinuxVersionFile = exports._getOsVersion = exports._findMatch = void 0; +const semver = __importStar(__nccwpck_require__(71494)); +const core_1 = __nccwpck_require__(65681); +// needs to be require for core node modules to be mocked +/* eslint @typescript-eslint/no-require-imports: 0 */ +const os = __nccwpck_require__(22037); +const cp = __nccwpck_require__(32081); +const fs = __nccwpck_require__(57147); +function _findMatch(versionSpec, stable, candidates, archFilter) { + return __awaiter(this, void 0, void 0, function* () { + const platFilter = os.platform(); + let result; + let match; + let file; + for (const candidate of candidates) { + const version = candidate.version; + core_1.debug(`check ${version} satisfies ${versionSpec}`); + if (semver.satisfies(version, versionSpec) && + (!stable || candidate.stable === stable)) { + file = candidate.files.find(item => { + core_1.debug(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); + let chk = item.arch === archFilter && item.platform === platFilter; + if (chk && item.platform_version) { + const osVersion = module.exports._getOsVersion(); + if (osVersion === item.platform_version) { + chk = true; + } + else { + chk = semver.satisfies(osVersion, item.platform_version); + } + } + return chk; + }); + if (file) { + core_1.debug(`matched ${candidate.version}`); + match = candidate; + break; + } + } } - else { - tokenizer._currentState = "QUERY"; + if (match && file) { + // clone since we're mutating the file list to be only the file that matches + result = Object.assign({}, match); + result.files = [file]; } - } -} -function nextHost(tokenizer) { - if (peekCharacters(tokenizer, 3) === "://") { - nextCharacter(tokenizer, 3); - } - const host = readUntilCharacter(tokenizer, ":", "/", "?"); - tokenizer._currentToken = URLToken.host(host); - if (!hasCurrentCharacter(tokenizer)) { - tokenizer._currentState = "DONE"; - } - else if (getCurrentCharacter(tokenizer) === ":") { - tokenizer._currentState = "PORT"; - } - else if (getCurrentCharacter(tokenizer) === "/") { - tokenizer._currentState = "PATH"; - } - else { - tokenizer._currentState = "QUERY"; - } + return result; + }); } -function nextPort(tokenizer) { - if (getCurrentCharacter(tokenizer) === ":") { - nextCharacter(tokenizer); - } - const port = readUntilCharacter(tokenizer, "/", "?"); - tokenizer._currentToken = URLToken.port(port); - if (!hasCurrentCharacter(tokenizer)) { - tokenizer._currentState = "DONE"; - } - else if (getCurrentCharacter(tokenizer) === "/") { - tokenizer._currentState = "PATH"; +exports._findMatch = _findMatch; +function _getOsVersion() { + // TODO: add windows and other linux, arm variants + // right now filtering on version is only an ubuntu and macos scenario for tools we build for hosted (python) + const plat = os.platform(); + let version = ''; + if (plat === 'darwin') { + version = cp.execSync('sw_vers -productVersion').toString(); } - else { - tokenizer._currentState = "QUERY"; + else if (plat === 'linux') { + // lsb_release process not in some containers, readfile + // Run cat /etc/lsb-release + // DISTRIB_ID=Ubuntu + // DISTRIB_RELEASE=18.04 + // DISTRIB_CODENAME=bionic + // DISTRIB_DESCRIPTION="Ubuntu 18.04.4 LTS" + const lsbContents = module.exports._readLinuxVersionFile(); + if (lsbContents) { + const lines = lsbContents.split('\n'); + for (const line of lines) { + const parts = line.split('='); + if (parts.length === 2 && + (parts[0].trim() === 'VERSION_ID' || + parts[0].trim() === 'DISTRIB_RELEASE')) { + version = parts[1] + .trim() + .replace(/^"/, '') + .replace(/"$/, ''); + break; + } + } + } } + return version; } -function nextPath(tokenizer) { - const path = readUntilCharacter(tokenizer, "?"); - tokenizer._currentToken = URLToken.path(path); - if (!hasCurrentCharacter(tokenizer)) { - tokenizer._currentState = "DONE"; - } - else { - tokenizer._currentState = "QUERY"; +exports._getOsVersion = _getOsVersion; +function _readLinuxVersionFile() { + const lsbReleaseFile = '/etc/lsb-release'; + const osReleaseFile = '/etc/os-release'; + let contents = ''; + if (fs.existsSync(lsbReleaseFile)) { + contents = fs.readFileSync(lsbReleaseFile).toString(); } -} -function nextQuery(tokenizer) { - if (getCurrentCharacter(tokenizer) === "?") { - nextCharacter(tokenizer); + else if (fs.existsSync(osReleaseFile)) { + contents = fs.readFileSync(osReleaseFile).toString(); } - const query = readRemaining(tokenizer); - tokenizer._currentToken = URLToken.query(query); - tokenizer._currentState = "DONE"; + return contents; } +exports._readLinuxVersionFile = _readLinuxVersionFile; +//# sourceMappingURL=manifest.js.map -// Copyright (c) Microsoft Corporation. -function createProxyAgent(requestUrl, proxySettings, headers) { - const host = URLBuilder.parse(proxySettings.host).getHost(); - if (!host) { - throw new Error("Expecting a non-empty host in proxy settings."); +/***/ }), + +/***/ 84193: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RetryHelper = void 0; +const core = __importStar(__nccwpck_require__(65681)); +/** + * Internal class for retries + */ +class RetryHelper { + constructor(maxAttempts, minSeconds, maxSeconds) { + if (maxAttempts < 1) { + throw new Error('max attempts should be greater than or equal to 1'); + } + this.maxAttempts = maxAttempts; + this.minSeconds = Math.floor(minSeconds); + this.maxSeconds = Math.floor(maxSeconds); + if (this.minSeconds > this.maxSeconds) { + throw new Error('min seconds should be less than or equal to max seconds'); + } } - if (!isValidPort(proxySettings.port)) { - throw new Error("Expecting a valid port number in the range of [0, 65535] in proxy settings."); + execute(action, isRetryable) { + return __awaiter(this, void 0, void 0, function* () { + let attempt = 1; + while (attempt < this.maxAttempts) { + // Try + try { + return yield action(); + } + catch (err) { + if (isRetryable && !isRetryable(err)) { + throw err; + } + core.info(err.message); + } + // Sleep + const seconds = this.getSleepAmount(); + core.info(`Waiting ${seconds} seconds before trying again`); + yield this.sleep(seconds); + attempt++; + } + // Last attempt + return yield action(); + }); } - const tunnelOptions = { - proxy: { - host: host, - port: proxySettings.port, - headers: (headers && headers.rawHeaders()) || {}, - }, - }; - if (proxySettings.username && proxySettings.password) { - tunnelOptions.proxy.proxyAuth = `${proxySettings.username}:${proxySettings.password}`; + getSleepAmount() { + return (Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + + this.minSeconds); } - else if (proxySettings.username) { - tunnelOptions.proxy.proxyAuth = `${proxySettings.username}`; + sleep(seconds) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise(resolve => setTimeout(resolve, seconds * 1000)); + }); } - const isRequestHttps = isUrlHttps(requestUrl); - const isProxyHttps = isUrlHttps(proxySettings.host); - const proxyAgent = { - isHttps: isRequestHttps, - agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions), - }; - return proxyAgent; -} -function isUrlHttps(url) { - const urlScheme = URLBuilder.parse(url).getScheme() || ""; - return urlScheme.toLowerCase() === "https"; } -function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) { - if (isRequestHttps && isProxyHttps) { - return tunnel__namespace.httpsOverHttps(tunnelOptions); - } - else if (isRequestHttps && !isProxyHttps) { - return tunnel__namespace.httpsOverHttp(tunnelOptions); - } - else if (!isRequestHttps && isProxyHttps) { - return tunnel__namespace.httpOverHttps(tunnelOptions); - } - else { - return tunnel__namespace.httpOverHttp(tunnelOptions); +exports.RetryHelper = RetryHelper; +//# sourceMappingURL=retry-helper.js.map + +/***/ }), + +/***/ 32721: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.evaluateVersions = exports.isExplicitVersion = exports.findFromManifest = exports.getManifestFromRepo = exports.findAllVersions = exports.find = exports.cacheFile = exports.cacheDir = exports.extractZip = exports.extractXar = exports.extractTar = exports.extract7z = exports.downloadTool = exports.HTTPError = void 0; +const core = __importStar(__nccwpck_require__(65681)); +const io = __importStar(__nccwpck_require__(50157)); +const fs = __importStar(__nccwpck_require__(57147)); +const mm = __importStar(__nccwpck_require__(73937)); +const os = __importStar(__nccwpck_require__(22037)); +const path = __importStar(__nccwpck_require__(71017)); +const httpm = __importStar(__nccwpck_require__(9706)); +const semver = __importStar(__nccwpck_require__(71494)); +const stream = __importStar(__nccwpck_require__(12781)); +const util = __importStar(__nccwpck_require__(73837)); +const assert_1 = __nccwpck_require__(39491); +const v4_1 = __importDefault(__nccwpck_require__(98666)); +const exec_1 = __nccwpck_require__(15082); +const retry_helper_1 = __nccwpck_require__(84193); +class HTTPError extends Error { + constructor(httpStatusCode) { + super(`Unexpected HTTP response: ${httpStatusCode}`); + this.httpStatusCode = httpStatusCode; + Object.setPrototypeOf(this, new.target.prototype); } } -function isValidPort(port) { - // any port in 0-65535 range is valid (RFC 793) even though almost all implementations - // will reserve 0 for a specific purpose, and a range of numbers for ephemeral ports - return 0 <= port && port <= 65535; -} - -// Copyright (c) Microsoft Corporation. -const RedactedString = "REDACTED"; -const defaultAllowedHeaderNames = [ - "x-ms-client-request-id", - "x-ms-return-client-request-id", - "x-ms-useragent", - "x-ms-correlation-request-id", - "x-ms-request-id", - "client-request-id", - "ms-cv", - "return-client-request-id", - "traceparent", - "Access-Control-Allow-Credentials", - "Access-Control-Allow-Headers", - "Access-Control-Allow-Methods", - "Access-Control-Allow-Origin", - "Access-Control-Expose-Headers", - "Access-Control-Max-Age", - "Access-Control-Request-Headers", - "Access-Control-Request-Method", - "Origin", - "Accept", - "Accept-Encoding", - "Cache-Control", - "Connection", - "Content-Length", - "Content-Type", - "Date", - "ETag", - "Expires", - "If-Match", - "If-Modified-Since", - "If-None-Match", - "If-Unmodified-Since", - "Last-Modified", - "Pragma", - "Request-Id", - "Retry-After", - "Server", - "Transfer-Encoding", - "User-Agent", - "WWW-Authenticate", -]; -const defaultAllowedQueryParameters = ["api-version"]; -class Sanitizer { - constructor({ allowedHeaderNames = [], allowedQueryParameters = [] } = {}) { - allowedHeaderNames = Array.isArray(allowedHeaderNames) - ? defaultAllowedHeaderNames.concat(allowedHeaderNames) - : defaultAllowedHeaderNames; - allowedQueryParameters = Array.isArray(allowedQueryParameters) - ? defaultAllowedQueryParameters.concat(allowedQueryParameters) - : defaultAllowedQueryParameters; - this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); - this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); - } - sanitize(obj) { - const seen = new Set(); - return JSON.stringify(obj, (key, value) => { - // Ensure Errors include their interesting non-enumerable members - if (value instanceof Error) { - return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); - } - if (key === "_headersMap") { - return this.sanitizeHeaders(value); +exports.HTTPError = HTTPError; +const IS_WINDOWS = process.platform === 'win32'; +const IS_MAC = process.platform === 'darwin'; +const userAgent = 'actions/tool-cache'; +/** + * Download a tool from an url and stream it into a file + * + * @param url url of tool to download + * @param dest path to download tool + * @param auth authorization header + * @param headers other headers + * @returns path to downloaded tool + */ +function downloadTool(url, dest, auth, headers) { + return __awaiter(this, void 0, void 0, function* () { + dest = dest || path.join(_getTempDirectory(), v4_1.default()); + yield io.mkdirP(path.dirname(dest)); + core.debug(`Downloading ${url}`); + core.debug(`Destination ${dest}`); + const maxAttempts = 3; + const minSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS', 10); + const maxSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS', 20); + const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); + return yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { + return yield downloadToolAttempt(url, dest || '', auth, headers); + }), (err) => { + if (err instanceof HTTPError && err.httpStatusCode) { + // Don't retry anything less than 500, except 408 Request Timeout and 429 Too Many Requests + if (err.httpStatusCode < 500 && + err.httpStatusCode !== 408 && + err.httpStatusCode !== 429) { + return false; + } } - else if (key === "url") { - return this.sanitizeUrl(value); + // Otherwise retry + return true; + }); + }); +} +exports.downloadTool = downloadTool; +function downloadToolAttempt(url, dest, auth, headers) { + return __awaiter(this, void 0, void 0, function* () { + if (fs.existsSync(dest)) { + throw new Error(`Destination file path ${dest} already exists`); + } + // Get the response headers + const http = new httpm.HttpClient(userAgent, [], { + allowRetries: false + }); + if (auth) { + core.debug('set auth'); + if (headers === undefined) { + headers = {}; } - else if (key === "query") { - return this.sanitizeQuery(value); + headers.authorization = auth; + } + const response = yield http.get(url, headers); + if (response.message.statusCode !== 200) { + const err = new HTTPError(response.message.statusCode); + core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); + throw err; + } + // Download the response body + const pipeline = util.promisify(stream.pipeline); + const responseMessageFactory = _getGlobal('TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY', () => response.message); + const readStream = responseMessageFactory(); + let succeeded = false; + try { + yield pipeline(readStream, fs.createWriteStream(dest)); + core.debug('download complete'); + succeeded = true; + return dest; + } + finally { + // Error, delete dest before retry + if (!succeeded) { + core.debug('download failed'); + try { + yield io.rmRF(dest); + } + catch (err) { + core.debug(`Failed to delete '${dest}'. ${err.message}`); + } } - else if (key === "body") { - // Don't log the request body - return undefined; + } + }); +} +/** + * Extract a .7z file + * + * @param file path to the .7z file + * @param dest destination directory. Optional. + * @param _7zPath path to 7zr.exe. Optional, for long path support. Most .7z archives do not have this + * problem. If your .7z archive contains very long paths, you can pass the path to 7zr.exe which will + * gracefully handle long paths. By default 7zdec.exe is used because it is a very small program and is + * bundled with the tool lib. However it does not support long paths. 7zr.exe is the reduced command line + * interface, it is smaller than the full command line interface, and it does support long paths. At the + * time of this writing, it is freely available from the LZMA SDK that is available on the 7zip website. + * Be sure to check the current license agreement. If 7zr.exe is bundled with your action, then the path + * to 7zr.exe can be pass to this function. + * @returns path to the destination directory + */ +function extract7z(file, dest, _7zPath) { + return __awaiter(this, void 0, void 0, function* () { + assert_1.ok(IS_WINDOWS, 'extract7z() not supported on current OS'); + assert_1.ok(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + const originalCwd = process.cwd(); + process.chdir(dest); + if (_7zPath) { + try { + const logLevel = core.isDebug() ? '-bb1' : '-bb0'; + const args = [ + 'x', + logLevel, + '-bd', + '-sccUTF-8', + file + ]; + const options = { + silent: true + }; + yield exec_1.exec(`"${_7zPath}"`, args, options); } - else if (key === "response") { - // Don't log response again - return undefined; + finally { + process.chdir(originalCwd); } - else if (key === "operationSpec") { - // When using sendOperationRequest, the request carries a massive - // field with the autorest spec. No need to log it. - return undefined; + } + else { + const escapedScript = path + .join(__dirname, '..', 'scripts', 'Invoke-7zdec.ps1') + .replace(/'/g, "''") + .replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); + const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ''); + const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; + const args = [ + '-NoLogo', + '-Sta', + '-NoProfile', + '-NonInteractive', + '-ExecutionPolicy', + 'Unrestricted', + '-Command', + command + ]; + const options = { + silent: true + }; + try { + const powershellPath = yield io.which('powershell', true); + yield exec_1.exec(`"${powershellPath}"`, args, options); } - else if (Array.isArray(value) || isObject(value)) { - if (seen.has(value)) { - return "[Circular]"; - } - seen.add(value); + finally { + process.chdir(originalCwd); } - return value; - }, 2); - } - sanitizeHeaders(value) { - return this.sanitizeObject(value, this.allowedHeaderNames, (v, k) => v[k].value); - } - sanitizeQuery(value) { - return this.sanitizeObject(value, this.allowedQueryParameters, (v, k) => v[k]); - } - sanitizeObject(value, allowedKeys, accessor) { - if (typeof value !== "object" || value === null) { - return value; } - const sanitized = {}; - for (const k of Object.keys(value)) { - if (allowedKeys.has(k.toLowerCase())) { - sanitized[k] = accessor(value, k); - } - else { - sanitized[k] = RedactedString; + return dest; + }); +} +exports.extract7z = extract7z; +/** + * Extract a compressed tar archive + * + * @param file path to the tar + * @param dest destination directory. Optional. + * @param flags flags for the tar command to use for extraction. Defaults to 'xz' (extracting gzipped tars). Optional. + * @returns path to the destination directory + */ +function extractTar(file, dest, flags = 'xz') { + return __awaiter(this, void 0, void 0, function* () { + if (!file) { + throw new Error("parameter 'file' is required"); + } + // Create dest + dest = yield _createExtractFolder(dest); + // Determine whether GNU tar + core.debug('Checking tar --version'); + let versionOutput = ''; + yield exec_1.exec('tar --version', [], { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => (versionOutput += data.toString()), + stderr: (data) => (versionOutput += data.toString()) } + }); + core.debug(versionOutput.trim()); + const isGnuTar = versionOutput.toUpperCase().includes('GNU TAR'); + // Initialize args + let args; + if (flags instanceof Array) { + args = flags; } - return sanitized; - } - sanitizeUrl(value) { - if (typeof value !== "string" || value === null) { - return value; + else { + args = [flags]; } - const urlBuilder = URLBuilder.parse(value); - const queryString = urlBuilder.getQuery(); - if (!queryString) { - return value; + if (core.isDebug() && !flags.includes('v')) { + args.push('-v'); } - const query = URLQuery.parse(queryString); - for (const k of query.keys()) { - if (!this.allowedQueryParameters.has(k.toLowerCase())) { - query.set(k, RedactedString); - } + let destArg = dest; + let fileArg = file; + if (IS_WINDOWS && isGnuTar) { + args.push('--force-local'); + destArg = dest.replace(/\\/g, '/'); + // Technically only the dest needs to have `/` but for aesthetic consistency + // convert slashes in the file arg too. + fileArg = file.replace(/\\/g, '/'); } - urlBuilder.setQuery(query.toString()); - return urlBuilder.toString(); - } + if (isGnuTar) { + // Suppress warnings when using GNU tar to extract archives created by BSD tar + args.push('--warning=no-unknown-keyword'); + args.push('--overwrite'); + } + args.push('-C', destArg, '-f', fileArg); + yield exec_1.exec(`tar`, args); + return dest; + }); } - -// Copyright (c) Microsoft Corporation. -const custom = util.inspect.custom; - -// Copyright (c) Microsoft Corporation. -const errorSanitizer = new Sanitizer(); +exports.extractTar = extractTar; /** - * An error resulting from an HTTP request to a service endpoint. + * Extract a xar compatible archive + * + * @param file path to the archive + * @param dest destination directory. Optional. + * @param flags flags for the xar. Optional. + * @returns path to the destination directory */ -class RestError extends Error { - constructor(message, code, statusCode, request, response) { - super(message); - this.name = "RestError"; - this.code = code; - this.statusCode = statusCode; - this.request = request; - this.response = response; - Object.setPrototypeOf(this, RestError.prototype); - } - /** - * Logging method for util.inspect in Node - */ - [custom]() { - return `RestError: ${this.message} \n ${errorSanitizer.sanitize(this)}`; - } +function extractXar(file, dest, flags = []) { + return __awaiter(this, void 0, void 0, function* () { + assert_1.ok(IS_MAC, 'extractXar() not supported on current OS'); + assert_1.ok(file, 'parameter "file" is required'); + dest = yield _createExtractFolder(dest); + let args; + if (flags instanceof Array) { + args = flags; + } + else { + args = [flags]; + } + args.push('-x', '-C', dest, '-f', file); + if (core.isDebug()) { + args.push('-v'); + } + const xarPath = yield io.which('xar', true); + yield exec_1.exec(`"${xarPath}"`, _unique(args)); + return dest; + }); } +exports.extractXar = extractXar; /** - * A constant string to identify errors that may arise when making an HTTP request that indicates an issue with the transport layer (e.g. the hostname of the URL cannot be resolved via DNS.) - */ -RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; -/** - * A constant string to identify errors that may arise from parsing an incoming HTTP response. Usually indicates a malformed HTTP body, such as an encoded JSON payload that is incomplete. + * Extract a zip + * + * @param file path to the zip + * @param dest destination directory. Optional. + * @returns path to the destination directory */ -RestError.PARSE_ERROR = "PARSE_ERROR"; - -// Copyright (c) Microsoft Corporation. -const logger = logger$1.createClientLogger("core-http"); - -// Copyright (c) Microsoft Corporation. -function getCachedAgent(isHttps, agentCache) { - return isHttps ? agentCache.httpsAgent : agentCache.httpAgent; +function extractZip(file, dest) { + return __awaiter(this, void 0, void 0, function* () { + if (!file) { + throw new Error("parameter 'file' is required"); + } + dest = yield _createExtractFolder(dest); + if (IS_WINDOWS) { + yield extractZipWin(file, dest); + } + else { + yield extractZipNix(file, dest); + } + return dest; + }); } -class ReportTransform extends stream.Transform { - constructor(progressCallback) { - super(); - this.progressCallback = progressCallback; - this.loadedBytes = 0; - } - _transform(chunk, _encoding, callback) { - this.push(chunk); - this.loadedBytes += chunk.length; - this.progressCallback({ loadedBytes: this.loadedBytes }); - callback(undefined); - } +exports.extractZip = extractZip; +function extractZipWin(file, dest) { + return __awaiter(this, void 0, void 0, function* () { + // build the powershell command + const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines + const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ''); + const pwshPath = yield io.which('pwsh', false); + //To match the file overwrite behavior on nix systems, we use the overwrite = true flag for ExtractToDirectory + //and the -Force flag for Expand-Archive as a fallback + if (pwshPath) { + //attempt to use pwsh with ExtractToDirectory, if this fails attempt Expand-Archive + const pwshCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.ZipFile } catch { } ;`, + `try { [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }`, + `catch { if (($_.Exception.GetType().FullName -eq 'System.Management.Automation.MethodException') -or ($_.Exception.GetType().FullName -eq 'System.Management.Automation.RuntimeException') ){ Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force } else { throw $_ } } ;` + ].join(' '); + const args = [ + '-NoLogo', + '-NoProfile', + '-NonInteractive', + '-ExecutionPolicy', + 'Unrestricted', + '-Command', + pwshCommand + ]; + core.debug(`Using pwsh at path: ${pwshPath}`); + yield exec_1.exec(`"${pwshPath}"`, args); + } + else { + const powershellCommand = [ + `$ErrorActionPreference = 'Stop' ;`, + `try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ;`, + `if ((Get-Command -Name Expand-Archive -Module Microsoft.PowerShell.Archive -ErrorAction Ignore)) { Expand-Archive -LiteralPath '${escapedFile}' -DestinationPath '${escapedDest}' -Force }`, + `else {[System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}', $true) }` + ].join(' '); + const args = [ + '-NoLogo', + '-Sta', + '-NoProfile', + '-NonInteractive', + '-ExecutionPolicy', + 'Unrestricted', + '-Command', + powershellCommand + ]; + const powershellPath = yield io.which('powershell', true); + core.debug(`Using powershell at path: ${powershellPath}`); + yield exec_1.exec(`"${powershellPath}"`, args); + } + }); } -function isReadableStream(body) { - return body && typeof body.pipe === "function"; +function extractZipNix(file, dest) { + return __awaiter(this, void 0, void 0, function* () { + const unzipPath = yield io.which('unzip', true); + const args = [file]; + if (!core.isDebug()) { + args.unshift('-q'); + } + args.unshift('-o'); //overwrite with -o, otherwise a prompt is shown which freezes the run + yield exec_1.exec(`"${unzipPath}"`, args, { cwd: dest }); + }); } -function isStreamComplete(stream, aborter) { - return new Promise((resolve) => { - stream.once("close", () => { - aborter === null || aborter === void 0 ? void 0 : aborter.abort(); - resolve(); - }); - stream.once("end", resolve); - stream.once("error", resolve); +/** + * Caches a directory and installs it into the tool cacheDir + * + * @param sourceDir the directory to cache into tools + * @param tool tool name + * @param version version of the tool. semver format + * @param arch architecture of the tool. Optional. Defaults to machine architecture + */ +function cacheDir(sourceDir, tool, version, arch) { + return __awaiter(this, void 0, void 0, function* () { + version = semver.clean(version) || version; + arch = arch || os.arch(); + core.debug(`Caching tool ${tool} ${version} ${arch}`); + core.debug(`source dir: ${sourceDir}`); + if (!fs.statSync(sourceDir).isDirectory()) { + throw new Error('sourceDir is not a directory'); + } + // Create the tool dir + const destPath = yield _createToolPath(tool, version, arch); + // copy each child item. do not move. move can fail on Windows + // due to anti-virus software having an open handle on a file. + for (const itemName of fs.readdirSync(sourceDir)) { + const s = path.join(sourceDir, itemName); + yield io.cp(s, destPath, { recursive: true }); + } + // write .complete + _completeToolPath(tool, version, arch); + return destPath; }); } +exports.cacheDir = cacheDir; /** - * Transforms a set of headers into the key/value pair defined by {@link HttpHeadersLike} + * Caches a downloaded file (GUID) and installs it + * into the tool cache with a given targetName + * + * @param sourceFile the file to cache into tools. Typically a result of downloadTool which is a guid. + * @param targetFile the name of the file name in the tools directory + * @param tool tool name + * @param version version of the tool. semver format + * @param arch architecture of the tool. Optional. Defaults to machine architecture */ -function parseHeaders(headers) { - const httpHeaders = new HttpHeaders(); - headers.forEach((value, key) => { - httpHeaders.set(key, value); +function cacheFile(sourceFile, targetFile, tool, version, arch) { + return __awaiter(this, void 0, void 0, function* () { + version = semver.clean(version) || version; + arch = arch || os.arch(); + core.debug(`Caching tool ${tool} ${version} ${arch}`); + core.debug(`source file: ${sourceFile}`); + if (!fs.statSync(sourceFile).isFile()) { + throw new Error('sourceFile is not a file'); + } + // create the tool dir + const destFolder = yield _createToolPath(tool, version, arch); + // copy instead of move. move can fail on Windows due to + // anti-virus software having an open handle on a file. + const destPath = path.join(destFolder, targetFile); + core.debug(`destination file ${destPath}`); + yield io.cp(sourceFile, destPath); + // write .complete + _completeToolPath(tool, version, arch); + return destFolder; }); - return httpHeaders; } +exports.cacheFile = cacheFile; /** - * An HTTP client that uses `node-fetch`. + * Finds the path to a tool version in the local installed tool cache + * + * @param toolName name of the tool + * @param versionSpec version of the tool + * @param arch optional arch. defaults to arch of computer */ -class NodeFetchHttpClient { - constructor() { - // a mapping of proxy settings string `${host}:${port}:${username}:${password}` to agent - this.proxyAgentMap = new Map(); - this.keepAliveAgents = {}; - this.cookieJar = new tough__namespace.CookieJar(undefined, { looseMode: true }); +function find(toolName, versionSpec, arch) { + if (!toolName) { + throw new Error('toolName parameter is required'); } - /** - * Provides minimum viable error handling and the logic that executes the abstract methods. - * @param httpRequest - Object representing the outgoing HTTP request. - * @returns An object representing the incoming HTTP response. - */ - async sendRequest(httpRequest) { - var _a; - if (!httpRequest && typeof httpRequest !== "object") { - throw new Error("'httpRequest' (WebResourceLike) cannot be null or undefined and must be of type object."); - } - const abortController$1 = new abortController.AbortController(); - let abortListener; - if (httpRequest.abortSignal) { - if (httpRequest.abortSignal.aborted) { - throw new abortController.AbortError("The operation was aborted."); - } - abortListener = (event) => { - if (event.type === "abort") { - abortController$1.abort(); - } - }; - httpRequest.abortSignal.addEventListener("abort", abortListener); + if (!versionSpec) { + throw new Error('versionSpec parameter is required'); + } + arch = arch || os.arch(); + // attempt to resolve an explicit version + if (!isExplicitVersion(versionSpec)) { + const localVersions = findAllVersions(toolName, arch); + const match = evaluateVersions(localVersions, versionSpec); + versionSpec = match; + } + // check for the explicit version in the cache + let toolPath = ''; + if (versionSpec) { + versionSpec = semver.clean(versionSpec) || ''; + const cachePath = path.join(_getCacheDirectory(), toolName, versionSpec, arch); + core.debug(`checking cache: ${cachePath}`); + if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) { + core.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); + toolPath = cachePath; } - if (httpRequest.timeout) { - setTimeout(() => { - abortController$1.abort(); - }, httpRequest.timeout); + else { + core.debug('not found'); } - if (httpRequest.formData) { - const formData = httpRequest.formData; - const requestForm = new FormData__default["default"](); - const appendFormValue = (key, value) => { - // value function probably returns a stream so we can provide a fresh stream on each retry - if (typeof value === "function") { - value = value(); - } - if (value && - Object.prototype.hasOwnProperty.call(value, "value") && - Object.prototype.hasOwnProperty.call(value, "options")) { - requestForm.append(key, value.value, value.options); - } - else { - requestForm.append(key, value); - } - }; - for (const formKey of Object.keys(formData)) { - const formValue = formData[formKey]; - if (Array.isArray(formValue)) { - for (let j = 0; j < formValue.length; j++) { - appendFormValue(formKey, formValue[j]); - } - } - else { - appendFormValue(formKey, formValue); - } - } - httpRequest.body = requestForm; - httpRequest.formData = undefined; - const contentType = httpRequest.headers.get("Content-Type"); - if (contentType && contentType.indexOf("multipart/form-data") !== -1) { - if (typeof requestForm.getBoundary === "function") { - httpRequest.headers.set("Content-Type", `multipart/form-data; boundary=${requestForm.getBoundary()}`); - } - else { - // browser will automatically apply a suitable content-type header - httpRequest.headers.remove("Content-Type"); + } + return toolPath; +} +exports.find = find; +/** + * Finds the paths to all versions of a tool that are installed in the local tool cache + * + * @param toolName name of the tool + * @param arch optional arch. defaults to arch of computer + */ +function findAllVersions(toolName, arch) { + const versions = []; + arch = arch || os.arch(); + const toolPath = path.join(_getCacheDirectory(), toolName); + if (fs.existsSync(toolPath)) { + const children = fs.readdirSync(toolPath); + for (const child of children) { + if (isExplicitVersion(child)) { + const fullPath = path.join(toolPath, child, arch || ''); + if (fs.existsSync(fullPath) && fs.existsSync(`${fullPath}.complete`)) { + versions.push(child); } } } - let body = httpRequest.body - ? typeof httpRequest.body === "function" - ? httpRequest.body() - : httpRequest.body - : undefined; - if (httpRequest.onUploadProgress && httpRequest.body) { - const onUploadProgress = httpRequest.onUploadProgress; - const uploadReportStream = new ReportTransform(onUploadProgress); - if (isReadableStream(body)) { - body.pipe(uploadReportStream); - } - else { - uploadReportStream.end(body); - } - body = uploadReportStream; - } - const platformSpecificRequestInit = await this.prepareRequest(httpRequest); - const requestInit = Object.assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController$1.signal, redirect: "manual" }, platformSpecificRequestInit); - let operationResponse; - try { - const response = await this.fetch(httpRequest.url, requestInit); - const headers = parseHeaders(response.headers); - const streaming = ((_a = httpRequest.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(response.status)) || - httpRequest.streamResponseBody; - operationResponse = { - headers: headers, - request: httpRequest, - status: response.status, - readableStreamBody: streaming - ? response.body - : undefined, - bodyAsText: !streaming ? await response.text() : undefined, - }; - const onDownloadProgress = httpRequest.onDownloadProgress; - if (onDownloadProgress) { - const responseBody = response.body || undefined; - if (isReadableStream(responseBody)) { - const downloadReportStream = new ReportTransform(onDownloadProgress); - responseBody.pipe(downloadReportStream); - operationResponse.readableStreamBody = downloadReportStream; - } - else { - const length = parseInt(headers.get("Content-Length")) || undefined; - if (length) { - // Calling callback for non-stream response for consistency with browser - onDownloadProgress({ loadedBytes: length }); - } - } - } - await this.processRequest(operationResponse); - return operationResponse; + } + return versions; +} +exports.findAllVersions = findAllVersions; +function getManifestFromRepo(owner, repo, auth, branch = 'master') { + return __awaiter(this, void 0, void 0, function* () { + let releases = []; + const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; + const http = new httpm.HttpClient('tool-cache'); + const headers = {}; + if (auth) { + core.debug('set auth'); + headers.authorization = auth; } - catch (error) { - const fetchError = error; - if (fetchError.code === "ENOTFOUND") { - throw new RestError(fetchError.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); - } - else if (fetchError.type === "aborted") { - throw new abortController.AbortError("The operation was aborted."); - } - throw fetchError; + const response = yield http.getJson(treeUrl, headers); + if (!response.result) { + return releases; } - finally { - // clean up event listener - if (httpRequest.abortSignal && abortListener) { - let uploadStreamDone = Promise.resolve(); - if (isReadableStream(body)) { - uploadStreamDone = isStreamComplete(body); - } - let downloadStreamDone = Promise.resolve(); - if (isReadableStream(operationResponse === null || operationResponse === void 0 ? void 0 : operationResponse.readableStreamBody)) { - downloadStreamDone = isStreamComplete(operationResponse.readableStreamBody, abortController$1); - } - Promise.all([uploadStreamDone, downloadStreamDone]) - .then(() => { - var _a; - (_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener); - return; - }) - .catch((e) => { - logger.warning("Error when cleaning up abortListener on httpRequest", e); - }); + let manifestUrl = ''; + for (const item of response.result.tree) { + if (item.path === 'versions-manifest.json') { + manifestUrl = item.url; + break; } } - } - getOrCreateAgent(httpRequest) { - var _a; - const isHttps = isUrlHttps(httpRequest.url); - // At the moment, proxy settings and keepAlive are mutually - // exclusive because the 'tunnel' library currently lacks the - // ability to create a proxy with keepAlive turned on. - if (httpRequest.proxySettings) { - const { host, port, username, password } = httpRequest.proxySettings; - const key = `${host}:${port}:${username}:${password}`; - const proxyAgents = (_a = this.proxyAgentMap.get(key)) !== null && _a !== void 0 ? _a : {}; - let agent = getCachedAgent(isHttps, proxyAgents); - if (agent) { - return agent; - } - const tunnel = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers); - agent = tunnel.agent; - if (tunnel.isHttps) { - proxyAgents.httpsAgent = tunnel.agent; + headers['accept'] = 'application/vnd.github.VERSION.raw'; + let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); + if (versionsRaw) { + // shouldn't be needed but protects against invalid json saved with BOM + versionsRaw = versionsRaw.replace(/^\uFEFF/, ''); + try { + releases = JSON.parse(versionsRaw); } - else { - proxyAgents.httpAgent = tunnel.agent; + catch (_a) { + core.debug('Invalid json'); } - this.proxyAgentMap.set(key, proxyAgents); - return agent; } - else if (httpRequest.keepAlive) { - let agent = getCachedAgent(isHttps, this.keepAliveAgents); - if (agent) { - return agent; - } - const agentOptions = { - keepAlive: httpRequest.keepAlive, - }; - if (isHttps) { - agent = this.keepAliveAgents.httpsAgent = new https__namespace.Agent(agentOptions); - } - else { - agent = this.keepAliveAgents.httpAgent = new http__namespace.Agent(agentOptions); - } - return agent; + return releases; + }); +} +exports.getManifestFromRepo = getManifestFromRepo; +function findFromManifest(versionSpec, stable, manifest, archFilter = os.arch()) { + return __awaiter(this, void 0, void 0, function* () { + // wrap the internal impl + const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); + return match; + }); +} +exports.findFromManifest = findFromManifest; +function _createExtractFolder(dest) { + return __awaiter(this, void 0, void 0, function* () { + if (!dest) { + // create a temp dir + dest = path.join(_getTempDirectory(), v4_1.default()); } - else { - return isHttps ? https__namespace.globalAgent : http__namespace.globalAgent; + yield io.mkdirP(dest); + return dest; + }); +} +function _createToolPath(tool, version, arch) { + return __awaiter(this, void 0, void 0, function* () { + const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || ''); + core.debug(`destination ${folderPath}`); + const markerPath = `${folderPath}.complete`; + yield io.rmRF(folderPath); + yield io.rmRF(markerPath); + yield io.mkdirP(folderPath); + return folderPath; + }); +} +function _completeToolPath(tool, version, arch) { + const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || ''); + const markerPath = `${folderPath}.complete`; + fs.writeFileSync(markerPath, ''); + core.debug('finished caching tool'); +} +/** + * Check if version string is explicit + * + * @param versionSpec version string to check + */ +function isExplicitVersion(versionSpec) { + const c = semver.clean(versionSpec) || ''; + core.debug(`isExplicit: ${c}`); + const valid = semver.valid(c) != null; + core.debug(`explicit? ${valid}`); + return valid; +} +exports.isExplicitVersion = isExplicitVersion; +/** + * Get the highest satisfiying semantic version in `versions` which satisfies `versionSpec` + * + * @param versions array of versions to evaluate + * @param versionSpec semantic version spec to satisfy + */ +function evaluateVersions(versions, versionSpec) { + let version = ''; + core.debug(`evaluating ${versions.length} versions`); + versions = versions.sort((a, b) => { + if (semver.gt(a, b)) { + return 1; } - } - /** - * Uses `node-fetch` to perform the request. - */ - // eslint-disable-next-line @azure/azure-sdk/ts-apisurface-standardized-verbs - async fetch(input, init) { - return node_fetch__default["default"](input, init); - } - /** - * Prepares a request based on the provided web resource. - */ - async prepareRequest(httpRequest) { - const requestInit = {}; - if (this.cookieJar && !httpRequest.headers.get("Cookie")) { - const cookieString = await new Promise((resolve, reject) => { - this.cookieJar.getCookieString(httpRequest.url, (err, cookie) => { - if (err) { - reject(err); - } - else { - resolve(cookie); - } - }); - }); - httpRequest.headers.set("Cookie", cookieString); + return -1; + }); + for (let i = versions.length - 1; i >= 0; i--) { + const potential = versions[i]; + const satisfied = semver.satisfies(potential, versionSpec); + if (satisfied) { + version = potential; + break; } - // Set the http(s) agent - requestInit.agent = this.getOrCreateAgent(httpRequest); - requestInit.compress = httpRequest.decompressResponse; - return requestInit; } - /** - * Process an HTTP response. Handles persisting a cookie for subsequent requests if the response has a "Set-Cookie" header. - */ - async processRequest(operationResponse) { - if (this.cookieJar) { - const setCookieHeader = operationResponse.headers.get("Set-Cookie"); - if (setCookieHeader !== undefined) { - await new Promise((resolve, reject) => { - this.cookieJar.setCookie(setCookieHeader, operationResponse.request.url, { ignoreError: true }, (err) => { - if (err) { - reject(err); - } - else { - resolve(); - } - }); - }); - } - } + if (version) { + core.debug(`matched: ${version}`); } + else { + core.debug('match not found'); + } + return version; } - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +exports.evaluateVersions = evaluateVersions; /** - * The different levels of logs that can be used with the HttpPipelineLogger. + * Gets RUNNER_TOOL_CACHE */ -exports.HttpPipelineLogLevel = void 0; -(function (HttpPipelineLogLevel) { - /** - * A log level that indicates that no logs will be logged. - */ - HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF"; - /** - * An error log. - */ - HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR"; - /** - * A warning log. - */ - HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING"; - /** - * An information log. - */ - HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO"; -})(exports.HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = {})); - -// Copyright (c) Microsoft Corporation. +function _getCacheDirectory() { + const cacheDirectory = process.env['RUNNER_TOOL_CACHE'] || ''; + assert_1.ok(cacheDirectory, 'Expected RUNNER_TOOL_CACHE to be defined'); + return cacheDirectory; +} +/** + * Gets RUNNER_TEMP + */ +function _getTempDirectory() { + const tempDirectory = process.env['RUNNER_TEMP'] || ''; + assert_1.ok(tempDirectory, 'Expected RUNNER_TEMP to be defined'); + return tempDirectory; +} +/** + * Gets a global variable + */ +function _getGlobal(key, defaultValue) { + /* eslint-disable @typescript-eslint/no-explicit-any */ + const value = global[key]; + /* eslint-enable @typescript-eslint/no-explicit-any */ + return value !== undefined ? value : defaultValue; +} /** - * Converts an OperationOptions to a RequestOptionsBase - * - * @param opts - OperationOptions object to convert to RequestOptionsBase + * Returns an array of unique values. + * @param values Values to make unique. */ -function operationOptionsToRequestOptionsBase(opts) { - const { requestOptions, tracingOptions } = opts, additionalOptions = tslib.__rest(opts, ["requestOptions", "tracingOptions"]); - let result = additionalOptions; - if (requestOptions) { - result = Object.assign(Object.assign({}, result), requestOptions); - } - if (tracingOptions) { - result.tracingContext = tracingOptions.tracingContext; - // By passing spanOptions if they exist at runtime, we're backwards compatible with @azure/core-tracing@preview.13 and earlier. - result.spanOptions = tracingOptions === null || tracingOptions === void 0 ? void 0 : tracingOptions.spanOptions; - } - return result; +function _unique(values) { + return Array.from(new Set(values)); } +//# sourceMappingURL=tool-cache.js.map + +/***/ }), + +/***/ 97675: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/// +const listenersMap = new WeakMap(); +const abortedMap = new WeakMap(); /** - * The base class from which all request policies derive. + * 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 + * ```ts + * await doAsyncWork(AbortSignal.none); + * ``` */ -class BaseRequestPolicy { +class AbortSignal { + constructor() { + /** + * onabort event listener. + */ + this.onabort = null; + listenersMap.set(this, []); + abortedMap.set(this, false); + } /** - * The main method to implement that manipulates a request/response. + * Status of whether aborted or not. + * + * @readonly */ - constructor( + get aborted() { + if (!abortedMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); + } + return abortedMap.get(this); + } /** - * The next policy in the pipeline. Each policy is responsible for executing the next one if the request is to continue through the pipeline. + * Creates a new AbortSignal instance that will never be aborted. + * + * @readonly */ - _nextPolicy, + static get none() { + return new AbortSignal(); + } /** - * The options that can be passed to a given request policy. + * Added new "abort" event listener, only support "abort" event. + * + * @param _type - Only support "abort" event + * @param listener - The listener to be added */ - _options) { - this._nextPolicy = _nextPolicy; - this._options = _options; + addEventListener( + // tslint:disable-next-line:variable-name + _type, listener) { + if (!listenersMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); + } + const listeners = listenersMap.get(this); + listeners.push(listener); } /** - * Get whether or not a log with the provided log level should be logged. - * @param logLevel - The log level of the log that will be logged. - * @returns Whether or not a log with the provided log level should be logged. + * Remove "abort" event listener, only support "abort" event. + * + * @param _type - Only support "abort" event + * @param listener - The listener to be removed */ - shouldLog(logLevel) { - return this._options.shouldLog(logLevel); + removeEventListener( + // tslint:disable-next-line:variable-name + _type, listener) { + if (!listenersMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); + } + const listeners = listenersMap.get(this); + const index = listeners.indexOf(listener); + if (index > -1) { + listeners.splice(index, 1); + } } /** - * Attempt to log the provided message to the provided logger. If no logger was provided or if - * the log level does not meat the logger's threshold, then nothing will be logged. - * @param logLevel - The log level of this log. - * @param message - The message of this log. + * Dispatches a synthetic event to the AbortSignal. */ - log(logLevel, message) { - this._options.log(logLevel, message); + dispatchEvent(_event) { + throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes."); } } /** - * Optional properties that can be used when creating a RequestPolicy. + * 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. + * + * @internal */ -class RequestPolicyOptions { - constructor(_logger) { - this._logger = _logger; +// eslint-disable-next-line @azure/azure-sdk/ts-use-interface-parameters +function abortSignal(signal) { + if (signal.aborted) { + return; } - /** - * Get whether or not a log with the provided log level should be logged. - * @param logLevel - The log level of the log that will be logged. - * @returns Whether or not a log with the provided log level should be logged. - */ - shouldLog(logLevel) { - return (!!this._logger && - logLevel !== exports.HttpPipelineLogLevel.OFF && - logLevel <= this._logger.minimumLogLevel); + if (signal.onabort) { + signal.onabort.call(signal); } - /** - * Attempt to log the provided message to the provided logger. If no logger was provided or if - * the log level does not meet the logger's threshold, then nothing will be logged. - * @param logLevel - The log level of this log. - * @param message - The message of this log. - */ - log(logLevel, message) { - if (this._logger && this.shouldLog(logLevel)) { - this._logger.log(logLevel, message); - } + const listeners = listenersMap.get(signal); + if (listeners) { + // Create a copy of listeners so mutations to the array + // (e.g. via removeListener calls) don't affect the listeners + // we invoke. + listeners.slice().forEach((listener) => { + listener.call(signal, { type: "abort" }); + }); } + abortedMap.set(signal, true); } // Copyright (c) Microsoft Corporation. -// Note: The reason we re-define all of the xml2js default settings (version 2.0) here is because the default settings object exposed -// by the xm2js library is mutable. See /~https://github.com/Leonidas-from-XIV/node-xml2js/issues/536 -// By creating a new copy of the settings each time we instantiate the parser, -// we are safeguarding against the possibility of the default settings being mutated elsewhere unintentionally. -const xml2jsDefaultOptionsV2 = { - explicitCharkey: false, - trim: false, - normalize: false, - normalizeTags: false, - attrkey: XML_ATTRKEY, - explicitArray: true, - ignoreAttrs: false, - mergeAttrs: false, - explicitRoot: true, - validator: undefined, - xmlns: false, - explicitChildren: false, - preserveChildrenOrder: false, - childkey: "$$", - charsAsChildren: false, - includeWhiteChars: false, - async: false, - strict: true, - attrNameProcessors: undefined, - attrValueProcessors: undefined, - tagNameProcessors: undefined, - valueProcessors: undefined, - rootName: "root", - xmldec: { - version: "1.0", - encoding: "UTF-8", - standalone: true, - }, - doctype: undefined, - renderOpts: { - pretty: true, - indent: " ", - newline: "\n", - }, - headless: false, - chunkSize: 10000, - emptyTag: "", - cdata: false, -}; -// The xml2js settings for general XML parsing operations. -const xml2jsParserSettings = Object.assign({}, xml2jsDefaultOptionsV2); -xml2jsParserSettings.explicitArray = false; -// The xml2js settings for general XML building operations. -const xml2jsBuilderSettings = Object.assign({}, xml2jsDefaultOptionsV2); -xml2jsBuilderSettings.explicitArray = false; -xml2jsBuilderSettings.renderOpts = { - pretty: false, -}; -/** - * Converts given JSON object to XML string - * @param obj - JSON object to be converted into XML string - * @param opts - Options that govern the parsing of given JSON object - */ -function stringifyXML(obj, opts = {}) { - var _a; - xml2jsBuilderSettings.rootName = opts.rootName; - xml2jsBuilderSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; - const builder = new xml2js__namespace.Builder(xml2jsBuilderSettings); - return builder.buildObject(obj); -} -/** - * Converts given XML string into JSON - * @param str - String containing the XML content to be parsed into JSON - * @param opts - Options that govern the parsing of given xml string - */ -function parseXML(str, opts = {}) { - var _a; - xml2jsParserSettings.explicitRoot = !!opts.includeRoot; - xml2jsParserSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; - const xmlParser = new xml2js__namespace.Parser(xml2jsParserSettings); - return new Promise((resolve, reject) => { - if (!str) { - reject(new Error("Document is empty")); - } - else { - xmlParser.parseString(str, (err, res) => { - if (err) { - reject(err); - } - else { - resolve(res); - } - }); - } - }); -} - -// Copyright (c) Microsoft Corporation. -/** - * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they - * pass through the HTTP pipeline. - */ -function deserializationPolicy(deserializationContentTypes, parsingOptions) { - return { - create: (nextPolicy, options) => { - return new DeserializationPolicy(nextPolicy, options, deserializationContentTypes, parsingOptions); - }, - }; -} -const defaultJsonContentTypes = ["application/json", "text/json"]; -const defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; -const DefaultDeserializationOptions = { - expectedContentTypes: { - json: defaultJsonContentTypes, - xml: defaultXmlContentTypes, - }, -}; /** - * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the - * HTTP pipeline. + * 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 + * ```ts + * const controller = new AbortController(); + * controller.abort(); + * try { + * doAsyncWork(controller.signal) + * } catch (e) { + * if (e.name === 'AbortError') { + * // handle abort error here. + * } + * } + * ``` */ -class DeserializationPolicy extends BaseRequestPolicy { - constructor(nextPolicy, requestPolicyOptions, deserializationContentTypes, parsingOptions = {}) { - var _a; - super(nextPolicy, requestPolicyOptions); - this.jsonContentTypes = - (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes; - this.xmlContentTypes = - (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes; - this.xmlCharKey = (_a = parsingOptions.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; - } - async sendRequest(request) { - return this._nextPolicy.sendRequest(request).then((response) => deserializeResponseBody(this.jsonContentTypes, this.xmlContentTypes, response, { - xmlCharKey: this.xmlCharKey, - })); - } -} -function getOperationResponse(parsedResponse) { - let result; - const request = parsedResponse.request; - const operationSpec = request.operationSpec; - if (operationSpec) { - const operationResponseGetter = request.operationResponseGetter; - if (!operationResponseGetter) { - result = operationSpec.responses[parsedResponse.status]; - } - else { - result = operationResponseGetter(operationSpec, parsedResponse); - } - } - return result; -} -function shouldDeserializeResponse(parsedResponse) { - const shouldDeserialize = parsedResponse.request.shouldDeserialize; - let result; - if (shouldDeserialize === undefined) { - result = true; - } - else if (typeof shouldDeserialize === "boolean") { - result = shouldDeserialize; - } - else { - result = shouldDeserialize(parsedResponse); +class AbortError extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; } - return result; } /** - * Given a particular set of content types to parse as either JSON or XML, consumes the HTTP response to produce the result object defined by the request's {@link OperationSpec}. - * @param jsonContentTypes - Response content types to parse the body as JSON. - * @param xmlContentTypes - Response content types to parse the body as XML. - * @param response - HTTP Response from the pipeline. - * @param options - Options to the serializer, mostly for configuring the XML parser if needed. - * @returns A parsed {@link HttpOperationResponse} object that can be returned by the {@link ServiceClient}. + * 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 + * ```ts + * const controller = new AbortController(); + * const signal = controller.signal; + * doAsyncWork(signal); + * button.addEventListener('click', () => controller.abort()); + * ``` + * + * @example + * Share aborter cross multiple operations in 30s + * ```ts + * // 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 + * ```ts + * // 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)); + * ``` */ -function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options = {}) { - var _a, _b, _c; - const updatedOptions = { - rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", - includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, - }; - return parse(jsonContentTypes, xmlContentTypes, response, updatedOptions).then((parsedResponse) => { - if (!shouldDeserializeResponse(parsedResponse)) { - return parsedResponse; - } - const operationSpec = parsedResponse.request.operationSpec; - if (!operationSpec || !operationSpec.responses) { - return parsedResponse; - } - const responseSpec = getOperationResponse(parsedResponse); - const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec); - if (error) { - throw error; - } - else if (shouldReturnResponse) { - return parsedResponse; - } - // An operation response spec does exist for current status code, so - // use it to deserialize the response. - if (responseSpec) { - if (responseSpec.bodyMapper) { - let valueToDeserialize = parsedResponse.parsedBody; - if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) { - valueToDeserialize = - typeof valueToDeserialize === "object" - ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] - : []; - } - try { - parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); - } - catch (innerError) { - const restError = new RestError(`Error ${innerError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); - throw restError; - } - } - else if (operationSpec.httpMethod === "HEAD") { - // head methods never have a body, but we return a boolean to indicate presence/absence of the resource - parsedResponse.parsedBody = response.status >= 200 && response.status < 300; - } - if (responseSpec.headersMapper) { - parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders", options); - } - } - return parsedResponse; - }); -} -function isOperationSpecEmpty(operationSpec) { - const expectedStatusCodes = Object.keys(operationSpec.responses); - return (expectedStatusCodes.length === 0 || - (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); -} -function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { - var _a; - const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; - const isExpectedStatusCode = isOperationSpecEmpty(operationSpec) - ? isSuccessByStatus - : !!responseSpec; - if (isExpectedStatusCode) { - if (responseSpec) { - if (!responseSpec.isError) { - return { error: null, shouldReturnResponse: false }; - } +class AbortController { + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + constructor(parentSignals) { + this._signal = new AbortSignal(); + if (!parentSignals) { + return; } - else { - return { error: null, shouldReturnResponse: false }; + // coerce parentSignals into an array + if (!Array.isArray(parentSignals)) { + // eslint-disable-next-line prefer-rest-params + parentSignals = arguments; } - } - const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; - const streaming = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) || - parsedResponse.request.streamResponseBody; - const initialErrorMessage = streaming - ? `Unexpected status code: ${parsedResponse.status}` - : parsedResponse.bodyAsText; - const error = new RestError(initialErrorMessage, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); - // If the item failed but there's no error spec or default spec to deserialize the error, - // we should fail so we just throw the parsed response - if (!errorResponseSpec) { - throw error; - } - const defaultBodyMapper = errorResponseSpec.bodyMapper; - const defaultHeadersMapper = errorResponseSpec.headersMapper; - try { - // If error response has a body, try to deserialize it using default body mapper. - // Then try to extract error code & message from it - if (parsedResponse.parsedBody) { - const parsedBody = parsedResponse.parsedBody; - let parsedError; - if (defaultBodyMapper) { - let valueToDeserialize = parsedBody; - if (operationSpec.isXML && defaultBodyMapper.type.name === MapperType.Sequence) { - valueToDeserialize = - typeof parsedBody === "object" ? parsedBody[defaultBodyMapper.xmlElementName] : []; - } - parsedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody"); - } - const internalError = parsedBody.error || parsedError || parsedBody; - error.code = internalError.code; - if (internalError.message) { - error.message = internalError.message; + for (const parentSignal of parentSignals) { + // if the parent signal has already had abort() called, + // then call abort on this signal as well. + if (parentSignal.aborted) { + this.abort(); } - if (defaultBodyMapper) { - error.response.parsedBody = parsedError; + else { + // when the parent signal aborts, this signal should as well. + parentSignal.addEventListener("abort", () => { + this.abort(); + }); } } - // If error response has headers, try to deserialize it using default header mapper - if (parsedResponse.headers && defaultHeadersMapper) { - error.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders"); - } } - catch (defaultError) { - error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`; + /** + * The AbortSignal associated with this controller that will signal aborted + * when the abort method is called on this controller. + * + * @readonly + */ + get signal() { + return this._signal; } - return { error, shouldReturnResponse: false }; -} -function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { - var _a; - const errorHandler = (err) => { - const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`; - const errCode = err.code || RestError.PARSE_ERROR; - const e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse); - return Promise.reject(e); - }; - const streaming = ((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) || - operationResponse.request.streamResponseBody; - if (!streaming && operationResponse.bodyAsText) { - const text = operationResponse.bodyAsText; - const contentType = operationResponse.headers.get("Content-Type") || ""; - const contentComponents = !contentType - ? [] - : contentType.split(";").map((component) => component.toLowerCase()); - if (contentComponents.length === 0 || - contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) { - return new Promise((resolve) => { - operationResponse.parsedBody = JSON.parse(text); - resolve(operationResponse); - }).catch(errorHandler); - } - else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) { - return parseXML(text, opts) - .then((body) => { - operationResponse.parsedBody = body; - return operationResponse; - }) - .catch(errorHandler); + /** + * Signal that any operations passed this controller's associated abort signal + * to cancel any remaining work and throw an `AbortError`. + */ + abort() { + abortSignal(this._signal); + } + /** + * Creates a new AbortSignal instance that will abort after the provided ms. + * @param ms - Elapsed time in milliseconds to trigger an abort. + */ + static timeout(ms) { + const signal = new AbortSignal(); + const 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 Promise.resolve(operationResponse); } +exports.AbortController = AbortController; +exports.AbortError = AbortError; +exports.AbortSignal = AbortSignal; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 383: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** - * By default, HTTP connections are maintained for future requests. - */ -const DefaultKeepAliveOptions = { - enable: true, -}; -/** - * Creates a policy that controls whether HTTP connections are maintained on future requests. - * @param keepAliveOptions - Keep alive options. By default, HTTP connections are maintained for future requests. - * @returns An instance of the {@link KeepAlivePolicy} - */ -function keepAlivePolicy(keepAliveOptions) { - return { - create: (nextPolicy, options) => { - return new KeepAlivePolicy(nextPolicy, options, keepAliveOptions || DefaultKeepAliveOptions); - }, - }; -} -/** - * KeepAlivePolicy is a policy used to control keep alive settings for every request. + * A static-key-based credential that supports updating + * the underlying key value. */ -class KeepAlivePolicy extends BaseRequestPolicy { +class AzureKeyCredential { /** - * Creates an instance of KeepAlivePolicy. + * Create an instance of an AzureKeyCredential for use + * with a service client. * - * @param nextPolicy - - * @param options - - * @param keepAliveOptions - + * @param key - The initial value of the key to use in authentication */ - constructor(nextPolicy, options, keepAliveOptions) { - super(nextPolicy, options); - this.keepAliveOptions = keepAliveOptions; + constructor(key) { + if (!key) { + throw new Error("key must be a non-empty string"); + } + this._key = key; } /** - * Sends out request. + * The value of the key to be used in authentication + */ + get key() { + return this._key; + } + /** + * Change the value of the key. * - * @param request - - * @returns + * Updates will take effect upon the next request after + * updating the key value. + * + * @param newKey - The new key value to be used */ - async sendRequest(request) { - request.keepAlive = this.keepAliveOptions.enable; - return this._nextPolicy.sendRequest(request); + update(newKey) { + this._key = newKey; } } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** - * Methods that are allowed to follow redirects 301 and 302 + * Helper TypeGuard that checks if something is defined or not. + * @param thing - Anything + * @internal */ -const allowedRedirect = ["GET", "HEAD"]; -const DefaultRedirectOptions = { - handleRedirects: true, - maxRetries: 20, -}; +function isDefined(thing) { + return typeof thing !== "undefined" && thing !== null; +} /** - * Creates a redirect policy, which sends a repeats the request to a new destination if a response arrives with a "location" header, and a status code between 300 and 307. - * @param maximumRetries - Maximum number of redirects to follow. - * @returns An instance of the {@link RedirectPolicy} + * Helper TypeGuard that checks if the input is an object with the specified properties. + * Note: The properties may be inherited. + * @param thing - Anything. + * @param properties - The name of the properties that should appear in the object. + * @internal */ -function redirectPolicy(maximumRetries = 20) { - return { - create: (nextPolicy, options) => { - return new RedirectPolicy(nextPolicy, options, maximumRetries); - }, - }; +function isObjectWithProperties(thing, properties) { + if (!isDefined(thing) || typeof thing !== "object") { + return false; + } + for (const property of properties) { + if (!objectHasProperty(thing, property)) { + return false; + } + } + return true; } /** - * Resends the request to a new destination if a response arrives with a "location" header, and a status code between 300 and 307. + * Helper TypeGuard that checks if the input is an object with the specified property. + * Note: The property may be inherited. + * @param thing - Any object. + * @param property - The name of the property that should appear in the object. + * @internal */ -class RedirectPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, maxRetries = 20) { - super(nextPolicy, options); - this.maxRetries = maxRetries; +function objectHasProperty(thing, property) { + return typeof thing === "object" && property in thing; +} + +// Copyright (c) Microsoft Corporation. +/** + * A static name/key-based credential that supports updating + * the underlying name and key values. + */ +class AzureNamedKeyCredential { + /** + * Create an instance of an AzureNamedKeyCredential for use + * with a service client. + * + * @param name - The initial value of the name to use in authentication. + * @param key - The initial value of the key to use in authentication. + */ + constructor(name, key) { + if (!name || !key) { + throw new TypeError("name and key must be non-empty strings"); + } + this._name = name; + this._key = key; } - sendRequest(request) { - return this._nextPolicy - .sendRequest(request) - .then((response) => handleRedirect(this, response, 0)); + /** + * The value of the key to be used in authentication. + */ + get key() { + return this._key; } -} -function handleRedirect(policy, response, currentRetries) { - const { request, status } = response; - const locationHeader = response.headers.get("location"); - if (locationHeader && - (status === 300 || - (status === 301 && allowedRedirect.includes(request.method)) || - (status === 302 && allowedRedirect.includes(request.method)) || - (status === 303 && request.method === "POST") || - status === 307) && - (!policy.maxRetries || currentRetries < policy.maxRetries)) { - const builder = URLBuilder.parse(request.url); - builder.setPath(locationHeader); - request.url = builder.toString(); - // POST request with Status code 303 should be converted into a - // redirected GET request if the redirect url is present in the location header - if (status === 303) { - request.method = "GET"; - delete request.body; + /** + * The value of the name to be used in authentication. + */ + get name() { + return this._name; + } + /** + * Change the value of the key. + * + * Updates will take effect upon the next request after + * updating the key value. + * + * @param newName - The new name value to be used. + * @param newKey - The new key value to be used. + */ + update(newName, newKey) { + if (!newName || !newKey) { + throw new TypeError("newName and newKey must be non-empty strings"); } - return policy._nextPolicy - .sendRequest(request) - .then((res) => handleRedirect(policy, res, currentRetries + 1)); + this._name = newName; + this._key = newKey; } - return Promise.resolve(response); +} +/** + * Tests an object to determine whether it implements NamedKeyCredential. + * + * @param credential - The assumed NamedKeyCredential to be tested. + */ +function isNamedKeyCredential(credential) { + return (isObjectWithProperties(credential, ["name", "key"]) && + typeof credential.key === "string" && + typeof credential.name === "string"); } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -const DEFAULT_CLIENT_RETRY_COUNT = 3; -// intervals are in ms -const DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30; -const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90; -const DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3; -function isNumber(n) { - return typeof n === "number"; -} /** - * @internal - * Determines if the operation should be retried. - * - * @param retryLimit - Specifies the max number of retries. - * @param predicate - Initial chekck on whether to retry based on given responses or errors - * @param retryData - The retry data. - * @returns True if the operation qualifies for a retry; false otherwise. + * A static-signature-based credential that supports updating + * the underlying signature value. */ -function shouldRetry(retryLimit, predicate, retryData, response, error) { - if (!predicate(response, error)) { - return false; +class AzureSASCredential { + /** + * Create an instance of an AzureSASCredential for use + * with a service client. + * + * @param signature - The initial value of the shared access signature to use in authentication + */ + constructor(signature) { + if (!signature) { + throw new Error("shared access signature must be a non-empty string"); + } + this._signature = signature; + } + /** + * The value of the shared access signature to be used in authentication + */ + get signature() { + return this._signature; + } + /** + * Change the value of the signature. + * + * Updates will take effect upon the next request after + * updating the signature value. + * + * @param newSignature - The new shared access signature value to be used + */ + update(newSignature) { + if (!newSignature) { + throw new Error("shared access signature must be a non-empty string"); + } + this._signature = newSignature; } - return retryData.retryCount < retryLimit; } /** - * @internal - * Updates the retry data for the next attempt. + * Tests an object to determine whether it implements SASCredential. * - * @param retryOptions - specifies retry interval, and its lower bound and upper bound. - * @param retryData - The retry data. - * @param err - The operation"s error, if any. + * @param credential - The assumed SASCredential to be tested. */ -function updateRetryData(retryOptions, retryData = { retryCount: 0, retryInterval: 0 }, err) { - if (err) { - if (retryData.error) { - err.innerError = retryData.error; - } - retryData.error = err; - } - // Adjust retry count - retryData.retryCount++; - // Adjust retry interval - let incrementDelta = Math.pow(2, retryData.retryCount - 1) - 1; - const boundedRandDelta = retryOptions.retryInterval * 0.8 + - Math.floor(Math.random() * (retryOptions.retryInterval * 0.4)); - incrementDelta *= boundedRandDelta; - retryData.retryInterval = Math.min(retryOptions.minRetryInterval + incrementDelta, retryOptions.maxRetryInterval); - return retryData; +function isSASCredential(credential) { + return (isObjectWithProperties(credential, ["signature"]) && typeof credential.signature === "string"); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** - * Helper TypeGuard that checks if the value is not null or undefined. - * @param thing - Anything - * @internal + * Tests an object to determine whether it implements TokenCredential. + * + * @param credential - The assumed TokenCredential to be tested. */ -function isDefined(thing) { - return typeof thing !== "undefined" && thing !== null; +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. + const castCredential = credential; + return (castCredential && + typeof castCredential.getToken === "function" && + (castCredential.signRequest === undefined || castCredential.getToken.length > 0)); } -// Copyright (c) Microsoft Corporation. -const StandardAbortMessage$1 = "The operation was aborted."; -/** - * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds. - * @param delayInMs - The number of milliseconds to be delayed. - * @param value - The value to be resolved with after a timeout of t milliseconds. - * @param options - The options for delay - currently abort options - * @param abortSignal - The abortSignal associated with containing operation. - * @param abortErrorMsg - The abort error message associated with containing operation. - * @returns - Resolved promise - */ -function delay(delayInMs, value, options) { - return new Promise((resolve, reject) => { - let timer = undefined; - let onAborted = undefined; - const rejectOnAbort = () => { - return reject(new abortController.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage$1)); - }; - const removeListeners = () => { - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { - options.abortSignal.removeEventListener("abort", onAborted); - } - }; - onAborted = () => { - if (isDefined(timer)) { - clearTimeout(timer); +exports.AzureKeyCredential = AzureKeyCredential; +exports.AzureNamedKeyCredential = AzureNamedKeyCredential; +exports.AzureSASCredential = AzureSASCredential; +exports.isNamedKeyCredential = isNamedKeyCredential; +exports.isSASCredential = isSASCredential; +exports.isTokenCredential = isTokenCredential; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 12372: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var uuid = __nccwpck_require__(37066); +var util = __nccwpck_require__(73837); +var tslib = __nccwpck_require__(71398); +var xml2js = __nccwpck_require__(423); +var abortController = __nccwpck_require__(97675); +var coreUtil = __nccwpck_require__(33267); +var logger$1 = __nccwpck_require__(63264); +var coreAuth = __nccwpck_require__(383); +var os = __nccwpck_require__(22037); +var http = __nccwpck_require__(13685); +var https = __nccwpck_require__(95687); +var tough = __nccwpck_require__(85367); +var tunnel = __nccwpck_require__(68125); +var stream = __nccwpck_require__(12781); +var FormData = __nccwpck_require__(89834); +var node_fetch = __nccwpck_require__(69608); +var coreTracing = __nccwpck_require__(73179); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); } - removeListeners(); - return rejectOnAbort(); - }; - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { - return rejectOnAbort(); - } - timer = setTimeout(() => { - removeListeners(); - resolve(value); - }, delayInMs); - if (options === null || options === void 0 ? void 0 : options.abortSignal) { - options.abortSignal.addEventListener("abort", onAborted); - } - }); + }); + } + n["default"] = e; + return Object.freeze(n); } +var xml2js__namespace = /*#__PURE__*/_interopNamespace(xml2js); +var os__namespace = /*#__PURE__*/_interopNamespace(os); +var http__namespace = /*#__PURE__*/_interopNamespace(http); +var https__namespace = /*#__PURE__*/_interopNamespace(https); +var tough__namespace = /*#__PURE__*/_interopNamespace(tough); +var tunnel__namespace = /*#__PURE__*/_interopNamespace(tunnel); +var FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData); +var node_fetch__default = /*#__PURE__*/_interopDefaultLegacy(node_fetch); + // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** - * Policy that retries the request as many times as configured for as long as the max retry time interval specified, each retry waiting longer to begin than the last time. - * @param retryCount - Maximum number of retries. - * @param retryInterval - Base time between retries. - * @param maxRetryInterval - Maximum time to wait between retries. + * A collection of HttpHeaders that can be sent with a HTTP request. */ -function exponentialRetryPolicy(retryCount, retryInterval, maxRetryInterval) { - return { - create: (nextPolicy, options) => { - return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, maxRetryInterval); - }, - }; +function getHeaderKey(headerName) { + return headerName.toLowerCase(); +} +function isHttpHeadersLike(object) { + if (object && typeof object === "object") { + const castObject = object; + if (typeof castObject.rawHeaders === "function" && + typeof castObject.clone === "function" && + typeof castObject.get === "function" && + typeof castObject.set === "function" && + typeof castObject.contains === "function" && + typeof castObject.remove === "function" && + typeof castObject.headersArray === "function" && + typeof castObject.headerValues === "function" && + typeof castObject.headerNames === "function" && + typeof castObject.toJson === "function") { + return true; + } + } + return false; } /** - * Describes the Retry Mode type. Currently supporting only Exponential. + * A collection of HTTP header key/value pairs. */ -exports.RetryMode = void 0; -(function (RetryMode) { +class HttpHeaders { + constructor(rawHeaders) { + this._headersMap = {}; + if (rawHeaders) { + for (const headerName in rawHeaders) { + this.set(headerName, rawHeaders[headerName]); + } + } + } + /** + * Set a header in this collection with the provided name and value. The name is + * case-insensitive. + * @param headerName - The name of the header to set. This value is case-insensitive. + * @param headerValue - The value of the header to set. + */ + set(headerName, headerValue) { + this._headersMap[getHeaderKey(headerName)] = { + name: headerName, + value: headerValue.toString(), + }; + } + /** + * Get the header value for the provided header name, or undefined if no header exists in this + * collection with the provided name. + * @param headerName - The name of the header. + */ + get(headerName) { + const header = this._headersMap[getHeaderKey(headerName)]; + return !header ? undefined : header.value; + } /** - * Currently supported retry mode. - * Each time a retry happens, it will take exponentially more time than the last time. + * Get whether or not this header collection contains a header entry for the provided header name. */ - RetryMode[RetryMode["Exponential"] = 0] = "Exponential"; -})(exports.RetryMode || (exports.RetryMode = {})); -const DefaultRetryOptions = { - maxRetries: DEFAULT_CLIENT_RETRY_COUNT, - retryDelayInMs: DEFAULT_CLIENT_RETRY_INTERVAL, - maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL, -}; -/** - * Instantiates a new "ExponentialRetryPolicyFilter" instance. - */ -class ExponentialRetryPolicy extends BaseRequestPolicy { + contains(headerName) { + return !!this._headersMap[getHeaderKey(headerName)]; + } /** - * @param nextPolicy - The next RequestPolicy in the pipeline chain. - * @param options - The options for this RequestPolicy. - * @param retryCount - The client retry count. - * @param retryInterval - The client retry interval, in milliseconds. - * @param minRetryInterval - The minimum retry interval, in milliseconds. - * @param maxRetryInterval - The maximum retry interval, in milliseconds. + * Remove the header with the provided headerName. Return whether or not the header existed and + * was removed. + * @param headerName - The name of the header to remove. */ - constructor(nextPolicy, options, retryCount, retryInterval, maxRetryInterval) { - super(nextPolicy, options); - this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; - this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; - this.maxRetryInterval = isNumber(maxRetryInterval) - ? maxRetryInterval - : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + remove(headerName) { + const result = this.contains(headerName); + delete this._headersMap[getHeaderKey(headerName)]; + return result; } - sendRequest(request) { - return this._nextPolicy - .sendRequest(request.clone()) - .then((response) => retry$1(this, request, response)) - .catch((error) => retry$1(this, request, error.response, undefined, error)); + /** + * Get the headers that are contained this collection as an object. + */ + rawHeaders() { + return this.toJson({ preserveCase: true }); } -} -async function retry$1(policy, request, response, retryData, requestError) { - function shouldPolicyRetry(responseParam) { - const statusCode = responseParam === null || responseParam === void 0 ? void 0 : responseParam.status; - if (statusCode === 503 && (response === null || response === void 0 ? void 0 : response.headers.get(Constants.HeaderConstants.RETRY_AFTER))) { - return false; + /** + * Get the headers that are contained in this collection as an array. + */ + headersArray() { + const headers = []; + for (const headerKey in this._headersMap) { + headers.push(this._headersMap[headerKey]); } - if (statusCode === undefined || - (statusCode < 500 && statusCode !== 408) || - statusCode === 501 || - statusCode === 505) { - return false; + return headers; + } + /** + * Get the header names that are contained in this collection. + */ + headerNames() { + const headerNames = []; + const headers = this.headersArray(); + for (let i = 0; i < headers.length; ++i) { + headerNames.push(headers[i].name); } - return true; + return headerNames; } - retryData = updateRetryData({ - retryInterval: policy.retryInterval, - minRetryInterval: 0, - maxRetryInterval: policy.maxRetryInterval, - }, retryData, requestError); - const isAborted = request.abortSignal && request.abortSignal.aborted; - if (!isAborted && shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, response)) { - logger.info(`Retrying request in ${retryData.retryInterval}`); - try { - await delay(retryData.retryInterval); - const res = await policy._nextPolicy.sendRequest(request.clone()); - return retry$1(policy, request, res, retryData); + /** + * Get the header values that are contained in this collection. + */ + headerValues() { + const headerValues = []; + const headers = this.headersArray(); + for (let i = 0; i < headers.length; ++i) { + headerValues.push(headers[i].value); } - catch (err) { - return retry$1(policy, request, response, retryData, err); + return headerValues; + } + /** + * Get the JSON object representation of this HTTP header collection. + */ + toJson(options = {}) { + const result = {}; + if (options.preserveCase) { + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + result[header.name] = header.value; + } + } + else { + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + result[getHeaderKey(header.name)] = header.value; + } } + return result; } - else if (isAborted || requestError || !response) { - // If the operation failed in the end, return all errors instead of just the last one - const err = retryData.error || - new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response); - throw err; + /** + * Get the string representation of this HTTP header collection. + */ + toString() { + return JSON.stringify(this.toJson({ preserveCase: true })); } - else { - return response; + /** + * Create a deep clone/copy of this HttpHeaders collection. + */ + clone() { + const resultPreservingCasing = {}; + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + resultPreservingCasing[header.name] = header.value; + } + return new HttpHeaders(resultPreservingCasing); } } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** - * Creates a policy that logs information about the outgoing request and the incoming responses. - * @param loggingOptions - Logging options. - * @returns An instance of the {@link LogPolicy} + * Encodes a string in base64 format. + * @param value - The string to encode */ -function logPolicy(loggingOptions = {}) { - return { - create: (nextPolicy, options) => { - return new LogPolicy(nextPolicy, options, loggingOptions); - }, - }; +function encodeString(value) { + return Buffer.from(value).toString("base64"); } /** - * A policy that logs information about the outgoing request and the incoming responses. + * Encodes a byte array in base64 format. + * @param value - The Uint8Aray to encode */ -class LogPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, { logger: logger$1 = logger.info, allowedHeaderNames = [], allowedQueryParameters = [], } = {}) { - super(nextPolicy, options); - this.logger = logger$1; - this.sanitizer = new Sanitizer({ allowedHeaderNames, allowedQueryParameters }); - } +function encodeByteArray(value) { + // Buffer.from accepts | -- the TypeScript definition is off here + // https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length + const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer); + return bufferValue.toString("base64"); +} +/** + * Decodes a base64 string into a byte array. + * @param value - The base64 string to decode + */ +function decodeString(value) { + return Buffer.from(value, "base64"); +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * A set of constants used internally when processing requests. + */ +const Constants = { /** - * Header names whose values will be logged when logging is enabled. Defaults to - * Date, traceparent, x-ms-client-request-id, and x-ms-request id. Any headers - * specified in this field will be added to that list. Any other values will - * be written to logs as "REDACTED". - * @deprecated Pass these into the constructor instead. + * The core-http version */ - get allowedHeaderNames() { - return this.sanitizer.allowedHeaderNames; - } + coreHttpVersion: "2.2.7", /** - * Header names whose values will be logged when logging is enabled. Defaults to - * Date, traceparent, x-ms-client-request-id, and x-ms-request id. Any headers - * specified in this field will be added to that list. Any other values will - * be written to logs as "REDACTED". - * @deprecated Pass these into the constructor instead. + * Specifies HTTP. */ - set allowedHeaderNames(allowedHeaderNames) { - this.sanitizer.allowedHeaderNames = allowedHeaderNames; - } + HTTP: "http:", /** - * Query string names whose values will be logged when logging is enabled. By default no - * query string values are logged. - * @deprecated Pass these into the constructor instead. + * Specifies HTTPS. */ - get allowedQueryParameters() { - return this.sanitizer.allowedQueryParameters; - } + HTTPS: "https:", /** - * Query string names whose values will be logged when logging is enabled. By default no - * query string values are logged. - * @deprecated Pass these into the constructor instead. + * Specifies HTTP Proxy. */ - set allowedQueryParameters(allowedQueryParameters) { - this.sanitizer.allowedQueryParameters = allowedQueryParameters; - } - sendRequest(request) { - if (!this.logger.enabled) - return this._nextPolicy.sendRequest(request); - this.logRequest(request); - return this._nextPolicy.sendRequest(request).then((response) => this.logResponse(response)); - } - logRequest(request) { - this.logger(`Request: ${this.sanitizer.sanitize(request)}`); - } - logResponse(response) { - this.logger(`Response status code: ${response.status}`); - this.logger(`Headers: ${this.sanitizer.sanitize(response.headers)}`); - return response; - } -} + HTTP_PROXY: "HTTP_PROXY", + /** + * Specifies HTTPS Proxy. + */ + HTTPS_PROXY: "HTTPS_PROXY", + /** + * Specifies NO Proxy. + */ + NO_PROXY: "NO_PROXY", + /** + * Specifies ALL Proxy. + */ + ALL_PROXY: "ALL_PROXY", + HttpConstants: { + /** + * Http Verbs + */ + HttpVerbs: { + PUT: "PUT", + GET: "GET", + DELETE: "DELETE", + POST: "POST", + MERGE: "MERGE", + HEAD: "HEAD", + PATCH: "PATCH", + }, + StatusCodes: { + TooManyRequests: 429, + ServiceUnavailable: 503, + }, + }, + /** + * Defines constants for use with HTTP headers. + */ + HeaderConstants: { + /** + * The Authorization header. + */ + AUTHORIZATION: "authorization", + AUTHORIZATION_SCHEME: "Bearer", + /** + * The Retry-After response-header field can be used with a 503 (Service + * Unavailable) or 349 (Too Many Requests) responses to indicate how long + * the service is expected to be unavailable to the requesting client. + */ + RETRY_AFTER: "Retry-After", + /** + * The UserAgent header. + */ + USER_AGENT: "User-Agent", + }, +}; // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** - * Get the path to this parameter's value as a dotted string (a.b.c). - * @param parameter - The parameter to get the path string for. - * @returns The path to this parameter's value as a dotted string. + * Default key used to access the XML attributes. */ -function getPathStringFromParameter(parameter) { - return getPathStringFromParameterPath(parameter.parameterPath, parameter.mapper); -} -function getPathStringFromParameterPath(parameterPath, mapper) { - let result; - if (typeof parameterPath === "string") { - result = parameterPath; - } - else if (Array.isArray(parameterPath)) { - result = parameterPath.join("."); - } - else { - result = mapper.serializedName; - } - return result; -} +const XML_ATTRKEY = "$"; +/** + * Default key used to access the XML value content. + */ +const XML_CHARKEY = "_"; // Copyright (c) Microsoft Corporation. +const validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i; /** - * Gets the list of status codes for streaming responses. - * @internal + * A constant that indicates whether the environment is node.js or browser based. */ -function getStreamResponseStatusCodes(operationSpec) { - const result = new Set(); - for (const statusCode in operationSpec.responses) { - const operationResponse = operationSpec.responses[statusCode]; - if (operationResponse.bodyMapper && - operationResponse.bodyMapper.type.name === MapperType.Stream) { - result.add(Number(statusCode)); - } +const isNode = typeof process !== "undefined" && + !!process.version && + !!process.versions && + !!process.versions.node; +/** + * Encodes an URI. + * + * @param uri - The URI to be encoded. + * @returns The encoded URI. + */ +function encodeUri(uri) { + return encodeURIComponent(uri) + .replace(/!/g, "%21") + .replace(/"/g, "%27") + .replace(/\(/g, "%28") + .replace(/\)/g, "%29") + .replace(/\*/g, "%2A"); +} +/** + * Returns a stripped version of the Http Response which only contains body, + * headers and the status. + * + * @param response - The Http Response + * @returns The stripped version of Http Response. + */ +function stripResponse(response) { + const strippedResponse = {}; + strippedResponse.body = response.bodyAsText; + strippedResponse.headers = response.headers; + strippedResponse.status = response.status; + return strippedResponse; +} +/** + * Returns a stripped version of the Http Request that does not contain the + * Authorization header. + * + * @param request - The Http Request object + * @returns The stripped version of Http Request. + */ +function stripRequest(request) { + const strippedRequest = request.clone(); + if (strippedRequest.headers) { + strippedRequest.headers.remove("authorization"); } - return result; + return strippedRequest; } - -// Copyright (c) Microsoft Corporation. -function getDefaultUserAgentKey() { - return Constants.HeaderConstants.USER_AGENT; +/** + * Validates the given uuid as a string + * + * @param uuid - The uuid as a string that needs to be validated + * @returns True if the uuid is valid; false otherwise. + */ +function isValidUuid(uuid) { + return validUuidRegex.test(uuid); } -function getPlatformSpecificData() { - const runtimeInfo = { - key: "Node", - value: process.version, - }; - const osInfo = { - key: "OS", - value: `(${os__namespace.arch()}-${os__namespace.type()}-${os__namespace.release()})`, +/** + * Generated UUID + * + * @returns RFC4122 v4 UUID. + */ +function generateUuid() { + return uuid.v4(); +} +/** + * Executes an array of promises sequentially. Inspiration of this method is here: + * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises! + * + * @param promiseFactories - An array of promise factories(A function that return a promise) + * @param kickstart - Input to the first promise that is used to kickstart the promise chain. + * If not provided then the promise chain starts with undefined. + * @returns A chain of resolved or rejected promises + */ +function executePromisesSequentially(promiseFactories, kickstart) { + let result = Promise.resolve(kickstart); + promiseFactories.forEach((promiseFactory) => { + result = result.then(promiseFactory); + }); + return result; +} +/** + * Converts a Promise to a callback. + * @param promise - The Promise to be converted to a callback + * @returns A function that takes the callback `(cb: Function) => void` + * @deprecated generated code should instead depend on responseToBody + */ +// eslint-disable-next-line @typescript-eslint/ban-types +function promiseToCallback(promise) { + if (typeof promise.then !== "function") { + throw new Error("The provided input is not a Promise."); + } + // eslint-disable-next-line @typescript-eslint/ban-types + return (cb) => { + promise + .then((data) => { + // eslint-disable-next-line promise/no-callback-in-promise + return cb(undefined, data); + }) + .catch((err) => { + // eslint-disable-next-line promise/no-callback-in-promise + cb(err); + }); }; - return [runtimeInfo, osInfo]; } - -// Copyright (c) Microsoft Corporation. -function getRuntimeInfo() { - const msRestRuntime = { - key: "core-http", - value: Constants.coreHttpVersion, +/** + * Converts a Promise to a service callback. + * @param promise - The Promise of HttpOperationResponse to be converted to a service callback + * @returns A function that takes the service callback (cb: ServiceCallback): void + */ +function promiseToServiceCallback(promise) { + if (typeof promise.then !== "function") { + throw new Error("The provided input is not a Promise."); + } + return (cb) => { + promise + .then((data) => { + return process.nextTick(cb, undefined, data.parsedBody, data.request, data); + }) + .catch((err) => { + process.nextTick(cb, err); + }); }; - return [msRestRuntime]; } -function getUserAgentString(telemetryInfo, keySeparator = " ", valueSeparator = "/") { - return telemetryInfo - .map((info) => { - const value = info.value ? `${valueSeparator}${info.value}` : ""; - return `${info.key}${value}`; - }) - .join(keySeparator); +function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { + if (!Array.isArray(obj)) { + obj = [obj]; + } + if (!xmlNamespaceKey || !xmlNamespace) { + return { [elementName]: obj }; + } + const result = { [elementName]: obj }; + result[XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace }; + return result; } -const getDefaultUserAgentHeaderName = getDefaultUserAgentKey; /** - * The default approach to generate user agents. - * Uses static information from this package, plus system information available from the runtime. + * Applies the properties on the prototype of sourceCtors to the prototype of targetCtor + * @param targetCtor - The target object on which the properties need to be applied. + * @param sourceCtors - An array of source objects from which the properties need to be taken. */ -function getDefaultUserAgentValue() { - const runtimeInfo = getRuntimeInfo(); - const platformSpecificData = getPlatformSpecificData(); - const userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData)); - return userAgent; +function applyMixins(targetCtorParam, sourceCtors) { + const castTargetCtorParam = targetCtorParam; + sourceCtors.forEach((sourceCtor) => { + Object.getOwnPropertyNames(sourceCtor.prototype).forEach((name) => { + castTargetCtorParam.prototype[name] = sourceCtor.prototype[name]; + }); + }); } +const validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; /** - * Returns a policy that adds the user agent header to outgoing requests based on the given {@link TelemetryInfo}. - * @param userAgentData - Telemetry information. - * @returns A new {@link UserAgentPolicy}. + * Indicates whether the given string is in ISO 8601 format. + * @param value - The value to be validated for ISO 8601 duration format. + * @returns `true` if valid, `false` otherwise. + */ +function isDuration(value) { + return validateISODuration.test(value); +} +/** + * Replace all of the instances of searchValue in value with the provided replaceValue. + * @param value - The value to search and replace in. + * @param searchValue - The value to search for in the value argument. + * @param replaceValue - The value to replace searchValue with in the value argument. + * @returns The value where each instance of searchValue was replaced with replacedValue. */ -function userAgentPolicy(userAgentData) { - const key = !userAgentData || userAgentData.key === undefined || userAgentData.key === null - ? getDefaultUserAgentKey() - : userAgentData.key; - const value = !userAgentData || userAgentData.value === undefined || userAgentData.value === null - ? getDefaultUserAgentValue() - : userAgentData.value; - return { - create: (nextPolicy, options) => { - return new UserAgentPolicy(nextPolicy, options, key, value); - }, - }; +function replaceAll(value, searchValue, replaceValue) { + return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || ""); } /** - * A policy that adds the user agent header to outgoing requests based on the given {@link TelemetryInfo}. + * Determines whether the given entity is a basic/primitive type + * (string, number, boolean, null, undefined). + * @param value - Any entity + * @returns true is it is primitive type, false otherwise. */ -class UserAgentPolicy extends BaseRequestPolicy { - constructor(_nextPolicy, _options, headerKey, headerValue) { - super(_nextPolicy, _options); - this._nextPolicy = _nextPolicy; - this._options = _options; - this.headerKey = headerKey; - this.headerValue = headerValue; - } - sendRequest(request) { - this.addUserAgentHeader(request); - return this._nextPolicy.sendRequest(request); +function isPrimitiveType(value) { + return (typeof value !== "object" && typeof value !== "function") || value === null; +} +function getEnvironmentValue(name) { + if (process.env[name]) { + return process.env[name]; } - /** - * Adds the user agent header to the outgoing request. - */ - addUserAgentHeader(request) { - if (!request.headers) { - request.headers = new HttpHeaders(); - } - if (!request.headers.get(this.headerKey) && this.headerValue) { - request.headers.set(this.headerKey, this.headerValue); - } + else if (process.env[name.toLowerCase()]) { + return process.env[name.toLowerCase()]; } + return undefined; +} +/** + * @internal + * @returns true when input is an object type that is not null, Array, RegExp, or Date. + */ +function isObject(input) { + return (typeof input === "object" && + input !== null && + !Array.isArray(input) && + !(input instanceof RegExp) && + !(input instanceof Date)); } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// This file contains utility code to serialize and deserialize network operations according to `OperationSpec` objects generated by AutoRest.TypeScript from OpenAPI specifications. /** - * The format that will be used to join an array of values together for a query parameter value. + * Used to map raw response objects to final shapes. + * Helps packing and unpacking Dates and other encoded types that are not intrinsic to JSON. + * Also allows pulling values from headers, as well as inserting default values and constants. */ -exports.QueryCollectionFormat = void 0; -(function (QueryCollectionFormat) { - /** - * CSV: Each pair of segments joined by a single comma. - */ - QueryCollectionFormat["Csv"] = ","; - /** - * SSV: Each pair of segments joined by a single space character. - */ - QueryCollectionFormat["Ssv"] = " "; +class Serializer { + constructor( /** - * TSV: Each pair of segments joined by a single tab character. + * The provided model mapper. */ - QueryCollectionFormat["Tsv"] = "\t"; + modelMappers = {}, /** - * Pipes: Each pair of segments joined by a single pipe character. + * Whether the contents are XML or not. */ - QueryCollectionFormat["Pipes"] = "|"; + isXML) { + this.modelMappers = modelMappers; + this.isXML = isXML; + } /** - * Denotes this is an array of values that should be passed to the server in multiple key/value pairs, e.g. `?queryParam=value1&queryParam=value2` + * Validates constraints, if any. This function will throw if the provided value does not respect those constraints. + * @param mapper - The definition of data models. + * @param value - The value. + * @param objectName - Name of the object. Used in the error messages. + * @deprecated Removing the constraints validation on client side. */ - QueryCollectionFormat["Multi"] = "Multi"; -})(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {})); - -// Copyright (c) Microsoft Corporation. -// Default options for the cycler if none are provided -const DEFAULT_CYCLER_OPTIONS = { - forcedRefreshWindowInMs: 1000, - retryIntervalInMs: 3000, - refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry -}; -/** - * Converts an an unreliable access token getter (which may resolve with null) - * into an AccessTokenGetter by retrying the unreliable getter in a regular - * interval. - * - * @param getAccessToken - a function that produces a promise of an access - * token that may fail by returning null - * @param retryIntervalInMs - the time (in milliseconds) to wait between retry - * attempts - * @param timeoutInMs - the timestamp after which the refresh attempt will fail, - * throwing an exception - * @returns - a promise that, if it resolves, will resolve with an access token - */ -async function beginRefresh(getAccessToken, retryIntervalInMs, timeoutInMs) { - // This wrapper handles exceptions gracefully as long as we haven't exceeded - // the timeout. - async function tryGetAccessToken() { - if (Date.now() < timeoutInMs) { - try { - return await getAccessToken(); + validateConstraints(mapper, value, objectName) { + const failValidation = (constraintName, constraintValue) => { + throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`); + }; + if (mapper.constraints && value != undefined) { + const valueAsNumber = value; + const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints; + if (ExclusiveMaximum != undefined && valueAsNumber >= ExclusiveMaximum) { + failValidation("ExclusiveMaximum", ExclusiveMaximum); } - catch (_a) { - return null; + if (ExclusiveMinimum != undefined && valueAsNumber <= ExclusiveMinimum) { + failValidation("ExclusiveMinimum", ExclusiveMinimum); } - } - else { - const finalToken = await getAccessToken(); - // Timeout is up, so throw if it's still null - if (finalToken === null) { - throw new Error("Failed to refresh access token."); + if (InclusiveMaximum != undefined && valueAsNumber > InclusiveMaximum) { + failValidation("InclusiveMaximum", InclusiveMaximum); + } + if (InclusiveMinimum != undefined && valueAsNumber < InclusiveMinimum) { + failValidation("InclusiveMinimum", InclusiveMinimum); + } + const valueAsArray = value; + if (MaxItems != undefined && valueAsArray.length > MaxItems) { + failValidation("MaxItems", MaxItems); + } + if (MaxLength != undefined && valueAsArray.length > MaxLength) { + failValidation("MaxLength", MaxLength); + } + if (MinItems != undefined && valueAsArray.length < MinItems) { + failValidation("MinItems", MinItems); + } + if (MinLength != undefined && valueAsArray.length < MinLength) { + failValidation("MinLength", MinLength); + } + if (MultipleOf != undefined && valueAsNumber % MultipleOf !== 0) { + failValidation("MultipleOf", MultipleOf); + } + if (Pattern) { + const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern; + if (typeof value !== "string" || value.match(pattern) === null) { + failValidation("Pattern", Pattern); + } + } + if (UniqueItems && + valueAsArray.some((item, i, ar) => ar.indexOf(item) !== i)) { + failValidation("UniqueItems", UniqueItems); } - return finalToken; } } - let token = await tryGetAccessToken(); - while (token === null) { - await delay(retryIntervalInMs); - token = await tryGetAccessToken(); - } - return token; -} -/** - * Creates a token cycler from a credential, scopes, and optional settings. - * - * A token cycler represents a way to reliably retrieve a valid access token - * from a TokenCredential. It will handle initializing the token, refreshing it - * when it nears expiration, and synchronizes refresh attempts to avoid - * concurrency hazards. - * - * @param credential - the underlying TokenCredential that provides the access - * token - * @param scopes - the scopes to request authorization for - * @param tokenCyclerOptions - optionally override default settings for the cycler - * - * @returns - a function that reliably produces a valid access token - */ -function createTokenCycler(credential, scopes, tokenCyclerOptions) { - let refreshWorker = null; - let token = null; - const options = Object.assign(Object.assign({}, DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); - /** - * This little holder defines several predicates that we use to construct - * the rules of refreshing the token. - */ - const cycler = { - /** - * Produces true if a refresh job is currently in progress. - */ - get isRefreshing() { - return refreshWorker !== null; - }, - /** - * Produces true if the cycler SHOULD refresh (we are within the refresh - * window and not already refreshing) - */ - get shouldRefresh() { - var _a; - return (!cycler.isRefreshing && - ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now()); - }, - /** - * Produces true if the cycler MUST refresh (null or nearly-expired - * token). - */ - get mustRefresh() { - return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now()); - }, - }; /** - * Starts a refresh job or returns the existing job if one is already - * running. + * Serialize the given object based on its metadata defined in the mapper. + * + * @param mapper - The mapper which defines the metadata of the serializable object. + * @param object - A valid Javascript object to be serialized. + * @param objectName - Name of the serialized object. + * @param options - additional options to deserialization. + * @returns A valid serialized Javascript object. */ - function refresh(getTokenOptions) { - var _a; - if (!cycler.isRefreshing) { - // We bind `scopes` here to avoid passing it around a lot - const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); - // Take advantage of promise chaining to insert an assignment to `token` - // before the refresh can be considered done. - refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs, - // If we don't have a token, then we should timeout immediately - (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now()) - .then((_token) => { - refreshWorker = null; - token = _token; - return token; - }) - .catch((reason) => { - // We also should reset the refresher if we enter a failed state. All - // existing awaiters will throw, but subsequent requests will start a - // new retry chain. - refreshWorker = null; - token = null; - throw reason; - }); + serialize(mapper, object, objectName, options = {}) { + var _a, _b, _c; + const updatedOptions = { + rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", + includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, + xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, + }; + let payload = {}; + const mapperType = mapper.type.name; + if (!objectName) { + objectName = mapper.serializedName; } - return refreshWorker; - } - return async (tokenOptions) => { - // - // Simple rules: - // - If we MUST refresh, then return the refresh task, blocking - // the pipeline until a token is available. - // - If we SHOULD refresh, then run refresh but don't return it - // (we can still use the cached token). - // - Return the token, since it's fine if we didn't return in - // step 1. - // - if (cycler.mustRefresh) - return refresh(tokenOptions); - if (cycler.shouldRefresh) { - refresh(tokenOptions); + if (mapperType.match(/^Sequence$/i) !== null) { + payload = []; } - return token; - }; -} -// #endregion -/** - * Creates a new factory for a RequestPolicy that applies a bearer token to - * the requests' `Authorization` headers. - * - * @param credential - The TokenCredential implementation that can supply the bearer token. - * @param scopes - The scopes for which the bearer token applies. - */ -function bearerTokenAuthenticationPolicy(credential, scopes) { - // This simple function encapsulates the entire process of reliably retrieving the token - const getToken = createTokenCycler(credential, scopes /* , options */); - class BearerTokenAuthenticationPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options) { - super(nextPolicy, options); + if (mapper.isConstant) { + object = mapper.defaultValue; } - async sendRequest(webResource) { - if (!webResource.url.toLowerCase().startsWith("https://")) { - throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); + // This table of allowed values should help explain + // the mapper.required and mapper.nullable properties. + // X means "neither undefined or null are allowed". + // || required + // || true | false + // nullable || ========================== + // true || null | undefined/null + // false || X | undefined + // undefined || X | undefined/null + const { required, nullable } = mapper; + if (required && nullable && object === undefined) { + throw new Error(`${objectName} cannot be undefined.`); + } + if (required && !nullable && object == undefined) { + throw new Error(`${objectName} cannot be null or undefined.`); + } + if (!required && nullable === false && object === null) { + throw new Error(`${objectName} cannot be null.`); + } + if (object == undefined) { + payload = object; + } + else { + if (mapperType.match(/^any$/i) !== null) { + payload = object; + } + else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) { + payload = serializeBasicTypes(mapperType, objectName, object); + } + else if (mapperType.match(/^Enum$/i) !== null) { + const enumMapper = mapper; + payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object); + } + else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) { + payload = serializeDateTypes(mapperType, object, objectName); + } + else if (mapperType.match(/^ByteArray$/i) !== null) { + payload = serializeByteArrayType(objectName, object); + } + else if (mapperType.match(/^Base64Url$/i) !== null) { + payload = serializeBase64UrlType(objectName, object); + } + else if (mapperType.match(/^Sequence$/i) !== null) { + payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + } + else if (mapperType.match(/^Dictionary$/i) !== null) { + payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + } + else if (mapperType.match(/^Composite$/i) !== null) { + payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); } - const { token } = await getToken({ - abortSignal: webResource.abortSignal, - tracingOptions: { - tracingContext: webResource.tracingContext, - }, - }); - webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${token}`); - return this._nextPolicy.sendRequest(webResource); } - } - return { - create: (nextPolicy, options) => { - return new BearerTokenAuthenticationPolicy(nextPolicy, options); - }, - }; -} - -// Copyright (c) Microsoft Corporation. -/** - * Returns a request policy factory that can be used to create an instance of - * {@link DisableResponseDecompressionPolicy}. - */ -function disableResponseDecompressionPolicy() { - return { - create: (nextPolicy, options) => { - return new DisableResponseDecompressionPolicy(nextPolicy, options); - }, - }; -} -/** - * A policy to disable response decompression according to Accept-Encoding header - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding - */ -class DisableResponseDecompressionPolicy extends BaseRequestPolicy { - /** - * Creates an instance of DisableResponseDecompressionPolicy. - * - * @param nextPolicy - - * @param options - - */ - // The parent constructor is protected. - /* eslint-disable-next-line @typescript-eslint/no-useless-constructor */ - constructor(nextPolicy, options) { - super(nextPolicy, options); + return payload; } /** - * Sends out request. + * Deserialize the given object based on its metadata defined in the mapper. * - * @param request - - * @returns + * @param mapper - The mapper which defines the metadata of the serializable object. + * @param responseBody - A valid Javascript entity to be deserialized. + * @param objectName - Name of the deserialized object. + * @param options - Controls behavior of XML parser and builder. + * @returns A valid deserialized Javascript object. */ - async sendRequest(request) { - request.decompressResponse = false; - return this._nextPolicy.sendRequest(request); - } -} - -// Copyright (c) Microsoft Corporation. -/** - * Creates a policy that assigns a unique request id to outgoing requests. - * @param requestIdHeaderName - The name of the header to use when assigning the unique id to the request. - */ -function generateClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { - return { - create: (nextPolicy, options) => { - return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName); - }, - }; -} -class GenerateClientRequestIdPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, _requestIdHeaderName) { - super(nextPolicy, options); - this._requestIdHeaderName = _requestIdHeaderName; - } - sendRequest(request) { - if (!request.headers.contains(this._requestIdHeaderName)) { - request.headers.set(this._requestIdHeaderName, request.requestId); + deserialize(mapper, responseBody, objectName, options = {}) { + var _a, _b, _c; + const updatedOptions = { + rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", + includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, + xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, + }; + if (responseBody == undefined) { + if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) { + // Edge case for empty XML non-wrapped lists. xml2js can't distinguish + // between the list being empty versus being missing, + // so let's do the more user-friendly thing and return an empty list. + responseBody = []; + } + // specifically check for undefined as default value can be a falsey value `0, "", false, null` + if (mapper.defaultValue !== undefined) { + responseBody = mapper.defaultValue; + } + return responseBody; + } + let payload; + const mapperType = mapper.type.name; + if (!objectName) { + objectName = mapper.serializedName; + } + if (mapperType.match(/^Composite$/i) !== null) { + payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions); + } + else { + if (this.isXML) { + const xmlCharKey = updatedOptions.xmlCharKey; + const castResponseBody = responseBody; + /** + * If the mapper specifies this as a non-composite type value but the responseBody contains + * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties, + * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property. + */ + if (castResponseBody[XML_ATTRKEY] != undefined && + castResponseBody[xmlCharKey] != undefined) { + responseBody = castResponseBody[xmlCharKey]; + } + } + if (mapperType.match(/^Number$/i) !== null) { + payload = parseFloat(responseBody); + if (isNaN(payload)) { + payload = responseBody; + } + } + else if (mapperType.match(/^Boolean$/i) !== null) { + if (responseBody === "true") { + payload = true; + } + else if (responseBody === "false") { + payload = false; + } + else { + payload = responseBody; + } + } + else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) { + payload = responseBody; + } + else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) { + payload = new Date(responseBody); + } + else if (mapperType.match(/^UnixTime$/i) !== null) { + payload = unixTimeToDate(responseBody); + } + else if (mapperType.match(/^ByteArray$/i) !== null) { + payload = decodeString(responseBody); + } + else if (mapperType.match(/^Base64Url$/i) !== null) { + payload = base64UrlToByteArray(responseBody); + } + else if (mapperType.match(/^Sequence$/i) !== null) { + payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions); + } + else if (mapperType.match(/^Dictionary$/i) !== null) { + payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions); + } } - return this._nextPolicy.sendRequest(request); + if (mapper.isConstant) { + payload = mapper.defaultValue; + } + return payload; } } - -// Copyright (c) Microsoft Corporation. -let cachedHttpClient; -function getCachedDefaultHttpClient() { - if (!cachedHttpClient) { - cachedHttpClient = new NodeFetchHttpClient(); +function trimEnd(str, ch) { + let len = str.length; + while (len - 1 >= 0 && str[len - 1] === ch) { + --len; } - return cachedHttpClient; -} - -// Copyright (c) Microsoft Corporation. -function ndJsonPolicy() { - return { - create: (nextPolicy, options) => { - return new NdJsonPolicy(nextPolicy, options); - }, - }; + return str.substr(0, len); } -/** - * NdJsonPolicy that formats a JSON array as newline-delimited JSON - */ -class NdJsonPolicy extends BaseRequestPolicy { - /** - * Creates an instance of KeepAlivePolicy. - */ - constructor(nextPolicy, options) { - super(nextPolicy, options); +function bufferToBase64Url(buffer) { + if (!buffer) { + return undefined; } - /** - * Sends a request. - */ - async sendRequest(request) { - // There currently isn't a good way to bypass the serializer - if (typeof request.body === "string" && request.body.startsWith("[")) { - const body = JSON.parse(request.body); - if (Array.isArray(body)) { - request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); - } - } - return this._nextPolicy.sendRequest(request); + if (!(buffer instanceof Uint8Array)) { + throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`); } + // Uint8Array to Base64. + const str = encodeByteArray(buffer); + // Base64 to Base64Url. + return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_"); } - -// Copyright (c) Microsoft Corporation. -/** - * Stores the patterns specified in NO_PROXY environment variable. - * @internal - */ -const globalNoProxyList = []; -let noProxyListLoaded = false; -/** A cache of whether a host should bypass the proxy. */ -const globalBypassedMap = new Map(); -function loadEnvironmentProxyValue() { - if (!process) { +function base64UrlToByteArray(str) { + if (!str) { return undefined; } - const httpsProxy = getEnvironmentValue(Constants.HTTPS_PROXY); - const allProxy = getEnvironmentValue(Constants.ALL_PROXY); - const httpProxy = getEnvironmentValue(Constants.HTTP_PROXY); - return httpsProxy || allProxy || httpProxy; -} -/** - * Check whether the host of a given `uri` matches any pattern in the no proxy list. - * If there's a match, any request sent to the same host shouldn't have the proxy settings set. - * This implementation is a port of /~https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210 - */ -function isBypassed(uri, noProxyList, bypassedMap) { - if (noProxyList.length === 0) { - return false; - } - const host = URLBuilder.parse(uri).getHost(); - if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { - return bypassedMap.get(host); + if (str && typeof str.valueOf() !== "string") { + throw new Error("Please provide an input of type string for converting to Uint8Array"); } - let isBypassedFlag = false; - for (const pattern of noProxyList) { - if (pattern[0] === ".") { - // This should match either domain it self or any subdomain or host - // .foo.com will match foo.com it self or *.foo.com - if (host.endsWith(pattern)) { - isBypassedFlag = true; + // Base64Url to Base64. + str = str.replace(/-/g, "+").replace(/_/g, "/"); + // Base64 to Uint8Array. + return decodeString(str); +} +function splitSerializeName(prop) { + const classes = []; + let partialclass = ""; + if (prop) { + const subwords = prop.split("."); + for (const item of subwords) { + if (item.charAt(item.length - 1) === "\\") { + partialclass += item.substr(0, item.length - 1) + "."; } else { - if (host.length === pattern.length - 1 && host === pattern.slice(1)) { - isBypassedFlag = true; - } - } - } - else { - if (host === pattern) { - isBypassedFlag = true; + partialclass += item; + classes.push(partialclass); + partialclass = ""; } } } - bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); - return isBypassedFlag; -} -/** - * @internal - */ -function loadNoProxy() { - const noProxy = getEnvironmentValue(Constants.NO_PROXY); - noProxyListLoaded = true; - if (noProxy) { - return noProxy - .split(",") - .map((item) => item.trim()) - .filter((item) => item.length); - } - return []; -} -/** - * Converts a given URL of a proxy server into `ProxySettings` or attempts to retrieve `ProxySettings` from the current environment if one is not passed. - * @param proxyUrl - URL of the proxy - * @returns The default proxy settings, or undefined. - */ -function getDefaultProxySettings(proxyUrl) { - if (!proxyUrl) { - proxyUrl = loadEnvironmentProxyValue(); - if (!proxyUrl) { - return undefined; - } - } - const { username, password, urlWithoutAuth } = extractAuthFromUrl(proxyUrl); - const parsedUrl = URLBuilder.parse(urlWithoutAuth); - const schema = parsedUrl.getScheme() ? parsedUrl.getScheme() + "://" : ""; - return { - host: schema + parsedUrl.getHost(), - port: Number.parseInt(parsedUrl.getPort() || "80"), - username, - password, - }; + return classes; } -/** - * A policy that allows one to apply proxy settings to all requests. - * If not passed static settings, they will be retrieved from the HTTPS_PROXY - * or HTTP_PROXY environment variables. - * @param proxySettings - ProxySettings to use on each request. - * @param options - additional settings, for example, custom NO_PROXY patterns - */ -function proxyPolicy(proxySettings, options) { - if (!proxySettings) { - proxySettings = getDefaultProxySettings(); +function dateToUnixTime(d) { + if (!d) { + return undefined; } - if (!noProxyListLoaded) { - globalNoProxyList.push(...loadNoProxy()); + if (typeof d.valueOf() === "string") { + d = new Date(d); } - return { - create: (nextPolicy, requestPolicyOptions) => { - return new ProxyPolicy(nextPolicy, requestPolicyOptions, proxySettings, options === null || options === void 0 ? void 0 : options.customNoProxyList); - }, - }; + return Math.floor(d.getTime() / 1000); } -function extractAuthFromUrl(url) { - const atIndex = url.indexOf("@"); - if (atIndex === -1) { - return { urlWithoutAuth: url }; +function unixTimeToDate(n) { + if (!n) { + return undefined; } - const schemeIndex = url.indexOf("://"); - const authStart = schemeIndex !== -1 ? schemeIndex + 3 : 0; - const auth = url.substring(authStart, atIndex); - const colonIndex = auth.indexOf(":"); - const hasPassword = colonIndex !== -1; - const username = hasPassword ? auth.substring(0, colonIndex) : auth; - const password = hasPassword ? auth.substring(colonIndex + 1) : undefined; - const urlWithoutAuth = url.substring(0, authStart) + url.substring(atIndex + 1); - return { - username, - password, - urlWithoutAuth, - }; + return new Date(n * 1000); } -class ProxyPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, proxySettings, customNoProxyList) { - super(nextPolicy, options); - this.proxySettings = proxySettings; - this.customNoProxyList = customNoProxyList; - } - sendRequest(request) { - var _a; - if (!request.proxySettings && - !isBypassed(request.url, (_a = this.customNoProxyList) !== null && _a !== void 0 ? _a : globalNoProxyList, this.customNoProxyList ? undefined : globalBypassedMap)) { - request.proxySettings = this.proxySettings; +function serializeBasicTypes(typeName, objectName, value) { + if (value !== null && value !== undefined) { + if (typeName.match(/^Number$/i) !== null) { + if (typeof value !== "number") { + throw new Error(`${objectName} with value ${value} must be of type number.`); + } } - return this._nextPolicy.sendRequest(request); - } -} - -// Copyright (c) Microsoft Corporation. -function rpRegistrationPolicy(retryTimeout = 30) { - return { - create: (nextPolicy, options) => { - return new RPRegistrationPolicy(nextPolicy, options, retryTimeout); - }, - }; -} -class RPRegistrationPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, _retryTimeout = 30) { - super(nextPolicy, options); - this._retryTimeout = _retryTimeout; - } - sendRequest(request) { - return this._nextPolicy - .sendRequest(request.clone()) - .then((response) => registerIfNeeded(this, request, response)); - } -} -function registerIfNeeded(policy, request, response) { - if (response.status === 409) { - const rpName = checkRPNotRegisteredError(response.bodyAsText); - if (rpName) { - const urlPrefix = extractSubscriptionUrl(request.url); - return (registerRP(policy, urlPrefix, rpName, request) - // Autoregistration of ${provider} failed for some reason. We will not return this error - // instead will return the initial response with 409 status code back to the user. - // do nothing here as we are returning the original response at the end of this method. - .catch(() => false) - .then((registrationStatus) => { - if (registrationStatus) { - // Retry the original request. We have to change the x-ms-client-request-id - // otherwise Azure endpoint will return the initial 409 (cached) response. - request.headers.set("x-ms-client-request-id", generateUuid()); - return policy._nextPolicy.sendRequest(request.clone()); - } - return response; - })); + else if (typeName.match(/^String$/i) !== null) { + if (typeof value.valueOf() !== "string") { + throw new Error(`${objectName} with value "${value}" must be of type string.`); + } } - } - return Promise.resolve(response); -} -/** - * Reuses the headers of the original request and url (if specified). - * @param originalRequest - The original request - * @param reuseUrlToo - Should the url from the original request be reused as well. Default false. - * @returns A new request object with desired headers. - */ -function getRequestEssentials(originalRequest, reuseUrlToo = false) { - const reqOptions = originalRequest.clone(); - if (reuseUrlToo) { - reqOptions.url = originalRequest.url; - } - // We have to change the x-ms-client-request-id otherwise Azure endpoint - // will return the initial 409 (cached) response. - reqOptions.headers.set("x-ms-client-request-id", generateUuid()); - // Set content-type to application/json - reqOptions.headers.set("Content-Type", "application/json; charset=utf-8"); - return reqOptions; -} -/** - * Validates the error code and message associated with 409 response status code. If it matches to that of - * RP not registered then it returns the name of the RP else returns undefined. - * @param body - The response body received after making the original request. - * @returns The name of the RP if condition is satisfied else undefined. - */ -function checkRPNotRegisteredError(body) { - let result, responseBody; - if (body) { - try { - responseBody = JSON.parse(body); + else if (typeName.match(/^Uuid$/i) !== null) { + if (!(typeof value.valueOf() === "string" && isValidUuid(value))) { + throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`); + } } - catch (err) { - // do nothing; + else if (typeName.match(/^Boolean$/i) !== null) { + if (typeof value !== "boolean") { + throw new Error(`${objectName} with value ${value} must be of type boolean.`); + } } - if (responseBody && - responseBody.error && - responseBody.error.message && - responseBody.error.code && - responseBody.error.code === "MissingSubscriptionRegistration") { - const matchRes = responseBody.error.message.match(/.*'(.*)'/i); - if (matchRes) { - result = matchRes.pop(); + else if (typeName.match(/^Stream$/i) !== null) { + const objectType = typeof value; + if (objectType !== "string" && + objectType !== "function" && + !(value instanceof ArrayBuffer) && + !ArrayBuffer.isView(value) && + !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob)) { + throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream.`); } } } - return result; + return value; } -/** - * Extracts the first part of the URL, just after subscription: - * https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ - * @param url - The original request url - * @returns The url prefix as explained above. - */ -function extractSubscriptionUrl(url) { - let result; - const matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//gi); - if (matchRes && matchRes[0]) { - result = matchRes[0]; - } - else { - throw new Error(`Unable to extract subscriptionId from the given url - ${url}.`); +function serializeEnumType(objectName, allowedValues, value) { + if (!allowedValues) { + throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`); } - return result; -} -/** - * Registers the given provider. - * @param policy - The RPRegistrationPolicy this function is being called against. - * @param urlPrefix - https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ - * @param provider - The provider name to be registered. - * @param originalRequest - The original request sent by the user that returned a 409 response - * with a message that the provider is not registered. - */ -async function registerRP(policy, urlPrefix, provider, originalRequest) { - const postUrl = `${urlPrefix}providers/${provider}/register?api-version=2016-02-01`; - const getUrl = `${urlPrefix}providers/${provider}?api-version=2016-02-01`; - const reqOptions = getRequestEssentials(originalRequest); - reqOptions.method = "POST"; - reqOptions.url = postUrl; - const response = await policy._nextPolicy.sendRequest(reqOptions); - if (response.status !== 200) { - throw new Error(`Autoregistration of ${provider} failed. Please try registering manually.`); + const isPresent = allowedValues.some((item) => { + if (typeof item.valueOf() === "string") { + return item.toLowerCase() === value.toLowerCase(); + } + return item === value; + }); + if (!isPresent) { + throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`); } - return getRegistrationStatus(policy, getUrl, originalRequest); + return value; } -/** - * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds. - * Polling will happen till the registrationState property of the response body is "Registered". - * @param policy - The RPRegistrationPolicy this function is being called against. - * @param url - The request url for polling - * @param originalRequest - The original request sent by the user that returned a 409 response - * with a message that the provider is not registered. - * @returns True if RP Registration is successful. - */ -async function getRegistrationStatus(policy, url, originalRequest) { - const reqOptions = getRequestEssentials(originalRequest); - reqOptions.url = url; - reqOptions.method = "GET"; - const res = await policy._nextPolicy.sendRequest(reqOptions); - const obj = res.parsedBody; - if (res.parsedBody && obj.registrationState && obj.registrationState === "Registered") { - return true; - } - else { - await delay(policy._retryTimeout * 1000); - return getRegistrationStatus(policy, url, originalRequest); +function serializeByteArrayType(objectName, value) { + let returnValue = ""; + if (value != undefined) { + if (!(value instanceof Uint8Array)) { + throw new Error(`${objectName} must be of type Uint8Array.`); + } + returnValue = encodeByteArray(value); } + return returnValue; } - -// Copyright (c) Microsoft Corporation. -/** - * Creates a policy that signs outgoing requests by calling to the provided `authenticationProvider`'s `signRequest` method. - * @param authenticationProvider - The authentication provider. - * @returns An instance of the {@link SigningPolicy}. - */ -function signingPolicy(authenticationProvider) { - return { - create: (nextPolicy, options) => { - return new SigningPolicy(nextPolicy, options, authenticationProvider); - }, - }; -} -/** - * A policy that signs outgoing requests by calling to the provided `authenticationProvider`'s `signRequest` method. - */ -class SigningPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, authenticationProvider) { - super(nextPolicy, options); - this.authenticationProvider = authenticationProvider; - } - signRequest(request) { - return this.authenticationProvider.signRequest(request); - } - sendRequest(request) { - return this.signRequest(request).then((nextRequest) => this._nextPolicy.sendRequest(nextRequest)); +function serializeBase64UrlType(objectName, value) { + let returnValue = ""; + if (value != undefined) { + if (!(value instanceof Uint8Array)) { + throw new Error(`${objectName} must be of type Uint8Array.`); + } + returnValue = bufferToBase64Url(value) || ""; } + return returnValue; } - -// Copyright (c) Microsoft Corporation. -/** - * A policy that retries when there's a system error, identified by the codes "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNREFUSED", "ECONNRESET" or "ENOENT". - * @param retryCount - Maximum number of retries. - * @param retryInterval - The client retry interval, in milliseconds. - * @param minRetryInterval - The minimum retry interval, in milliseconds. - * @param maxRetryInterval - The maximum retry interval, in milliseconds. - * @returns An instance of the {@link SystemErrorRetryPolicy} - */ -function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) { - return { - create: (nextPolicy, options) => { - return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval); - }, - }; -} -/** - * A policy that retries when there's a system error, identified by the codes "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNREFUSED", "ECONNRESET" or "ENOENT". - * @param retryCount - The client retry count. - * @param retryInterval - The client retry interval, in milliseconds. - * @param minRetryInterval - The minimum retry interval, in milliseconds. - * @param maxRetryInterval - The maximum retry interval, in milliseconds. - */ -class SystemErrorRetryPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) { - super(nextPolicy, options); - this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; - this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; - this.minRetryInterval = isNumber(minRetryInterval) - ? minRetryInterval - : DEFAULT_CLIENT_MIN_RETRY_INTERVAL; - this.maxRetryInterval = isNumber(maxRetryInterval) - ? maxRetryInterval - : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; - } - sendRequest(request) { - return this._nextPolicy - .sendRequest(request.clone()) - .catch((error) => retry(this, request, error.response, error)); +function serializeDateTypes(typeName, value, objectName) { + if (value != undefined) { + if (typeName.match(/^Date$/i) !== null) { + if (!(value instanceof Date || + (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { + throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); + } + value = + value instanceof Date + ? value.toISOString().substring(0, 10) + : new Date(value).toISOString().substring(0, 10); + } + else if (typeName.match(/^DateTime$/i) !== null) { + if (!(value instanceof Date || + (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { + throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); + } + value = value instanceof Date ? value.toISOString() : new Date(value).toISOString(); + } + else if (typeName.match(/^DateTimeRfc1123$/i) !== null) { + if (!(value instanceof Date || + (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { + throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`); + } + value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString(); + } + else if (typeName.match(/^UnixTime$/i) !== null) { + if (!(value instanceof Date || + (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { + throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` + + `for it to be serialized in UnixTime/Epoch format.`); + } + value = dateToUnixTime(value); + } + else if (typeName.match(/^TimeSpan$/i) !== null) { + if (!isDuration(value)) { + throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`); + } + } } + return value; } -async function retry(policy, request, operationResponse, err, retryData) { - retryData = updateRetryData(policy, retryData, err); - function shouldPolicyRetry(_response, error) { - if (error && - error.code && - (error.code === "ETIMEDOUT" || - error.code === "ESOCKETTIMEDOUT" || - error.code === "ECONNREFUSED" || - error.code === "ECONNRESET" || - error.code === "ENOENT")) { - return true; - } - return false; +function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) { + if (!Array.isArray(object)) { + throw new Error(`${objectName} must be of type Array.`); } - if (shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, operationResponse, err)) { - // If previous operation ended with an error and the policy allows a retry, do that - try { - await delay(retryData.retryInterval); - return policy._nextPolicy.sendRequest(request.clone()); + const elementType = mapper.type.element; + if (!elementType || typeof elementType !== "object") { + throw new Error(`element" metadata for an Array must be defined in the ` + + `mapper and it must of type "object" in ${objectName}.`); + } + const tempArray = []; + for (let i = 0; i < object.length; i++) { + const serializedValue = serializer.serialize(elementType, object[i], objectName, options); + if (isXml && elementType.xmlNamespace) { + const xmlnsKey = elementType.xmlNamespacePrefix + ? `xmlns:${elementType.xmlNamespacePrefix}` + : "xmlns"; + if (elementType.type.name === "Composite") { + tempArray[i] = Object.assign({}, serializedValue); + tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; + } + else { + tempArray[i] = {}; + tempArray[i][options.xmlCharKey] = serializedValue; + tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; + } } - catch (nestedErr) { - return retry(policy, request, operationResponse, nestedErr, retryData); + else { + tempArray[i] = serializedValue; } } - else { - if (err) { - // If the operation failed in the end, return all errors instead of just the last one - return Promise.reject(retryData.error); - } - return operationResponse; + return tempArray; +} +function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) { + if (typeof object !== "object") { + throw new Error(`${objectName} must be of type object.`); + } + const valueType = mapper.type.value; + if (!valueType || typeof valueType !== "object") { + throw new Error(`"value" metadata for a Dictionary must be defined in the ` + + `mapper and it must of type "object" in ${objectName}.`); + } + const tempDictionary = {}; + for (const key of Object.keys(object)) { + const serializedValue = serializer.serialize(valueType, object[key], objectName, options); + // If the element needs an XML namespace we need to add it within the $ property + tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options); + } + // Add the namespace to the root element if needed + if (isXml && mapper.xmlNamespace) { + const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; + const result = tempDictionary; + result[XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace }; + return result; } + return tempDictionary; } - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. /** - * Maximum number of retries for the throttling retry policy + * Resolves the additionalProperties property from a referenced mapper. + * @param serializer - The serializer containing the entire set of mappers. + * @param mapper - The composite mapper to resolve. + * @param objectName - Name of the object being serialized. */ -const DEFAULT_CLIENT_MAX_RETRY_COUNT = 3; - -// Copyright (c) Microsoft Corporation. -const StatusCodes = Constants.HttpConstants.StatusCodes; +function resolveAdditionalProperties(serializer, mapper, objectName) { + const additionalProperties = mapper.type.additionalProperties; + if (!additionalProperties && mapper.type.className) { + const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); + return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties; + } + return additionalProperties; +} /** - * Creates a policy that re-sends the request if the response indicates the request failed because of throttling reasons. - * For example, if the response contains a `Retry-After` header, it will retry sending the request based on the value of that header. - * - * To learn more, please refer to - * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits, - * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and - * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors - * @returns + * Finds the mapper referenced by `className`. + * @param serializer - The serializer containing the entire set of mappers + * @param mapper - The composite mapper to resolve + * @param objectName - Name of the object being serialized */ -function throttlingRetryPolicy() { - return { - create: (nextPolicy, options) => { - return new ThrottlingRetryPolicy(nextPolicy, options); - }, - }; +function resolveReferencedMapper(serializer, mapper, objectName) { + const className = mapper.type.className; + if (!className) { + throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`); + } + return serializer.modelMappers[className]; } -const StandardAbortMessage = "The operation was aborted."; /** - * Creates a policy that re-sends the request if the response indicates the request failed because of throttling reasons. - * For example, if the response contains a `Retry-After` header, it will retry sending the request based on the value of that header. - * - * To learn more, please refer to - * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits, - * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and - * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors + * Resolves a composite mapper's modelProperties. + * @param serializer - The serializer containing the entire set of mappers + * @param mapper - The composite mapper to resolve */ -class ThrottlingRetryPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, _handleResponse) { - super(nextPolicy, options); - this.numberOfRetries = 0; - this._handleResponse = _handleResponse || this._defaultResponseHandler; - } - async sendRequest(httpRequest) { - const response = await this._nextPolicy.sendRequest(httpRequest.clone()); - if (response.status !== StatusCodes.TooManyRequests && - response.status !== StatusCodes.ServiceUnavailable) { - return response; +function resolveModelProperties(serializer, mapper, objectName) { + let modelProps = mapper.type.modelProperties; + if (!modelProps) { + const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); + if (!modelMapper) { + throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`); } - else { - return this._handleResponse(httpRequest, response); + modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties; + if (!modelProps) { + throw new Error(`modelProperties cannot be null or undefined in the ` + + `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`); } } - async _defaultResponseHandler(httpRequest, httpResponse) { - var _a; - const retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER); - if (retryAfterHeader) { - const delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader); - if (delayInMs) { - this.numberOfRetries += 1; - await delay(delayInMs, undefined, { - abortSignal: httpRequest.abortSignal, - abortErrorMsg: StandardAbortMessage, - }); - if ((_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { - throw new abortController.AbortError(StandardAbortMessage); - } - if (this.numberOfRetries < DEFAULT_CLIENT_MAX_RETRY_COUNT) { - return this.sendRequest(httpRequest); + return modelProps; +} +function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) { + if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { + mapper = getPolymorphicMapper(serializer, mapper, object, "clientName"); + } + if (object != undefined) { + const payload = {}; + const modelProps = resolveModelProperties(serializer, mapper, objectName); + for (const key of Object.keys(modelProps)) { + const propertyMapper = modelProps[key]; + if (propertyMapper.readOnly) { + continue; + } + let propName; + let parentObject = payload; + if (serializer.isXML) { + if (propertyMapper.xmlIsWrapped) { + propName = propertyMapper.xmlName; } else { - return this._nextPolicy.sendRequest(httpRequest); + propName = propertyMapper.xmlElementName || propertyMapper.xmlName; + } + } + else { + const paths = splitSerializeName(propertyMapper.serializedName); + propName = paths.pop(); + for (const pathName of paths) { + const childObject = parentObject[pathName]; + if (childObject == undefined && + (object[key] != undefined || propertyMapper.defaultValue !== undefined)) { + parentObject[pathName] = {}; + } + parentObject = parentObject[pathName]; + } + } + if (parentObject != undefined) { + if (isXml && mapper.xmlNamespace) { + const xmlnsKey = mapper.xmlNamespacePrefix + ? `xmlns:${mapper.xmlNamespacePrefix}` + : "xmlns"; + parentObject[XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace }); + } + const propertyObjectName = propertyMapper.serializedName !== "" + ? objectName + "." + propertyMapper.serializedName + : objectName; + let toSerialize = object[key]; + const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); + if (polymorphicDiscriminator && + polymorphicDiscriminator.clientName === key && + toSerialize == undefined) { + toSerialize = mapper.serializedName; + } + const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options); + if (serializedValue !== undefined && propName != undefined) { + const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options); + if (isXml && propertyMapper.xmlIsAttribute) { + // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js. + // This keeps things simple while preventing name collision + // with names in user documents. + parentObject[XML_ATTRKEY] = parentObject[XML_ATTRKEY] || {}; + parentObject[XML_ATTRKEY][propName] = serializedValue; + } + else if (isXml && propertyMapper.xmlIsWrapped) { + parentObject[propName] = { [propertyMapper.xmlElementName]: value }; + } + else { + parentObject[propName] = value; + } } } } - return httpResponse; - } - static parseRetryAfterHeader(headerValue) { - const retryAfterInSeconds = Number(headerValue); - if (Number.isNaN(retryAfterInSeconds)) { - return ThrottlingRetryPolicy.parseDateRetryAfterHeader(headerValue); - } - else { - return retryAfterInSeconds * 1000; + const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName); + if (additionalPropertiesMapper) { + const propNames = Object.keys(modelProps); + for (const clientPropName in object) { + const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName); + if (isAdditionalProperty) { + payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options); + } + } } + return payload; } - static parseDateRetryAfterHeader(headerValue) { - try { - const now = Date.now(); - const date = Date.parse(headerValue); - const diff = date - now; - return Number.isNaN(diff) ? undefined : diff; + return object; +} +function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { + if (!isXml || !propertyMapper.xmlNamespace) { + return serializedValue; + } + const xmlnsKey = propertyMapper.xmlNamespacePrefix + ? `xmlns:${propertyMapper.xmlNamespacePrefix}` + : "xmlns"; + const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace }; + if (["Composite"].includes(propertyMapper.type.name)) { + if (serializedValue[XML_ATTRKEY]) { + return serializedValue; } - catch (error) { - return undefined; + else { + const result = Object.assign({}, serializedValue); + result[XML_ATTRKEY] = xmlNamespace; + return result; } } + const result = {}; + result[options.xmlCharKey] = serializedValue; + result[XML_ATTRKEY] = xmlNamespace; + return result; } - -// Copyright (c) Microsoft Corporation. -const createSpan = coreTracing.createSpanFunction({ - packagePrefix: "", - namespace: "", -}); -/** - * Creates a policy that wraps outgoing requests with a tracing span. - * @param tracingOptions - Tracing options. - * @returns An instance of the {@link TracingPolicy} class. - */ -function tracingPolicy(tracingOptions = {}) { - return { - create(nextPolicy, options) { - return new TracingPolicy(nextPolicy, options, tracingOptions); - }, - }; +function isSpecialXmlProperty(propertyName, options) { + return [XML_ATTRKEY, options.xmlCharKey].includes(propertyName); } -/** - * A policy that wraps outgoing requests with a tracing span. - */ -class TracingPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, tracingOptions) { - super(nextPolicy, options); - this.userAgent = tracingOptions.userAgent; +function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) { + var _a; + if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { + mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); } - async sendRequest(request) { - if (!request.tracingContext) { - return this._nextPolicy.sendRequest(request); - } - const span = this.tryCreateSpan(request); - if (!span) { - return this._nextPolicy.sendRequest(request); + const modelProps = resolveModelProperties(serializer, mapper, objectName); + let instance = {}; + const handledPropertyNames = []; + for (const key of Object.keys(modelProps)) { + const propertyMapper = modelProps[key]; + const paths = splitSerializeName(modelProps[key].serializedName); + handledPropertyNames.push(paths[0]); + const { serializedName, xmlName, xmlElementName } = propertyMapper; + let propertyObjectName = objectName; + if (serializedName !== "" && serializedName !== undefined) { + propertyObjectName = objectName + "." + serializedName; } - try { - const response = await this._nextPolicy.sendRequest(request); - this.tryProcessResponse(span, response); - return response; + const headerCollectionPrefix = propertyMapper.headerCollectionPrefix; + if (headerCollectionPrefix) { + const dictionary = {}; + for (const headerKey of Object.keys(responseBody)) { + if (headerKey.startsWith(headerCollectionPrefix)) { + dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options); + } + handledPropertyNames.push(headerKey); + } + instance[key] = dictionary; } - catch (err) { - this.tryProcessError(span, err); - throw err; + else if (serializer.isXML) { + if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) { + instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options); + } + else { + const propertyName = xmlElementName || xmlName || serializedName; + if (propertyMapper.xmlIsWrapped) { + /* a list of wrapped by + For the xml example below + + ... + ... + + the responseBody has + { + Cors: { + CorsRule: [{...}, {...}] + } + } + xmlName is "Cors" and xmlElementName is"CorsRule". + */ + const wrapped = responseBody[xmlName]; + const elementList = (_a = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _a !== void 0 ? _a : []; + instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options); + } + else { + const property = responseBody[propertyName]; + instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options); + } + } } - } - tryCreateSpan(request) { - var _a; - try { - // Passing spanOptions as part of tracingOptions to maintain compatibility @azure/core-tracing@preview.13 and earlier. - // We can pass this as a separate parameter once we upgrade to the latest core-tracing. - const { span } = createSpan(`HTTP ${request.method}`, { - tracingOptions: { - spanOptions: Object.assign(Object.assign({}, request.spanOptions), { kind: coreTracing.SpanKind.CLIENT }), - tracingContext: request.tracingContext, - }, - }); - // If the span is not recording, don't do any more work. - if (!span.isRecording()) { - span.end(); - return undefined; + else { + // deserialize the property if it is present in the provided responseBody instance + let propertyInstance; + let res = responseBody; + // traversing the object step by step. + for (const item of paths) { + if (!res) + break; + res = res[item]; } - const namespaceFromContext = (_a = request.tracingContext) === null || _a === void 0 ? void 0 : _a.getValue(Symbol.for("az.namespace")); - if (typeof namespaceFromContext === "string") { - span.setAttribute("az.namespace", namespaceFromContext); + propertyInstance = res; + const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator; + // checking that the model property name (key)(ex: "fishtype") and the + // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype") + // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type") + // is a better approach. The generator is not consistent with escaping '\.' in the + // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator + // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However, + // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and + // the transformation of model property name (ex: "fishtype") is done consistently. + // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator. + if (polymorphicDiscriminator && + key === polymorphicDiscriminator.clientName && + propertyInstance == undefined) { + propertyInstance = mapper.serializedName; } - span.setAttributes({ - "http.method": request.method, - "http.url": request.url, - requestId: request.requestId, - }); - if (this.userAgent) { - span.setAttribute("http.user_agent", this.userAgent); + let serializedValue; + // paging + if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") { + propertyInstance = responseBody[key]; + const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); + // Copy over any properties that have already been added into the instance, where they do + // not exist on the newly de-serialized array + for (const [k, v] of Object.entries(instance)) { + if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) { + arrayInstance[k] = v; + } + } + instance = arrayInstance; } - // set headers - const spanContext = span.spanContext(); - const traceParentHeader = coreTracing.getTraceParentHeader(spanContext); - if (traceParentHeader && coreTracing.isSpanContextValid(spanContext)) { - request.headers.set("traceparent", traceParentHeader); - const traceState = spanContext.traceState && spanContext.traceState.serialize(); - // if tracestate is set, traceparent MUST be set, so only set tracestate after traceparent - if (traceState) { - request.headers.set("tracestate", traceState); + else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) { + serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); + instance[key] = serializedValue; + } + } + } + const additionalPropertiesMapper = mapper.type.additionalProperties; + if (additionalPropertiesMapper) { + const isAdditionalProperty = (responsePropName) => { + for (const clientPropName in modelProps) { + const paths = splitSerializeName(modelProps[clientPropName].serializedName); + if (paths[0] === responsePropName) { + return false; } } - return span; + return true; + }; + for (const responsePropName in responseBody) { + if (isAdditionalProperty(responsePropName)) { + instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options); + } } - catch (error) { - logger.warning(`Skipping creating a tracing span due to an error: ${error.message}`); - return undefined; + } + else if (responseBody) { + for (const key of Object.keys(responseBody)) { + if (instance[key] === undefined && + !handledPropertyNames.includes(key) && + !isSpecialXmlProperty(key, options)) { + instance[key] = responseBody[key]; + } + } + } + return instance; +} +function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) { + const value = mapper.type.value; + if (!value || typeof value !== "object") { + throw new Error(`"value" metadata for a Dictionary must be defined in the ` + + `mapper and it must of type "object" in ${objectName}`); + } + if (responseBody) { + const tempDictionary = {}; + for (const key of Object.keys(responseBody)) { + tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options); } + return tempDictionary; } - tryProcessError(span, err) { - try { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: err.message, - }); - if (err.statusCode) { - span.setAttribute("http.status_code", err.statusCode); - } - span.end(); + return responseBody; +} +function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) { + const element = mapper.type.element; + if (!element || typeof element !== "object") { + throw new Error(`element" metadata for an Array must be defined in the ` + + `mapper and it must of type "object" in ${objectName}`); + } + if (responseBody) { + if (!Array.isArray(responseBody)) { + // xml2js will interpret a single element array as just the element, so force it to be an array + responseBody = [responseBody]; } - catch (error) { - logger.warning(`Skipping tracing span processing due to an error: ${error.message}`); + const tempArray = []; + for (let i = 0; i < responseBody.length; i++) { + tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options); } + return tempArray; } - tryProcessResponse(span, response) { - try { - span.setAttribute("http.status_code", response.status); - const serviceRequestId = response.headers.get("x-ms-request-id"); - if (serviceRequestId) { - span.setAttribute("serviceRequestId", serviceRequestId); + return responseBody; +} +function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) { + const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); + if (polymorphicDiscriminator) { + const discriminatorName = polymorphicDiscriminator[polymorphicPropertyName]; + if (discriminatorName != undefined) { + const discriminatorValue = object[discriminatorName]; + if (discriminatorValue != undefined) { + const typeName = mapper.type.uberParent || mapper.type.className; + const indexDiscriminator = discriminatorValue === typeName + ? discriminatorValue + : typeName + "." + discriminatorValue; + const polymorphicMapper = serializer.modelMappers.discriminators[indexDiscriminator]; + if (polymorphicMapper) { + mapper = polymorphicMapper; + } } - span.setStatus({ - code: coreTracing.SpanStatusCode.OK, - }); - span.end(); } - catch (error) { - logger.warning(`Skipping tracing span processing due to an error: ${error.message}`); + } + return mapper; +} +function getPolymorphicDiscriminatorRecursively(serializer, mapper) { + return (mapper.type.polymorphicDiscriminator || + getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) || + getPolymorphicDiscriminatorSafely(serializer, mapper.type.className)); +} +function getPolymorphicDiscriminatorSafely(serializer, typeName) { + return (typeName && + serializer.modelMappers[typeName] && + serializer.modelMappers[typeName].type.polymorphicDiscriminator); +} +/** + * Utility function that serializes an object that might contain binary information into a plain object, array or a string. + */ +function serializeObject(toSerialize) { + const castToSerialize = toSerialize; + if (toSerialize == undefined) + return undefined; + if (toSerialize instanceof Uint8Array) { + toSerialize = encodeByteArray(toSerialize); + return toSerialize; + } + else if (toSerialize instanceof Date) { + return toSerialize.toISOString(); + } + else if (Array.isArray(toSerialize)) { + const array = []; + for (let i = 0; i < toSerialize.length; i++) { + array.push(serializeObject(toSerialize[i])); + } + return array; + } + else if (typeof toSerialize === "object") { + const dictionary = {}; + for (const property in toSerialize) { + dictionary[property] = serializeObject(castToSerialize[property]); } + return dictionary; + } + return toSerialize; +} +/** + * Utility function to create a K:V from a list of strings + */ +function strEnum(o) { + const result = {}; + for (const key of o) { + result[key] = key; } + return result; } +/** + * String enum containing the string types of property mappers. + */ +// eslint-disable-next-line @typescript-eslint/no-redeclare +const MapperType = strEnum([ + "Base64Url", + "Boolean", + "ByteArray", + "Composite", + "Date", + "DateTime", + "DateTimeRfc1123", + "Dictionary", + "Enum", + "Number", + "Object", + "Sequence", + "String", + "Stream", + "TimeSpan", + "UnixTime", +]); // Copyright (c) Microsoft Corporation. +function isWebResourceLike(object) { + if (object && typeof object === "object") { + const castObject = object; + if (typeof castObject.url === "string" && + typeof castObject.method === "string" && + typeof castObject.headers === "object" && + isHttpHeadersLike(castObject.headers) && + typeof castObject.validateRequestProperties === "function" && + typeof castObject.prepare === "function" && + typeof castObject.clone === "function") { + return true; + } + } + return false; +} /** - * ServiceClient sends service requests and receives responses. + * Creates a new WebResource object. + * + * This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary + * properties to initiate a request. */ -class ServiceClient { +class WebResource { + constructor(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, decompressResponse, streamResponseStatusCodes) { + this.streamResponseBody = streamResponseBody; + this.streamResponseStatusCodes = streamResponseStatusCodes; + this.url = url || ""; + this.method = method || "GET"; + this.headers = isHttpHeadersLike(headers) ? headers : new HttpHeaders(headers); + this.body = body; + this.query = query; + this.formData = undefined; + this.withCredentials = withCredentials || false; + this.abortSignal = abortSignal; + this.timeout = timeout || 0; + this.onUploadProgress = onUploadProgress; + this.onDownloadProgress = onDownloadProgress; + this.proxySettings = proxySettings; + this.keepAlive = keepAlive; + this.decompressResponse = decompressResponse; + this.requestId = this.headers.get("x-ms-client-request-id") || generateUuid(); + } /** - * The ServiceClient constructor - * @param credentials - The credentials used for authentication with the service. - * @param options - The service client options that govern the behavior of the client. + * Validates that the required properties such as method, url, headers["Content-Type"], + * headers["accept-language"] are defined. It will throw an error if one of the above + * mentioned properties are not defined. */ - constructor(credentials, - /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options */ - options) { - if (!options) { - options = {}; - } - this._withCredentials = options.withCredentials || false; - this._httpClient = options.httpClient || getCachedDefaultHttpClient(); - this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger); - let requestPolicyFactories; - if (Array.isArray(options.requestPolicyFactories)) { - logger.info("ServiceClient: using custom request policies"); - requestPolicyFactories = options.requestPolicyFactories; + validateRequestProperties() { + if (!this.method) { + throw new Error("WebResource.method is required."); } - else { - let authPolicyFactory = undefined; - if (coreAuth.isTokenCredential(credentials)) { - logger.info("ServiceClient: creating bearer token authentication policy from provided credentials"); - // Create a wrapped RequestPolicyFactory here so that we can provide the - // correct scope to the BearerTokenAuthenticationPolicy at the first time - // one is requested. This is needed because generated ServiceClient - // implementations do not set baseUri until after ServiceClient's constructor - // is finished, leaving baseUri empty at the time when it is needed to - // build the correct scope name. - const wrappedPolicyFactory = () => { - let bearerTokenPolicyFactory = undefined; - // eslint-disable-next-line @typescript-eslint/no-this-alias - const serviceClient = this; - const serviceClientOptions = options; - return { - create(nextPolicy, createOptions) { - const credentialScopes = getCredentialScopes(serviceClientOptions, serviceClient.baseUri); - if (!credentialScopes) { - throw new Error(`When using credential, the ServiceClient must contain a baseUri or a credentialScopes in ServiceClientOptions. Unable to create a bearerTokenAuthenticationPolicy`); - } - if (bearerTokenPolicyFactory === undefined || bearerTokenPolicyFactory === null) { - bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy(credentials, credentialScopes); - } - return bearerTokenPolicyFactory.create(nextPolicy, createOptions); - }, - }; - }; - authPolicyFactory = wrappedPolicyFactory(); - } - else if (credentials && typeof credentials.signRequest === "function") { - logger.info("ServiceClient: creating signing policy from provided credentials"); - authPolicyFactory = signingPolicy(credentials); - } - else if (credentials !== undefined && credentials !== null) { - throw new Error("The credentials argument must implement the TokenCredential interface"); - } - logger.info("ServiceClient: using default request policies"); - requestPolicyFactories = createDefaultRequestPolicyFactories(authPolicyFactory, options); - if (options.requestPolicyFactories) { - // options.requestPolicyFactories can also be a function that manipulates - // the default requestPolicyFactories array - const newRequestPolicyFactories = options.requestPolicyFactories(requestPolicyFactories); - if (newRequestPolicyFactories) { - requestPolicyFactories = newRequestPolicyFactories; - } - } + if (!this.url) { + throw new Error("WebResource.url is required."); } - this._requestPolicyFactories = requestPolicyFactories; } /** - * Send the provided httpRequest. + * Prepares the request. + * @param options - Options to provide for preparing the request. + * @returns Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline. */ - sendRequest(options) { - if (options === null || options === undefined || typeof options !== "object") { - throw new Error("options cannot be null or undefined and it must be of type object."); + prepare(options) { + if (!options) { + throw new Error("options object is required"); } - let httpRequest; - try { - if (isWebResourceLike(options)) { - options.validateRequestProperties(); - httpRequest = options; - } - else { - httpRequest = new WebResource(); - httpRequest = httpRequest.prepare(options); - } + if (options.method === undefined || + options.method === null || + typeof options.method.valueOf() !== "string") { + throw new Error("options.method must be a string."); } - catch (error) { - return Promise.reject(error); + if (options.url && options.pathTemplate) { + throw new Error("options.url and options.pathTemplate are mutually exclusive. Please provide exactly one of them."); } - let httpPipeline = this._httpClient; - if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) { - for (let i = this._requestPolicyFactories.length - 1; i >= 0; --i) { - httpPipeline = this._requestPolicyFactories[i].create(httpPipeline, this._requestPolicyOptions); + if ((options.pathTemplate === undefined || + options.pathTemplate === null || + typeof options.pathTemplate.valueOf() !== "string") && + (options.url === undefined || + options.url === null || + typeof options.url.valueOf() !== "string")) { + throw new Error("Please provide exactly one of options.pathTemplate or options.url."); + } + // set the url if it is provided. + if (options.url) { + if (typeof options.url !== "string") { + throw new Error('options.url must be of type "string".'); } + this.url = options.url; } - return httpPipeline.sendRequest(httpRequest); - } - /** - * Send an HTTP request that is populated using the provided OperationSpec. - * @param operationArguments - The arguments that the HTTP request's templated values will be populated from. - * @param operationSpec - The OperationSpec to use to populate the httpRequest. - * @param callback - The callback to call when the response is received. - */ - async sendOperationRequest(operationArguments, operationSpec, callback) { - var _a; - if (typeof operationArguments.options === "function") { - callback = operationArguments.options; - operationArguments.options = undefined; + // set the method + if (options.method) { + const validMethods = ["GET", "PUT", "HEAD", "DELETE", "OPTIONS", "POST", "PATCH", "TRACE"]; + if (validMethods.indexOf(options.method.toUpperCase()) === -1) { + throw new Error('The provided method "' + + options.method + + '" is invalid. Supported HTTP methods are: ' + + JSON.stringify(validMethods)); + } } - const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; - const httpRequest = new WebResource(); - let result; - try { - const baseUri = operationSpec.baseUrl || this.baseUri; - if (!baseUri) { - throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a baseUri string property that contains the base URL to use."); + this.method = options.method.toUpperCase(); + // construct the url if path template is provided + if (options.pathTemplate) { + const { pathTemplate, pathParameters } = options; + if (typeof pathTemplate !== "string") { + throw new Error('options.pathTemplate must be of type "string".'); } - httpRequest.method = operationSpec.httpMethod; - httpRequest.operationSpec = operationSpec; - const requestUrl = URLBuilder.parse(baseUri); - if (operationSpec.path) { - requestUrl.appendPath(operationSpec.path); + if (!options.baseUrl) { + options.baseUrl = "https://management.azure.com"; } - if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) { - for (const urlParameter of operationSpec.urlParameters) { - let urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer); - urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter), serializerOptions); - if (!urlParameter.skipEncoding) { - urlParameterValue = encodeURIComponent(urlParameterValue); - } - requestUrl.replaceAll(`{${urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)}}`, urlParameterValue); + const baseUrl = options.baseUrl; + let url = baseUrl + + (baseUrl.endsWith("/") ? "" : "/") + + (pathTemplate.startsWith("/") ? pathTemplate.slice(1) : pathTemplate); + const segments = url.match(/({[\w-]*\s*[\w-]*})/gi); + if (segments && segments.length) { + if (!pathParameters) { + throw new Error(`pathTemplate: ${pathTemplate} has been provided. Hence, options.pathParameters must also be provided.`); } - } - if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) { - for (const queryParameter of operationSpec.queryParameters) { - let queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer); - if (queryParameterValue !== undefined && queryParameterValue !== null) { - queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter), serializerOptions); - if (queryParameter.collectionFormat !== undefined && - queryParameter.collectionFormat !== null) { - if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Multi) { - if (queryParameterValue.length === 0) { - // The collection is empty, no need to try serializing the current queryParam - continue; - } - else { - for (const index in queryParameterValue) { - const item = queryParameterValue[index]; - queryParameterValue[index] = - item === undefined || item === null ? "" : item.toString(); - } - } - } - else if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Ssv || - queryParameter.collectionFormat === exports.QueryCollectionFormat.Tsv) { - queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); - } - } - if (!queryParameter.skipEncoding) { - if (Array.isArray(queryParameterValue)) { - for (const index in queryParameterValue) { - if (queryParameterValue[index] !== undefined && - queryParameterValue[index] !== null) { - queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]); - } - } - } - else { - queryParameterValue = encodeURIComponent(queryParameterValue); - } - } - if (queryParameter.collectionFormat !== undefined && - queryParameter.collectionFormat !== null && - queryParameter.collectionFormat !== exports.QueryCollectionFormat.Multi && - queryParameter.collectionFormat !== exports.QueryCollectionFormat.Ssv && - queryParameter.collectionFormat !== exports.QueryCollectionFormat.Tsv) { - queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); - } - requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue); + segments.forEach(function (item) { + const pathParamName = item.slice(1, -1); + const pathParam = pathParameters[pathParamName]; + if (pathParam === null || + pathParam === undefined || + !(typeof pathParam === "string" || typeof pathParam === "object")) { + const stringifiedPathParameters = JSON.stringify(pathParameters, undefined, 2); + throw new Error(`pathTemplate: ${pathTemplate} contains the path parameter ${pathParamName}` + + ` however, it is not present in parameters: ${stringifiedPathParameters}.` + + `The value of the path parameter can either be a "string" of the form { ${pathParamName}: "some sample value" } or ` + + `it can be an "object" of the form { "${pathParamName}": { value: "some sample value", skipUrlEncoding: true } }.`); } - } - } - httpRequest.url = requestUrl.toString(); - const contentType = operationSpec.contentType || this.requestContentType; - if (contentType && operationSpec.requestBody) { - httpRequest.headers.set("Content-Type", contentType); - } - if (operationSpec.headerParameters) { - for (const headerParameter of operationSpec.headerParameters) { - let headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer); - if (headerValue !== undefined && headerValue !== null) { - headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter), serializerOptions); - const headerCollectionPrefix = headerParameter.mapper - .headerCollectionPrefix; - if (headerCollectionPrefix) { - for (const key of Object.keys(headerValue)) { - httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]); - } + if (typeof pathParam.valueOf() === "string") { + url = url.replace(item, encodeURIComponent(pathParam)); + } + if (typeof pathParam.valueOf() === "object") { + if (!pathParam.value) { + throw new Error(`options.pathParameters[${pathParamName}] is of type "object" but it does not contain a "value" property.`); + } + if (pathParam.skipUrlEncoding) { + url = url.replace(item, pathParam.value); } else { - httpRequest.headers.set(headerParameter.mapper.serializedName || - getPathStringFromParameter(headerParameter), headerValue); + url = url.replace(item, encodeURIComponent(pathParam.value)); } } - } - } - const options = operationArguments.options; - if (options) { - if (options.customHeaders) { - for (const customHeaderName in options.customHeaders) { - httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]); - } - } - if (options.abortSignal) { - httpRequest.abortSignal = options.abortSignal; - } - if (options.timeout) { - httpRequest.timeout = options.timeout; - } - if (options.onUploadProgress) { - httpRequest.onUploadProgress = options.onUploadProgress; - } - if (options.onDownloadProgress) { - httpRequest.onDownloadProgress = options.onDownloadProgress; - } - if (options.spanOptions) { - // By passing spanOptions if they exist at runtime, we're backwards compatible with @azure/core-tracing@preview.13 and earlier. - httpRequest.spanOptions = options.spanOptions; - } - if (options.tracingContext) { - httpRequest.tracingContext = options.tracingContext; - } - if (options.shouldDeserialize !== undefined && options.shouldDeserialize !== null) { - httpRequest.shouldDeserialize = options.shouldDeserialize; - } - } - httpRequest.withCredentials = this._withCredentials; - serializeRequestBody(this, httpRequest, operationArguments, operationSpec); - if (httpRequest.streamResponseStatusCodes === undefined) { - httpRequest.streamResponseStatusCodes = getStreamResponseStatusCodes(operationSpec); + }); } - let rawResponse; - let sendRequestError; - try { - rawResponse = await this.sendRequest(httpRequest); + this.url = url; + } + // append query parameters to the url if they are provided. They can be provided with pathTemplate or url option. + if (options.queryParameters) { + const queryParameters = options.queryParameters; + if (typeof queryParameters !== "object") { + throw new Error(`options.queryParameters must be of type object. It should be a JSON object ` + + `of "query-parameter-name" as the key and the "query-parameter-value" as the value. ` + + `The "query-parameter-value" may be fo type "string" or an "object" of the form { value: "query-parameter-value", skipUrlEncoding: true }.`); } - catch (error) { - sendRequestError = error; + // append question mark if it is not present in the url + if (this.url && this.url.indexOf("?") === -1) { + this.url += "?"; } - if (sendRequestError) { - if (sendRequestError.response) { - sendRequestError.details = flattenResponse(sendRequestError.response, operationSpec.responses[sendRequestError.statusCode] || - operationSpec.responses["default"]); + // construct queryString + const queryParams = []; + // We need to populate this.query as a dictionary if the request is being used for Sway's validateRequest(). + this.query = {}; + for (const queryParamName in queryParameters) { + const queryParam = queryParameters[queryParamName]; + if (queryParam) { + if (typeof queryParam === "string") { + queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam)); + this.query[queryParamName] = encodeURIComponent(queryParam); + } + else if (typeof queryParam === "object") { + if (!queryParam.value) { + throw new Error(`options.queryParameters[${queryParamName}] is of type "object" but it does not contain a "value" property.`); + } + if (queryParam.skipUrlEncoding) { + queryParams.push(queryParamName + "=" + queryParam.value); + this.query[queryParamName] = queryParam.value; + } + else { + queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam.value)); + this.query[queryParamName] = encodeURIComponent(queryParam.value); + } + } } - result = Promise.reject(sendRequestError); - } - else { - result = Promise.resolve(flattenResponse(rawResponse, operationSpec.responses[rawResponse.status])); + } // end-of-for + // append the queryString + this.url += queryParams.join("&"); + } + // add headers to the request if they are provided + if (options.headers) { + const headers = options.headers; + for (const headerName of Object.keys(options.headers)) { + this.headers.set(headerName, headers[headerName]); } } - catch (error) { - result = Promise.reject(error); + // ensure accept-language is set correctly + if (!this.headers.get("accept-language")) { + this.headers.set("accept-language", "en-US"); } - const cb = callback; - if (cb) { - result - .then((res) => cb(null, res._response.parsedBody, res._response.request, res._response)) - .catch((err) => cb(err)); + // ensure the request-id is set correctly + if (!this.headers.get("x-ms-client-request-id") && !options.disableClientRequestId) { + this.headers.set("x-ms-client-request-id", this.requestId); } - return result; - } -} -function serializeRequestBody(serviceClient, httpRequest, operationArguments, operationSpec) { - var _a, _b, _c, _d, _e, _f; - const serializerOptions = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions) !== null && _b !== void 0 ? _b : {}; - const updatedOptions = { - rootName: (_c = serializerOptions.rootName) !== null && _c !== void 0 ? _c : "", - includeRoot: (_d = serializerOptions.includeRoot) !== null && _d !== void 0 ? _d : false, - xmlCharKey: (_e = serializerOptions.xmlCharKey) !== null && _e !== void 0 ? _e : XML_CHARKEY, - }; - const xmlCharKey = serializerOptions.xmlCharKey; - if (operationSpec.requestBody && operationSpec.requestBody.mapper) { - httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer); - const bodyMapper = operationSpec.requestBody.mapper; - const { required, xmlName, xmlElementName, serializedName, xmlNamespace, xmlNamespacePrefix } = bodyMapper; - const typeName = bodyMapper.type.name; - try { - if ((httpRequest.body !== undefined && httpRequest.body !== null) || required) { - const requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody); - httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString, updatedOptions); - const isStream = typeName === MapperType.Stream; - if (operationSpec.isXML) { - const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns"; - const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, httpRequest.body, updatedOptions); - if (typeName === MapperType.Sequence) { - httpRequest.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { - rootName: xmlName || serializedName, - xmlCharKey, - }); - } - else if (!isStream) { - httpRequest.body = stringifyXML(value, { - rootName: xmlName || serializedName, - xmlCharKey, - }); - } + // default + if (!this.headers.get("Content-Type")) { + this.headers.set("Content-Type", "application/json; charset=utf-8"); + } + // set the request body. request.js automatically sets the Content-Length request header, so we need not set it explicitly + this.body = options.body; + if (options.body !== undefined && options.body !== null) { + // body as a stream special case. set the body as-is and check for some special request headers specific to sending a stream. + if (options.bodyIsStream) { + if (!this.headers.get("Transfer-Encoding")) { + this.headers.set("Transfer-Encoding", "chunked"); } - else if (typeName === MapperType.String && - (((_f = operationSpec.contentType) === null || _f === void 0 ? void 0 : _f.match("text/plain")) || operationSpec.mediaType === "text")) { - // the String serializer has validated that request body is a string - // so just send the string. - return; + if (this.headers.get("Content-Type") !== "application/octet-stream") { + this.headers.set("Content-Type", "application/octet-stream"); } - else if (!isStream) { - httpRequest.body = JSON.stringify(httpRequest.body); + } + else { + if (options.serializationMapper) { + this.body = new Serializer(options.mappers).serialize(options.serializationMapper, options.body, "requestBody"); + } + if (!options.disableJsonStringifyOnBody) { + this.body = JSON.stringify(options.body); } } } - catch (error) { - throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`); + if (options.spanOptions) { + this.spanOptions = options.spanOptions; + } + if (options.tracingContext) { + this.tracingContext = options.tracingContext; } + this.abortSignal = options.abortSignal; + this.onDownloadProgress = options.onDownloadProgress; + this.onUploadProgress = options.onUploadProgress; + return this; } - else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) { - httpRequest.formData = {}; - for (const formDataParameter of operationSpec.formDataParameters) { - const formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer); - if (formDataParameterValue !== undefined && formDataParameterValue !== null) { - const formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter); - httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter), updatedOptions); - } + /** + * Clone this WebResource HTTP request object. + * @returns The clone of this WebResource HTTP request object. + */ + clone() { + const result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.decompressResponse, this.streamResponseStatusCodes); + if (this.formData) { + result.formData = this.formData; + } + if (this.operationSpec) { + result.operationSpec = this.operationSpec; + } + if (this.shouldDeserialize) { + result.shouldDeserialize = this.shouldDeserialize; + } + if (this.operationResponseGetter) { + result.operationResponseGetter = this.operationResponseGetter; } + return result; } } + +// Copyright (c) Microsoft Corporation. /** - * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself + * A class that handles the query portion of a URLBuilder. */ -function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) { - // Composite and Sequence schemas already got their root namespace set during serialization - // We just need to add xmlns to the other schema types - if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) { - const result = {}; - result[options.xmlCharKey] = serializedValue; - result[XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace }; - return result; - } - return serializedValue; -} -function getValueOrFunctionResult(value, defaultValueCreator) { - let result; - if (typeof value === "string") { - result = value; +class URLQuery { + constructor() { + this._rawQuery = {}; } - else { - result = defaultValueCreator(); - if (typeof value === "function") { - result = value(result); - } + /** + * Get whether or not there any query parameters in this URLQuery. + */ + any() { + return Object.keys(this._rawQuery).length > 0; } - return result; -} -function createDefaultRequestPolicyFactories(authPolicyFactory, options) { - const factories = []; - if (options.generateClientRequestIdHeader) { - factories.push(generateClientRequestIdPolicy(options.clientRequestIdHeaderName)); + /** + * Get the keys of the query string. + */ + keys() { + return Object.keys(this._rawQuery); } - if (authPolicyFactory) { - factories.push(authPolicyFactory); + /** + * Set a query parameter with the provided name and value. If the parameterValue is undefined or + * empty, then this will attempt to remove an existing query parameter with the provided + * parameterName. + */ + set(parameterName, parameterValue) { + const caseParameterValue = parameterValue; + if (parameterName) { + if (caseParameterValue !== undefined && caseParameterValue !== null) { + const newValue = Array.isArray(caseParameterValue) + ? caseParameterValue + : caseParameterValue.toString(); + this._rawQuery[parameterName] = newValue; + } + else { + delete this._rawQuery[parameterName]; + } + } } - const userAgentHeaderName = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName); - const userAgentHeaderValue = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue); - if (userAgentHeaderName && userAgentHeaderValue) { - factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue })); + /** + * Get the value of the query parameter with the provided name. If no parameter exists with the + * provided parameter name, then undefined will be returned. + */ + get(parameterName) { + return parameterName ? this._rawQuery[parameterName] : undefined; } - factories.push(redirectPolicy()); - factories.push(rpRegistrationPolicy(options.rpRegistrationRetryTimeout)); - if (!options.noRetryPolicy) { - factories.push(exponentialRetryPolicy()); - factories.push(systemErrorRetryPolicy()); - factories.push(throttlingRetryPolicy()); + /** + * Get the string representation of this query. The return value will not start with a "?". + */ + toString() { + let result = ""; + for (const parameterName in this._rawQuery) { + if (result) { + result += "&"; + } + const parameterValue = this._rawQuery[parameterName]; + if (Array.isArray(parameterValue)) { + const parameterStrings = []; + for (const parameterValueElement of parameterValue) { + parameterStrings.push(`${parameterName}=${parameterValueElement}`); + } + result += parameterStrings.join("&"); + } + else { + result += `${parameterName}=${parameterValue}`; + } + } + return result; } - factories.push(deserializationPolicy(options.deserializationContentTypes)); - if (isNode) { - factories.push(proxyPolicy(options.proxySettings)); + /** + * Parse a URLQuery from the provided text. + */ + static parse(text) { + const result = new URLQuery(); + if (text) { + if (text.startsWith("?")) { + text = text.substring(1); + } + let currentState = "ParameterName"; + let parameterName = ""; + let parameterValue = ""; + for (let i = 0; i < text.length; ++i) { + const currentCharacter = text[i]; + switch (currentState) { + case "ParameterName": + switch (currentCharacter) { + case "=": + currentState = "ParameterValue"; + break; + case "&": + parameterName = ""; + parameterValue = ""; + break; + default: + parameterName += currentCharacter; + break; + } + break; + case "ParameterValue": + switch (currentCharacter) { + case "&": + result.set(parameterName, parameterValue); + parameterName = ""; + parameterValue = ""; + currentState = "ParameterName"; + break; + default: + parameterValue += currentCharacter; + break; + } + break; + default: + throw new Error("Unrecognized URLQuery parse state: " + currentState); + } + } + if (currentState === "ParameterValue") { + result.set(parameterName, parameterValue); + } + } + return result; } - factories.push(logPolicy({ logger: logger.info })); - return factories; } /** - * Creates an HTTP pipeline based on the given options. - * @param pipelineOptions - Defines options that are used to configure policies in the HTTP pipeline for an SDK client. - * @param authPolicyFactory - An optional authentication policy factory to use for signing requests. - * @returns A set of options that can be passed to create a new {@link ServiceClient}. + * A class that handles creating, modifying, and parsing URLs. */ -function createPipelineFromOptions(pipelineOptions, authPolicyFactory) { - const requestPolicyFactories = []; - if (pipelineOptions.sendStreamingJson) { - requestPolicyFactories.push(ndJsonPolicy()); - } - let userAgentValue = undefined; - if (pipelineOptions.userAgentOptions && pipelineOptions.userAgentOptions.userAgentPrefix) { - const userAgentInfo = []; - userAgentInfo.push(pipelineOptions.userAgentOptions.userAgentPrefix); - // Add the default user agent value if it isn't already specified - // by the userAgentPrefix option. - const defaultUserAgentInfo = getDefaultUserAgentValue(); - if (userAgentInfo.indexOf(defaultUserAgentInfo) === -1) { - userAgentInfo.push(defaultUserAgentInfo); +class URLBuilder { + /** + * Set the scheme/protocol for this URL. If the provided scheme contains other parts of a URL + * (such as a host, port, path, or query), those parts will be added to this URL as well. + */ + setScheme(scheme) { + if (!scheme) { + this._scheme = undefined; + } + else { + this.set(scheme, "SCHEME"); } - userAgentValue = userAgentInfo.join(" "); } - const keepAliveOptions = Object.assign(Object.assign({}, DefaultKeepAliveOptions), pipelineOptions.keepAliveOptions); - const retryOptions = Object.assign(Object.assign({}, DefaultRetryOptions), pipelineOptions.retryOptions); - const redirectOptions = Object.assign(Object.assign({}, DefaultRedirectOptions), pipelineOptions.redirectOptions); - if (isNode) { - requestPolicyFactories.push(proxyPolicy(pipelineOptions.proxyOptions)); + /** + * Get the scheme that has been set in this URL. + */ + getScheme() { + return this._scheme; } - const deserializationOptions = Object.assign(Object.assign({}, DefaultDeserializationOptions), pipelineOptions.deserializationOptions); - const loggingOptions = Object.assign({}, pipelineOptions.loggingOptions); - requestPolicyFactories.push(tracingPolicy({ userAgent: userAgentValue }), keepAlivePolicy(keepAliveOptions), userAgentPolicy({ value: userAgentValue }), generateClientRequestIdPolicy(), deserializationPolicy(deserializationOptions.expectedContentTypes), throttlingRetryPolicy(), systemErrorRetryPolicy(), exponentialRetryPolicy(retryOptions.maxRetries, retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs)); - if (redirectOptions.handleRedirects) { - requestPolicyFactories.push(redirectPolicy(redirectOptions.maxRetries)); + /** + * Set the host for this URL. If the provided host contains other parts of a URL (such as a + * port, path, or query), those parts will be added to this URL as well. + */ + setHost(host) { + if (!host) { + this._host = undefined; + } + else { + this.set(host, "SCHEME_OR_HOST"); + } } - if (authPolicyFactory) { - requestPolicyFactories.push(authPolicyFactory); + /** + * Get the host that has been set in this URL. + */ + getHost() { + return this._host; } - requestPolicyFactories.push(logPolicy(loggingOptions)); - if (isNode && pipelineOptions.decompressResponse === false) { - requestPolicyFactories.push(disableResponseDecompressionPolicy()); + /** + * Set the port for this URL. If the provided port contains other parts of a URL (such as a + * path or query), those parts will be added to this URL as well. + */ + setPort(port) { + if (port === undefined || port === null || port === "") { + this._port = undefined; + } + else { + this.set(port.toString(), "PORT"); + } } - return { - httpClient: pipelineOptions.httpClient, - requestPolicyFactories, - }; -} -function getOperationArgumentValueFromParameter(serviceClient, operationArguments, parameter, serializer) { - return getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameter.parameterPath, parameter.mapper, serializer); -} -function getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, serializer) { - var _a; - let value; - if (typeof parameterPath === "string") { - parameterPath = [parameterPath]; + /** + * Get the port that has been set in this URL. + */ + getPort() { + return this._port; } - const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; - if (Array.isArray(parameterPath)) { - if (parameterPath.length > 0) { - if (parameterMapper.isConstant) { - value = parameterMapper.defaultValue; + /** + * Set the path for this URL. If the provided path contains a query, then it will be added to + * this URL as well. + */ + setPath(path) { + if (!path) { + this._path = undefined; + } + else { + const schemeIndex = path.indexOf("://"); + if (schemeIndex !== -1) { + const schemeStart = path.lastIndexOf("/", schemeIndex); + // Make sure to only grab the URL part of the path before setting the state back to SCHEME + // this will handle cases such as "/a/b/c/https://microsoft.com" => "https://microsoft.com" + this.set(schemeStart === -1 ? path : path.substr(schemeStart + 1), "SCHEME"); } else { - let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath); - if (!propertySearchResult.propertyFound) { - propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath); + this.set(path, "PATH"); + } + } + } + /** + * Append the provided path to this URL's existing path. If the provided path contains a query, + * then it will be added to this URL as well. + */ + appendPath(path) { + if (path) { + let currentPath = this.getPath(); + if (currentPath) { + if (!currentPath.endsWith("/")) { + currentPath += "/"; } - let useDefaultValue = false; - if (!propertySearchResult.propertyFound) { - useDefaultValue = - parameterMapper.required || - (parameterPath[0] === "options" && parameterPath.length === 2); + if (path.startsWith("/")) { + path = path.substring(1); } - value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue; + path = currentPath + path; } - // Serialize just for validation purposes. - const parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper); - serializer.serialize(parameterMapper, value, parameterPathString, serializerOptions); + this.set(path, "PATH"); } } - else { - if (parameterMapper.required) { - value = {}; + /** + * Get the path that has been set in this URL. + */ + getPath() { + return this._path; + } + /** + * Set the query in this URL. + */ + setQuery(query) { + if (!query) { + this._query = undefined; } - for (const propertyName in parameterPath) { - const propertyMapper = parameterMapper.type.modelProperties[propertyName]; - const propertyPath = parameterPath[propertyName]; - const propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer); - // Serialize just for validation purposes. - const propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper); - serializer.serialize(propertyMapper, propertyValue, propertyPathString, serializerOptions); - if (propertyValue !== undefined && propertyValue !== null) { - if (!value) { - value = {}; + else { + this._query = URLQuery.parse(query); + } + } + /** + * Set a query parameter with the provided name and value in this URL's query. If the provided + * query parameter value is undefined or empty, then the query parameter will be removed if it + * existed. + */ + setQueryParameter(queryParameterName, queryParameterValue) { + if (queryParameterName) { + if (!this._query) { + this._query = new URLQuery(); + } + this._query.set(queryParameterName, queryParameterValue); + } + } + /** + * Get the value of the query parameter with the provided query parameter name. If no query + * parameter exists with the provided name, then undefined will be returned. + */ + getQueryParameterValue(queryParameterName) { + return this._query ? this._query.get(queryParameterName) : undefined; + } + /** + * Get the query in this URL. + */ + getQuery() { + return this._query ? this._query.toString() : undefined; + } + /** + * Set the parts of this URL by parsing the provided text using the provided startState. + */ + set(text, startState) { + const tokenizer = new URLTokenizer(text, startState); + while (tokenizer.next()) { + const token = tokenizer.current(); + let tokenPath; + if (token) { + switch (token.type) { + case "SCHEME": + this._scheme = token.text || undefined; + break; + case "HOST": + this._host = token.text || undefined; + break; + case "PORT": + this._port = token.text || undefined; + break; + case "PATH": + tokenPath = token.text || undefined; + if (!this._path || this._path === "/" || tokenPath !== "/") { + this._path = tokenPath; + } + break; + case "QUERY": + this._query = URLQuery.parse(token.text); + break; + default: + throw new Error(`Unrecognized URLTokenType: ${token.type}`); } - value[propertyName] = propertyValue; } } } - return value; -} -function getPropertyFromParameterPath(parent, parameterPath) { - const result = { propertyFound: false }; - let i = 0; - for (; i < parameterPath.length; ++i) { - const parameterPathPart = parameterPath[i]; - // Make sure to check inherited properties too, so don't use hasOwnProperty(). - if (parent !== undefined && parent !== null && parameterPathPart in parent) { - parent = parent[parameterPathPart]; + /** + * Serializes the URL as a string. + * @returns the URL as a string. + */ + toString() { + let result = ""; + if (this._scheme) { + result += `${this._scheme}://`; } - else { - break; + if (this._host) { + result += this._host; } - } - if (i === parameterPath.length) { - result.propertyValue = parent; - result.propertyFound = true; - } - return result; -} -/** - * Parses an {@link HttpOperationResponse} into a normalized HTTP response object ({@link RestResponse}). - * @param _response - Wrapper object for http response. - * @param responseSpec - Mappers for how to parse the response properties. - * @returns - A normalized response object. - */ -function flattenResponse(_response, responseSpec) { - const parsedHeaders = _response.parsedHeaders; - const bodyMapper = responseSpec && responseSpec.bodyMapper; - const addOperationResponse = (obj) => { - return Object.defineProperty(obj, "_response", { - value: _response, - }); - }; - if (bodyMapper) { - const typeName = bodyMapper.type.name; - if (typeName === "Stream") { - return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody })); + if (this._port) { + result += `:${this._port}`; } - const modelProperties = (typeName === "Composite" && bodyMapper.type.modelProperties) || {}; - const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === ""); - if (typeName === "Sequence" || isPageableResponse) { - const arrayResponse = [...(_response.parsedBody || [])]; - for (const key of Object.keys(modelProperties)) { - if (modelProperties[key].serializedName) { - arrayResponse[key] = _response.parsedBody[key]; - } - } - if (parsedHeaders) { - for (const key of Object.keys(parsedHeaders)) { - arrayResponse[key] = parsedHeaders[key]; - } + if (this._path) { + if (!this._path.startsWith("/")) { + result += "/"; } - addOperationResponse(arrayResponse); - return arrayResponse; + result += this._path; } - if (typeName === "Composite" || typeName === "Dictionary") { - return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), _response.parsedBody)); + if (this._query && this._query.any()) { + result += `?${this._query.toString()}`; } + return result; } - if (bodyMapper || - _response.request.method === "HEAD" || - isPrimitiveType(_response.parsedBody)) { - // primitive body types and HEAD booleans - return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), { body: _response.parsedBody })); + /** + * If the provided searchValue is found in this URLBuilder, then replace it with the provided + * replaceValue. + */ + replaceAll(searchValue, replaceValue) { + if (searchValue) { + this.setScheme(replaceAll(this.getScheme(), searchValue, replaceValue)); + this.setHost(replaceAll(this.getHost(), searchValue, replaceValue)); + this.setPort(replaceAll(this.getPort(), searchValue, replaceValue)); + this.setPath(replaceAll(this.getPath(), searchValue, replaceValue)); + this.setQuery(replaceAll(this.getQuery(), searchValue, replaceValue)); + } + } + /** + * Parses a given string URL into a new {@link URLBuilder}. + */ + static parse(text) { + const result = new URLBuilder(); + result.set(text, "SCHEME_OR_HOST"); + return result; } - return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), _response.parsedBody)); } -function getCredentialScopes(options, baseUri) { - if (options === null || options === void 0 ? void 0 : options.credentialScopes) { - const scopes = options.credentialScopes; - return Array.isArray(scopes) - ? scopes.map((scope) => new URL(scope).toString()) - : new URL(scopes).toString(); +class URLToken { + constructor(text, type) { + this.text = text; + this.type = type; } - if (baseUri) { - return `${baseUri}/.default`; + static scheme(text) { + return new URLToken(text, "SCHEME"); + } + static host(text) { + return new URLToken(text, "HOST"); + } + static port(text) { + return new URLToken(text, "PORT"); + } + static path(text) { + return new URLToken(text, "PATH"); + } + static query(text) { + return new URLToken(text, "QUERY"); } - return undefined; } - -// Copyright (c) Microsoft Corporation. /** - * This function is only here for compatibility. Use createSpanFunction in core-tracing. - * - * @deprecated This function is only here for compatibility. Use createSpanFunction in core-tracing. - * @hidden - - * @param spanConfig - The name of the operation being performed. - * @param tracingOptions - The options for the underlying http request. + * Get whether or not the provided character (single character string) is an alphanumeric (letter or + * digit) character. */ -function createSpanFunction(args) { - return coreTracing.createSpanFunction(args); +function isAlphaNumericCharacter(character) { + const characterCode = character.charCodeAt(0); + return ((48 /* '0' */ <= characterCode && characterCode <= 57) /* '9' */ || + (65 /* 'A' */ <= characterCode && characterCode <= 90) /* 'Z' */ || + (97 /* 'a' */ <= characterCode && characterCode <= 122) /* 'z' */); } - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * Defines the default token refresh buffer duration. - */ -const TokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes /** - * Provides an {@link AccessTokenCache} implementation which clears - * the cached {@link AccessToken}'s after the expiresOnTimestamp has - * passed. - * - * @deprecated No longer used in the bearer authorization policy. + * A class that tokenizes URL strings. */ -class ExpiringAccessTokenCache { - /** - * Constructs an instance of {@link ExpiringAccessTokenCache} with - * an optional expiration buffer time. - */ - constructor(tokenRefreshBufferMs = TokenRefreshBufferMs) { - this.cachedToken = undefined; - this.tokenRefreshBufferMs = tokenRefreshBufferMs; +class URLTokenizer { + constructor(_text, state) { + this._text = _text; + this._textLength = _text ? _text.length : 0; + this._currentState = state !== undefined && state !== null ? state : "SCHEME_OR_HOST"; + this._currentIndex = 0; } /** - * Saves an access token into the internal in-memory cache. - * @param accessToken - Access token or undefined to clear the cache. + * Get the current URLToken this URLTokenizer is pointing at, or undefined if the URLTokenizer + * hasn't started or has finished tokenizing. */ - setCachedToken(accessToken) { - this.cachedToken = accessToken; + current() { + return this._currentToken; } /** - * Returns the cached access token, or `undefined` if one is not cached or the cached one is expiring soon. + * Advance to the next URLToken and return whether or not a URLToken was found. */ - getCachedToken() { - if (this.cachedToken && - Date.now() + this.tokenRefreshBufferMs >= this.cachedToken.expiresOnTimestamp) { - this.cachedToken = undefined; + next() { + if (!hasCurrentCharacter(this)) { + this._currentToken = undefined; } - return this.cachedToken; + else { + switch (this._currentState) { + case "SCHEME": + nextScheme(this); + break; + case "SCHEME_OR_HOST": + nextSchemeOrHost(this); + break; + case "HOST": + nextHost(this); + break; + case "PORT": + nextPort(this); + break; + case "PATH": + nextPath(this); + break; + case "QUERY": + nextQuery(this); + break; + default: + throw new Error(`Unrecognized URLTokenizerState: ${this._currentState}`); + } + } + return !!this._currentToken; } } - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. /** - * Helps the core-http token authentication policies with requesting a new token if we're not currently waiting for a new token. - * - * @deprecated No longer used in the bearer authorization policy. + * Read the remaining characters from this Tokenizer's character stream. */ -class AccessTokenRefresher { - constructor(credential, scopes, requiredMillisecondsBeforeNewRefresh = 30000) { - this.credential = credential; - this.scopes = scopes; - this.requiredMillisecondsBeforeNewRefresh = requiredMillisecondsBeforeNewRefresh; - this.lastCalled = 0; +function readRemaining(tokenizer) { + let result = ""; + if (tokenizer._currentIndex < tokenizer._textLength) { + result = tokenizer._text.substring(tokenizer._currentIndex); + tokenizer._currentIndex = tokenizer._textLength; } - /** - * Returns true if the required milliseconds(defaulted to 30000) have been passed signifying - * that we are ready for a new refresh. - */ - isReady() { - // We're only ready for a new refresh if the required milliseconds have passed. - return (!this.lastCalled || Date.now() - this.lastCalled > this.requiredMillisecondsBeforeNewRefresh); + return result; +} +/** + * Whether or not this URLTokenizer has a current character. + */ +function hasCurrentCharacter(tokenizer) { + return tokenizer._currentIndex < tokenizer._textLength; +} +/** + * Get the character in the text string at the current index. + */ +function getCurrentCharacter(tokenizer) { + return tokenizer._text[tokenizer._currentIndex]; +} +/** + * Advance to the character in text that is "step" characters ahead. If no step value is provided, + * then step will default to 1. + */ +function nextCharacter(tokenizer, step) { + if (hasCurrentCharacter(tokenizer)) { + if (!step) { + step = 1; + } + tokenizer._currentIndex += step; } - /** - * Stores the time in which it is called, - * then requests a new token, - * then sets this.promise to undefined, - * then returns the token. - */ - async getToken(options) { - this.lastCalled = Date.now(); - const token = await this.credential.getToken(this.scopes, options); - this.promise = undefined; - return token || undefined; +} +/** + * Starting with the current character, peek "charactersToPeek" number of characters ahead in this + * Tokenizer's stream of characters. + */ +function peekCharacters(tokenizer, charactersToPeek) { + let endIndex = tokenizer._currentIndex + charactersToPeek; + if (tokenizer._textLength < endIndex) { + endIndex = tokenizer._textLength; } - /** - * Requests a new token if we're not currently waiting for a new token. - * Returns null if the required time between each call hasn't been reached. - */ - refresh(options) { - if (!this.promise) { - this.promise = this.getToken(options); + return tokenizer._text.substring(tokenizer._currentIndex, endIndex); +} +/** + * Read characters from this Tokenizer until the end of the stream or until the provided condition + * is false when provided the current character. + */ +function readWhile(tokenizer, condition) { + let result = ""; + while (hasCurrentCharacter(tokenizer)) { + const currentCharacter = getCurrentCharacter(tokenizer); + if (!condition(currentCharacter)) { + break; + } + else { + result += currentCharacter; + nextCharacter(tokenizer); } - return this.promise; } + return result; } - -// Copyright (c) Microsoft Corporation. -const HeaderConstants = Constants.HeaderConstants; -const DEFAULT_AUTHORIZATION_SCHEME = "Basic"; /** - * A simple {@link ServiceClientCredential} that authenticates with a username and a password. + * Read characters from this Tokenizer until a non-alphanumeric character or the end of the + * character stream is reached. */ -class BasicAuthenticationCredentials { - /** - * Creates a new BasicAuthenticationCredentials object. - * - * @param userName - User name. - * @param password - Password. - * @param authorizationScheme - The authorization scheme. - */ - constructor(userName, password, authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME) { - /** - * Authorization scheme. Defaults to "Basic". - * More information about authorization schemes is available here: https://developer.mozilla.org/docs/Web/HTTP/Authentication#authentication_schemes - */ - this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME; - if (userName === null || userName === undefined || typeof userName.valueOf() !== "string") { - throw new Error("userName cannot be null or undefined and must be of type string."); +function readWhileLetterOrDigit(tokenizer) { + return readWhile(tokenizer, (character) => isAlphaNumericCharacter(character)); +} +/** + * Read characters from this Tokenizer until one of the provided terminating characters is read or + * the end of the character stream is reached. + */ +function readUntilCharacter(tokenizer, ...terminatingCharacters) { + return readWhile(tokenizer, (character) => terminatingCharacters.indexOf(character) === -1); +} +function nextScheme(tokenizer) { + const scheme = readWhileLetterOrDigit(tokenizer); + tokenizer._currentToken = URLToken.scheme(scheme); + if (!hasCurrentCharacter(tokenizer)) { + tokenizer._currentState = "DONE"; + } + else { + tokenizer._currentState = "HOST"; + } +} +function nextSchemeOrHost(tokenizer) { + const schemeOrHost = readUntilCharacter(tokenizer, ":", "/", "?"); + if (!hasCurrentCharacter(tokenizer)) { + tokenizer._currentToken = URLToken.host(schemeOrHost); + tokenizer._currentState = "DONE"; + } + else if (getCurrentCharacter(tokenizer) === ":") { + if (peekCharacters(tokenizer, 3) === "://") { + tokenizer._currentToken = URLToken.scheme(schemeOrHost); + tokenizer._currentState = "HOST"; } - if (password === null || password === undefined || typeof password.valueOf() !== "string") { - throw new Error("password cannot be null or undefined and must be of type string."); + else { + tokenizer._currentToken = URLToken.host(schemeOrHost); + tokenizer._currentState = "PORT"; } - this.userName = userName; - this.password = password; - this.authorizationScheme = authorizationScheme; } - /** - * Signs a request with the Authentication header. - * - * @param webResource - The WebResourceLike to be signed. - * @returns The signed request object. - */ - signRequest(webResource) { - const credentials = `${this.userName}:${this.password}`; - const encodedCredentials = `${this.authorizationScheme} ${encodeString(credentials)}`; - if (!webResource.headers) - webResource.headers = new HttpHeaders(); - webResource.headers.set(HeaderConstants.AUTHORIZATION, encodedCredentials); - return Promise.resolve(webResource); + else { + tokenizer._currentToken = URLToken.host(schemeOrHost); + if (getCurrentCharacter(tokenizer) === "/") { + tokenizer._currentState = "PATH"; + } + else { + tokenizer._currentState = "QUERY"; + } + } +} +function nextHost(tokenizer) { + if (peekCharacters(tokenizer, 3) === "://") { + nextCharacter(tokenizer, 3); + } + const host = readUntilCharacter(tokenizer, ":", "/", "?"); + tokenizer._currentToken = URLToken.host(host); + if (!hasCurrentCharacter(tokenizer)) { + tokenizer._currentState = "DONE"; + } + else if (getCurrentCharacter(tokenizer) === ":") { + tokenizer._currentState = "PORT"; + } + else if (getCurrentCharacter(tokenizer) === "/") { + tokenizer._currentState = "PATH"; + } + else { + tokenizer._currentState = "QUERY"; + } +} +function nextPort(tokenizer) { + if (getCurrentCharacter(tokenizer) === ":") { + nextCharacter(tokenizer); + } + const port = readUntilCharacter(tokenizer, "/", "?"); + tokenizer._currentToken = URLToken.port(port); + if (!hasCurrentCharacter(tokenizer)) { + tokenizer._currentState = "DONE"; + } + else if (getCurrentCharacter(tokenizer) === "/") { + tokenizer._currentState = "PATH"; + } + else { + tokenizer._currentState = "QUERY"; + } +} +function nextPath(tokenizer) { + const path = readUntilCharacter(tokenizer, "?"); + tokenizer._currentToken = URLToken.path(path); + if (!hasCurrentCharacter(tokenizer)) { + tokenizer._currentState = "DONE"; + } + else { + tokenizer._currentState = "QUERY"; + } +} +function nextQuery(tokenizer) { + if (getCurrentCharacter(tokenizer) === "?") { + nextCharacter(tokenizer); } + const query = readRemaining(tokenizer); + tokenizer._currentToken = URLToken.query(query); + tokenizer._currentState = "DONE"; } // Copyright (c) Microsoft Corporation. -/** - * Authenticates to a service using an API key. - */ -class ApiKeyCredentials { - /** - * @param options - Specifies the options to be provided for auth. Either header or query needs to be provided. - */ - constructor(options) { - if (!options || (options && !options.inHeader && !options.inQuery)) { - throw new Error(`options cannot be null or undefined. Either "inHeader" or "inQuery" property of the options object needs to be provided.`); - } - this.inHeader = options.inHeader; - this.inQuery = options.inQuery; +function createProxyAgent(requestUrl, proxySettings, headers) { + const host = URLBuilder.parse(proxySettings.host).getHost(); + if (!host) { + throw new Error("Expecting a non-empty host in proxy settings."); + } + if (!isValidPort(proxySettings.port)) { + throw new Error("Expecting a valid port number in the range of [0, 65535] in proxy settings."); + } + const tunnelOptions = { + proxy: { + host: host, + port: proxySettings.port, + headers: (headers && headers.rawHeaders()) || {}, + }, + }; + if (proxySettings.username && proxySettings.password) { + tunnelOptions.proxy.proxyAuth = `${proxySettings.username}:${proxySettings.password}`; + } + else if (proxySettings.username) { + tunnelOptions.proxy.proxyAuth = `${proxySettings.username}`; + } + const isRequestHttps = isUrlHttps(requestUrl); + const isProxyHttps = isUrlHttps(proxySettings.host); + const proxyAgent = { + isHttps: isRequestHttps, + agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions), + }; + return proxyAgent; +} +function isUrlHttps(url) { + const urlScheme = URLBuilder.parse(url).getScheme() || ""; + return urlScheme.toLowerCase() === "https"; +} +function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) { + if (isRequestHttps && isProxyHttps) { + return tunnel__namespace.httpsOverHttps(tunnelOptions); + } + else if (isRequestHttps && !isProxyHttps) { + return tunnel__namespace.httpsOverHttp(tunnelOptions); + } + else if (!isRequestHttps && isProxyHttps) { + return tunnel__namespace.httpOverHttps(tunnelOptions); + } + else { + return tunnel__namespace.httpOverHttp(tunnelOptions); } - /** - * Signs a request with the values provided in the inHeader and inQuery parameter. - * - * @param webResource - The WebResourceLike to be signed. - * @returns The signed request object. - */ - signRequest(webResource) { - if (!webResource) { - return Promise.reject(new Error(`webResource cannot be null or undefined and must be of type "object".`)); - } - if (this.inHeader) { - if (!webResource.headers) { - webResource.headers = new HttpHeaders(); +} +function isValidPort(port) { + // any port in 0-65535 range is valid (RFC 793) even though almost all implementations + // will reserve 0 for a specific purpose, and a range of numbers for ephemeral ports + return 0 <= port && port <= 65535; +} + +// Copyright (c) Microsoft Corporation. +const RedactedString = "REDACTED"; +const defaultAllowedHeaderNames = [ + "x-ms-client-request-id", + "x-ms-return-client-request-id", + "x-ms-useragent", + "x-ms-correlation-request-id", + "x-ms-request-id", + "client-request-id", + "ms-cv", + "return-client-request-id", + "traceparent", + "Access-Control-Allow-Credentials", + "Access-Control-Allow-Headers", + "Access-Control-Allow-Methods", + "Access-Control-Allow-Origin", + "Access-Control-Expose-Headers", + "Access-Control-Max-Age", + "Access-Control-Request-Headers", + "Access-Control-Request-Method", + "Origin", + "Accept", + "Accept-Encoding", + "Cache-Control", + "Connection", + "Content-Length", + "Content-Type", + "Date", + "ETag", + "Expires", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "Last-Modified", + "Pragma", + "Request-Id", + "Retry-After", + "Server", + "Transfer-Encoding", + "User-Agent", + "WWW-Authenticate", +]; +const defaultAllowedQueryParameters = ["api-version"]; +class Sanitizer { + constructor({ allowedHeaderNames = [], allowedQueryParameters = [] } = {}) { + allowedHeaderNames = Array.isArray(allowedHeaderNames) + ? defaultAllowedHeaderNames.concat(allowedHeaderNames) + : defaultAllowedHeaderNames; + allowedQueryParameters = Array.isArray(allowedQueryParameters) + ? defaultAllowedQueryParameters.concat(allowedQueryParameters) + : defaultAllowedQueryParameters; + this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); + this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); + } + sanitize(obj) { + const seen = new Set(); + return JSON.stringify(obj, (key, value) => { + // Ensure Errors include their interesting non-enumerable members + if (value instanceof Error) { + return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); } - for (const headerName in this.inHeader) { - webResource.headers.set(headerName, this.inHeader[headerName]); + if (key === "_headersMap") { + return this.sanitizeHeaders(value); } - } - if (this.inQuery) { - if (!webResource.url) { - return Promise.reject(new Error(`url cannot be null in the request object.`)); + else if (key === "url") { + return this.sanitizeUrl(value); } - if (webResource.url.indexOf("?") < 0) { - webResource.url += "?"; + else if (key === "query") { + return this.sanitizeQuery(value); } - for (const key in this.inQuery) { - if (!webResource.url.endsWith("?")) { - webResource.url += "&"; + else if (key === "body") { + // Don't log the request body + return undefined; + } + else if (key === "response") { + // Don't log response again + return undefined; + } + else if (key === "operationSpec") { + // When using sendOperationRequest, the request carries a massive + // field with the autorest spec. No need to log it. + return undefined; + } + else if (Array.isArray(value) || isObject(value)) { + if (seen.has(value)) { + return "[Circular]"; } - webResource.url += `${key}=${this.inQuery[key]}`; + seen.add(value); } - } - return Promise.resolve(webResource); - } -} - -// Copyright (c) Microsoft Corporation. -/** - * A {@link TopicCredentials} object used for Azure Event Grid. - */ -class TopicCredentials extends ApiKeyCredentials { - /** - * Creates a new EventGrid TopicCredentials object. - * - * @param topicKey - The EventGrid topic key - */ - constructor(topicKey) { - if (!topicKey || (topicKey && typeof topicKey !== "string")) { - throw new Error("topicKey cannot be null or undefined and must be of type string."); - } - const options = { - inHeader: { - "aeg-sas-key": topicKey, - }, - }; - super(options); - } -} - -Object.defineProperty(exports, "isTokenCredential", ({ - enumerable: true, - get: function () { return coreAuth.isTokenCredential; } -})); -exports.AccessTokenRefresher = AccessTokenRefresher; -exports.ApiKeyCredentials = ApiKeyCredentials; -exports.BaseRequestPolicy = BaseRequestPolicy; -exports.BasicAuthenticationCredentials = BasicAuthenticationCredentials; -exports.Constants = Constants; -exports.DefaultHttpClient = NodeFetchHttpClient; -exports.ExpiringAccessTokenCache = ExpiringAccessTokenCache; -exports.HttpHeaders = HttpHeaders; -exports.MapperType = MapperType; -exports.RequestPolicyOptions = RequestPolicyOptions; -exports.RestError = RestError; -exports.Serializer = Serializer; -exports.ServiceClient = ServiceClient; -exports.TopicCredentials = TopicCredentials; -exports.URLBuilder = URLBuilder; -exports.URLQuery = URLQuery; -exports.WebResource = WebResource; -exports.XML_ATTRKEY = XML_ATTRKEY; -exports.XML_CHARKEY = XML_CHARKEY; -exports.applyMixins = applyMixins; -exports.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; -exports.createPipelineFromOptions = createPipelineFromOptions; -exports.createSpanFunction = createSpanFunction; -exports.delay = delay; -exports.deserializationPolicy = deserializationPolicy; -exports.deserializeResponseBody = deserializeResponseBody; -exports.disableResponseDecompressionPolicy = disableResponseDecompressionPolicy; -exports.encodeUri = encodeUri; -exports.executePromisesSequentially = executePromisesSequentially; -exports.exponentialRetryPolicy = exponentialRetryPolicy; -exports.flattenResponse = flattenResponse; -exports.generateClientRequestIdPolicy = generateClientRequestIdPolicy; -exports.generateUuid = generateUuid; -exports.getDefaultProxySettings = getDefaultProxySettings; -exports.getDefaultUserAgentValue = getDefaultUserAgentValue; -exports.isDuration = isDuration; -exports.isNode = isNode; -exports.isValidUuid = isValidUuid; -exports.keepAlivePolicy = keepAlivePolicy; -exports.logPolicy = logPolicy; -exports.operationOptionsToRequestOptionsBase = operationOptionsToRequestOptionsBase; -exports.parseXML = parseXML; -exports.promiseToCallback = promiseToCallback; -exports.promiseToServiceCallback = promiseToServiceCallback; -exports.proxyPolicy = proxyPolicy; -exports.redirectPolicy = redirectPolicy; -exports.serializeObject = serializeObject; -exports.signingPolicy = signingPolicy; -exports.stringifyXML = stringifyXML; -exports.stripRequest = stripRequest; -exports.stripResponse = stripResponse; -exports.systemErrorRetryPolicy = systemErrorRetryPolicy; -exports.throttlingRetryPolicy = throttlingRetryPolicy; -exports.tracingPolicy = tracingPolicy; -exports.userAgentPolicy = userAgentPolicy; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 46279: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var CombinedStream = __nccwpck_require__(85443); -var util = __nccwpck_require__(73837); -var path = __nccwpck_require__(71017); -var http = __nccwpck_require__(13685); -var https = __nccwpck_require__(95687); -var parseUrl = (__nccwpck_require__(57310).parse); -var fs = __nccwpck_require__(57147); -var Stream = (__nccwpck_require__(12781).Stream); -var mime = __nccwpck_require__(43583); -var asynckit = __nccwpck_require__(14812); -var populate = __nccwpck_require__(63971); - -// Public API -module.exports = FormData; - -// make it a Stream -util.inherits(FormData, CombinedStream); - -/** - * Create readable "multipart/form-data" streams. - * Can be used to submit forms - * and file uploads to other web applications. - * - * @constructor - * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream - */ -function FormData(options) { - if (!(this instanceof FormData)) { - return new FormData(options); - } - - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; - - CombinedStream.call(this); - - options = options || {}; - for (var option in options) { - this[option] = options[option]; - } -} - -FormData.LINE_BREAK = '\r\n'; -FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; - -FormData.prototype.append = function(field, value, options) { - - options = options || {}; - - // allow filename as single option - if (typeof options == 'string') { - options = {filename: options}; - } - - var append = CombinedStream.prototype.append.bind(this); - - // all that streamy business can't handle numbers - if (typeof value == 'number') { - value = '' + value; - } - - // /~https://github.com/felixge/node-form-data/issues/38 - if (util.isArray(value)) { - // Please convert your array into string - // the way web server expects it - this._error(new Error('Arrays are not supported.')); - return; - } - - var header = this._multiPartHeader(field, value, options); - var footer = this._multiPartFooter(); - - append(header); - append(value); - append(footer); - - // pass along options.knownLength - this._trackLength(header, value, options); -}; - -FormData.prototype._trackLength = function(header, value, options) { - var valueLength = 0; - - // used w/ getLengthSync(), when length is known. - // e.g. for streaming directly from a remote server, - // w/ a known file a size, and not wanting to wait for - // incoming file to finish to get its size. - if (options.knownLength != null) { - valueLength += +options.knownLength; - } else if (Buffer.isBuffer(value)) { - valueLength = value.length; - } else if (typeof value === 'string') { - valueLength = Buffer.byteLength(value); - } - - this._valueLength += valueLength; - - // @check why add CRLF? does this account for custom/multiple CRLFs? - this._overheadLength += - Buffer.byteLength(header) + - FormData.LINE_BREAK.length; - - // empty or either doesn't have path or not an http response or not a stream - if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { - return; - } - - // no need to bother with the length - if (!options.knownLength) { - this._valuesToMeasure.push(value); - } -}; - -FormData.prototype._lengthRetriever = function(value, callback) { - - if (value.hasOwnProperty('fd')) { - - // take read range into a account - // `end` = Infinity –> read file till the end - // - // TODO: Looks like there is bug in Node fs.createReadStream - // it doesn't respect `end` options without `start` options - // Fix it when node fixes it. - // /~https://github.com/joyent/node/issues/7819 - if (value.end != undefined && value.end != Infinity && value.start != undefined) { - - // when end specified - // no need to calculate range - // inclusive, starts with 0 - callback(null, value.end + 1 - (value.start ? value.start : 0)); - - // not that fast snoopy - } else { - // still need to fetch file size from fs - fs.stat(value.path, function(err, stat) { - - var fileSize; - - if (err) { - callback(err); - return; - } - - // update final size based on the range options - fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); + return value; + }, 2); } - - // or http response - } else if (value.hasOwnProperty('httpVersion')) { - callback(null, +value.headers['content-length']); - - // or request stream http://github.com/mikeal/request - } else if (value.hasOwnProperty('httpModule')) { - // wait till response come back - value.on('response', function(response) { - value.pause(); - callback(null, +response.headers['content-length']); - }); - value.resume(); - - // something else - } else { - callback('Unknown stream'); - } -}; - -FormData.prototype._multiPartHeader = function(field, value, options) { - // custom header specified (as string)? - // it becomes responsible for boundary - // (e.g. to handle extra CRLFs on .NET servers) - if (typeof options.header == 'string') { - return options.header; - } - - var contentDisposition = this._getContentDisposition(value, options); - var contentType = this._getContentType(value, options); - - var contents = ''; - var headers = { - // add custom disposition as third element or keep it two elements if not - 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), - // if no content type. allow it to be empty array - 'Content-Type': [].concat(contentType || []) - }; - - // allow custom headers. - if (typeof options.header == 'object') { - populate(headers, options.header); - } - - var header; - for (var prop in headers) { - if (!headers.hasOwnProperty(prop)) continue; - header = headers[prop]; - - // skip nullish headers. - if (header == null) { - continue; + sanitizeHeaders(value) { + return this.sanitizeObject(value, this.allowedHeaderNames, (v, k) => v[k].value); } - - // convert all headers to arrays. - if (!Array.isArray(header)) { - header = [header]; + sanitizeQuery(value) { + return this.sanitizeObject(value, this.allowedQueryParameters, (v, k) => v[k]); } - - // add non-empty headers. - if (header.length) { - contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; + sanitizeObject(value, allowedKeys, accessor) { + if (typeof value !== "object" || value === null) { + return value; + } + const sanitized = {}; + for (const k of Object.keys(value)) { + if (allowedKeys.has(k.toLowerCase())) { + sanitized[k] = accessor(value, k); + } + else { + sanitized[k] = RedactedString; + } + } + return sanitized; } - } - - return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; -}; - -FormData.prototype._getContentDisposition = function(value, options) { - - var filename - , contentDisposition - ; - - if (typeof options.filepath === 'string') { - // custom filepath for relative paths - filename = path.normalize(options.filepath).replace(/\\/g, '/'); - } else if (options.filename || value.name || value.path) { - // custom filename take precedence - // formidable and the browser add a name property - // fs- and request- streams have path property - filename = path.basename(options.filename || value.name || value.path); - } else if (value.readable && value.hasOwnProperty('httpVersion')) { - // or try http response - filename = path.basename(value.client._httpMessage.path || ''); - } - - if (filename) { - contentDisposition = 'filename="' + filename + '"'; - } - - return contentDisposition; -}; - -FormData.prototype._getContentType = function(value, options) { - - // use custom content-type above all - var contentType = options.contentType; - - // or try `name` from formidable, browser - if (!contentType && value.name) { - contentType = mime.lookup(value.name); - } - - // or try `path` from fs-, request- streams - if (!contentType && value.path) { - contentType = mime.lookup(value.path); - } - - // or if it's http-reponse - if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { - contentType = value.headers['content-type']; - } - - // or guess it from the filepath or filename - if (!contentType && (options.filepath || options.filename)) { - contentType = mime.lookup(options.filepath || options.filename); - } - - // fallback to the default content type if `value` is not simple value - if (!contentType && typeof value == 'object') { - contentType = FormData.DEFAULT_CONTENT_TYPE; - } - - return contentType; -}; - -FormData.prototype._multiPartFooter = function() { - return function(next) { - var footer = FormData.LINE_BREAK; - - var lastPart = (this._streams.length === 0); - if (lastPart) { - footer += this._lastBoundary(); + sanitizeUrl(value) { + if (typeof value !== "string" || value === null) { + return value; + } + const urlBuilder = URLBuilder.parse(value); + const queryString = urlBuilder.getQuery(); + if (!queryString) { + return value; + } + const query = URLQuery.parse(queryString); + for (const k of query.keys()) { + if (!this.allowedQueryParameters.has(k.toLowerCase())) { + query.set(k, RedactedString); + } + } + urlBuilder.setQuery(query.toString()); + return urlBuilder.toString(); } +} - next(footer); - }.bind(this); -}; - -FormData.prototype._lastBoundary = function() { - return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; -}; - -FormData.prototype.getHeaders = function(userHeaders) { - var header; - var formHeaders = { - 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() - }; +// Copyright (c) Microsoft Corporation. +const custom = util.inspect.custom; - for (header in userHeaders) { - if (userHeaders.hasOwnProperty(header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; +// Copyright (c) Microsoft Corporation. +const errorSanitizer = new Sanitizer(); +/** + * An error resulting from an HTTP request to a service endpoint. + */ +class RestError extends Error { + constructor(message, code, statusCode, request, response) { + super(message); + this.name = "RestError"; + this.code = code; + this.statusCode = statusCode; + this.request = request; + this.response = response; + Object.setPrototypeOf(this, RestError.prototype); } - } - - return formHeaders; -}; - -FormData.prototype.setBoundary = function(boundary) { - this._boundary = boundary; -}; - -FormData.prototype.getBoundary = function() { - if (!this._boundary) { - this._generateBoundary(); - } - - return this._boundary; -}; - -FormData.prototype.getBuffer = function() { - var dataBuffer = new Buffer.alloc( 0 ); - var boundary = this.getBoundary(); - - // Create the form content. Add Line breaks to the end of data. - for (var i = 0, len = this._streams.length; i < len; i++) { - if (typeof this._streams[i] !== 'function') { - - // Add content to the buffer. - if(Buffer.isBuffer(this._streams[i])) { - dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); - }else { - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); - } - - // Add break after content. - if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); - } + /** + * Logging method for util.inspect in Node + */ + [custom]() { + return `RestError: ${this.message} \n ${errorSanitizer.sanitize(this)}`; } - } - - // Add the footer and return the Buffer object. - return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); -}; - -FormData.prototype._generateBoundary = function() { - // This generates a 50 character boundary similar to those used by Firefox. - // They are optimized for boyer-moore parsing. - var boundary = '--------------------------'; - for (var i = 0; i < 24; i++) { - boundary += Math.floor(Math.random() * 10).toString(16); - } - - this._boundary = boundary; -}; - -// Note: getLengthSync DOESN'T calculate streams length -// As workaround one can calculate file size manually -// and add it as knownLength option -FormData.prototype.getLengthSync = function() { - var knownLength = this._overheadLength + this._valueLength; - - // Don't get confused, there are 3 "internal" streams for each keyval pair - // so it basically checks if there is any value added to the form - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } - - // /~https://github.com/form-data/form-data/issues/40 - if (!this.hasKnownLength()) { - // Some async length retrievers are present - // therefore synchronous length calculation is false. - // Please use getLength(callback) to get proper length - this._error(new Error('Cannot calculate proper length in synchronous way.')); - } - - return knownLength; -}; - -// Public API to check if length of added values is known -// /~https://github.com/form-data/form-data/issues/196 -// /~https://github.com/form-data/form-data/issues/262 -FormData.prototype.hasKnownLength = function() { - var hasKnownLength = true; - - if (this._valuesToMeasure.length) { - hasKnownLength = false; - } - - return hasKnownLength; -}; - -FormData.prototype.getLength = function(cb) { - var knownLength = this._overheadLength + this._valueLength; - - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } +} +/** + * A constant string to identify errors that may arise when making an HTTP request that indicates an issue with the transport layer (e.g. the hostname of the URL cannot be resolved via DNS.) + */ +RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; +/** + * A constant string to identify errors that may arise from parsing an incoming HTTP response. Usually indicates a malformed HTTP body, such as an encoded JSON payload that is incomplete. + */ +RestError.PARSE_ERROR = "PARSE_ERROR"; - if (!this._valuesToMeasure.length) { - process.nextTick(cb.bind(this, null, knownLength)); - return; - } +// Copyright (c) Microsoft Corporation. +const logger = logger$1.createClientLogger("core-http"); - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { - if (err) { - cb(err); - return; +// Copyright (c) Microsoft Corporation. +function getCachedAgent(isHttps, agentCache) { + return isHttps ? agentCache.httpsAgent : agentCache.httpAgent; +} +class ReportTransform extends stream.Transform { + constructor(progressCallback) { + super(); + this.progressCallback = progressCallback; + this.loadedBytes = 0; } - - values.forEach(function(length) { - knownLength += length; + _transform(chunk, _encoding, callback) { + this.push(chunk); + this.loadedBytes += chunk.length; + this.progressCallback({ loadedBytes: this.loadedBytes }); + callback(undefined); + } +} +function isReadableStream(body) { + return body && typeof body.pipe === "function"; +} +function isStreamComplete(stream, aborter) { + return new Promise((resolve) => { + stream.once("close", () => { + aborter === null || aborter === void 0 ? void 0 : aborter.abort(); + resolve(); + }); + stream.once("end", resolve); + stream.once("error", resolve); }); - - cb(null, knownLength); - }); -}; - -FormData.prototype.submit = function(params, cb) { - var request - , options - , defaults = {method: 'post'} - ; - - // parse provided url if it's string - // or treat it as options object - if (typeof params == 'string') { - - params = parseUrl(params); - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults); - - // use custom params - } else { - - options = populate(params, defaults); - // if no port provided use default one - if (!options.port) { - options.port = options.protocol == 'https:' ? 443 : 80; +} +/** + * Transforms a set of headers into the key/value pair defined by {@link HttpHeadersLike} + */ +function parseHeaders(headers) { + const httpHeaders = new HttpHeaders(); + headers.forEach((value, key) => { + httpHeaders.set(key, value); + }); + return httpHeaders; +} +/** + * An HTTP client that uses `node-fetch`. + */ +class NodeFetchHttpClient { + constructor() { + // a mapping of proxy settings string `${host}:${port}:${username}:${password}` to agent + this.proxyAgentMap = new Map(); + this.keepAliveAgents = {}; + this.cookieJar = new tough__namespace.CookieJar(undefined, { looseMode: true }); } - } - - // put that good code in getHeaders to some use - options.headers = this.getHeaders(params.headers); + /** + * Provides minimum viable error handling and the logic that executes the abstract methods. + * @param httpRequest - Object representing the outgoing HTTP request. + * @returns An object representing the incoming HTTP response. + */ + async sendRequest(httpRequest) { + var _a; + if (!httpRequest && typeof httpRequest !== "object") { + throw new Error("'httpRequest' (WebResourceLike) cannot be null or undefined and must be of type object."); + } + const abortController$1 = new abortController.AbortController(); + let abortListener; + if (httpRequest.abortSignal) { + if (httpRequest.abortSignal.aborted) { + throw new abortController.AbortError("The operation was aborted."); + } + abortListener = (event) => { + if (event.type === "abort") { + abortController$1.abort(); + } + }; + httpRequest.abortSignal.addEventListener("abort", abortListener); + } + if (httpRequest.timeout) { + setTimeout(() => { + abortController$1.abort(); + }, httpRequest.timeout); + } + if (httpRequest.formData) { + const formData = httpRequest.formData; + const requestForm = new FormData__default["default"](); + const appendFormValue = (key, value) => { + // value function probably returns a stream so we can provide a fresh stream on each retry + if (typeof value === "function") { + value = value(); + } + if (value && + Object.prototype.hasOwnProperty.call(value, "value") && + Object.prototype.hasOwnProperty.call(value, "options")) { + requestForm.append(key, value.value, value.options); + } + else { + requestForm.append(key, value); + } + }; + for (const formKey of Object.keys(formData)) { + const formValue = formData[formKey]; + if (Array.isArray(formValue)) { + for (let j = 0; j < formValue.length; j++) { + appendFormValue(formKey, formValue[j]); + } + } + else { + appendFormValue(formKey, formValue); + } + } + httpRequest.body = requestForm; + httpRequest.formData = undefined; + const contentType = httpRequest.headers.get("Content-Type"); + if (contentType && contentType.indexOf("multipart/form-data") !== -1) { + if (typeof requestForm.getBoundary === "function") { + httpRequest.headers.set("Content-Type", `multipart/form-data; boundary=${requestForm.getBoundary()}`); + } + else { + // browser will automatically apply a suitable content-type header + httpRequest.headers.remove("Content-Type"); + } + } + } + let body = httpRequest.body + ? typeof httpRequest.body === "function" + ? httpRequest.body() + : httpRequest.body + : undefined; + if (httpRequest.onUploadProgress && httpRequest.body) { + const onUploadProgress = httpRequest.onUploadProgress; + const uploadReportStream = new ReportTransform(onUploadProgress); + if (isReadableStream(body)) { + body.pipe(uploadReportStream); + } + else { + uploadReportStream.end(body); + } + body = uploadReportStream; + } + const platformSpecificRequestInit = await this.prepareRequest(httpRequest); + const requestInit = Object.assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController$1.signal, redirect: "manual" }, platformSpecificRequestInit); + let operationResponse; + try { + const response = await this.fetch(httpRequest.url, requestInit); + const headers = parseHeaders(response.headers); + const streaming = ((_a = httpRequest.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(response.status)) || + httpRequest.streamResponseBody; + operationResponse = { + headers: headers, + request: httpRequest, + status: response.status, + readableStreamBody: streaming + ? response.body + : undefined, + bodyAsText: !streaming ? await response.text() : undefined, + }; + const onDownloadProgress = httpRequest.onDownloadProgress; + if (onDownloadProgress) { + const responseBody = response.body || undefined; + if (isReadableStream(responseBody)) { + const downloadReportStream = new ReportTransform(onDownloadProgress); + responseBody.pipe(downloadReportStream); + operationResponse.readableStreamBody = downloadReportStream; + } + else { + const length = parseInt(headers.get("Content-Length")) || undefined; + if (length) { + // Calling callback for non-stream response for consistency with browser + onDownloadProgress({ loadedBytes: length }); + } + } + } + await this.processRequest(operationResponse); + return operationResponse; + } + catch (error) { + const fetchError = error; + if (fetchError.code === "ENOTFOUND") { + throw new RestError(fetchError.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); + } + else if (fetchError.type === "aborted") { + throw new abortController.AbortError("The operation was aborted."); + } + throw fetchError; + } + finally { + // clean up event listener + if (httpRequest.abortSignal && abortListener) { + let uploadStreamDone = Promise.resolve(); + if (isReadableStream(body)) { + uploadStreamDone = isStreamComplete(body); + } + let downloadStreamDone = Promise.resolve(); + if (isReadableStream(operationResponse === null || operationResponse === void 0 ? void 0 : operationResponse.readableStreamBody)) { + downloadStreamDone = isStreamComplete(operationResponse.readableStreamBody, abortController$1); + } + Promise.all([uploadStreamDone, downloadStreamDone]) + .then(() => { + var _a; + (_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener); + return; + }) + .catch((e) => { + logger.warning("Error when cleaning up abortListener on httpRequest", e); + }); + } + } + } + getOrCreateAgent(httpRequest) { + var _a; + const isHttps = isUrlHttps(httpRequest.url); + // At the moment, proxy settings and keepAlive are mutually + // exclusive because the 'tunnel' library currently lacks the + // ability to create a proxy with keepAlive turned on. + if (httpRequest.proxySettings) { + const { host, port, username, password } = httpRequest.proxySettings; + const key = `${host}:${port}:${username}:${password}`; + const proxyAgents = (_a = this.proxyAgentMap.get(key)) !== null && _a !== void 0 ? _a : {}; + let agent = getCachedAgent(isHttps, proxyAgents); + if (agent) { + return agent; + } + const tunnel = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers); + agent = tunnel.agent; + if (tunnel.isHttps) { + proxyAgents.httpsAgent = tunnel.agent; + } + else { + proxyAgents.httpAgent = tunnel.agent; + } + this.proxyAgentMap.set(key, proxyAgents); + return agent; + } + else if (httpRequest.keepAlive) { + let agent = getCachedAgent(isHttps, this.keepAliveAgents); + if (agent) { + return agent; + } + const agentOptions = { + keepAlive: httpRequest.keepAlive, + }; + if (isHttps) { + agent = this.keepAliveAgents.httpsAgent = new https__namespace.Agent(agentOptions); + } + else { + agent = this.keepAliveAgents.httpAgent = new http__namespace.Agent(agentOptions); + } + return agent; + } + else { + return isHttps ? https__namespace.globalAgent : http__namespace.globalAgent; + } + } + /** + * Uses `node-fetch` to perform the request. + */ + // eslint-disable-next-line @azure/azure-sdk/ts-apisurface-standardized-verbs + async fetch(input, init) { + return node_fetch__default["default"](input, init); + } + /** + * Prepares a request based on the provided web resource. + */ + async prepareRequest(httpRequest) { + const requestInit = {}; + if (this.cookieJar && !httpRequest.headers.get("Cookie")) { + const cookieString = await new Promise((resolve, reject) => { + this.cookieJar.getCookieString(httpRequest.url, (err, cookie) => { + if (err) { + reject(err); + } + else { + resolve(cookie); + } + }); + }); + httpRequest.headers.set("Cookie", cookieString); + } + // Set the http(s) agent + requestInit.agent = this.getOrCreateAgent(httpRequest); + requestInit.compress = httpRequest.decompressResponse; + return requestInit; + } + /** + * Process an HTTP response. Handles persisting a cookie for subsequent requests if the response has a "Set-Cookie" header. + */ + async processRequest(operationResponse) { + if (this.cookieJar) { + const setCookieHeader = operationResponse.headers.get("Set-Cookie"); + if (setCookieHeader !== undefined) { + await new Promise((resolve, reject) => { + this.cookieJar.setCookie(setCookieHeader, operationResponse.request.url, { ignoreError: true }, (err) => { + if (err) { + reject(err); + } + else { + resolve(); + } + }); + }); + } + } + } +} - // https if specified, fallback to http in any other case - if (options.protocol == 'https:') { - request = https.request(options); - } else { - request = http.request(options); - } +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * The different levels of logs that can be used with the HttpPipelineLogger. + */ +exports.HttpPipelineLogLevel = void 0; +(function (HttpPipelineLogLevel) { + /** + * A log level that indicates that no logs will be logged. + */ + HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF"; + /** + * An error log. + */ + HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR"; + /** + * A warning log. + */ + HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING"; + /** + * An information log. + */ + HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO"; +})(exports.HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = {})); - // get content length and fire away - this.getLength(function(err, length) { - if (err && err !== 'Unknown stream') { - this._error(err); - return; +// Copyright (c) Microsoft Corporation. +/** + * Converts an OperationOptions to a RequestOptionsBase + * + * @param opts - OperationOptions object to convert to RequestOptionsBase + */ +function operationOptionsToRequestOptionsBase(opts) { + const { requestOptions, tracingOptions } = opts, additionalOptions = tslib.__rest(opts, ["requestOptions", "tracingOptions"]); + let result = additionalOptions; + if (requestOptions) { + result = Object.assign(Object.assign({}, result), requestOptions); } - - // add content length - if (length) { - request.setHeader('Content-Length', length); + if (tracingOptions) { + result.tracingContext = tracingOptions.tracingContext; + // By passing spanOptions if they exist at runtime, we're backwards compatible with @azure/core-tracing@preview.13 and earlier. + result.spanOptions = tracingOptions === null || tracingOptions === void 0 ? void 0 : tracingOptions.spanOptions; } + return result; +} - this.pipe(request); - if (cb) { - var onResponse; - - var callback = function (error, responce) { - request.removeListener('error', callback); - request.removeListener('response', onResponse); - - return cb.call(this, error, responce); - }; - - onResponse = callback.bind(this, null); - - request.on('error', callback); - request.on('response', onResponse); +// Copyright (c) Microsoft Corporation. +/** + * The base class from which all request policies derive. + */ +class BaseRequestPolicy { + /** + * The main method to implement that manipulates a request/response. + */ + constructor( + /** + * The next policy in the pipeline. Each policy is responsible for executing the next one if the request is to continue through the pipeline. + */ + _nextPolicy, + /** + * The options that can be passed to a given request policy. + */ + _options) { + this._nextPolicy = _nextPolicy; + this._options = _options; } - }.bind(this)); - - return request; -}; + /** + * Get whether or not a log with the provided log level should be logged. + * @param logLevel - The log level of the log that will be logged. + * @returns Whether or not a log with the provided log level should be logged. + */ + shouldLog(logLevel) { + return this._options.shouldLog(logLevel); + } + /** + * Attempt to log the provided message to the provided logger. If no logger was provided or if + * the log level does not meat the logger's threshold, then nothing will be logged. + * @param logLevel - The log level of this log. + * @param message - The message of this log. + */ + log(logLevel, message) { + this._options.log(logLevel, message); + } +} +/** + * Optional properties that can be used when creating a RequestPolicy. + */ +class RequestPolicyOptions { + constructor(_logger) { + this._logger = _logger; + } + /** + * Get whether or not a log with the provided log level should be logged. + * @param logLevel - The log level of the log that will be logged. + * @returns Whether or not a log with the provided log level should be logged. + */ + shouldLog(logLevel) { + return (!!this._logger && + logLevel !== exports.HttpPipelineLogLevel.OFF && + logLevel <= this._logger.minimumLogLevel); + } + /** + * Attempt to log the provided message to the provided logger. If no logger was provided or if + * the log level does not meet the logger's threshold, then nothing will be logged. + * @param logLevel - The log level of this log. + * @param message - The message of this log. + */ + log(logLevel, message) { + if (this._logger && this.shouldLog(logLevel)) { + this._logger.log(logLevel, message); + } + } +} -FormData.prototype._error = function(err) { - if (!this.error) { - this.error = err; - this.pause(); - this.emit('error', err); - } +// Copyright (c) Microsoft Corporation. +// Note: The reason we re-define all of the xml2js default settings (version 2.0) here is because the default settings object exposed +// by the xm2js library is mutable. See /~https://github.com/Leonidas-from-XIV/node-xml2js/issues/536 +// By creating a new copy of the settings each time we instantiate the parser, +// we are safeguarding against the possibility of the default settings being mutated elsewhere unintentionally. +const xml2jsDefaultOptionsV2 = { + explicitCharkey: false, + trim: false, + normalize: false, + normalizeTags: false, + attrkey: XML_ATTRKEY, + explicitArray: true, + ignoreAttrs: false, + mergeAttrs: false, + explicitRoot: true, + validator: undefined, + xmlns: false, + explicitChildren: false, + preserveChildrenOrder: false, + childkey: "$$", + charsAsChildren: false, + includeWhiteChars: false, + async: false, + strict: true, + attrNameProcessors: undefined, + attrValueProcessors: undefined, + tagNameProcessors: undefined, + valueProcessors: undefined, + rootName: "root", + xmldec: { + version: "1.0", + encoding: "UTF-8", + standalone: true, + }, + doctype: undefined, + renderOpts: { + pretty: true, + indent: " ", + newline: "\n", + }, + headless: false, + chunkSize: 10000, + emptyTag: "", + cdata: false, }; - -FormData.prototype.toString = function () { - return '[object FormData]'; +// The xml2js settings for general XML parsing operations. +const xml2jsParserSettings = Object.assign({}, xml2jsDefaultOptionsV2); +xml2jsParserSettings.explicitArray = false; +// The xml2js settings for general XML building operations. +const xml2jsBuilderSettings = Object.assign({}, xml2jsDefaultOptionsV2); +xml2jsBuilderSettings.explicitArray = false; +xml2jsBuilderSettings.renderOpts = { + pretty: false, }; +/** + * Converts given JSON object to XML string + * @param obj - JSON object to be converted into XML string + * @param opts - Options that govern the parsing of given JSON object + */ +function stringifyXML(obj, opts = {}) { + var _a; + xml2jsBuilderSettings.rootName = opts.rootName; + xml2jsBuilderSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; + const builder = new xml2js__namespace.Builder(xml2jsBuilderSettings); + return builder.buildObject(obj); +} +/** + * Converts given XML string into JSON + * @param str - String containing the XML content to be parsed into JSON + * @param opts - Options that govern the parsing of given xml string + */ +function parseXML(str, opts = {}) { + var _a; + xml2jsParserSettings.explicitRoot = !!opts.includeRoot; + xml2jsParserSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; + const xmlParser = new xml2js__namespace.Parser(xml2jsParserSettings); + return new Promise((resolve, reject) => { + if (!str) { + reject(new Error("Document is empty")); + } + else { + xmlParser.parseString(str, (err, res) => { + if (err) { + reject(err); + } + else { + resolve(res); + } + }); + } + }); +} - -/***/ }), - -/***/ 63971: -/***/ ((module) => { - -// populates missing values -module.exports = function(dst, src) { - - Object.keys(src).forEach(function(prop) - { - dst[prop] = dst[prop] || src[prop]; - }); - - return dst; +// Copyright (c) Microsoft Corporation. +/** + * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they + * pass through the HTTP pipeline. + */ +function deserializationPolicy(deserializationContentTypes, parsingOptions) { + return { + create: (nextPolicy, options) => { + return new DeserializationPolicy(nextPolicy, options, deserializationContentTypes, parsingOptions); + }, + }; +} +const defaultJsonContentTypes = ["application/json", "text/json"]; +const defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; +const DefaultDeserializationOptions = { + expectedContentTypes: { + json: defaultJsonContentTypes, + xml: defaultXmlContentTypes, + }, }; - - -/***/ }), - -/***/ 18165: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -/*! - * Copyright (c) 2015-2020, 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 RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the + * HTTP pipeline. */ +class DeserializationPolicy extends BaseRequestPolicy { + constructor(nextPolicy, requestPolicyOptions, deserializationContentTypes, parsingOptions = {}) { + var _a; + super(nextPolicy, requestPolicyOptions); + this.jsonContentTypes = + (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes; + this.xmlContentTypes = + (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes; + this.xmlCharKey = (_a = parsingOptions.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; + } + async sendRequest(request) { + return this._nextPolicy.sendRequest(request).then((response) => deserializeResponseBody(this.jsonContentTypes, this.xmlContentTypes, response, { + xmlCharKey: this.xmlCharKey, + })); + } +} +function getOperationResponse(parsedResponse) { + let result; + const request = parsedResponse.request; + const operationSpec = request.operationSpec; + if (operationSpec) { + const operationResponseGetter = request.operationResponseGetter; + if (!operationResponseGetter) { + result = operationSpec.responses[parsedResponse.status]; + } + else { + result = operationResponseGetter(operationSpec, parsedResponse); + } + } + return result; +} +function shouldDeserializeResponse(parsedResponse) { + const shouldDeserialize = parsedResponse.request.shouldDeserialize; + let result; + if (shouldDeserialize === undefined) { + result = true; + } + else if (typeof shouldDeserialize === "boolean") { + result = shouldDeserialize; + } + else { + result = shouldDeserialize(parsedResponse); + } + return result; +} +/** + * Given a particular set of content types to parse as either JSON or XML, consumes the HTTP response to produce the result object defined by the request's {@link OperationSpec}. + * @param jsonContentTypes - Response content types to parse the body as JSON. + * @param xmlContentTypes - Response content types to parse the body as XML. + * @param response - HTTP Response from the pipeline. + * @param options - Options to the serializer, mostly for configuring the XML parser if needed. + * @returns A parsed {@link HttpOperationResponse} object that can be returned by the {@link ServiceClient}. + */ +function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options = {}) { + var _a, _b, _c; + const updatedOptions = { + rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", + includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, + xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, + }; + return parse(jsonContentTypes, xmlContentTypes, response, updatedOptions).then((parsedResponse) => { + if (!shouldDeserializeResponse(parsedResponse)) { + return parsedResponse; + } + const operationSpec = parsedResponse.request.operationSpec; + if (!operationSpec || !operationSpec.responses) { + return parsedResponse; + } + const responseSpec = getOperationResponse(parsedResponse); + const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec); + if (error) { + throw error; + } + else if (shouldReturnResponse) { + return parsedResponse; + } + // An operation response spec does exist for current status code, so + // use it to deserialize the response. + if (responseSpec) { + if (responseSpec.bodyMapper) { + let valueToDeserialize = parsedResponse.parsedBody; + if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) { + valueToDeserialize = + typeof valueToDeserialize === "object" + ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] + : []; + } + try { + parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); + } + catch (innerError) { + const restError = new RestError(`Error ${innerError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); + throw restError; + } + } + else if (operationSpec.httpMethod === "HEAD") { + // head methods never have a body, but we return a boolean to indicate presence/absence of the resource + parsedResponse.parsedBody = response.status >= 200 && response.status < 300; + } + if (responseSpec.headersMapper) { + parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJson(), "operationRes.parsedHeaders", options); + } + } + return parsedResponse; + }); +} +function isOperationSpecEmpty(operationSpec) { + const expectedStatusCodes = Object.keys(operationSpec.responses); + return (expectedStatusCodes.length === 0 || + (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); +} +function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { + var _a; + const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; + const isExpectedStatusCode = isOperationSpecEmpty(operationSpec) + ? isSuccessByStatus + : !!responseSpec; + if (isExpectedStatusCode) { + if (responseSpec) { + if (!responseSpec.isError) { + return { error: null, shouldReturnResponse: false }; + } + } + else { + return { error: null, shouldReturnResponse: false }; + } + } + const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; + const streaming = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) || + parsedResponse.request.streamResponseBody; + const initialErrorMessage = streaming + ? `Unexpected status code: ${parsedResponse.status}` + : parsedResponse.bodyAsText; + const error = new RestError(initialErrorMessage, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); + // If the item failed but there's no error spec or default spec to deserialize the error, + // we should fail so we just throw the parsed response + if (!errorResponseSpec) { + throw error; + } + const defaultBodyMapper = errorResponseSpec.bodyMapper; + const defaultHeadersMapper = errorResponseSpec.headersMapper; + try { + // If error response has a body, try to deserialize it using default body mapper. + // Then try to extract error code & message from it + if (parsedResponse.parsedBody) { + const parsedBody = parsedResponse.parsedBody; + let parsedError; + if (defaultBodyMapper) { + let valueToDeserialize = parsedBody; + if (operationSpec.isXML && defaultBodyMapper.type.name === MapperType.Sequence) { + valueToDeserialize = + typeof parsedBody === "object" ? parsedBody[defaultBodyMapper.xmlElementName] : []; + } + parsedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody"); + } + const internalError = parsedBody.error || parsedError || parsedBody; + error.code = internalError.code; + if (internalError.message) { + error.message = internalError.message; + } + if (defaultBodyMapper) { + error.response.parsedBody = parsedError; + } + } + // If error response has headers, try to deserialize it using default header mapper + if (parsedResponse.headers && defaultHeadersMapper) { + error.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJson(), "operationRes.parsedHeaders"); + } + } + catch (defaultError) { + error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`; + } + return { error, shouldReturnResponse: false }; +} +function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { + var _a; + const errorHandler = (err) => { + const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`; + const errCode = err.code || RestError.PARSE_ERROR; + const e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse); + return Promise.reject(e); + }; + const streaming = ((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) || + operationResponse.request.streamResponseBody; + if (!streaming && operationResponse.bodyAsText) { + const text = operationResponse.bodyAsText; + const contentType = operationResponse.headers.get("Content-Type") || ""; + const contentComponents = !contentType + ? [] + : contentType.split(";").map((component) => component.toLowerCase()); + if (contentComponents.length === 0 || + contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) { + return new Promise((resolve) => { + operationResponse.parsedBody = JSON.parse(text); + resolve(operationResponse); + }).catch(errorHandler); + } + else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) { + return parseXML(text, opts) + .then((body) => { + operationResponse.parsedBody = body; + return operationResponse; + }) + .catch(errorHandler); + } + } + return Promise.resolve(operationResponse); +} -const punycode = __nccwpck_require__(99540); -const urlParse = __nccwpck_require__(25682); -const pubsuffix = __nccwpck_require__(78292); -const Store = (__nccwpck_require__(17707)/* .Store */ .y); -const MemoryCookieStore = (__nccwpck_require__(96738)/* .MemoryCookieStore */ .m); -const pathMatch = (__nccwpck_require__(60807)/* .pathMatch */ .U); -const validators = __nccwpck_require__(71598); -const VERSION = __nccwpck_require__(78742); -const { fromCallback } = __nccwpck_require__(9046); -const { getCustomInspectSymbol } = __nccwpck_require__(9375); - -// 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 +// Copyright (c) Microsoft Corporation. +/** + * By default, HTTP connections are maintained for future requests. + */ +const DefaultKeepAliveOptions = { + enable: true, }; - -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) { - validators.validate(validators.isNonEmptyString(value), value); - const context = String(value).toLowerCase(); - if (context === "none" || context === "lax" || context === "strict") { - return context; - } else { - return null; - } +/** + * Creates a policy that controls whether HTTP connections are maintained on future requests. + * @param keepAliveOptions - Keep alive options. By default, HTTP connections are maintained for future requests. + * @returns An instance of the {@link KeepAlivePolicy} + */ +function keepAlivePolicy(keepAliveOptions) { + return { + create: (nextPolicy, options) => { + return new KeepAlivePolicy(nextPolicy, options, keepAliveOptions || DefaultKeepAliveOptions); + }, + }; +} +/** + * KeepAlivePolicy is a policy used to control keep alive settings for every request. + */ +class KeepAlivePolicy extends BaseRequestPolicy { + /** + * Creates an instance of KeepAlivePolicy. + * + * @param nextPolicy - + * @param options - + * @param keepAliveOptions - + */ + constructor(nextPolicy, options, keepAliveOptions) { + super(nextPolicy, options); + this.keepAliveOptions = keepAliveOptions; + } + /** + * Sends out request. + * + * @param request - + * @returns + */ + async sendRequest(request) { + request.keepAlive = this.keepAliveOptions.enable; + return this._nextPolicy.sendRequest(request); + } } -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 -const 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}|:)))$)/; -const IP_V6_REGEX = ` -\\[?(?: -(?:[a-fA-F\\d]{1,4}:){7}(?:[a-fA-F\\d]{1,4}|:)| -(?:[a-fA-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-fA-F\\d]{1,4}|:)| -(?:[a-fA-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-fA-F\\d]{1,4}){1,2}|:)| -(?:[a-fA-F\\d]{1,4}:){4}(?:(?::[a-fA-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-fA-F\\d]{1,4}){1,3}|:)| -(?:[a-fA-F\\d]{1,4}:){3}(?:(?::[a-fA-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-fA-F\\d]{1,4}){1,4}|:)| -(?:[a-fA-F\\d]{1,4}:){2}(?:(?::[a-fA-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-fA-F\\d]{1,4}){1,5}|:)| -(?:[a-fA-F\\d]{1,4}:){1}(?:(?::[a-fA-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-fA-F\\d]{1,4}){1,6}|:)| -(?::(?:(?::[a-fA-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-fA-F\\d]{1,4}){1,7}|:)) -)(?:%[0-9a-zA-Z]{1,})?\\]? -` - .replace(/\s*\/\/.*$/gm, "") - .replace(/\n/g, "") - .trim(); -const IP_V6_REGEX_OBJECT = new RegExp(`^${IP_V6_REGEX}$`); +// Copyright (c) Microsoft Corporation. +/** + * Methods that are allowed to follow redirects 301 and 302 + */ +const allowedRedirect = ["GET", "HEAD"]; +const DefaultRedirectOptions = { + handleRedirects: true, + maxRetries: 20, +}; +/** + * Creates a redirect policy, which sends a repeats the request to a new destination if a response arrives with a "location" header, and a status code between 300 and 307. + * @param maximumRetries - Maximum number of redirects to follow. + * @returns An instance of the {@link RedirectPolicy} + */ +function redirectPolicy(maximumRetries = 20) { + return { + create: (nextPolicy, options) => { + return new RedirectPolicy(nextPolicy, options, maximumRetries); + }, + }; +} +/** + * Resends the request to a new destination if a response arrives with a "location" header, and a status code between 300 and 307. + */ +class RedirectPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, maxRetries = 20) { + super(nextPolicy, options); + this.maxRetries = maxRetries; + } + sendRequest(request) { + return this._nextPolicy + .sendRequest(request) + .then((response) => handleRedirect(this, response, 0)); + } +} +function handleRedirect(policy, response, currentRetries) { + const { request, status } = response; + const locationHeader = response.headers.get("location"); + if (locationHeader && + (status === 300 || + (status === 301 && allowedRedirect.includes(request.method)) || + (status === 302 && allowedRedirect.includes(request.method)) || + (status === 303 && request.method === "POST") || + status === 307) && + (!policy.maxRetries || currentRetries < policy.maxRetries)) { + const builder = URLBuilder.parse(request.url); + builder.setPath(locationHeader); + request.url = builder.toString(); + // POST request with Status code 303 should be converted into a + // redirected GET request if the redirect url is present in the location header + if (status === 303) { + request.method = "GET"; + delete request.body; + } + return policy._nextPolicy + .sendRequest(request) + .then((res) => handleRedirect(policy, res, currentRetries + 1)); + } + return Promise.resolve(response); +} -/* - * Parses a Natural number (i.e., non-negative integer) with either the - * *DIGIT ( non-digit *OCTET ) - * or - * *DIGIT - * grammar (RFC6265 S5.1.1). +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +const DEFAULT_CLIENT_RETRY_COUNT = 3; +// intervals are in ms +const DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30; +const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90; +const DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3; +function isNumber(n) { + return typeof n === "number"; +} +/** + * @internal + * Determines if the operation should be retried. * - * The "trailingOK" boolean controls if the grammar accepts a - * "( non-digit *OCTET )" trailer. + * @param retryLimit - Specifies the max number of retries. + * @param predicate - Initial chekck on whether to retry based on given responses or errors + * @param retryData - The retry data. + * @returns True if the operation qualifies for a retry; false otherwise. */ -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; +function shouldRetry(retryLimit, predicate, retryData, response, error) { + if (!predicate(response, error)) { + return false; } - 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); + return retryData.retryCount < retryLimit; } - -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; +/** + * @internal + * Updates the retry data for the next attempt. + * + * @param retryOptions - specifies retry interval, and its lower bound and upper bound. + * @param retryData - The retry data. + * @param err - The operation"s error, if any. + */ +function updateRetryData(retryOptions, retryData = { retryCount: 0, retryInterval: 0 }, err) { + if (err) { + if (retryData.error) { + err.innerError = retryData.error; + } + retryData.error = err; } - result[i] = num; - } - - return result; + // Adjust retry count + retryData.retryCount++; + // Adjust retry interval + let incrementDelta = Math.pow(2, retryData.retryCount - 1) - 1; + const boundedRandDelta = retryOptions.retryInterval * 0.8 + + Math.floor(Math.random() * (retryOptions.retryInterval * 0.4)); + incrementDelta *= boundedRandDelta; + retryData.retryInterval = Math.min(retryOptions.minRetryInterval + incrementDelta, retryOptions.maxRetryInterval); + return retryData; } -function parseMonth(token) { - token = String(token) - .substr(0, 3) - .toLowerCase(); - const num = MONTH_TO_NUM[token]; - return num >= 0 ? num : null; +// Copyright (c) Microsoft Corporation. +const StandardAbortMessage$1 = "The operation was aborted."; +/** + * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds. + * @param delayInMs - The number of milliseconds to be delayed. + * @param value - The value to be resolved with after a timeout of t milliseconds. + * @param options - The options for delay - currently abort options + * @param abortSignal - The abortSignal associated with containing operation. + * @param abortErrorMsg - The abort error message associated with containing operation. + * @returns - Resolved promise + */ +function delay(delayInMs, value, options) { + return new Promise((resolve, reject) => { + let timer = undefined; + let onAborted = undefined; + const rejectOnAbort = () => { + return reject(new abortController.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage$1)); + }; + const removeListeners = () => { + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { + options.abortSignal.removeEventListener("abort", onAborted); + } + }; + onAborted = () => { + if (coreUtil.isDefined(timer)) { + clearTimeout(timer); + } + removeListeners(); + return rejectOnAbort(); + }; + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { + return rejectOnAbort(); + } + timer = setTimeout(() => { + removeListeners(); + resolve(value); + }, delayInMs); + if (options === null || options === void 0 ? void 0 : options.abortSignal) { + options.abortSignal.addEventListener("abort", onAborted); + } + }); } -/* - * RFC6265 S5.1.1 date parser (see RFC for full grammar) +// Copyright (c) Microsoft Corporation. +/** + * Policy that retries the request as many times as configured for as long as the max retry time interval specified, each retry waiting longer to begin than the last time. + * @param retryCount - Maximum number of retries. + * @param retryInterval - Base time between retries. + * @param maxRetryInterval - Maximum time to wait between retries. */ -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; +function exponentialRetryPolicy(retryCount, retryInterval, maxRetryInterval) { + return { + create: (nextPolicy, options) => { + return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, maxRetryInterval); + }, + }; +} +/** + * Describes the Retry Mode type. Currently supporting only Exponential. + */ +exports.RetryMode = void 0; +(function (RetryMode) { + /** + * Currently supported retry mode. + * Each time a retry happens, it will take exponentially more time than the last time. + */ + RetryMode[RetryMode["Exponential"] = 0] = "Exponential"; +})(exports.RetryMode || (exports.RetryMode = {})); +const DefaultRetryOptions = { + maxRetries: DEFAULT_CLIENT_RETRY_COUNT, + retryDelayInMs: DEFAULT_CLIENT_RETRY_INTERVAL, + maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL, +}; +/** + * Instantiates a new "ExponentialRetryPolicyFilter" instance. + */ +class ExponentialRetryPolicy extends BaseRequestPolicy { + /** + * @param nextPolicy - The next RequestPolicy in the pipeline chain. + * @param options - The options for this RequestPolicy. + * @param retryCount - The client retry count. + * @param retryInterval - The client retry interval, in milliseconds. + * @param minRetryInterval - The minimum retry interval, in milliseconds. + * @param maxRetryInterval - The maximum retry interval, in milliseconds. + */ + constructor(nextPolicy, options, retryCount, retryInterval, maxRetryInterval) { + super(nextPolicy, options); + this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; + this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; + this.maxRetryInterval = isNumber(maxRetryInterval) + ? maxRetryInterval + : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; } + sendRequest(request) { + return this._nextPolicy + .sendRequest(request.clone()) + .then((response) => retry$1(this, request, response)) + .catch((error) => retry$1(this, request, error.response, undefined, error)); + } +} +async function retry$1(policy, request, response, retryData, requestError) { + function shouldPolicyRetry(responseParam) { + const statusCode = responseParam === null || responseParam === void 0 ? void 0 : responseParam.status; + if (statusCode === 503 && (response === null || response === void 0 ? void 0 : response.headers.get(Constants.HeaderConstants.RETRY_AFTER))) { + return false; + } + if (statusCode === undefined || + (statusCode < 500 && statusCode !== 408) || + statusCode === 501 || + statusCode === 505) { + return false; + } + return true; + } + retryData = updateRetryData({ + retryInterval: policy.retryInterval, + minRetryInterval: 0, + maxRetryInterval: policy.maxRetryInterval, + }, retryData, requestError); + const isAborted = request.abortSignal && request.abortSignal.aborted; + if (!isAborted && shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, response)) { + logger.info(`Retrying request in ${retryData.retryInterval}`); + try { + await delay(retryData.retryInterval); + const res = await policy._nextPolicy.sendRequest(request.clone()); + return retry$1(policy, request, res, retryData); + } + catch (err) { + return retry$1(policy, request, response, retryData, err); + } + } + else if (isAborted || requestError || !response) { + // If the operation failed in the end, return all errors instead of just the last one + const err = retryData.error || + new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response); + throw err; + } + else { + return response; + } +} - 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. +// Copyright (c) Microsoft Corporation. +/** + * Creates a policy that logs information about the outgoing request and the incoming responses. + * @param loggingOptions - Logging options. + * @returns An instance of the {@link LogPolicy} + */ +function logPolicy(loggingOptions = {}) { + return { + create: (nextPolicy, options) => { + return new LogPolicy(nextPolicy, options, loggingOptions); + }, + }; +} +/** + * A policy that logs information about the outgoing request and the incoming responses. + */ +class LogPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, { logger: logger$1 = logger.info, allowedHeaderNames = [], allowedQueryParameters = [], } = {}) { + super(nextPolicy, options); + this.logger = logger$1; + this.sanitizer = new Sanitizer({ allowedHeaderNames, allowedQueryParameters }); + } + /** + * Header names whose values will be logged when logging is enabled. Defaults to + * Date, traceparent, x-ms-client-request-id, and x-ms-request id. Any headers + * specified in this field will be added to that list. Any other values will + * be written to logs as "REDACTED". + * @deprecated Pass these into the constructor instead. */ - if (second === null) { - result = parseTime(token); - if (result) { - hour = result[0]; - minute = result[1]; - second = result[2]; - continue; - } + get allowedHeaderNames() { + return this.sanitizer.allowedHeaderNames; + } + /** + * Header names whose values will be logged when logging is enabled. Defaults to + * Date, traceparent, x-ms-client-request-id, and x-ms-request id. Any headers + * specified in this field will be added to that list. Any other values will + * be written to logs as "REDACTED". + * @deprecated Pass these into the constructor instead. + */ + set allowedHeaderNames(allowedHeaderNames) { + this.sanitizer.allowedHeaderNames = allowedHeaderNames; + } + /** + * Query string names whose values will be logged when logging is enabled. By default no + * query string values are logged. + * @deprecated Pass these into the constructor instead. + */ + get allowedQueryParameters() { + return this.sanitizer.allowedQueryParameters; + } + /** + * Query string names whose values will be logged when logging is enabled. By default no + * query string values are logged. + * @deprecated Pass these into the constructor instead. + */ + set allowedQueryParameters(allowedQueryParameters) { + this.sanitizer.allowedQueryParameters = allowedQueryParameters; + } + sendRequest(request) { + if (!this.logger.enabled) + return this._nextPolicy.sendRequest(request); + this.logRequest(request); + return this._nextPolicy.sendRequest(request).then((response) => this.logResponse(response)); } - - /* 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; - } + logRequest(request) { + this.logger(`Request: ${this.sanitizer.sanitize(request)}`); + } + logResponse(response) { + this.logger(`Response status code: ${response.status}`); + this.logger(`Headers: ${this.sanitizer.sanitize(response.headers)}`); + return response; } +} - /* 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; - } +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Get the path to this parameter's value as a dotted string (a.b.c). + * @param parameter - The parameter to get the path string for. + * @returns The path to this parameter's value as a dotted string. + */ +function getPathStringFromParameter(parameter) { + return getPathStringFromParameterPath(parameter.parameterPath, parameter.mapper); +} +function getPathStringFromParameterPath(parameterPath, mapper) { + let result; + if (typeof parameterPath === "string") { + result = parameterPath; + } + else if (Array.isArray(parameterPath)) { + result = parameterPath.join("."); + } + else { + result = mapper.serializedName; } + return result; +} - /* 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; +// Copyright (c) Microsoft Corporation. +/** + * Gets the list of status codes for streaming responses. + * @internal + */ +function getStreamResponseStatusCodes(operationSpec) { + const result = new Set(); + for (const statusCode in operationSpec.responses) { + const operationResponse = operationSpec.responses[statusCode]; + if (operationResponse.bodyMapper && + operationResponse.bodyMapper.type.name === MapperType.Stream) { + result.add(Number(statusCode)); } - } } - } - - /* 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)); + return result; } -function formatDate(date) { - validators.validate(validators.isDate(date), date); - return date.toUTCString(); +// Copyright (c) Microsoft Corporation. +function getDefaultUserAgentKey() { + return Constants.HeaderConstants.USER_AGENT; } - -// 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 . - - if (IP_V6_REGEX_OBJECT.test(str)) { - str = str.replace("[", "").replace("]", ""); - } - - // convert to IDN if any non-ASCII characters - if (punycode && /[^\u0001-\u007f]/.test(str)) { - str = punycode.toASCII(str); - } - - return str.toLowerCase(); +function getPlatformSpecificData() { + const runtimeInfo = { + key: "Node", + value: process.version, + }; + const osInfo = { + key: "OS", + value: `(${os__namespace.arch()}-${os__namespace.type()}-${os__namespace.release()})`, + }; + return [runtimeInfo, osInfo]; } -// 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.lastIndexOf(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; +// Copyright (c) Microsoft Corporation. +function getRuntimeInfo() { + const msRestRuntime = { + key: "core-http", + value: Constants.coreHttpVersion, + }; + return [msRestRuntime]; } - -// 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 getUserAgentString(telemetryInfo, keySeparator = " ", valueSeparator = "/") { + return telemetryInfo + .map((info) => { + const value = info.value ? `${valueSeparator}${info.value}` : ""; + return `${info.key}${value}`; + }) + .join(keySeparator); } - -function trimTerminator(str) { - if (validators.isEmptyString(str)) return 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; +const getDefaultUserAgentHeaderName = getDefaultUserAgentKey; +/** + * The default approach to generate user agents. + * Uses static information from this package, plus system information available from the runtime. + */ +function getDefaultUserAgentValue() { + const runtimeInfo = getRuntimeInfo(); + const platformSpecificData = getPlatformSpecificData(); + const userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData)); + return userAgent; } - -function parseCookiePair(cookiePair, looseMode) { - cookiePair = trimTerminator(cookiePair); - validators.validate(validators.isString(cookiePair), 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; +/** + * Returns a policy that adds the user agent header to outgoing requests based on the given {@link TelemetryInfo}. + * @param userAgentData - Telemetry information. + * @returns A new {@link UserAgentPolicy}. + */ +function userAgentPolicy(userAgentData) { + const key = !userAgentData || userAgentData.key === undefined || userAgentData.key === null + ? getDefaultUserAgentKey() + : userAgentData.key; + const value = !userAgentData || userAgentData.value === undefined || userAgentData.value === null + ? getDefaultUserAgentValue() + : userAgentData.value; + return { + create: (nextPolicy, options) => { + return new UserAgentPolicy(nextPolicy, options, key, value); + }, + }; } - -function parse(str, options) { - if (!options || typeof options !== "object") { - options = {}; - } - - if (validators.isEmptyString(str) || !validators.isString(str)) { - return null; - } - - 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; +/** + * A policy that adds the user agent header to outgoing requests based on the given {@link TelemetryInfo}. + */ +class UserAgentPolicy extends BaseRequestPolicy { + constructor(_nextPolicy, _options, headerKey, headerValue) { + super(_nextPolicy, _options); + this._nextPolicy = _nextPolicy; + this._options = _options; + this.headerKey = headerKey; + this.headerValue = headerValue; } - 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); + sendRequest(request) { + this.addUserAgentHeader(request); + return this._nextPolicy.sendRequest(request); } - - av_key = av_key.trim().toLowerCase(); - - if (av_value) { - av_value = av_value.trim(); + /** + * Adds the user agent header to the outgoing request. + */ + addUserAgentHeader(request) { + if (!request.headers) { + request.headers = new HttpHeaders(); + } + if (!request.headers.get(this.headerKey) && this.headerValue) { + request.headers.set(this.headerKey, this.headerValue); + } } +} - 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; +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * The format that will be used to join an array of values together for a query parameter value. + */ +exports.QueryCollectionFormat = void 0; +(function (QueryCollectionFormat) { + /** + * CSV: Each pair of segments joined by a single comma. + */ + QueryCollectionFormat["Csv"] = ","; + /** + * SSV: Each pair of segments joined by a single space character. + */ + QueryCollectionFormat["Ssv"] = " "; + /** + * TSV: Each pair of segments joined by a single tab character. + */ + QueryCollectionFormat["Tsv"] = "\t"; + /** + * Pipes: Each pair of segments joined by a single pipe character. + */ + QueryCollectionFormat["Pipes"] = "|"; + /** + * Denotes this is an array of values that should be passed to the server in multiple key/value pairs, e.g. `?queryParam=value1&queryParam=value2` + */ + QueryCollectionFormat["Multi"] = "Multi"; +})(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {})); - 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); - } +// Copyright (c) Microsoft Corporation. +// Default options for the cycler if none are provided +const DEFAULT_CYCLER_OPTIONS = { + forcedRefreshWindowInMs: 1000, + retryIntervalInMs: 3000, + refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry +}; +/** + * Converts an an unreliable access token getter (which may resolve with null) + * into an AccessTokenGetter by retrying the unreliable getter in a regular + * interval. + * + * @param getAccessToken - a function that produces a promise of an access + * token that may fail by returning null + * @param retryIntervalInMs - the time (in milliseconds) to wait between retry + * attempts + * @param timeoutInMs - the timestamp after which the refresh attempt will fail, + * throwing an exception + * @returns - a promise that, if it resolves, will resolve with an access token + */ +async function beginRefresh(getAccessToken, retryIntervalInMs, timeoutInMs) { + // This wrapper handles exceptions gracefully as long as we haven't exceeded + // the timeout. + async function tryGetAccessToken() { + if (Date.now() < timeoutInMs) { + try { + return await getAccessToken(); + } + catch (_a) { + return null; + } } - 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(); - } + else { + const finalToken = await getAccessToken(); + // Timeout is up, so throw if it's still null + if (finalToken === null) { + throw new Error("Failed to refresh access token."); + } + return finalToken; } - 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. + } + let token = await tryGetAccessToken(); + while (token === null) { + await delay(retryIntervalInMs); + token = await tryGetAccessToken(); + } + return token; +} +/** + * Creates a token cycler from a credential, scopes, and optional settings. + * + * A token cycler represents a way to reliably retrieve a valid access token + * from a TokenCredential. It will handle initializing the token, refreshing it + * when it nears expiration, and synchronizes refresh attempts to avoid + * concurrency hazards. + * + * @param credential - the underlying TokenCredential that provides the access + * token + * @param scopes - the scopes to request authorization for + * @param tokenCyclerOptions - optionally override default settings for the cycler + * + * @returns - a function that reliably produces a valid access token + */ +function createTokenCycler(credential, scopes, tokenCyclerOptions) { + let refreshWorker = null; + let token = null; + const options = Object.assign(Object.assign({}, DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); + /** + * This little holder defines several predicates that we use to construct + * the rules of refreshing the token. + */ + const cycler = { + /** + * Produces true if a refresh job is currently in progress. */ - 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." + get isRefreshing() { + return refreshWorker !== null; + }, + /** + * Produces true if the cycler SHOULD refresh (we are within the refresh + * window and not already refreshing) */ - 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; - case "none": - c.sameSite = "none"; - break; - default: - c.sameSite = undefined; - break; + get shouldRefresh() { + var _a; + return (!cycler.isRefreshing && + ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now()); + }, + /** + * Produces true if the cycler MUST refresh (null or nearly-expired + * token). + */ + get mustRefresh() { + return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now()); + }, + }; + /** + * Starts a refresh job or returns the existing job if one is already + * running. + */ + function refresh(getTokenOptions) { + var _a; + if (!cycler.isRefreshing) { + // We bind `scopes` here to avoid passing it around a lot + const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); + // Take advantage of promise chaining to insert an assignment to `token` + // before the refresh can be considered done. + refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs, + // If we don't have a token, then we should timeout immediately + (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now()) + .then((_token) => { + refreshWorker = null; + token = _token; + return token; + }) + .catch((reason) => { + // We also should reset the refresher if we enter a failed state. All + // existing awaiters will throw, but subsequent requests will start a + // new retry chain. + refreshWorker = null; + token = null; + throw reason; + }); } - break; - - default: - c.extensions = c.extensions || []; - c.extensions.push(av); - break; + return refreshWorker; } - } - - return c; + return async (tokenOptions) => { + // + // Simple rules: + // - If we MUST refresh, then return the refresh task, blocking + // the pipeline until a token is available. + // - If we SHOULD refresh, then run refresh but don't return it + // (we can still use the cached token). + // - Return the token, since it's fine if we didn't return in + // step 1. + // + if (cycler.mustRefresh) + return refresh(tokenOptions); + if (cycler.shouldRefresh) { + refresh(tokenOptions); + } + return token; + }; } - +// #endregion /** - * 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 + * Creates a new factory for a RequestPolicy that applies a bearer token to + * the requests' `Authorization` headers. + * + * @param credential - The TokenCredential implementation that can supply the bearer token. + * @param scopes - The scopes for which the bearer token applies. */ -function isSecurePrefixConditionMet(cookie) { - validators.validate(validators.isObject(cookie), cookie); - return !cookie.key.startsWith("__Secure-") || cookie.secure; +function bearerTokenAuthenticationPolicy(credential, scopes) { + // This simple function encapsulates the entire process of reliably retrieving the token + const getToken = createTokenCycler(credential, scopes /* , options */); + class BearerTokenAuthenticationPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options) { + super(nextPolicy, options); + } + async sendRequest(webResource) { + if (!webResource.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); + } + const { token } = await getToken({ + abortSignal: webResource.abortSignal, + tracingOptions: { + tracingContext: webResource.tracingContext, + }, + }); + webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${token}`); + return this._nextPolicy.sendRequest(webResource); + } + } + return { + create: (nextPolicy, options) => { + return new BearerTokenAuthenticationPolicy(nextPolicy, options); + }, + }; } +// Copyright (c) Microsoft Corporation. /** - * 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 + * Returns a request policy factory that can be used to create an instance of + * {@link DisableResponseDecompressionPolicy}. */ -function isHostPrefixConditionMet(cookie) { - validators.validate(validators.isObject(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 disableResponseDecompressionPolicy() { + return { + create: (nextPolicy, options) => { + return new DisableResponseDecompressionPolicy(nextPolicy, options); + }, + }; } - -function fromJSON(str) { - if (!str || validators.isEmptyString(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 +/** + * A policy to disable response decompression according to Accept-Encoding header + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding + */ +class DisableResponseDecompressionPolicy extends BaseRequestPolicy { + /** + * Creates an instance of DisableResponseDecompressionPolicy. + * + * @param nextPolicy - + * @param options - + */ + // The parent constructor is protected. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor */ + constructor(nextPolicy, options) { + super(nextPolicy, options); } - - 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]; + /** + * Sends out request. + * + * @param request - + * @returns + */ + async sendRequest(request) { + request.decompressResponse = false; + return this._nextPolicy.sendRequest(request); } - } - - 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." +// Copyright (c) Microsoft Corporation. +/** + * Creates a policy that assigns a unique request id to outgoing requests. + * @param requestIdHeaderName - The name of the header to use when assigning the unique id to the request. */ - -function cookieCompare(a, b) { - validators.validate(validators.isObject(a), a); - validators.validate(validators.isObject(b), 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; +function generateClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { + return { + create: (nextPolicy, options) => { + return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName); + }, + }; } - -// 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) { - validators.validate(validators.isString(path)); - if (path === "/") { - return ["/"]; - } - const permutations = [path]; - while (path.length > 1) { - const lindex = path.lastIndexOf("/"); - if (lindex === 0) { - break; +class GenerateClientRequestIdPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, _requestIdHeaderName) { + super(nextPolicy, options); + this._requestIdHeaderName = _requestIdHeaderName; + } + sendRequest(request) { + if (!request.headers.contains(this._requestIdHeaderName)) { + request.headers.set(this._requestIdHeaderName, request.requestId); + } + return this._nextPolicy.sendRequest(request); } - 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); +// Copyright (c) Microsoft Corporation. +let cachedHttpClient; +function getCachedDefaultHttpClient() { + if (!cachedHttpClient) { + cachedHttpClient = new NodeFetchHttpClient(); + } + return cachedHttpClient; } -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: undefined -}; - -class Cookie { - constructor(options = {}) { - const customInspectSymbol = getCustomInspectSymbol(); - if (customInspectSymbol) { - this[customInspectSymbol] = this.inspect; +// Copyright (c) Microsoft Corporation. +function ndJsonPolicy() { + return { + create: (nextPolicy, options) => { + return new NdJsonPolicy(nextPolicy, options); + }, + }; +} +/** + * NdJsonPolicy that formats a JSON array as newline-delimited JSON + */ +class NdJsonPolicy extends BaseRequestPolicy { + /** + * Creates an instance of KeepAlivePolicy. + */ + constructor(nextPolicy, options) { + super(nextPolicy, options); } - - 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]; + /** + * Sends a request. + */ + async sendRequest(request) { + // There currently isn't a good way to bypass the serializer + if (typeof request.body === "string" && request.body.startsWith("[")) { + const body = JSON.parse(request.body); + if (Array.isArray(body)) { + request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); + } } - } - } - - return 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; + return this._nextPolicy.sendRequest(request); } +} - 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 +// Copyright (c) Microsoft Corporation. +/** + * Stores the patterns specified in NO_PROXY environment variable. + * @internal + */ +const globalNoProxyList = []; +let noProxyListLoaded = false; +/** A cache of whether a host should bypass the proxy. */ +const globalBypassedMap = new Map(); +function loadEnvironmentProxyValue() { + if (!process) { + return undefined; + } + const httpsProxy = getEnvironmentValue(Constants.HTTPS_PROXY); + const allProxy = getEnvironmentValue(Constants.ALL_PROXY); + const httpProxy = getEnvironmentValue(Constants.HTTP_PROXY); + return httpsProxy || allProxy || httpProxy; +} +/** + * Check whether the host of a given `uri` matches any pattern in the no proxy list. + * If there's a match, any request sent to the same host shouldn't have the proxy settings set. + * This implementation is a port of /~https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210 + */ +function isBypassed(uri, noProxyList, bypassedMap) { + if (noProxyList.length === 0) { return false; - } } - return true; - } - - setExpires(exp) { - if (exp instanceof Date) { - this.expires = exp; - } else { - this.expires = parseDate(exp) || "Infinity"; + const host = URLBuilder.parse(uri).getHost(); + if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { + return bypassedMap.get(host); } - } - - setMaxAge(age) { - if (age === Infinity || age === -Infinity) { - this.maxAge = age.toString(); // so JSON.stringify() works - } else { - this.maxAge = age; + let isBypassedFlag = false; + for (const pattern of noProxyList) { + if (pattern[0] === ".") { + // This should match either domain it self or any subdomain or host + // .foo.com will match foo.com it self or *.foo.com + if (host.endsWith(pattern)) { + isBypassedFlag = true; + } + else { + if (host.length === pattern.length - 1 && host === pattern.slice(1)) { + isBypassedFlag = true; + } + } + } + else { + if (host === pattern) { + isBypassedFlag = true; + } + } } - } - - cookieString() { - let val = this.value; - if (val == null) { - val = ""; + bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); + return isBypassedFlag; +} +/** + * @internal + */ +function loadNoProxy() { + const noProxy = getEnvironmentValue(Constants.NO_PROXY); + noProxyListLoaded = true; + if (noProxy) { + return noProxy + .split(",") + .map((item) => item.trim()) + .filter((item) => item.length); } - if (this.key === "") { - return val; + return []; +} +/** + * Converts a given URL of a proxy server into `ProxySettings` or attempts to retrieve `ProxySettings` from the current environment if one is not passed. + * @param proxyUrl - URL of the proxy + * @returns The default proxy settings, or undefined. + */ +function getDefaultProxySettings(proxyUrl) { + if (!proxyUrl) { + proxyUrl = loadEnvironmentProxyValue(); + if (!proxyUrl) { + return undefined; + } } - 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}`; - } + const { username, password, urlWithoutAuth } = extractAuthFromUrl(proxyUrl); + const parsedUrl = URLBuilder.parse(urlWithoutAuth); + const schema = parsedUrl.getScheme() ? parsedUrl.getScheme() + "://" : ""; + return { + host: schema + parsedUrl.getHost(), + port: Number.parseInt(parsedUrl.getPort() || "80"), + username, + password, + }; +} +/** + * A policy that allows one to apply proxy settings to all requests. + * If not passed static settings, they will be retrieved from the HTTPS_PROXY + * or HTTP_PROXY environment variables. + * @param proxySettings - ProxySettings to use on each request. + * @param options - additional settings, for example, custom NO_PROXY patterns + */ +function proxyPolicy(proxySettings, options) { + if (!proxySettings) { + proxySettings = getDefaultProxySettings(); } - - if (this.maxAge != null && this.maxAge != Infinity) { - str += `; Max-Age=${this.maxAge}`; + if (!noProxyListLoaded) { + globalNoProxyList.push(...loadNoProxy()); } - - if (this.domain && !this.hostOnly) { - str += `; Domain=${this.domain}`; + return { + create: (nextPolicy, requestPolicyOptions) => { + return new ProxyPolicy(nextPolicy, requestPolicyOptions, proxySettings, options === null || options === void 0 ? void 0 : options.customNoProxyList); + }, + }; +} +function extractAuthFromUrl(url) { + const atIndex = url.indexOf("@"); + if (atIndex === -1) { + return { urlWithoutAuth: url }; } - if (this.path) { - str += `; Path=${this.path}`; + const schemeIndex = url.indexOf("://"); + const authStart = schemeIndex !== -1 ? schemeIndex + 3 : 0; + const auth = url.substring(authStart, atIndex); + const colonIndex = auth.indexOf(":"); + const hasPassword = colonIndex !== -1; + const username = hasPassword ? auth.substring(0, colonIndex) : auth; + const password = hasPassword ? auth.substring(colonIndex + 1) : undefined; + const urlWithoutAuth = url.substring(0, authStart) + url.substring(atIndex + 1); + return { + username, + password, + urlWithoutAuth, + }; +} +class ProxyPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, proxySettings, customNoProxyList) { + super(nextPolicy, options); + this.proxySettings = proxySettings; + this.customNoProxyList = customNoProxyList; + } + sendRequest(request) { + var _a; + if (!request.proxySettings && + !isBypassed(request.url, (_a = this.customNoProxyList) !== null && _a !== void 0 ? _a : globalNoProxyList, this.customNoProxyList ? undefined : globalBypassedMap)) { + request.proxySettings = this.proxySettings; + } + return this._nextPolicy.sendRequest(request); } +} - if (this.secure) { - str += "; Secure"; +// Copyright (c) Microsoft Corporation. +function rpRegistrationPolicy(retryTimeout = 30) { + return { + create: (nextPolicy, options) => { + return new RPRegistrationPolicy(nextPolicy, options, retryTimeout); + }, + }; +} +class RPRegistrationPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, _retryTimeout = 30) { + super(nextPolicy, options); + this._retryTimeout = _retryTimeout; } - if (this.httpOnly) { - str += "; HttpOnly"; + sendRequest(request) { + return this._nextPolicy + .sendRequest(request.clone()) + .then((response) => registerIfNeeded(this, request, response)); } - if (this.sameSite && this.sameSite !== "none") { - const ssCanon = Cookie.sameSiteCanonical[this.sameSite.toLowerCase()]; - str += `; SameSite=${ssCanon ? ssCanon : this.sameSite}`; +} +function registerIfNeeded(policy, request, response) { + if (response.status === 409) { + const rpName = checkRPNotRegisteredError(response.bodyAsText); + if (rpName) { + const urlPrefix = extractSubscriptionUrl(request.url); + return (registerRP(policy, urlPrefix, rpName, request) + // Autoregistration of ${provider} failed for some reason. We will not return this error + // instead will return the initial response with 409 status code back to the user. + // do nothing here as we are returning the original response at the end of this method. + .catch(() => false) + .then((registrationStatus) => { + if (registrationStatus) { + // Retry the original request. We have to change the x-ms-client-request-id + // otherwise Azure endpoint will return the initial 409 (cached) response. + request.headers.set("x-ms-client-request-id", generateUuid()); + return policy._nextPolicy.sendRequest(request.clone()); + } + return response; + })); + } } - if (this.extensions) { - this.extensions.forEach(ext => { - str += `; ${ext}`; - }); + return Promise.resolve(response); +} +/** + * Reuses the headers of the original request and url (if specified). + * @param originalRequest - The original request + * @param reuseUrlToo - Should the url from the original request be reused as well. Default false. + * @returns A new request object with desired headers. + */ +function getRequestEssentials(originalRequest, reuseUrlToo = false) { + const reqOptions = originalRequest.clone(); + if (reuseUrlToo) { + reqOptions.url = originalRequest.url; } - - 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; + // We have to change the x-ms-client-request-id otherwise Azure endpoint + // will return the initial 409 (cached) response. + reqOptions.headers.set("x-ms-client-request-id", generateUuid()); + // Set content-type to application/json + reqOptions.headers.set("Content-Type", "application/json; charset=utf-8"); + return reqOptions; +} +/** + * Validates the error code and message associated with 409 response status code. If it matches to that of + * RP not registered then it returns the name of the RP else returns undefined. + * @param body - The response body received after making the original request. + * @returns The name of the RP if condition is satisfied else undefined. + */ +function checkRPNotRegisteredError(body) { + let result, responseBody; + if (body) { + try { + responseBody = JSON.parse(body); + } + catch (err) { + // do nothing; + } + if (responseBody && + responseBody.error && + responseBody.error.message && + responseBody.error.code && + responseBody.error.code === "MissingSubscriptionRegistration") { + const matchRes = responseBody.error.message.match(/.*'(.*)'/i); + if (matchRes) { + result = matchRes.pop(); + } + } } - - 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 result; +} +/** + * Extracts the first part of the URL, just after subscription: + * https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ + * @param url - The original request url + * @returns The url prefix as explained above. + */ +function extractSubscriptionUrl(url) { + let result; + const matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//gi); + if (matchRes && matchRes[0]) { + result = matchRes[0]; } - - 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; + else { + throw new Error(`Unable to extract subscriptionId from the given url - ${url}.`); } - - if (this.expires == Infinity) { - return Infinity; + return result; +} +/** + * Registers the given provider. + * @param policy - The RPRegistrationPolicy this function is being called against. + * @param urlPrefix - https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ + * @param provider - The provider name to be registered. + * @param originalRequest - The original request sent by the user that returned a 409 response + * with a message that the provider is not registered. + */ +async function registerRP(policy, urlPrefix, provider, originalRequest) { + const postUrl = `${urlPrefix}providers/${provider}/register?api-version=2016-02-01`; + const getUrl = `${urlPrefix}providers/${provider}?api-version=2016-02-01`; + const reqOptions = getRequestEssentials(originalRequest); + reqOptions.method = "POST"; + reqOptions.url = postUrl; + const response = await policy._nextPolicy.sendRequest(reqOptions); + if (response.status !== 200) { + throw new Error(`Autoregistration of ${provider} failed. Please try registering manually.`); } - 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); + return getRegistrationStatus(policy, getUrl, originalRequest); +} +/** + * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds. + * Polling will happen till the registrationState property of the response body is "Registered". + * @param policy - The RPRegistrationPolicy this function is being called against. + * @param url - The request url for polling + * @param originalRequest - The original request sent by the user that returned a 409 response + * with a message that the provider is not registered. + * @returns True if RP Registration is successful. + */ +async function getRegistrationStatus(policy, url, originalRequest) { + const reqOptions = getRequestEssentials(originalRequest); + reqOptions.url = url; + reqOptions.method = "GET"; + const res = await policy._nextPolicy.sendRequest(reqOptions); + const obj = res.parsedBody; + if (res.parsedBody && obj.registrationState && obj.registrationState === "Registered") { + return true; } - } - - // 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; + else { + await delay(policy._retryTimeout * 1000); + return getRegistrationStatus(policy, url, originalRequest); } - 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; +// Copyright (c) Microsoft Corporation. +/** + * Creates a policy that signs outgoing requests by calling to the provided `authenticationProvider`'s `signRequest` method. + * @param authenticationProvider - The authentication provider. + * @returns An instance of the {@link SigningPolicy}. + */ +function signingPolicy(authenticationProvider) { + return { + create: (nextPolicy, options) => { + return new SigningPolicy(nextPolicy, options, authenticationProvider); + }, + }; } - -class CookieJar { - constructor(store, options = { rejectPublicSuffixes: true }) { - if (typeof options === "boolean") { - options = { rejectPublicSuffixes: options }; +/** + * A policy that signs outgoing requests by calling to the provided `authenticationProvider`'s `signRequest` method. + */ +class SigningPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, authenticationProvider) { + super(nextPolicy, options); + this.authenticationProvider = authenticationProvider; } - validators.validate(validators.isObject(options), options); - this.rejectPublicSuffixes = options.rejectPublicSuffixes; - this.enableLooseMode = !!options.looseMode; - this.allowSpecialUseDomain = - typeof options.allowSpecialUseDomain === "boolean" - ? options.allowSpecialUseDomain - : true; - 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) { - validators.validate(validators.isNonEmptyString(url), cb, options); - let err; - - if (validators.isFunction(url)) { - cb = url; - return cb(new Error("No URL was specified")); + signRequest(request) { + return this.authenticationProvider.signRequest(request); } + sendRequest(request) { + return this.signRequest(request).then((nextRequest) => this._nextPolicy.sendRequest(nextRequest)); + } +} - const context = getCookieContext(url); - if (validators.isFunction(options)) { - cb = options; - options = {}; +// Copyright (c) Microsoft Corporation. +/** + * A policy that retries when there's a system error, identified by the codes "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNREFUSED", "ECONNRESET" or "ENOENT". + * @param retryCount - Maximum number of retries. + * @param retryInterval - The client retry interval, in milliseconds. + * @param minRetryInterval - The minimum retry interval, in milliseconds. + * @param maxRetryInterval - The maximum retry interval, in milliseconds. + * @returns An instance of the {@link SystemErrorRetryPolicy} + */ +function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) { + return { + create: (nextPolicy, options) => { + return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval); + }, + }; +} +/** + * A policy that retries when there's a system error, identified by the codes "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNREFUSED", "ECONNRESET" or "ENOENT". + * @param retryCount - The client retry count. + * @param retryInterval - The client retry interval, in milliseconds. + * @param minRetryInterval - The minimum retry interval, in milliseconds. + * @param maxRetryInterval - The maximum retry interval, in milliseconds. + */ +class SystemErrorRetryPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) { + super(nextPolicy, options); + this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; + this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; + this.minRetryInterval = isNumber(minRetryInterval) + ? minRetryInterval + : DEFAULT_CLIENT_MIN_RETRY_INTERVAL; + this.maxRetryInterval = isNumber(maxRetryInterval) + ? maxRetryInterval + : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; } - - validators.validate(validators.isFunction(cb), cb); - - if ( - !validators.isNonEmptyString(cookie) && - !validators.isObject(cookie) && - cookie instanceof String && - cookie.length == 0 - ) { - return cb(null); + sendRequest(request) { + return this._nextPolicy + .sendRequest(request.clone()) + .catch((error) => retry(this, request, error.response, error)); } - - 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)); - } +} +async function retry(policy, request, operationResponse, err, retryData) { + retryData = updateRetryData(policy, retryData, err); + function shouldPolicyRetry(_response, error) { + if (error && + error.code && + (error.code === "ETIMEDOUT" || + error.code === "ESOCKETTIMEDOUT" || + error.code === "ECONNREFUSED" || + error.code === "ECONNRESET" || + error.code === "ENOENT")) { + return true; + } + return false; } - - // 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); + if (shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, operationResponse, err)) { + // If previous operation ended with an error and the policy allows a retry, do that + try { + await delay(retryData.retryInterval); + return policy._nextPolicy.sendRequest(request.clone()); + } + catch (nestedErr) { + return retry(policy, request, operationResponse, nestedErr, retryData); + } } - - // 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(), { - allowSpecialUseDomain: this.allowSpecialUseDomain, - ignoreError: options.ignoreError - }); - if (suffix == null && !IP_V6_REGEX_OBJECT.test(cookie.domain)) { - // e.g. "com" - err = new Error("Cookie has domain set to a public suffix"); - return cb(options.ignoreError ? null : err); - } + else { + if (err) { + // If the operation failed in the end, return all errors instead of just the last one + return Promise.reject(retryData.error); + } + return operationResponse; } +} - // 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); - } +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Maximum number of retries for the throttling retry policy + */ +const DEFAULT_CLIENT_MAX_RETRY_COUNT = 3; - if (cookie.hostOnly == null) { - // don't reset if already set - cookie.hostOnly = false; - } - } else { - cookie.hostOnly = true; - cookie.domain = host; +// Copyright (c) Microsoft Corporation. +const StatusCodes = Constants.HttpConstants.StatusCodes; +/** + * Creates a policy that re-sends the request if the response indicates the request failed because of throttling reasons. + * For example, if the response contains a `Retry-After` header, it will retry sending the request based on the value of that header. + * + * To learn more, please refer to + * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits, + * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and + * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors + * @returns + */ +function throttlingRetryPolicy() { + return { + create: (nextPolicy, options) => { + return new ThrottlingRetryPolicy(nextPolicy, options); + }, + }; +} +const StandardAbortMessage = "The operation was aborted."; +/** + * Creates a policy that re-sends the request if the response indicates the request failed because of throttling reasons. + * For example, if the response contains a `Retry-After` header, it will retry sending the request based on the value of that header. + * + * To learn more, please refer to + * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits, + * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and + * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors + */ +class ThrottlingRetryPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, _handleResponse) { + super(nextPolicy, options); + this.numberOfRetries = 0; + this._handleResponse = _handleResponse || this._defaultResponseHandler; } - - //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; + async sendRequest(httpRequest) { + const response = await this._nextPolicy.sendRequest(httpRequest.clone()); + if (response.status !== StatusCodes.TooManyRequests && + response.status !== StatusCodes.ServiceUnavailable) { + return response; + } + else { + return this._handleResponse(httpRequest, response); + } } - - // 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); + async _defaultResponseHandler(httpRequest, httpResponse) { + var _a; + const retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER); + if (retryAfterHeader) { + const delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader); + if (delayInMs) { + this.numberOfRetries += 1; + await delay(delayInMs, undefined, { + abortSignal: httpRequest.abortSignal, + abortErrorMsg: StandardAbortMessage, + }); + if ((_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { + throw new abortController.AbortError(StandardAbortMessage); + } + if (this.numberOfRetries < DEFAULT_CLIENT_MAX_RETRY_COUNT) { + return this.sendRequest(httpRequest); + } + else { + return this._nextPolicy.sendRequest(httpRequest); + } + } + } + return httpResponse; } - - // 6252bis-02 S5.4 Step 13 & 14: - if ( - cookie.sameSite !== "none" && - cookie.sameSite !== undefined && - 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); - } + static parseRetryAfterHeader(headerValue) { + const retryAfterInSeconds = Number(headerValue); + if (Number.isNaN(retryAfterInSeconds)) { + return ThrottlingRetryPolicy.parseDateRetryAfterHeader(headerValue); + } + else { + return retryAfterInSeconds * 1000; + } } - - /* 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) - ); - } + static parseDateRetryAfterHeader(headerValue) { + try { + const now = Date.now(); + const date = Date.parse(headerValue); + const diff = date - now; + return Number.isNaN(diff) ? undefined : diff; + } + catch (error) { + return undefined; + } } +} - const store = this.store; - - if (!store.updateCookie) { - store.updateCookie = function(oldCookie, newCookie, cb) { - this.putCookie(newCookie, cb); - }; +// Copyright (c) Microsoft Corporation. +const createSpan = coreTracing.createSpanFunction({ + packagePrefix: "", + namespace: "", +}); +/** + * Creates a policy that wraps outgoing requests with a tracing span. + * @param tracingOptions - Tracing options. + * @returns An instance of the {@link TracingPolicy} class. + */ +function tracingPolicy(tracingOptions = {}) { + return { + create(nextPolicy, options) { + return new TracingPolicy(nextPolicy, options, tracingOptions); + }, + }; +} +/** + * A policy that wraps outgoing requests with a tracing span. + */ +class TracingPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, tracingOptions) { + super(nextPolicy, options); + this.userAgent = tracingOptions.userAgent; } - - function withCookie(err, oldCookie) { - if (err) { - return cb(err); - } - - const next = function(err) { - if (err) { - return cb(err); - } else { - cb(null, cookie); + async sendRequest(request) { + if (!request.tracingContext) { + return this._nextPolicy.sendRequest(request); } - }; - - 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); + const span = this.tryCreateSpan(request); + if (!span) { + return this._nextPolicy.sendRequest(request); + } + try { + const response = await this._nextPolicy.sendRequest(request); + this.tryProcessResponse(span, response); + return response; + } + catch (err) { + this.tryProcessError(span, err); + throw 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) { - validators.validate(validators.isNonEmptyString(url), cb, url); - const context = getCookieContext(url); - if (validators.isFunction(options)) { - cb = options; - options = {}; + tryCreateSpan(request) { + var _a; + try { + // Passing spanOptions as part of tracingOptions to maintain compatibility @azure/core-tracing@preview.13 and earlier. + // We can pass this as a separate parameter once we upgrade to the latest core-tracing. + const { span } = createSpan(`HTTP ${request.method}`, { + tracingOptions: { + spanOptions: Object.assign(Object.assign({}, request.spanOptions), { kind: coreTracing.SpanKind.CLIENT }), + tracingContext: request.tracingContext, + }, + }); + // If the span is not recording, don't do any more work. + if (!span.isRecording()) { + span.end(); + return undefined; + } + const namespaceFromContext = (_a = request.tracingContext) === null || _a === void 0 ? void 0 : _a.getValue(Symbol.for("az.namespace")); + if (typeof namespaceFromContext === "string") { + span.setAttribute("az.namespace", namespaceFromContext); + } + span.setAttributes({ + "http.method": request.method, + "http.url": request.url, + requestId: request.requestId, + }); + if (this.userAgent) { + span.setAttribute("http.user_agent", this.userAgent); + } + // set headers + const spanContext = span.spanContext(); + const traceParentHeader = coreTracing.getTraceParentHeader(spanContext); + if (traceParentHeader && coreTracing.isSpanContextValid(spanContext)) { + request.headers.set("traceparent", traceParentHeader); + const traceState = spanContext.traceState && spanContext.traceState.serialize(); + // if tracestate is set, traceparent MUST be set, so only set tracestate after traceparent + if (traceState) { + request.headers.set("tracestate", traceState); + } + } + return span; + } + catch (error) { + logger.warning(`Skipping creating a tracing span due to an error: ${error.message}`); + return undefined; + } } - validators.validate(validators.isObject(options), cb, options); - validators.validate(validators.isFunction(cb), cb); - - 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; + tryProcessError(span, err) { + try { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: err.message, + }); + if (err.statusCode) { + span.setAttribute("http.status_code", err.statusCode); + } + span.end(); + } + catch (error) { + logger.warning(`Skipping tracing span processing due to an error: ${error.message}`); + } } - - 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)); - } + tryProcessResponse(span, response) { + try { + span.setAttribute("http.status_code", response.status); + const serviceRequestId = response.headers.get("x-ms-request-id"); + if (serviceRequestId) { + span.setAttribute("serviceRequestId", serviceRequestId); + } + span.setStatus({ + code: coreTracing.SpanStatusCode.OK, + }); + span.end(); + } + catch (error) { + logger.warning(`Skipping tracing span processing due to an error: ${error.message}`); + } } +} - let http = options.http; - if (http == null) { - http = true; +// Copyright (c) Microsoft Corporation. +/** + * ServiceClient sends service requests and receives responses. + */ +class ServiceClient { + /** + * The ServiceClient constructor + * @param credentials - The credentials used for authentication with the service. + * @param options - The service client options that govern the behavior of the client. + */ + constructor(credentials, + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options */ + options) { + if (!options) { + options = {}; + } + this._withCredentials = options.withCredentials || false; + this._httpClient = options.httpClient || getCachedDefaultHttpClient(); + this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger); + let requestPolicyFactories; + if (Array.isArray(options.requestPolicyFactories)) { + logger.info("ServiceClient: using custom request policies"); + requestPolicyFactories = options.requestPolicyFactories; + } + else { + let authPolicyFactory = undefined; + if (coreAuth.isTokenCredential(credentials)) { + logger.info("ServiceClient: creating bearer token authentication policy from provided credentials"); + // Create a wrapped RequestPolicyFactory here so that we can provide the + // correct scope to the BearerTokenAuthenticationPolicy at the first time + // one is requested. This is needed because generated ServiceClient + // implementations do not set baseUri until after ServiceClient's constructor + // is finished, leaving baseUri empty at the time when it is needed to + // build the correct scope name. + const wrappedPolicyFactory = () => { + let bearerTokenPolicyFactory = undefined; + // eslint-disable-next-line @typescript-eslint/no-this-alias + const serviceClient = this; + const serviceClientOptions = options; + return { + create(nextPolicy, createOptions) { + const credentialScopes = getCredentialScopes(serviceClientOptions, serviceClient.baseUri); + if (!credentialScopes) { + throw new Error(`When using credential, the ServiceClient must contain a baseUri or a credentialScopes in ServiceClientOptions. Unable to create a bearerTokenAuthenticationPolicy`); + } + if (bearerTokenPolicyFactory === undefined || bearerTokenPolicyFactory === null) { + bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy(credentials, credentialScopes); + } + return bearerTokenPolicyFactory.create(nextPolicy, createOptions); + }, + }; + }; + authPolicyFactory = wrappedPolicyFactory(); + } + else if (credentials && typeof credentials.signRequest === "function") { + logger.info("ServiceClient: creating signing policy from provided credentials"); + authPolicyFactory = signingPolicy(credentials); + } + else if (credentials !== undefined && credentials !== null) { + throw new Error("The credentials argument must implement the TokenCredential interface"); + } + logger.info("ServiceClient: using default request policies"); + requestPolicyFactories = createDefaultRequestPolicyFactories(authPolicyFactory, options); + if (options.requestPolicyFactories) { + // options.requestPolicyFactories can also be a function that manipulates + // the default requestPolicyFactories array + const newRequestPolicyFactories = options.requestPolicyFactories(requestPolicyFactories); + if (newRequestPolicyFactories) { + requestPolicyFactories = newRequestPolicyFactories; + } + } + } + this._requestPolicyFactories = requestPolicyFactories; } - - 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; + /** + * Send the provided httpRequest. + */ + sendRequest(options) { + if (options === null || options === undefined || typeof options !== "object") { + throw new Error("options cannot be null or undefined and it must be of type object."); } - } else { - if (!domainMatch(host, c.domain, false)) { - return false; + let httpRequest; + try { + if (isWebResourceLike(options)) { + options.validateRequestProperties(); + httpRequest = options; + } + else { + httpRequest = new WebResource(); + httpRequest = httpRequest.prepare(options); + } } - } - - // "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; + catch (error) { + return Promise.reject(error); } - } - - // 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; + let httpPipeline = this._httpClient; + if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) { + for (let i = this._requestPolicyFactories.length - 1; i >= 0; --i) { + httpPipeline = this._requestPolicyFactories[i].create(httpPipeline, this._requestPolicyOptions); + } + } + return httpPipeline.sendRequest(httpRequest); } - - store.findCookies( - host, - allPaths ? null : path, - this.allowSpecialUseDomain, - (err, cookies) => { - if (err) { - return cb(err); + /** + * Send an HTTP request that is populated using the provided OperationSpec. + * @param operationArguments - The arguments that the HTTP request's templated values will be populated from. + * @param operationSpec - The OperationSpec to use to populate the httpRequest. + * @param callback - The callback to call when the response is received. + */ + async sendOperationRequest(operationArguments, operationSpec, callback) { + var _a; + if (typeof operationArguments.options === "function") { + callback = operationArguments.options; + operationArguments.options = undefined; } - - cookies = cookies.filter(matchingCookie); - - // sorting of S5.4 part 2 - if (options.sort !== false) { - cookies = cookies.sort(cookieCompare); + const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; + const httpRequest = new WebResource(); + let result; + try { + const baseUri = operationSpec.baseUrl || this.baseUri; + if (!baseUri) { + throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a baseUri string property that contains the base URL to use."); + } + httpRequest.method = operationSpec.httpMethod; + httpRequest.operationSpec = operationSpec; + const requestUrl = URLBuilder.parse(baseUri); + if (operationSpec.path) { + requestUrl.appendPath(operationSpec.path); + } + if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) { + for (const urlParameter of operationSpec.urlParameters) { + let urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer); + urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter), serializerOptions); + if (!urlParameter.skipEncoding) { + urlParameterValue = encodeURIComponent(urlParameterValue); + } + requestUrl.replaceAll(`{${urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)}}`, urlParameterValue); + } + } + if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) { + for (const queryParameter of operationSpec.queryParameters) { + let queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer); + if (queryParameterValue !== undefined && queryParameterValue !== null) { + queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter), serializerOptions); + if (queryParameter.collectionFormat !== undefined && + queryParameter.collectionFormat !== null) { + if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Multi) { + if (queryParameterValue.length === 0) { + // The collection is empty, no need to try serializing the current queryParam + continue; + } + else { + for (const index in queryParameterValue) { + const item = queryParameterValue[index]; + queryParameterValue[index] = + item === undefined || item === null ? "" : item.toString(); + } + } + } + else if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Ssv || + queryParameter.collectionFormat === exports.QueryCollectionFormat.Tsv) { + queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); + } + } + if (!queryParameter.skipEncoding) { + if (Array.isArray(queryParameterValue)) { + for (const index in queryParameterValue) { + if (queryParameterValue[index] !== undefined && + queryParameterValue[index] !== null) { + queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]); + } + } + } + else { + queryParameterValue = encodeURIComponent(queryParameterValue); + } + } + if (queryParameter.collectionFormat !== undefined && + queryParameter.collectionFormat !== null && + queryParameter.collectionFormat !== exports.QueryCollectionFormat.Multi && + queryParameter.collectionFormat !== exports.QueryCollectionFormat.Ssv && + queryParameter.collectionFormat !== exports.QueryCollectionFormat.Tsv) { + queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); + } + requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue); + } + } + } + httpRequest.url = requestUrl.toString(); + const contentType = operationSpec.contentType || this.requestContentType; + if (contentType && operationSpec.requestBody) { + httpRequest.headers.set("Content-Type", contentType); + } + if (operationSpec.headerParameters) { + for (const headerParameter of operationSpec.headerParameters) { + let headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer); + if (headerValue !== undefined && headerValue !== null) { + headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter), serializerOptions); + const headerCollectionPrefix = headerParameter.mapper + .headerCollectionPrefix; + if (headerCollectionPrefix) { + for (const key of Object.keys(headerValue)) { + httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]); + } + } + else { + httpRequest.headers.set(headerParameter.mapper.serializedName || + getPathStringFromParameter(headerParameter), headerValue); + } + } + } + } + const options = operationArguments.options; + if (options) { + if (options.customHeaders) { + for (const customHeaderName in options.customHeaders) { + httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]); + } + } + if (options.abortSignal) { + httpRequest.abortSignal = options.abortSignal; + } + if (options.timeout) { + httpRequest.timeout = options.timeout; + } + if (options.onUploadProgress) { + httpRequest.onUploadProgress = options.onUploadProgress; + } + if (options.onDownloadProgress) { + httpRequest.onDownloadProgress = options.onDownloadProgress; + } + if (options.spanOptions) { + // By passing spanOptions if they exist at runtime, we're backwards compatible with @azure/core-tracing@preview.13 and earlier. + httpRequest.spanOptions = options.spanOptions; + } + if (options.tracingContext) { + httpRequest.tracingContext = options.tracingContext; + } + if (options.shouldDeserialize !== undefined && options.shouldDeserialize !== null) { + httpRequest.shouldDeserialize = options.shouldDeserialize; + } + } + httpRequest.withCredentials = this._withCredentials; + serializeRequestBody(this, httpRequest, operationArguments, operationSpec); + if (httpRequest.streamResponseStatusCodes === undefined) { + httpRequest.streamResponseStatusCodes = getStreamResponseStatusCodes(operationSpec); + } + let rawResponse; + let sendRequestError; + try { + rawResponse = await this.sendRequest(httpRequest); + } + catch (error) { + sendRequestError = error; + } + if (sendRequestError) { + if (sendRequestError.response) { + sendRequestError.details = flattenResponse(sendRequestError.response, operationSpec.responses[sendRequestError.statusCode] || + operationSpec.responses["default"]); + } + result = Promise.reject(sendRequestError); + } + else { + result = Promise.resolve(flattenResponse(rawResponse, operationSpec.responses[rawResponse.status])); + } } - - // S5.4 part 3 - const now = new Date(); - for (const cookie of cookies) { - cookie.lastAccessed = now; + catch (error) { + result = Promise.reject(error); } - // TODO persist lastAccessed - - cb(null, cookies); - } - ); - } - - getCookieString(...args) { - const cb = args.pop(); - validators.validate(validators.isFunction(cb), cb); - 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(); - validators.validate(validators.isFunction(cb), cb); - 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) { - validators.validate(validators.isFunction(cb), cb); - let type = this.store.constructor.name; - if (validators.isObject(type)) { - 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, - enableLooseMode: !!this.enableLooseMode, - allowSpecialUseDomain: !!this.allowSpecialUseDomain, - prefixSecurity: getNormalizedPrefixSecurity(this.prefixSecurity), - - // 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")); + const cb = callback; + if (cb) { + result + .then((res) => cb(null, res._response.parsedBody, res._response.request, res._response)) + .catch((err) => cb(err)); + } + return result; } - 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); +} +function serializeRequestBody(serviceClient, httpRequest, operationArguments, operationSpec) { + var _a, _b, _c, _d, _e, _f; + const serializerOptions = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions) !== null && _b !== void 0 ? _b : {}; + const updatedOptions = { + rootName: (_c = serializerOptions.rootName) !== null && _c !== void 0 ? _c : "", + includeRoot: (_d = serializerOptions.includeRoot) !== null && _d !== void 0 ? _d : false, + xmlCharKey: (_e = serializerOptions.xmlCharKey) !== null && _e !== void 0 ? _e : XML_CHARKEY, }; - - 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) { - validators.validate(validators.isFunction(cb), 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); + const xmlCharKey = serializerOptions.xmlCharKey; + if (operationSpec.requestBody && operationSpec.requestBody.mapper) { + httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer); + const bodyMapper = operationSpec.requestBody.mapper; + const { required, xmlName, xmlElementName, serializedName, xmlNamespace, xmlNamespacePrefix } = bodyMapper; + const typeName = bodyMapper.type.name; + try { + if ((httpRequest.body !== undefined && httpRequest.body !== null) || required) { + const requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody); + httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString, updatedOptions); + const isStream = typeName === MapperType.Stream; + if (operationSpec.isXML) { + const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns"; + const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, httpRequest.body, updatedOptions); + if (typeName === MapperType.Sequence) { + httpRequest.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { + rootName: xmlName || serializedName, + xmlCharKey, + }); + } + else if (!isStream) { + httpRequest.body = stringifyXML(value, { + rootName: xmlName || serializedName, + xmlCharKey, + }); + } + } + else if (typeName === MapperType.String && + (((_f = operationSpec.contentType) === null || _f === void 0 ? void 0 : _f.match("text/plain")) || operationSpec.mediaType === "text")) { + // the String serializer has validated that request body is a string + // so just send the string. + return; + } + else if (!isStream) { + httpRequest.body = JSON.stringify(httpRequest.body); + } + } } - - completedCount++; - - if (completedCount === cookies.length) { - return cb(removeErrors.length ? removeErrors[0] : null); + catch (error) { + throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`); } - } - - 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; } - validators.validate(validators.isFunction(cb), cb); - - let serialized; - if (typeof strOrObj === "string") { - serialized = jsonParse(strOrObj); - if (serialized instanceof Error) { - return cb(serialized); - } - } else { - serialized = strOrObj; + else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) { + httpRequest.formData = {}; + for (const formDataParameter of operationSpec.formDataParameters) { + const formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer); + if (formDataParameterValue !== undefined && formDataParameterValue !== null) { + const formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter); + httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter), updatedOptions); + } + } } - - const jar = new CookieJar(store, { - rejectPublicSuffixes: serialized.rejectPublicSuffixes, - looseMode: serialized.enableLooseMode, - allowSpecialUseDomain: serialized.allowSpecialUseDomain, - prefixSecurity: serialized.prefixSecurity - }); - 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, { - rejectPublicSuffixes: serialized.rejectPublicSuffixes, - looseMode: serialized.enableLooseMode - }); - - // catch this mistake early: - if (!jar.store.synchronous) { - throw new Error( - "CookieJar store is not synchronous; use async API instead." - ); +} +/** + * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself + */ +function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) { + // Composite and Sequence schemas already got their root namespace set during serialization + // We just need to add xmlns to the other schema types + if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) { + const result = {}; + result[options.xmlCharKey] = serializedValue; + result[XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace }; + return result; } - - jar._importCookiesSync(serialized); - return jar; - } + return serializedValue; } -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." - ); +function getValueOrFunctionResult(value, defaultValueCreator) { + let result; + if (typeof value === "string") { + result = value; } - - let syncErr, syncResult; - this[method](...args, (err, result) => { - syncErr = err; - syncResult = result; - }); - - if (syncErr) { - throw syncErr; + else { + result = defaultValueCreator(); + if (typeof value === "function") { + result = value(result); + } } - return syncResult; - }; + return result; } - -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 = __nccwpck_require__(25696).permuteDomain; -exports.permutePath = permutePath; -exports.canonicalDomain = canonicalDomain; -exports.PrefixSecurityEnum = PrefixSecurityEnum; -exports.ParameterError = validators.ParameterError; - - -/***/ }), - -/***/ 96738: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -var __webpack_unused_export__; -/*! - * 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 { fromCallback } = __nccwpck_require__(9046); -const Store = (__nccwpck_require__(17707)/* .Store */ .y); -const permuteDomain = (__nccwpck_require__(25696).permuteDomain); -const pathMatch = (__nccwpck_require__(60807)/* .pathMatch */ .U); -const { getCustomInspectSymbol, getUtilInspect } = __nccwpck_require__(9375); - -class MemoryCookieStore extends Store { - constructor() { - super(); - this.synchronous = true; - this.idx = {}; - const customInspectSymbol = getCustomInspectSymbol(); - if (customInspectSymbol) { - this[customInspectSymbol] = this.inspect; +function createDefaultRequestPolicyFactories(authPolicyFactory, options) { + const factories = []; + if (options.generateClientRequestIdHeader) { + factories.push(generateClientRequestIdPolicy(options.clientRequestIdHeaderName)); } - } - - inspect() { - const util = { inspect: getUtilInspect(inspectFallback) }; - return `{ idx: ${util.inspect(this.idx, false, 2)} }`; - } - - findCookie(domain, path, key, cb) { - if (!this.idx[domain]) { - return cb(null, undefined); + if (authPolicyFactory) { + factories.push(authPolicyFactory); } - if (!this.idx[domain][path]) { - return cb(null, undefined); + const userAgentHeaderName = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName); + const userAgentHeaderValue = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue); + if (userAgentHeaderName && userAgentHeaderValue) { + factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue })); } - return cb(null, this.idx[domain][path][key] || null); - } - findCookies(domain, path, allowSpecialUseDomain, cb) { - const results = []; - if (typeof allowSpecialUseDomain === "function") { - cb = allowSpecialUseDomain; - allowSpecialUseDomain = true; + factories.push(redirectPolicy()); + factories.push(rpRegistrationPolicy(options.rpRegistrationRetryTimeout)); + if (!options.noRetryPolicy) { + factories.push(exponentialRetryPolicy()); + factories.push(systemErrorRetryPolicy()); + factories.push(throttlingRetryPolicy()); } - if (!domain) { - return cb(null, []); + factories.push(deserializationPolicy(options.deserializationContentTypes)); + if (isNode) { + factories.push(proxyPolicy(options.proxySettings)); } - - 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]); - } + factories.push(logPolicy({ logger: logger.info })); + return factories; +} +/** + * Creates an HTTP pipeline based on the given options. + * @param pipelineOptions - Defines options that are used to configure policies in the HTTP pipeline for an SDK client. + * @param authPolicyFactory - An optional authentication policy factory to use for signing requests. + * @returns A set of options that can be passed to create a new {@link ServiceClient}. + */ +function createPipelineFromOptions(pipelineOptions, authPolicyFactory) { + const requestPolicyFactories = []; + if (pipelineOptions.sendStreamingJson) { + requestPolicyFactories.push(ndJsonPolicy()); + } + let userAgentValue = undefined; + if (pipelineOptions.userAgentOptions && pipelineOptions.userAgentOptions.userAgentPrefix) { + const userAgentInfo = []; + userAgentInfo.push(pipelineOptions.userAgentOptions.userAgentPrefix); + // Add the default user agent value if it isn't already specified + // by the userAgentPrefix option. + const defaultUserAgentInfo = getDefaultUserAgentValue(); + if (userAgentInfo.indexOf(defaultUserAgentInfo) === -1) { + userAgentInfo.push(defaultUserAgentInfo); } - }; - } 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]); - } - } - }); - }; + userAgentValue = userAgentInfo.join(" "); } - - 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); - } - - putCookie(cookie, cb) { - if (!this.idx[cookie.domain]) { - this.idx[cookie.domain] = {}; + const keepAliveOptions = Object.assign(Object.assign({}, DefaultKeepAliveOptions), pipelineOptions.keepAliveOptions); + const retryOptions = Object.assign(Object.assign({}, DefaultRetryOptions), pipelineOptions.retryOptions); + const redirectOptions = Object.assign(Object.assign({}, DefaultRedirectOptions), pipelineOptions.redirectOptions); + if (isNode) { + requestPolicyFactories.push(proxyPolicy(pipelineOptions.proxyOptions)); } - if (!this.idx[cookie.domain][cookie.path]) { - this.idx[cookie.domain][cookie.path] = {}; + const deserializationOptions = Object.assign(Object.assign({}, DefaultDeserializationOptions), pipelineOptions.deserializationOptions); + const loggingOptions = Object.assign({}, pipelineOptions.loggingOptions); + requestPolicyFactories.push(tracingPolicy({ userAgent: userAgentValue }), keepAlivePolicy(keepAliveOptions), userAgentPolicy({ value: userAgentValue }), generateClientRequestIdPolicy(), deserializationPolicy(deserializationOptions.expectedContentTypes), throttlingRetryPolicy(), systemErrorRetryPolicy(), exponentialRetryPolicy(retryOptions.maxRetries, retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs)); + if (redirectOptions.handleRedirects) { + requestPolicyFactories.push(redirectPolicy(redirectOptions.maxRetries)); } - 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]; + if (authPolicyFactory) { + requestPolicyFactories.push(authPolicyFactory); } - cb(null); - } - removeCookies(domain, path, cb) { - if (this.idx[domain]) { - if (path) { - delete this.idx[domain][path]; - } else { - delete this.idx[domain]; - } + requestPolicyFactories.push(logPolicy(loggingOptions)); + if (isNode && pipelineOptions.decompressResponse === false) { + requestPolicyFactories.push(disableResponseDecompressionPolicy()); } - return cb(null); - } - removeAllCookies(cb) { - this.idx = {}; - return cb(null); - } - getAllCookies(cb) { - const cookies = []; - const idx = this.idx; - - 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]); - } - }); - }); - }); - - // 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); - }); - - cb(null, cookies); - } + return { + httpClient: pipelineOptions.httpClient, + requestPolicyFactories, + }; } - -[ - "findCookie", - "findCookies", - "putCookie", - "updateCookie", - "removeCookie", - "removeCookies", - "removeAllCookies", - "getAllCookies" -].forEach(name => { - MemoryCookieStore.prototype[name] = fromCallback( - MemoryCookieStore.prototype[name] - ); -}); - -exports.m = MemoryCookieStore; - -function inspectFallback(val) { - const domains = Object.keys(val); - if (domains.length === 0) { - return "{}"; - } - let result = "{\n"; - Object.keys(val).forEach((domain, i) => { - result += formatDomain(domain, val[domain]); - if (i < domains.length - 1) { - result += ","; +function getOperationArgumentValueFromParameter(serviceClient, operationArguments, parameter, serializer) { + return getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameter.parameterPath, parameter.mapper, serializer); +} +function getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, serializer) { + var _a; + let value; + if (typeof parameterPath === "string") { + parameterPath = [parameterPath]; + } + const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; + if (Array.isArray(parameterPath)) { + if (parameterPath.length > 0) { + if (parameterMapper.isConstant) { + value = parameterMapper.defaultValue; + } + else { + let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath); + if (!propertySearchResult.propertyFound) { + propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath); + } + let useDefaultValue = false; + if (!propertySearchResult.propertyFound) { + useDefaultValue = + parameterMapper.required || + (parameterPath[0] === "options" && parameterPath.length === 2); + } + value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue; + } + // Serialize just for validation purposes. + const parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper); + serializer.serialize(parameterMapper, value, parameterPathString, serializerOptions); + } + } + else { + if (parameterMapper.required) { + value = {}; + } + for (const propertyName in parameterPath) { + const propertyMapper = parameterMapper.type.modelProperties[propertyName]; + const propertyPath = parameterPath[propertyName]; + const propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer); + // Serialize just for validation purposes. + const propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper); + serializer.serialize(propertyMapper, propertyValue, propertyPathString, serializerOptions); + if (propertyValue !== undefined && propertyValue !== null) { + if (!value) { + value = {}; + } + value[propertyName] = propertyValue; + } + } + } + return value; +} +function getPropertyFromParameterPath(parent, parameterPath) { + const result = { propertyFound: false }; + let i = 0; + for (; i < parameterPath.length; ++i) { + const parameterPathPart = parameterPath[i]; + // Make sure to check inherited properties too, so don't use hasOwnProperty(). + if (parent !== undefined && parent !== null && parameterPathPart in parent) { + parent = parent[parameterPathPart]; + } + else { + break; + } + } + if (i === parameterPath.length) { + result.propertyValue = parent; + result.propertyFound = true; + } + return result; +} +/** + * Parses an {@link HttpOperationResponse} into a normalized HTTP response object ({@link RestResponse}). + * @param _response - Wrapper object for http response. + * @param responseSpec - Mappers for how to parse the response properties. + * @returns - A normalized response object. + */ +function flattenResponse(_response, responseSpec) { + const parsedHeaders = _response.parsedHeaders; + const bodyMapper = responseSpec && responseSpec.bodyMapper; + const addOperationResponse = (obj) => { + return Object.defineProperty(obj, "_response", { + value: _response, + }); + }; + if (bodyMapper) { + const typeName = bodyMapper.type.name; + if (typeName === "Stream") { + return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody })); + } + const modelProperties = (typeName === "Composite" && bodyMapper.type.modelProperties) || {}; + const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === ""); + if (typeName === "Sequence" || isPageableResponse) { + const arrayResponse = [...(_response.parsedBody || [])]; + for (const key of Object.keys(modelProperties)) { + if (modelProperties[key].serializedName) { + arrayResponse[key] = _response.parsedBody[key]; + } + } + if (parsedHeaders) { + for (const key of Object.keys(parsedHeaders)) { + arrayResponse[key] = parsedHeaders[key]; + } + } + addOperationResponse(arrayResponse); + return arrayResponse; + } + if (typeName === "Composite" || typeName === "Dictionary") { + return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), _response.parsedBody)); + } } - result += "\n"; - }); - result += "}"; - return result; -} - -function formatDomain(domainName, domainValue) { - const indent = " "; - let result = `${indent}'${domainName}': {\n`; - Object.keys(domainValue).forEach((path, i, paths) => { - result += formatPath(path, domainValue[path]); - if (i < paths.length - 1) { - result += ","; + if (bodyMapper || + _response.request.method === "HEAD" || + isPrimitiveType(_response.parsedBody)) { + // primitive body types and HEAD booleans + return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), { body: _response.parsedBody })); } - result += "\n"; - }); - result += `${indent}}`; - return result; + return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), _response.parsedBody)); } - -function formatPath(pathName, pathValue) { - const indent = " "; - let result = `${indent}'${pathName}': {\n`; - Object.keys(pathValue).forEach((cookieName, i, cookieNames) => { - const cookie = pathValue[cookieName]; - result += ` ${cookieName}: ${cookie.inspect()}`; - if (i < cookieNames.length - 1) { - result += ","; +function getCredentialScopes(options, baseUri) { + if (options === null || options === void 0 ? void 0 : options.credentialScopes) { + const scopes = options.credentialScopes; + return Array.isArray(scopes) + ? scopes.map((scope) => new URL(scope).toString()) + : new URL(scopes).toString(); } - result += "\n"; - }); - result += `${indent}}`; - return result; + if (baseUri) { + return `${baseUri}/.default`; + } + return undefined; } -__webpack_unused_export__ = inspectFallback; - - -/***/ }), - -/***/ 60807: -/***/ ((__unused_webpack_module, 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. +// Copyright (c) Microsoft Corporation. +/** + * This function is only here for compatibility. Use createSpanFunction in core-tracing. * - * 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. - */ + * @deprecated This function is only here for compatibility. Use createSpanFunction in core-tracing. + * @hidden -/* - * "A request-path path-matches a given cookie-path if at least one of the - * following conditions holds:" + * @param spanConfig - The name of the operation being performed. + * @param tracingOptions - The options for the underlying http request. */ -function pathMatch(reqPath, cookiePath) { - // "o The cookie-path and the request-path are identical." - if (cookiePath === reqPath) { - return true; - } - - 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; +function createSpanFunction(args) { + return coreTracing.createSpanFunction(args); } -exports.U = pathMatch; - - -/***/ }), - -/***/ 25696: -/***/ ((__unused_webpack_module, exports, __nccwpck_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. +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Defines the default token refresh buffer duration. */ - -const pubsuffix = __nccwpck_require__(78292); - -// Gives the permutation of all possible domainMatch()es of a given domain. The -// array is in shortest-to-longest order. Handy for indexing. - -function permuteDomain(domain, allowSpecialUseDomain) { - const pubSuf = pubsuffix.getPublicSuffix(domain, { - allowSpecialUseDomain: allowSpecialUseDomain - }); - - if (!pubSuf) { - return null; - } - if (pubSuf == domain) { - return [domain]; - } - - // Nuke trailing dot - if (domain.slice(-1) == ".") { - domain = domain.slice(0, -1); - } - - 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; - - -/***/ }), - -/***/ 78292: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -/*! - * Copyright (c) 2018, 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. +const TokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes +/** + * Provides an {@link AccessTokenCache} implementation which clears + * the cached {@link AccessToken}'s after the expiresOnTimestamp has + * passed. * - * 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. + * @deprecated No longer used in the bearer authorization policy. */ - -const psl = __nccwpck_require__(29975); - -// RFC 6761 -const SPECIAL_USE_DOMAINS = [ - "local", - "example", - "invalid", - "localhost", - "test" -]; - -const SPECIAL_TREATMENT_DOMAINS = ["localhost", "invalid"]; - -function getPublicSuffix(domain, options = {}) { - const domainParts = domain.split("."); - const topLevelDomain = domainParts[domainParts.length - 1]; - const allowSpecialUseDomain = !!options.allowSpecialUseDomain; - const ignoreError = !!options.ignoreError; - - if (allowSpecialUseDomain && SPECIAL_USE_DOMAINS.includes(topLevelDomain)) { - if (domainParts.length > 1) { - const secondLevelDomain = domainParts[domainParts.length - 2]; - // In aforementioned example, the eTLD/pubSuf will be apple.localhost - return `${secondLevelDomain}.${topLevelDomain}`; - } else if (SPECIAL_TREATMENT_DOMAINS.includes(topLevelDomain)) { - // For a single word special use domain, e.g. 'localhost' or 'invalid', per RFC 6761, - // "Application software MAY recognize {localhost/invalid} names as special, or - // MAY pass them to name resolution APIs as they would for other domain names." - return `${topLevelDomain}`; +class ExpiringAccessTokenCache { + /** + * Constructs an instance of {@link ExpiringAccessTokenCache} with + * an optional expiration buffer time. + */ + constructor(tokenRefreshBufferMs = TokenRefreshBufferMs) { + this.cachedToken = undefined; + this.tokenRefreshBufferMs = tokenRefreshBufferMs; + } + /** + * Saves an access token into the internal in-memory cache. + * @param accessToken - Access token or undefined to clear the cache. + */ + setCachedToken(accessToken) { + this.cachedToken = accessToken; + } + /** + * Returns the cached access token, or `undefined` if one is not cached or the cached one is expiring soon. + */ + getCachedToken() { + if (this.cachedToken && + Date.now() + this.tokenRefreshBufferMs >= this.cachedToken.expiresOnTimestamp) { + this.cachedToken = undefined; + } + return this.cachedToken; } - } - - if (!ignoreError && SPECIAL_USE_DOMAINS.includes(topLevelDomain)) { - throw new Error( - `Cookie has domain set to the public suffix "${topLevelDomain}" which is a special use domain. To allow this, configure your CookieJar with {allowSpecialUseDomain:true, rejectPublicSuffixes: false}.` - ); - } - - return psl.get(domain); } -exports.getPublicSuffix = getPublicSuffix; - - -/***/ }), - -/***/ 17707: -/***/ ((__unused_webpack_module, 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. +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Helps the core-http token authentication policies with requesting a new token if we're not currently waiting for a new token. * - * 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. + * @deprecated No longer used in the bearer authorization policy. */ - -/*jshint unused:false */ - -class Store { - constructor() { - this.synchronous = false; - } - - findCookie(domain, path, key, cb) { - throw new Error("findCookie is not implemented"); - } - - findCookies(domain, path, allowSpecialUseDomain, cb) { - throw new Error("findCookies is not implemented"); - } - - putCookie(cookie, cb) { - throw new Error("putCookie is not implemented"); - } - - 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"); - } - - removeCookies(domain, path, cb) { - throw new Error("removeCookies is not implemented"); - } - - removeAllCookies(cb) { - throw new Error("removeAllCookies is not implemented"); - } - - getAllCookies(cb) { - throw new Error( - "getAllCookies is not implemented (therefore jar cannot be serialized)" - ); - } +class AccessTokenRefresher { + constructor(credential, scopes, requiredMillisecondsBeforeNewRefresh = 30000) { + this.credential = credential; + this.scopes = scopes; + this.requiredMillisecondsBeforeNewRefresh = requiredMillisecondsBeforeNewRefresh; + this.lastCalled = 0; + } + /** + * Returns true if the required milliseconds(defaulted to 30000) have been passed signifying + * that we are ready for a new refresh. + */ + isReady() { + // We're only ready for a new refresh if the required milliseconds have passed. + return (!this.lastCalled || Date.now() - this.lastCalled > this.requiredMillisecondsBeforeNewRefresh); + } + /** + * Stores the time in which it is called, + * then requests a new token, + * then sets this.promise to undefined, + * then returns the token. + */ + async getToken(options) { + this.lastCalled = Date.now(); + const token = await this.credential.getToken(this.scopes, options); + this.promise = undefined; + return token || undefined; + } + /** + * Requests a new token if we're not currently waiting for a new token. + * Returns null if the required time between each call hasn't been reached. + */ + refresh(options) { + if (!this.promise) { + this.promise = this.getToken(options); + } + return this.promise; + } } -exports.y = Store; - - -/***/ }), - -/***/ 9375: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -function requireUtil() { - try { - // eslint-disable-next-line no-restricted-modules - return __nccwpck_require__(73837); - } catch (e) { - return null; - } +// Copyright (c) Microsoft Corporation. +const HeaderConstants = Constants.HeaderConstants; +const DEFAULT_AUTHORIZATION_SCHEME = "Basic"; +/** + * A simple {@link ServiceClientCredential} that authenticates with a username and a password. + */ +class BasicAuthenticationCredentials { + /** + * Creates a new BasicAuthenticationCredentials object. + * + * @param userName - User name. + * @param password - Password. + * @param authorizationScheme - The authorization scheme. + */ + constructor(userName, password, authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME) { + /** + * Authorization scheme. Defaults to "Basic". + * More information about authorization schemes is available here: https://developer.mozilla.org/docs/Web/HTTP/Authentication#authentication_schemes + */ + this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME; + if (userName === null || userName === undefined || typeof userName.valueOf() !== "string") { + throw new Error("userName cannot be null or undefined and must be of type string."); + } + if (password === null || password === undefined || typeof password.valueOf() !== "string") { + throw new Error("password cannot be null or undefined and must be of type string."); + } + this.userName = userName; + this.password = password; + this.authorizationScheme = authorizationScheme; + } + /** + * Signs a request with the Authentication header. + * + * @param webResource - The WebResourceLike to be signed. + * @returns The signed request object. + */ + signRequest(webResource) { + const credentials = `${this.userName}:${this.password}`; + const encodedCredentials = `${this.authorizationScheme} ${encodeString(credentials)}`; + if (!webResource.headers) + webResource.headers = new HttpHeaders(); + webResource.headers.set(HeaderConstants.AUTHORIZATION, encodedCredentials); + return Promise.resolve(webResource); + } } -// for v10.12.0+ -function lookupCustomInspectSymbol() { - return Symbol.for("nodejs.util.inspect.custom"); +// Copyright (c) Microsoft Corporation. +/** + * Authenticates to a service using an API key. + */ +class ApiKeyCredentials { + /** + * @param options - Specifies the options to be provided for auth. Either header or query needs to be provided. + */ + constructor(options) { + if (!options || (options && !options.inHeader && !options.inQuery)) { + throw new Error(`options cannot be null or undefined. Either "inHeader" or "inQuery" property of the options object needs to be provided.`); + } + this.inHeader = options.inHeader; + this.inQuery = options.inQuery; + } + /** + * Signs a request with the values provided in the inHeader and inQuery parameter. + * + * @param webResource - The WebResourceLike to be signed. + * @returns The signed request object. + */ + signRequest(webResource) { + if (!webResource) { + return Promise.reject(new Error(`webResource cannot be null or undefined and must be of type "object".`)); + } + if (this.inHeader) { + if (!webResource.headers) { + webResource.headers = new HttpHeaders(); + } + for (const headerName in this.inHeader) { + webResource.headers.set(headerName, this.inHeader[headerName]); + } + } + if (this.inQuery) { + if (!webResource.url) { + return Promise.reject(new Error(`url cannot be null in the request object.`)); + } + if (webResource.url.indexOf("?") < 0) { + webResource.url += "?"; + } + for (const key in this.inQuery) { + if (!webResource.url.endsWith("?")) { + webResource.url += "&"; + } + webResource.url += `${key}=${this.inQuery[key]}`; + } + } + return Promise.resolve(webResource); + } } -// for older node environments -function tryReadingCustomSymbolFromUtilInspect(options) { - const _requireUtil = options.requireUtil || requireUtil; - const util = _requireUtil(); - return util ? util.inspect.custom : null; +// Copyright (c) Microsoft Corporation. +/** + * A {@link TopicCredentials} object used for Azure Event Grid. + */ +class TopicCredentials extends ApiKeyCredentials { + /** + * Creates a new EventGrid TopicCredentials object. + * + * @param topicKey - The EventGrid topic key + */ + constructor(topicKey) { + if (!topicKey || (topicKey && typeof topicKey !== "string")) { + throw new Error("topicKey cannot be null or undefined and must be of type string."); + } + const options = { + inHeader: { + "aeg-sas-key": topicKey, + }, + }; + super(options); + } } -exports.getUtilInspect = function getUtilInspect(fallback, options = {}) { - const _requireUtil = options.requireUtil || requireUtil; - const util = _requireUtil(); - return function inspect(value, showHidden, depth) { - return util ? util.inspect(value, showHidden, depth) : fallback(value); - }; -}; - -exports.getCustomInspectSymbol = function getCustomInspectSymbol(options = {}) { - const _lookupCustomInspectSymbol = - options.lookupCustomInspectSymbol || lookupCustomInspectSymbol; - - // get custom inspect symbol for node environments - return ( - _lookupCustomInspectSymbol() || - tryReadingCustomSymbolFromUtilInspect(options) - ); -}; +Object.defineProperty(exports, "isTokenCredential", ({ + enumerable: true, + get: function () { return coreAuth.isTokenCredential; } +})); +exports.AccessTokenRefresher = AccessTokenRefresher; +exports.ApiKeyCredentials = ApiKeyCredentials; +exports.BaseRequestPolicy = BaseRequestPolicy; +exports.BasicAuthenticationCredentials = BasicAuthenticationCredentials; +exports.Constants = Constants; +exports.DefaultHttpClient = NodeFetchHttpClient; +exports.ExpiringAccessTokenCache = ExpiringAccessTokenCache; +exports.HttpHeaders = HttpHeaders; +exports.MapperType = MapperType; +exports.RequestPolicyOptions = RequestPolicyOptions; +exports.RestError = RestError; +exports.Serializer = Serializer; +exports.ServiceClient = ServiceClient; +exports.TopicCredentials = TopicCredentials; +exports.URLBuilder = URLBuilder; +exports.URLQuery = URLQuery; +exports.WebResource = WebResource; +exports.XML_ATTRKEY = XML_ATTRKEY; +exports.XML_CHARKEY = XML_CHARKEY; +exports.applyMixins = applyMixins; +exports.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; +exports.createPipelineFromOptions = createPipelineFromOptions; +exports.createSpanFunction = createSpanFunction; +exports.delay = delay; +exports.deserializationPolicy = deserializationPolicy; +exports.deserializeResponseBody = deserializeResponseBody; +exports.disableResponseDecompressionPolicy = disableResponseDecompressionPolicy; +exports.encodeUri = encodeUri; +exports.executePromisesSequentially = executePromisesSequentially; +exports.exponentialRetryPolicy = exponentialRetryPolicy; +exports.flattenResponse = flattenResponse; +exports.generateClientRequestIdPolicy = generateClientRequestIdPolicy; +exports.generateUuid = generateUuid; +exports.getDefaultProxySettings = getDefaultProxySettings; +exports.getDefaultUserAgentValue = getDefaultUserAgentValue; +exports.isDuration = isDuration; +exports.isNode = isNode; +exports.isValidUuid = isValidUuid; +exports.keepAlivePolicy = keepAlivePolicy; +exports.logPolicy = logPolicy; +exports.operationOptionsToRequestOptionsBase = operationOptionsToRequestOptionsBase; +exports.parseXML = parseXML; +exports.promiseToCallback = promiseToCallback; +exports.promiseToServiceCallback = promiseToServiceCallback; +exports.proxyPolicy = proxyPolicy; +exports.redirectPolicy = redirectPolicy; +exports.serializeObject = serializeObject; +exports.signingPolicy = signingPolicy; +exports.stringifyXML = stringifyXML; +exports.stripRequest = stripRequest; +exports.stripResponse = stripResponse; +exports.systemErrorRetryPolicy = systemErrorRetryPolicy; +exports.throttlingRetryPolicy = throttlingRetryPolicy; +exports.tracingPolicy = tracingPolicy; +exports.userAgentPolicy = userAgentPolicy; +//# sourceMappingURL=index.js.map /***/ }), -/***/ 71598: -/***/ ((__unused_webpack_module, exports) => { +/***/ 57395: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -/* ************************************************************************************ -Extracted from check-types.js -https://gitlab.com/philbooth/check-types.js - -MIT License - -Copyright (c) 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 Phil Booth -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. +Object.defineProperty(exports, "__esModule", ({ value: true })); -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 logger$1 = __nccwpck_require__(63264); +var abortController = __nccwpck_require__(97675); -************************************************************************************ */ +// Copyright (c) Microsoft Corporation. +/** + * The `@azure/logger` configuration for this package. + * @internal + */ +const logger = logger$1.createClientLogger("core-lro"); +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * The default time interval to wait before sending the next polling request. + */ +const POLL_INTERVAL_IN_MS = 2000; +/** + * The closed set of terminal states. + */ +const terminalStates = ["succeeded", "canceled", "failed"]; -/* Validation functions copied from check-types package - https://www.npmjs.com/package/check-types */ -function isFunction(data) { - return typeof data === "function"; +// Copyright (c) Microsoft Corporation. +/** + * Deserializes the state + */ +function deserializeState(serializedState) { + try { + return JSON.parse(serializedState).state; + } + catch (e) { + throw new Error(`Unable to deserialize input state: ${serializedState}`); + } } - -function isNonEmptyString(data) { - return isString(data) && data !== ""; +function setStateError(inputs) { + const { state, stateProxy } = inputs; + return (error) => { + stateProxy.setError(state, error); + stateProxy.setFailed(state); + throw error; + }; } - -function isDate(data) { - return isInstanceStrict(data, Date) && isInteger(data.getTime()); +function processOperationStatus(result) { + const { state, stateProxy, status } = result; + logger.verbose(`LRO: Status:\n\tPolling from: ${state.config.operationLocation}\n\tOperation status: ${status}\n\tPolling status: ${terminalStates.includes(status) ? "Stopped" : "Running"}`); + switch (status) { + case "succeeded": { + stateProxy.setSucceeded(state); + break; + } + case "failed": { + stateProxy.setError(state, new Error(`The long-running operation has failed`)); + stateProxy.setFailed(state); + break; + } + case "canceled": { + stateProxy.setCanceled(state); + break; + } + } } - -function isEmptyString(data) { - return data === "" || (data instanceof String && data.toString() === ""); +function buildResult(inputs) { + const { processResult, response, state } = inputs; + return processResult ? processResult(response, state) : response; } - -function isString(data) { - return typeof data === "string" || data instanceof String; +/** + * Initiates the long-running operation. + */ +async function initOperation(inputs) { + const { init, stateProxy, processResult, getOperationStatus, withOperationLocation } = inputs; + const { operationLocation, resourceLocation, metadata, response } = await init(); + if (operationLocation) + withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false); + const config = { + metadata, + operationLocation, + resourceLocation, + }; + logger.verbose(`LRO: Operation description:`, config); + const state = stateProxy.initState(config); + const status = getOperationStatus(response, state); + if (status === "succeeded" || operationLocation === undefined) { + stateProxy.setSucceeded(state); + stateProxy.setResult(state, buildResult({ + response, + state, + processResult, + })); + } + return state; } - -function isObject(data) { - return toString.call(data) === "[object Object]"; +async function pollOperationHelper(inputs) { + const { poll, state, stateProxy, operationLocation, resourceLocation, getOperationStatus, options, } = inputs; + const response = await poll(operationLocation, options).catch(setStateError({ + state, + stateProxy, + })); + const status = getOperationStatus(response, state); + processOperationStatus({ + status, + state, + stateProxy, + }); + if (status === "succeeded" && resourceLocation !== undefined) { + return { + response: await poll(resourceLocation).catch(setStateError({ state, stateProxy })), + status, + }; + } + return { response, status }; } -function isInstanceStrict(data, prototype) { - try { - return data instanceof prototype; - } catch (error) { - return false; - } +/** Polls the long-running operation. */ +async function pollOperation(inputs) { + const { poll, state, stateProxy, options, getOperationStatus, getOperationLocation, withOperationLocation, getPollingInterval, processResult, updateState, setDelay, isDone, } = inputs; + const { operationLocation, resourceLocation } = state.config; + if (operationLocation !== undefined) { + const { response, status } = await pollOperationHelper({ + poll, + getOperationStatus, + state, + stateProxy, + operationLocation, + resourceLocation, + options, + }); + if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) || + (isDone === undefined && ["succeeded", "canceled"].includes(status))) { + stateProxy.setResult(state, buildResult({ + response, + state, + processResult, + })); + } + else { + const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response); + if (intervalInMs) + setDelay(intervalInMs); + const location = getOperationLocation === null || getOperationLocation === void 0 ? void 0 : getOperationLocation(response, state); + if (location !== undefined) { + const isUpdated = operationLocation !== location; + state.config.operationLocation = location; + withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated); + } + else + withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false); + } + updateState === null || updateState === void 0 ? void 0 : updateState(state, response); + } } -function isInteger(data) { - return typeof data === "number" && data % 1 === 0; +// Copyright (c) Microsoft Corporation. +function getOperationLocationPollingUrl(inputs) { + const { azureAsyncOperation, operationLocation } = inputs; + return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation; } -/* End validation functions */ - -function validate(bool, cb, options) { - if (!isFunction(cb)) { - options = cb; - cb = null; - } - if (!isObject(options)) options = { Error: "Failed Check" }; - if (!bool) { - if (cb) { - cb(new ParameterError(options)); - } else { - throw new ParameterError(options); +function getLocationHeader(rawResponse) { + return rawResponse.headers["location"]; +} +function getOperationLocationHeader(rawResponse) { + return rawResponse.headers["operation-location"]; +} +function getAzureAsyncOperationHeader(rawResponse) { + return rawResponse.headers["azure-asyncoperation"]; +} +function findResourceLocation(inputs) { + const { location, requestMethod, requestPath, resourceLocationConfig } = inputs; + switch (requestMethod) { + case "PUT": { + return requestPath; + } + case "DELETE": { + return undefined; + } + default: { + switch (resourceLocationConfig) { + case "azure-async-operation": { + return undefined; + } + case "original-uri": { + return requestPath; + } + case "location": + default: { + return location; + } + } + } } - } } - -class ParameterError extends Error { - constructor(...params) { - super(...params); - } +function inferLroMode(inputs) { + const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs; + const operationLocation = getOperationLocationHeader(rawResponse); + const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse); + const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation }); + const location = getLocationHeader(rawResponse); + const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase(); + if (pollingUrl !== undefined) { + return { + mode: "OperationLocation", + operationLocation: pollingUrl, + resourceLocation: findResourceLocation({ + requestMethod: normalizedRequestMethod, + location, + requestPath, + resourceLocationConfig, + }), + }; + } + else if (location !== undefined) { + return { + mode: "ResourceLocation", + operationLocation: location, + }; + } + else if (normalizedRequestMethod === "PUT" && requestPath) { + return { + mode: "Body", + operationLocation: requestPath, + }; + } + else { + return undefined; + } +} +function transformStatus(status) { + switch (status === null || status === void 0 ? void 0 : status.toLowerCase()) { + case undefined: + case "succeeded": + return "succeeded"; + case "failed": + return "failed"; + case "running": + case "accepted": + case "canceling": + case "cancelling": + return "running"; + case "canceled": + case "cancelled": + return "canceled"; + default: { + logger.warning(`LRO: unrecognized operation status: ${status}`); + return status; + } + } +} +function getStatus(rawResponse) { + var _a; + const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + return transformStatus(status); +} +function getProvisioningState(rawResponse) { + var _a, _b; + const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + const state = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; + return transformStatus(state); +} +function toOperationStatus(statusCode) { + if (statusCode === 202) { + return "running"; + } + else if (statusCode < 300) { + return "succeeded"; + } + else { + return "failed"; + } +} +function parseRetryAfter({ rawResponse }) { + const retryAfter = rawResponse.headers["retry-after"]; + if (retryAfter !== undefined) { + // Retry-After header value is either in HTTP date format, or in seconds + const retryAfterInSeconds = parseInt(retryAfter); + return isNaN(retryAfterInSeconds) + ? calculatePollingIntervalFromDate(new Date(retryAfter)) + : retryAfterInSeconds * 1000; + } + return undefined; +} +function calculatePollingIntervalFromDate(retryAfterDate) { + const timeNow = Math.floor(new Date().getTime()); + const retryAfterTime = retryAfterDate.getTime(); + if (timeNow < retryAfterTime) { + return retryAfterTime - timeNow; + } + return undefined; +} +/** + * Initiates the long-running operation. + */ +async function initHttpOperation(inputs) { + const { stateProxy, resourceLocationConfig, processResult, lro } = inputs; + return initOperation({ + init: async () => { + const response = await lro.sendInitialRequest(); + const config = inferLroMode({ + rawResponse: response.rawResponse, + requestPath: lro.requestPath, + requestMethod: lro.requestMethod, + resourceLocationConfig, + }); + return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {})); + }, + stateProxy, + processResult: processResult + ? ({ flatResponse }, state) => processResult(flatResponse, state) + : ({ flatResponse }) => flatResponse, + getOperationStatus: (response, state) => { + var _a; + const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; + return mode === undefined || + (mode === "Body" && getOperationStatus(response, state) === "succeeded") + ? "succeeded" + : "running"; + }, + }); +} +function getOperationLocation({ rawResponse }, state) { + var _a; + const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; + switch (mode) { + case "OperationLocation": { + return getOperationLocationPollingUrl({ + operationLocation: getOperationLocationHeader(rawResponse), + azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse), + }); + } + case "ResourceLocation": { + return getLocationHeader(rawResponse); + } + case "Body": + default: { + return undefined; + } + } +} +function getOperationStatus({ rawResponse }, state) { + var _a; + const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; + switch (mode) { + case "OperationLocation": { + return getStatus(rawResponse); + } + case "ResourceLocation": { + return toOperationStatus(rawResponse.statusCode); + } + case "Body": { + return getProvisioningState(rawResponse); + } + default: + throw new Error(`Unexpected operation mode: ${mode}`); + } +} +/** Polls the long-running operation. */ +async function pollHttpOperation(inputs) { + const { lro, stateProxy, options, processResult, updateState, setDelay, state } = inputs; + return pollOperation({ + state, + stateProxy, + setDelay, + processResult: processResult + ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState) + : ({ flatResponse }) => flatResponse, + updateState, + getPollingInterval: parseRetryAfter, + getOperationLocation, + getOperationStatus, + options, + /** + * The expansion here is intentional because `lro` could be an object that + * references an inner this, so we need to preserve a reference to it. + */ + poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions), + }); } -exports.ParameterError = ParameterError; -exports.isFunction = isFunction; -exports.isNonEmptyString = isNonEmptyString; -exports.isDate = isDate; -exports.isEmptyString = isEmptyString; -exports.isString = isString; -exports.isObject = isObject; -exports.validate = validate; - - -/***/ }), - -/***/ 78742: -/***/ ((module) => { - -// generated by genversion -module.exports = '4.1.2' - - -/***/ }), - -/***/ 27094: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Map an optional value through a function + * @internal + */ +const maybemap = (value, f) => value === undefined ? undefined : f(value); +const INTERRUPTED = new Error("The poller is already stopped"); +/** + * A promise that delays resolution until a certain amount of time (in milliseconds) has passed, with facilities for + * robust cancellation. + * + * ### Example: + * + * ```javascript + * let toCancel; + * + * // Wait 20 seconds, and optionally allow the function to be cancelled. + * await delayMs(20000, (cancel) => { toCancel = cancel }); + * + * // ... if `toCancel` is called before the 20 second timer expires, then the delayMs promise will reject. + * ``` + * + * @internal + * @param ms - the number of milliseconds to wait before resolving + * @param cb - a callback that can provide the caller with a cancellation function + */ +function delayMs(ms) { + let aborted = false; + let toReject; + return Object.assign(new Promise((resolve, reject) => { + let token; + toReject = () => { + maybemap(token, clearTimeout); + reject(INTERRUPTED); + }; + // In the rare case that the operation is _already_ aborted, we will reject instantly. This could happen, for + // example, if the user calls the cancellation function immediately without yielding execution. + if (aborted) { + toReject(); + } + else { + token = setTimeout(resolve, ms); + } + }), { + cancel: () => { + aborted = true; + toReject === null || toReject === void 0 ? void 0 : toReject(); + }, + }); +} +// Copyright (c) Microsoft Corporation. +const createStateProxy$1 = () => ({ + /** + * The state at this point is created to be of type OperationState. + * It will be updated later to be of type TState when the + * customer-provided callback, `updateState`, is called during polling. + */ + initState: (config) => ({ status: "running", config }), + setCanceled: (state) => (state.status = "canceled"), + setError: (state, error) => (state.error = error), + setResult: (state, result) => (state.result = result), + setRunning: (state) => (state.status = "running"), + setSucceeded: (state) => (state.status = "succeeded"), + setFailed: (state) => (state.status = "failed"), + getError: (state) => state.error, + getResult: (state) => state.result, + isCanceled: (state) => state.status === "canceled", + isFailed: (state) => state.status === "failed", + isRunning: (state) => state.status === "running", + isSucceeded: (state) => state.status === "succeeded", +}); +/** + * Returns a poller factory. + */ +function buildCreatePoller(inputs) { + const { getOperationLocation, getStatusFromInitialResponse, getStatusFromPollResponse, getPollingInterval, } = inputs; + return async ({ init, poll }, options) => { + const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = POLL_INTERVAL_IN_MS, restoreFrom, } = options || {}; + const stateProxy = createStateProxy$1(); + const withOperationLocation = withOperationLocationCallback + ? (() => { + let called = false; + return (operationLocation, isUpdated) => { + if (isUpdated) + withOperationLocationCallback(operationLocation); + else if (!called) + withOperationLocationCallback(operationLocation); + called = true; + }; + })() + : undefined; + const state = restoreFrom + ? deserializeState(restoreFrom) + : await initOperation({ + init, + stateProxy, + processResult, + getOperationStatus: getStatusFromInitialResponse, + withOperationLocation, + }); + let resultPromise; + let cancelJob; + const abortController$1 = new abortController.AbortController(); + const handlers = new Map(); + const handleProgressEvents = async () => handlers.forEach((h) => h(state)); + let currentPollIntervalInMs = intervalInMs; + const poller = { + getOperationState: () => state, + getResult: () => state.result, + isDone: () => ["succeeded", "failed", "canceled"].includes(state.status), + isStopped: () => resultPromise === undefined, + stopPolling: () => { + abortController$1.abort(); + cancelJob === null || cancelJob === void 0 ? void 0 : cancelJob(); + }, + toString: () => JSON.stringify({ + state, + }), + onProgress: (callback) => { + const s = Symbol(); + handlers.set(s, callback); + return () => handlers.delete(s); + }, + pollUntilDone: (pollOptions) => (resultPromise !== null && resultPromise !== void 0 ? resultPromise : (resultPromise = (async () => { + const { abortSignal: inputAbortSignal } = pollOptions || {}; + const { signal: abortSignal } = inputAbortSignal + ? new abortController.AbortController([inputAbortSignal, abortController$1.signal]) + : abortController$1; + if (!poller.isDone()) { + await poller.poll({ abortSignal }); + while (!poller.isDone()) { + const delay = delayMs(currentPollIntervalInMs); + cancelJob = delay.cancel; + await delay; + await poller.poll({ abortSignal }); + } + } + switch (state.status) { + case "succeeded": { + return poller.getResult(); + } + case "canceled": { + throw new Error("Operation was canceled"); + } + case "failed": { + throw state.error; + } + case "notStarted": + case "running": { + // Unreachable + throw new Error(`polling completed without succeeding or failing`); + } + } + })().finally(() => { + resultPromise = undefined; + }))), + async poll(pollOptions) { + await pollOperation({ + poll, + state, + stateProxy, + getOperationLocation, + withOperationLocation, + getPollingInterval, + getOperationStatus: getStatusFromPollResponse, + processResult, + updateState, + options: pollOptions, + setDelay: (pollIntervalInMs) => { + currentPollIntervalInMs = pollIntervalInMs; + }, + }); + await handleProgressEvents(); + if (state.status === "canceled") { + throw new Error("Operation was canceled"); + } + if (state.status === "failed") { + throw state.error; + } + }, + }; + return poller; + }; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); +// Copyright (c) Microsoft Corporation. +/** + * Creates a poller that can be used to poll a long-running operation. + * @param lro - Description of the long-running operation + * @param options - options to configure the poller + * @returns an initialized poller + */ +async function createHttpPoller(lro, options) { + const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, } = options || {}; + return buildCreatePoller({ + getStatusFromInitialResponse: (response, state) => { + var _a; + const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; + return mode === undefined || + (mode === "Body" && getOperationStatus(response, state) === "succeeded") + ? "succeeded" + : "running"; + }, + getStatusFromPollResponse: getOperationStatus, + getOperationLocation, + getPollingInterval: parseRetryAfter, + })({ + init: async () => { + const response = await lro.sendInitialRequest(); + const config = inferLroMode({ + rawResponse: response.rawResponse, + requestPath: lro.requestPath, + requestMethod: lro.requestMethod, + resourceLocationConfig, + }); + return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {})); + }, + poll: lro.sendPollRequest, + }, { + intervalInMs, + withOperationLocation, + restoreFrom, + updateState, + processResult: processResult + ? ({ flatResponse }, state) => processResult(flatResponse, state) + : ({ flatResponse }) => flatResponse, + }); +} -var logger$1 = __nccwpck_require__(3233); +// Copyright (c) Microsoft Corporation. +const createStateProxy = () => ({ + initState: (config) => ({ config, isStarted: true }), + setCanceled: (state) => (state.isCancelled = true), + setError: (state, error) => (state.error = error), + setResult: (state, result) => (state.result = result), + setRunning: (state) => (state.isStarted = true), + setSucceeded: (state) => (state.isCompleted = true), + setFailed: () => { + /** empty body */ + }, + getError: (state) => state.error, + getResult: (state) => state.result, + isCanceled: (state) => !!state.isCancelled, + isFailed: (state) => !!state.error, + isRunning: (state) => !!state.isStarted, + isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error), +}); +class GenericPollOperation { + constructor(state, lro, lroResourceLocationConfig, processResult, updateState, isDone) { + this.state = state; + this.lro = lro; + this.lroResourceLocationConfig = lroResourceLocationConfig; + this.processResult = processResult; + this.updateState = updateState; + this.isDone = isDone; + } + setPollerConfig(pollerConfig) { + this.pollerConfig = pollerConfig; + } + async update(options) { + var _a; + const stateProxy = createStateProxy(); + if (!this.state.isStarted) { + this.state = Object.assign(Object.assign({}, this.state), (await initHttpOperation({ + lro: this.lro, + stateProxy, + resourceLocationConfig: this.lroResourceLocationConfig, + processResult: this.processResult, + }))); + } + const updateState = this.updateState; + const isDone = this.isDone; + if (!this.state.isCompleted) { + await pollHttpOperation({ + lro: this.lro, + state: this.state, + stateProxy, + processResult: this.processResult, + updateState: updateState + ? (state, { rawResponse }) => updateState(state, rawResponse) + : undefined, + isDone: isDone + ? ({ flatResponse }, state) => isDone(flatResponse, state) + : undefined, + options, + setDelay: (intervalInMs) => { + this.pollerConfig.intervalInMs = intervalInMs; + }, + }); + } + (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state); + return this; + } + async cancel() { + logger.error("`cancelOperation` is deprecated because it wasn't implemented"); + return this; + } + /** + * Serializes the Poller operation. + */ + toString() { + return JSON.stringify({ + state: this.state, + }); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -20372,12 +14533,12 @@ class Poller { * Starts a loop that will break only if the poller is done * or if the poller is stopped. */ - async startPolling() { + async startPolling(pollOptions = {}) { if (this.stopped) { this.stopped = false; } while (!this.isStopped() && !this.isDone()) { - await this.poll(); + await this.poll(pollOptions); await this.delay(); } } @@ -20448,7 +14609,7 @@ class Poller { } if (this.operation.state.isCancelled) { this.stopped = true; - const error = new PollerCancelledError("Poller cancelled"); + const error = new PollerCancelledError("Operation was canceled"); this.reject(error); throw error; } @@ -20464,9 +14625,9 @@ class Poller { /** * Returns a promise that will resolve once the underlying operation is completed. */ - async pollUntilDone() { + async pollUntilDone(pollOptions = {}) { if (this.stopped) { - this.startPolling().catch(this.reject); + this.startPolling(pollOptions).catch(this.reject); } // This is needed because the state could have been updated by // `cancelOperation`, e.g. the operation is canceled or an error occurred. @@ -20598,391 +14759,12 @@ class Poller { } // Copyright (c) Microsoft Corporation. -/** - * The `@azure/logger` configuration for this package. - * @internal - */ -const logger = logger$1.createClientLogger("core-lro"); - -// Copyright (c) Microsoft Corporation. -function throwIfUndefined(input, options = {}) { - var _a; - if (input === undefined) { - throw new Error((_a = options.errorMessage) !== null && _a !== void 0 ? _a : "undefined variable"); - } - return input; -} -function updatePollingUrl(inputs) { - var _a, _b; - const { info, rawResponse } = inputs; - switch (info.mode) { - case "OperationLocation": { - const operationLocation = getOperationLocation(rawResponse); - const azureAsyncOperation = getAzureAsyncOperation(rawResponse); - info.pollingUrl = - (_a = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation })) !== null && _a !== void 0 ? _a : throwIfUndefined(info.pollingUrl); - break; - } - case "ResourceLocation": { - info.pollingUrl = (_b = getLocation(rawResponse)) !== null && _b !== void 0 ? _b : throwIfUndefined(info.pollingUrl); - break; - } - } -} -function getOperationLocationPollingUrl(inputs) { - const { azureAsyncOperation, operationLocation } = inputs; - return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation; -} -function getLocation(rawResponse) { - return rawResponse.headers["location"]; -} -function getOperationLocation(rawResponse) { - return rawResponse.headers["operation-location"]; -} -function getAzureAsyncOperation(rawResponse) { - return rawResponse.headers["azure-asyncoperation"]; -} -function findResourceLocation(inputs) { - const { location, requestMethod, requestPath, lroResourceLocationConfig } = inputs; - switch (requestMethod) { - case "PUT": { - return requestPath; - } - case "DELETE": { - return undefined; - } - default: { - switch (lroResourceLocationConfig) { - case "azure-async-operation": { - return undefined; - } - case "original-uri": { - return requestPath; - } - case "location": - default: { - return location; - } - } - } - } -} -function inferLroMode(inputs) { - const { rawResponse, requestMethod, requestPath, lroResourceLocationConfig } = inputs; - const operationLocation = getOperationLocation(rawResponse); - const azureAsyncOperation = getAzureAsyncOperation(rawResponse); - const location = getLocation(rawResponse); - if (operationLocation !== undefined || azureAsyncOperation !== undefined) { - return { - mode: "OperationLocation", - pollingUrl: operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation, - resourceLocation: findResourceLocation({ - requestMethod, - location, - requestPath, - lroResourceLocationConfig, - }), - }; - } - else if (location !== undefined) { - return { - mode: "ResourceLocation", - pollingUrl: location, - }; - } - else if (requestMethod === "PUT") { - return { - mode: "Body", - pollingUrl: requestPath, - }; - } - else { - return { - mode: "None", - }; - } -} -class SimpleRestError extends Error { - constructor(message, statusCode) { - super(message); - this.name = "RestError"; - this.statusCode = statusCode; - Object.setPrototypeOf(this, SimpleRestError.prototype); - } -} -function throwIfError(rawResponse) { - const code = rawResponse.statusCode; - if (code >= 400) { - throw new SimpleRestError(`Received unexpected HTTP status code ${code} while polling. This may indicate a server issue.`, code); - } -} -function getStatus(rawResponse) { - var _a; - const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; - return typeof status === "string" ? status.toLowerCase() : "succeeded"; -} -function getProvisioningState(rawResponse) { - var _a, _b; - const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; - const state = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; - return typeof state === "string" ? state.toLowerCase() : "succeeded"; -} -function isCanceled(operation) { - const { state, operationStatus } = operation; - if (["canceled", "cancelled"].includes(operationStatus)) { - state.isCancelled = true; - return true; - } - return false; -} -function isTerminal(operation) { - const { state, operationStatus } = operation; - if (operationStatus === "failed") { - throw new Error(`The long-running operation has failed.`); - } - return operationStatus === "succeeded" || isCanceled({ state, operationStatus }); -} -function getOperationStatus(result) { - const { rawResponse, state, info, responseKind = "Polling" } = result; - throwIfError(rawResponse); - switch (info.mode) { - case "OperationLocation": { - const operationStatus = getStatus(rawResponse); - return { - operationStatus, - shouldStopPolling: responseKind === "Polling" && isTerminal({ state, operationStatus }), - }; - } - case "Body": { - const operationStatus = getProvisioningState(rawResponse); - return { - operationStatus, - shouldStopPolling: isTerminal({ state, operationStatus }), - }; - } - case "ResourceLocation": { - const operationStatus = rawResponse.statusCode; - return { - operationStatus, - shouldStopPolling: responseKind === "Polling" && operationStatus !== 202, - }; - } - case "None": { - return { - shouldStopPolling: true, - }; - } - } -} -function shouldStopPolling(result) { - const { rawResponse, state, info, responseKind = "Polling" } = result; - const { shouldStopPolling: isPollingStopped, operationStatus } = getOperationStatus({ - info, - rawResponse, - state, - responseKind, - }); - if (operationStatus) { - logger.verbose(`LRO: Status:\n\tPolling from: ${info.pollingUrl}\n\tOperation status: ${operationStatus}\n\tPolling status: ${isPollingStopped ? "Stopped" : "Running"}`); - } - else { - logger.verbose(`LRO: Status: Not an LRO`); - } - return isPollingStopped; -} -/** - * Creates a polling operation. - */ -function createPoll(lroPrimitives) { - return async (path, pollerConfig, getLroStatusFromResponse) => { - const response = await lroPrimitives.sendPollRequest(path); - const retryAfter = response.rawResponse.headers["retry-after"]; - if (retryAfter !== undefined) { - // Retry-After header value is either in HTTP date format, or in seconds - const retryAfterInSeconds = parseInt(retryAfter); - pollerConfig.intervalInMs = isNaN(retryAfterInSeconds) - ? calculatePollingIntervalFromDate(new Date(retryAfter), pollerConfig.intervalInMs) - : retryAfterInSeconds * 1000; - } - return getLroStatusFromResponse(response); - }; -} -function calculatePollingIntervalFromDate(retryAfterDate, defaultIntervalInMs) { - const timeNow = Math.floor(new Date().getTime()); - const retryAfterTime = retryAfterDate.getTime(); - if (timeNow < retryAfterTime) { - return retryAfterTime - timeNow; - } - return defaultIntervalInMs; -} -function buildResult(inputs) { - const { processResult, response, state } = inputs; - return processResult ? processResult(response, state) : response; -} -/** - * Creates a callback to be used to initialize the polling operation state. - */ -function createStateInitializer(inputs) { - const { requestMethod, requestPath, state, lroResourceLocationConfig, processResult } = inputs; - return (response) => { - const { rawResponse } = response; - state.isStarted = true; - state.config = inferLroMode({ - rawResponse, - requestPath, - requestMethod, - lroResourceLocationConfig, - }); - logger.verbose(`LRO: Operation description:`, state.config); - /** short circuit before polling */ - if (shouldStopPolling({ - rawResponse, - state, - info: state.config, - responseKind: "Initial", - })) { - state.result = buildResult({ - response: response.flatResponse, - state: state, - processResult, - }); - state.isCompleted = true; - } - }; -} -function createGetLroStatusFromResponse(inputs) { - const { lro, state, info } = inputs; - const location = info.resourceLocation; - return (response) => { - const isTerminalStatus = shouldStopPolling({ - info, - rawResponse: response.rawResponse, - state, - }); - return Object.assign(Object.assign({}, response), { done: isTerminalStatus && !location, next: !(isTerminalStatus && location) - ? undefined - : () => lro.sendPollRequest(location).then((res) => (Object.assign(Object.assign({}, res), { done: true }))) }); - }; -} - -// Copyright (c) Microsoft Corporation. -class GenericPollOperation { - constructor(state, lro, lroResourceLocationConfig, processResult, updateState, isDone) { - this.state = state; - this.lro = lro; - this.lroResourceLocationConfig = lroResourceLocationConfig; - this.processResult = processResult; - this.updateState = updateState; - this.isDone = isDone; - } - setPollerConfig(pollerConfig) { - this.pollerConfig = pollerConfig; - } - /** - * General update function for LROPoller, the general process is as follows - * 1. Check initial operation result to determine the strategy to use - * - Strategies: Location, Azure-AsyncOperation, Original Uri - * 2. Check if the operation result has a terminal state - * - Terminal state will be determined by each strategy - * 2.1 If it is terminal state Check if a final GET request is required, if so - * send final GET request and return result from operation. If no final GET - * is required, just return the result from operation. - * - Determining what to call for final request is responsibility of each strategy - * 2.2 If it is not terminal state, call the polling operation and go to step 1 - * - Determining what to call for polling is responsibility of each strategy - * - Strategies will always use the latest URI for polling if provided otherwise - * the last known one - */ - async update(options) { - var _a, _b, _c; - const state = this.state; - let lastResponse = undefined; - if (!state.isStarted) { - const initializeState = createStateInitializer({ - state, - requestPath: this.lro.requestPath, - requestMethod: this.lro.requestMethod, - lroResourceLocationConfig: this.lroResourceLocationConfig, - processResult: this.processResult, - }); - lastResponse = await this.lro.sendInitialRequest(); - initializeState(lastResponse); - } - if (!state.isCompleted) { - const config = throwIfUndefined(state.config, { - errorMessage: "Bad state: LRO mode is undefined. Check if the serialized state is well-formed.", - }); - if (!this.poll) { - this.poll = createPoll(this.lro); - } - if (!this.getLroStatusFromResponse) { - const isDone = this.isDone; - this.getLroStatusFromResponse = isDone - ? (response) => (Object.assign(Object.assign({}, response), { done: isDone(response.flatResponse, this.state) })) - : createGetLroStatusFromResponse({ - lro: this.lro, - info: config, - state: this.state, - }); - } - const currentState = await this.poll(throwIfUndefined(config.pollingUrl), this.pollerConfig, this.getLroStatusFromResponse); - if (currentState.done) { - state.result = buildResult({ - response: currentState.flatResponse, - state, - processResult: this.processResult, - }); - state.isCompleted = true; - } - else { - this.poll = (_a = currentState.next) !== null && _a !== void 0 ? _a : this.poll; - updatePollingUrl({ - rawResponse: currentState.rawResponse, - info: config, - }); - /** for backward compatability */ - state.pollingURL = config.pollingUrl; - } - lastResponse = currentState; - } - if (lastResponse) { - (_b = this.updateState) === null || _b === void 0 ? void 0 : _b.call(this, state, lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.rawResponse); - } - else { - logger.error(`LRO: no response was received`); - } - (_c = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _c === void 0 ? void 0 : _c.call(options, state); - return this; - } - async cancel() { - logger.error("`cancelOperation` is deprecated because it wasn't implemented"); - return this; - } - /** - * Serializes the Poller operation. - */ - toString() { - return JSON.stringify({ - state: this.state, - }); - } -} - -// Copyright (c) Microsoft Corporation. -function deserializeState(serializedState) { - try { - return JSON.parse(serializedState).state; - } - catch (e) { - throw new Error(`LroEngine: Unable to deserialize state: ${serializedState}`); - } -} /** * The LRO Engine, a class that performs polling. */ class LroEngine extends Poller { constructor(lro, options) { - const { intervalInMs = 2000, resumeFrom } = options || {}; + const { intervalInMs = POLL_INTERVAL_IN_MS, resumeFrom } = options || {}; const state = resumeFrom ? deserializeState(resumeFrom) : {}; @@ -21003,12 +14785,13 @@ exports.LroEngine = LroEngine; exports.Poller = Poller; exports.PollerCancelledError = PollerCancelledError; exports.PollerStoppedError = PollerStoppedError; +exports.createHttpPoller = createHttpPoller; //# sourceMappingURL=index.js.map /***/ }), -/***/ 74559: +/***/ 67902: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -21016,7 +14799,7 @@ exports.PollerStoppedError = PollerStoppedError; Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib = __nccwpck_require__(4351); +var tslib = __nccwpck_require__(71398); // Copyright (c) Microsoft Corporation. /** @@ -21094,7 +14877,7 @@ exports.getPagedAsyncIterator = getPagedAsyncIterator; /***/ }), -/***/ 94175: +/***/ 73179: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -21102,7 +14885,7 @@ exports.getPagedAsyncIterator = getPagedAsyncIterator; Object.defineProperty(exports, "__esModule", ({ value: true })); -var api = __nccwpck_require__(65163); +var api = __nccwpck_require__(68822); // Copyright (c) Microsoft Corporation. (function (SpanKind) { @@ -21321,7 +15104,181 @@ exports.setSpanContext = setSpanContext; /***/ }), -/***/ 3233: +/***/ 33267: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var crypto = __nccwpck_require__(6113); + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +var _a; +/** + * A constant that indicates whether the environment the code is running is Node.JS. + */ +const isNode = typeof process !== "undefined" && Boolean(process.version) && Boolean((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node); + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds. + * @param timeInMs - The number of milliseconds to be delayed. + * @returns Promise that is resolved after timeInMs + */ +function delay(timeInMs) { + return new Promise((resolve) => setTimeout(() => resolve(), timeInMs)); +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Returns a random integer value between a lower and upper bound, + * inclusive of both bounds. + * Note that this uses Math.random and isn't secure. If you need to use + * this for any kind of security purpose, find a better source of random. + * @param min - The smallest integer value allowed. + * @param max - The largest integer value allowed. + */ +function getRandomIntegerInclusive(min, max) { + // Make sure inputs are integers. + min = Math.ceil(min); + max = Math.floor(max); + // Pick a random offset from zero to the size of the range. + // Since Math.random() can never return 1, we have to make the range one larger + // in order to be inclusive of the maximum value after we take the floor. + const offset = Math.floor(Math.random() * (max - min + 1)); + return offset + min; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Helper to determine when an input is a generic JS object. + * @returns true when input is an object type that is not null, Array, RegExp, or Date. + */ +function isObject(input) { + return (typeof input === "object" && + input !== null && + !Array.isArray(input) && + !(input instanceof RegExp) && + !(input instanceof Date)); +} + +// Copyright (c) Microsoft Corporation. +/** + * Typeguard for an error object shape (has name and message) + * @param e - Something caught by a catch clause. + */ +function isError(e) { + if (isObject(e)) { + const hasName = typeof e.name === "string"; + const hasMessage = typeof e.message === "string"; + return hasName && hasMessage; + } + return false; +} +/** + * Given what is thought to be an error object, return the message if possible. + * If the message is missing, returns a stringified version of the input. + * @param e - Something thrown from a try block + * @returns The error message or a string of the input + */ +function getErrorMessage(e) { + if (isError(e)) { + return e.message; + } + else { + let stringified; + try { + if (typeof e === "object" && e) { + stringified = JSON.stringify(e); + } + else { + stringified = String(e); + } + } + catch (err) { + stringified = "[unable to stringify input]"; + } + return `Unknown error ${stringified}`; + } +} + +// Copyright (c) Microsoft Corporation. +/** + * Generates a SHA-256 HMAC signature. + * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash. + * @param stringToSign - The data to be signed. + * @param encoding - The textual encoding to use for the returned HMAC digest. + */ +async function computeSha256Hmac(key, stringToSign, encoding) { + const decodedKey = Buffer.from(key, "base64"); + return crypto.createHmac("sha256", decodedKey).update(stringToSign).digest(encoding); +} +/** + * Generates a SHA-256 hash. + * @param content - The data to be included in the hash. + * @param encoding - The textual encoding to use for the returned hash. + */ +async function computeSha256Hash(content, encoding) { + return crypto.createHash("sha256").update(content).digest(encoding); +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Helper TypeGuard that checks if something is defined or not. + * @param thing - Anything + */ +function isDefined(thing) { + return typeof thing !== "undefined" && thing !== null; +} +/** + * Helper TypeGuard that checks if the input is an object with the specified properties. + * @param thing - Anything. + * @param properties - The name of the properties that should appear in the object. + */ +function isObjectWithProperties(thing, properties) { + if (!isDefined(thing) || typeof thing !== "object") { + return false; + } + for (const property of properties) { + if (!objectHasProperty(thing, property)) { + return false; + } + } + return true; +} +/** + * Helper TypeGuard that checks if the input is an object with the specified property. + * @param thing - Any object. + * @param property - The name of the property that should appear in the object. + */ +function objectHasProperty(thing, property) { + return (isDefined(thing) && typeof thing === "object" && property in thing); +} + +exports.computeSha256Hash = computeSha256Hash; +exports.computeSha256Hmac = computeSha256Hmac; +exports.delay = delay; +exports.getErrorMessage = getErrorMessage; +exports.getRandomIntegerInclusive = getRandomIntegerInclusive; +exports.isDefined = isDefined; +exports.isError = isError; +exports.isNode = isNode; +exports.isObject = isObject; +exports.isObjectWithProperties = isObjectWithProperties; +exports.objectHasProperty = objectHasProperty; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 63264: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -21539,7 +15496,7 @@ exports.setLogLevel = setLogLevel; /***/ }), -/***/ 84100: +/***/ 36835: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -21547,16 +15504,16 @@ exports.setLogLevel = setLogLevel; Object.defineProperty(exports, "__esModule", ({ value: true })); -var coreHttp = __nccwpck_require__(24607); -var tslib = __nccwpck_require__(4351); -var coreTracing = __nccwpck_require__(94175); -var logger$1 = __nccwpck_require__(3233); -var abortController = __nccwpck_require__(52557); +var coreHttp = __nccwpck_require__(12372); +var tslib = __nccwpck_require__(71398); +var coreTracing = __nccwpck_require__(73179); +var logger$1 = __nccwpck_require__(63264); +var abortController = __nccwpck_require__(97675); var os = __nccwpck_require__(22037); var crypto = __nccwpck_require__(6113); var stream = __nccwpck_require__(12781); -__nccwpck_require__(74559); -var coreLro = __nccwpck_require__(27094); +__nccwpck_require__(67902); +var coreLro = __nccwpck_require__(57395); var events = __nccwpck_require__(82361); var fs = __nccwpck_require__(57147); var util = __nccwpck_require__(73837); @@ -46886,7 +40843,7 @@ exports.newPipeline = newPipeline; /***/ }), -/***/ 40334: +/***/ 2268: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -46949,7 +40906,7 @@ exports.createTokenAuth = createTokenAuth; /***/ }), -/***/ 76762: +/***/ 33520: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -46957,11 +40914,11 @@ exports.createTokenAuth = createTokenAuth; Object.defineProperty(exports, "__esModule", ({ value: true })); -var universalUserAgent = __nccwpck_require__(45030); -var beforeAfterHook = __nccwpck_require__(83682); -var request = __nccwpck_require__(36234); -var graphql = __nccwpck_require__(88467); -var authToken = __nccwpck_require__(40334); +var universalUserAgent = __nccwpck_require__(37571); +var beforeAfterHook = __nccwpck_require__(79081); +var request = __nccwpck_require__(89610); +var graphql = __nccwpck_require__(88129); +var authToken = __nccwpck_require__(2268); function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; @@ -47133,7 +41090,7 @@ exports.Octokit = Octokit; /***/ }), -/***/ 59440: +/***/ 48658: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -47141,8 +41098,8 @@ exports.Octokit = Octokit; Object.defineProperty(exports, "__esModule", ({ value: true })); -var isPlainObject = __nccwpck_require__(63287); -var universalUserAgent = __nccwpck_require__(45030); +var isPlainObject = __nccwpck_require__(34014); +var universalUserAgent = __nccwpck_require__(37571); function lowercaseKeys(object) { if (!object) { @@ -47531,7 +41488,7 @@ exports.endpoint = endpoint; /***/ }), -/***/ 88467: +/***/ 88129: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -47539,8 +41496,8 @@ exports.endpoint = endpoint; Object.defineProperty(exports, "__esModule", ({ value: true })); -var request = __nccwpck_require__(36234); -var universalUserAgent = __nccwpck_require__(45030); +var request = __nccwpck_require__(89610); +var universalUserAgent = __nccwpck_require__(37571); const VERSION = "4.8.0"; @@ -47657,7 +41614,7 @@ exports.withCustomRequest = withCustomRequest; /***/ }), -/***/ 64193: +/***/ 38810: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -47870,7 +41827,7 @@ exports.paginatingEndpoints = paginatingEndpoints; /***/ }), -/***/ 83044: +/***/ 55628: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -48985,7 +42942,7 @@ exports.restEndpointMethods = restEndpointMethods; /***/ }), -/***/ 10537: +/***/ 60877: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -48995,8 +42952,8 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var deprecation = __nccwpck_require__(58932); -var once = _interopDefault(__nccwpck_require__(1223)); +var deprecation = __nccwpck_require__(38455); +var once = _interopDefault(__nccwpck_require__(86210)); const logOnceCode = once(deprecation => console.warn(deprecation)); const logOnceHeaders = once(deprecation => console.warn(deprecation)); @@ -49067,7 +43024,7 @@ exports.RequestError = RequestError; /***/ }), -/***/ 36234: +/***/ 89610: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49077,11 +43034,11 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var endpoint = __nccwpck_require__(59440); -var universalUserAgent = __nccwpck_require__(45030); -var isPlainObject = __nccwpck_require__(63287); -var nodeFetch = _interopDefault(__nccwpck_require__(80467)); -var requestError = __nccwpck_require__(10537); +var endpoint = __nccwpck_require__(48658); +var universalUserAgent = __nccwpck_require__(37571); +var isPlainObject = __nccwpck_require__(34014); +var nodeFetch = _interopDefault(__nccwpck_require__(69608)); +var requestError = __nccwpck_require__(60877); const VERSION = "5.6.3"; @@ -49252,7 +43209,7 @@ exports.request = request; /***/ }), -/***/ 57171: +/***/ 43840: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -49279,9 +43236,9 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ContextAPI = void 0; -var NoopContextManager_1 = __nccwpck_require__(54118); -var global_utils_1 = __nccwpck_require__(85135); -var diag_1 = __nccwpck_require__(11877); +var NoopContextManager_1 = __nccwpck_require__(46623); +var global_utils_1 = __nccwpck_require__(37521); +var diag_1 = __nccwpck_require__(72505); var API_NAME = 'context'; var NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); /** @@ -49352,7 +43309,7 @@ exports.ContextAPI = ContextAPI; /***/ }), -/***/ 11877: +/***/ 72505: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49374,10 +43331,10 @@ exports.ContextAPI = ContextAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagAPI = void 0; -var ComponentLogger_1 = __nccwpck_require__(17978); -var logLevelLogger_1 = __nccwpck_require__(99639); -var types_1 = __nccwpck_require__(78077); -var global_utils_1 = __nccwpck_require__(85135); +var ComponentLogger_1 = __nccwpck_require__(22789); +var logLevelLogger_1 = __nccwpck_require__(76225); +var types_1 = __nccwpck_require__(89990); +var global_utils_1 = __nccwpck_require__(37521); var API_NAME = 'diag'; /** * Singleton object which represents the entry point to the OpenTelemetry internal @@ -49452,7 +43409,7 @@ exports.DiagAPI = DiagAPI; /***/ }), -/***/ 89909: +/***/ 86317: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49474,12 +43431,12 @@ exports.DiagAPI = DiagAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PropagationAPI = void 0; -var global_utils_1 = __nccwpck_require__(85135); -var NoopTextMapPropagator_1 = __nccwpck_require__(72368); -var TextMapPropagator_1 = __nccwpck_require__(80865); -var context_helpers_1 = __nccwpck_require__(37682); -var utils_1 = __nccwpck_require__(28136); -var diag_1 = __nccwpck_require__(11877); +var global_utils_1 = __nccwpck_require__(37521); +var NoopTextMapPropagator_1 = __nccwpck_require__(87155); +var TextMapPropagator_1 = __nccwpck_require__(61407); +var context_helpers_1 = __nccwpck_require__(20325); +var utils_1 = __nccwpck_require__(84438); +var diag_1 = __nccwpck_require__(72505); var API_NAME = 'propagation'; var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); /** @@ -49550,7 +43507,7 @@ exports.PropagationAPI = PropagationAPI; /***/ }), -/***/ 81539: +/***/ 4596: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49572,11 +43529,11 @@ exports.PropagationAPI = PropagationAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceAPI = void 0; -var global_utils_1 = __nccwpck_require__(85135); -var ProxyTracerProvider_1 = __nccwpck_require__(2285); -var spancontext_utils_1 = __nccwpck_require__(49745); -var context_utils_1 = __nccwpck_require__(23326); -var diag_1 = __nccwpck_require__(11877); +var global_utils_1 = __nccwpck_require__(37521); +var ProxyTracerProvider_1 = __nccwpck_require__(76409); +var spancontext_utils_1 = __nccwpck_require__(86095); +var context_utils_1 = __nccwpck_require__(88612); +var diag_1 = __nccwpck_require__(72505); var API_NAME = 'trace'; /** * Singleton object which represents the entry point to the OpenTelemetry Tracing API @@ -49589,6 +43546,7 @@ var TraceAPI = /** @class */ (function () { this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; this.deleteSpan = context_utils_1.deleteSpan; this.getSpan = context_utils_1.getSpan; + this.getActiveSpan = context_utils_1.getActiveSpan; this.getSpanContext = context_utils_1.getSpanContext; this.setSpan = context_utils_1.setSpan; this.setSpanContext = context_utils_1.setSpanContext; @@ -49636,7 +43594,7 @@ exports.TraceAPI = TraceAPI; /***/ }), -/***/ 37682: +/***/ 20325: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49658,7 +43616,7 @@ exports.TraceAPI = TraceAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deleteBaggage = exports.setBaggage = exports.getBaggage = void 0; -var context_1 = __nccwpck_require__(78242); +var context_1 = __nccwpck_require__(46565); /** * Baggage key */ @@ -49696,7 +43654,7 @@ exports.deleteBaggage = deleteBaggage; /***/ }), -/***/ 84811: +/***/ 2323: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49767,7 +43725,7 @@ exports.BaggageImpl = BaggageImpl; /***/ }), -/***/ 23542: +/***/ 58023: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49797,7 +43755,7 @@ exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); /***/ }), -/***/ 91508: +/***/ 5264: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49822,7 +43780,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 28136: +/***/ 84438: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49844,9 +43802,9 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.baggageEntryMetadataFromString = exports.createBaggage = void 0; -var diag_1 = __nccwpck_require__(11877); -var baggage_impl_1 = __nccwpck_require__(84811); -var symbol_1 = __nccwpck_require__(23542); +var diag_1 = __nccwpck_require__(72505); +var baggage_impl_1 = __nccwpck_require__(2323); +var symbol_1 = __nccwpck_require__(58023); var diag = diag_1.DiagAPI.instance(); /** * Create a new Baggage with optional entries @@ -49881,7 +43839,7 @@ exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; /***/ }), -/***/ 1109: +/***/ 82272: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49906,7 +43864,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 14447: +/***/ 93548: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49931,7 +43889,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 92358: +/***/ 74327: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49941,7 +43899,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 54118: +/***/ 46623: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -49968,7 +43926,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopContextManager = void 0; -var context_1 = __nccwpck_require__(78242); +var context_1 = __nccwpck_require__(46565); var NoopContextManager = /** @class */ (function () { function NoopContextManager() { } @@ -49998,7 +43956,7 @@ exports.NoopContextManager = NoopContextManager; /***/ }), -/***/ 78242: +/***/ 46565: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -50061,7 +44019,7 @@ exports.ROOT_CONTEXT = new BaseContext(); /***/ }), -/***/ 36504: +/***/ 32798: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -50086,7 +44044,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 17978: +/***/ 22789: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -50108,7 +44066,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagComponentLogger = void 0; -var global_utils_1 = __nccwpck_require__(85135); +var global_utils_1 = __nccwpck_require__(37521); /** * Component Logger which is meant to be used as part of any component which * will add automatically additional namespace in front of the log message. @@ -50173,7 +44131,7 @@ function logProxy(funcName, namespace, args) { /***/ }), -/***/ 3041: +/***/ 29946: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -50242,7 +44200,7 @@ exports.DiagConsoleLogger = DiagConsoleLogger; /***/ }), -/***/ 31634: +/***/ 87213: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -50273,13 +44231,13 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -__exportStar(__nccwpck_require__(3041), exports); -__exportStar(__nccwpck_require__(78077), exports); +__exportStar(__nccwpck_require__(29946), exports); +__exportStar(__nccwpck_require__(89990), exports); //# sourceMappingURL=index.js.map /***/ }), -/***/ 99639: +/***/ 76225: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -50301,7 +44259,7 @@ __exportStar(__nccwpck_require__(78077), exports); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createLogLevelDiagLogger = void 0; -var types_1 = __nccwpck_require__(78077); +var types_1 = __nccwpck_require__(89990); function createLogLevelDiagLogger(maxLevel, logger) { if (maxLevel < types_1.DiagLogLevel.NONE) { maxLevel = types_1.DiagLogLevel.NONE; @@ -50331,7 +44289,7 @@ exports.createLogLevelDiagLogger = createLogLevelDiagLogger; /***/ }), -/***/ 78077: +/***/ 89990: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -50382,7 +44340,7 @@ var DiagLogLevel; /***/ }), -/***/ 65163: +/***/ 68822: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -50414,52 +44372,52 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.diag = exports.propagation = exports.trace = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.baggageEntryMetadataFromString = void 0; -__exportStar(__nccwpck_require__(91508), exports); -var utils_1 = __nccwpck_require__(28136); +__exportStar(__nccwpck_require__(5264), exports); +var utils_1 = __nccwpck_require__(84438); Object.defineProperty(exports, "baggageEntryMetadataFromString", ({ enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } })); -__exportStar(__nccwpck_require__(14447), exports); -__exportStar(__nccwpck_require__(92358), exports); -__exportStar(__nccwpck_require__(1109), exports); -__exportStar(__nccwpck_require__(31634), exports); -__exportStar(__nccwpck_require__(80865), exports); -__exportStar(__nccwpck_require__(57492), exports); -__exportStar(__nccwpck_require__(44023), exports); -__exportStar(__nccwpck_require__(43503), exports); -__exportStar(__nccwpck_require__(2285), exports); -__exportStar(__nccwpck_require__(19671), exports); -__exportStar(__nccwpck_require__(33209), exports); -__exportStar(__nccwpck_require__(15769), exports); -__exportStar(__nccwpck_require__(31424), exports); -__exportStar(__nccwpck_require__(4416), exports); -__exportStar(__nccwpck_require__(20955), exports); -__exportStar(__nccwpck_require__(48845), exports); -__exportStar(__nccwpck_require__(26905), exports); -__exportStar(__nccwpck_require__(88384), exports); -var utils_2 = __nccwpck_require__(32615); +__exportStar(__nccwpck_require__(93548), exports); +__exportStar(__nccwpck_require__(74327), exports); +__exportStar(__nccwpck_require__(82272), exports); +__exportStar(__nccwpck_require__(87213), exports); +__exportStar(__nccwpck_require__(61407), exports); +__exportStar(__nccwpck_require__(11926), exports); +__exportStar(__nccwpck_require__(64072), exports); +__exportStar(__nccwpck_require__(43866), exports); +__exportStar(__nccwpck_require__(76409), exports); +__exportStar(__nccwpck_require__(14310), exports); +__exportStar(__nccwpck_require__(72560), exports); +__exportStar(__nccwpck_require__(91613), exports); +__exportStar(__nccwpck_require__(38423), exports); +__exportStar(__nccwpck_require__(64750), exports); +__exportStar(__nccwpck_require__(39240), exports); +__exportStar(__nccwpck_require__(8970), exports); +__exportStar(__nccwpck_require__(5683), exports); +__exportStar(__nccwpck_require__(66021), exports); +var utils_2 = __nccwpck_require__(48088); Object.defineProperty(exports, "createTraceState", ({ enumerable: true, get: function () { return utils_2.createTraceState; } })); -__exportStar(__nccwpck_require__(30891), exports); -__exportStar(__nccwpck_require__(33168), exports); -__exportStar(__nccwpck_require__(91823), exports); -var spancontext_utils_1 = __nccwpck_require__(49745); +__exportStar(__nccwpck_require__(22882), exports); +__exportStar(__nccwpck_require__(92707), exports); +__exportStar(__nccwpck_require__(90655), exports); +var spancontext_utils_1 = __nccwpck_require__(86095); Object.defineProperty(exports, "isSpanContextValid", ({ enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } })); Object.defineProperty(exports, "isValidTraceId", ({ enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } })); Object.defineProperty(exports, "isValidSpanId", ({ enumerable: true, get: function () { return spancontext_utils_1.isValidSpanId; } })); -var invalid_span_constants_1 = __nccwpck_require__(91760); +var invalid_span_constants_1 = __nccwpck_require__(22926); Object.defineProperty(exports, "INVALID_SPANID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } })); Object.defineProperty(exports, "INVALID_TRACEID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } })); Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } })); -__exportStar(__nccwpck_require__(78242), exports); -__exportStar(__nccwpck_require__(36504), exports); -var context_1 = __nccwpck_require__(57171); +__exportStar(__nccwpck_require__(46565), exports); +__exportStar(__nccwpck_require__(32798), exports); +var context_1 = __nccwpck_require__(43840); /** Entrypoint for context API */ exports.context = context_1.ContextAPI.getInstance(); -var trace_1 = __nccwpck_require__(81539); +var trace_1 = __nccwpck_require__(4596); /** Entrypoint for trace API */ exports.trace = trace_1.TraceAPI.getInstance(); -var propagation_1 = __nccwpck_require__(89909); +var propagation_1 = __nccwpck_require__(86317); /** Entrypoint for propagation API */ exports.propagation = propagation_1.PropagationAPI.getInstance(); -var diag_1 = __nccwpck_require__(11877); +var diag_1 = __nccwpck_require__(72505); /** * Entrypoint for Diag API. * Defines Diagnostic handler used for internal diagnostic logging operations. @@ -50477,7 +44435,7 @@ exports["default"] = { /***/ }), -/***/ 85135: +/***/ 37521: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -50499,9 +44457,9 @@ exports["default"] = { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; -var platform_1 = __nccwpck_require__(99957); -var version_1 = __nccwpck_require__(98996); -var semver_1 = __nccwpck_require__(81522); +var platform_1 = __nccwpck_require__(27573); +var version_1 = __nccwpck_require__(87189); +var semver_1 = __nccwpck_require__(94690); var major = version_1.VERSION.split('.')[0]; var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major); var _global = platform_1._globalThis; @@ -50549,7 +44507,7 @@ exports.unregisterGlobal = unregisterGlobal; /***/ }), -/***/ 81522: +/***/ 94690: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -50571,7 +44529,7 @@ exports.unregisterGlobal = unregisterGlobal; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isCompatible = exports._makeCompatibilityCheck = void 0; -var version_1 = __nccwpck_require__(98996); +var version_1 = __nccwpck_require__(87189); var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; /** * Create a function to test an API version to see if it is compatible with the provided ownVersion. @@ -50678,7 +44636,7 @@ exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION); /***/ }), -/***/ 99957: +/***/ 27573: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -50709,12 +44667,12 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -__exportStar(__nccwpck_require__(87200), exports); +__exportStar(__nccwpck_require__(33590), exports); //# sourceMappingURL=index.js.map /***/ }), -/***/ 89406: +/***/ 92825: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -50743,7 +44701,7 @@ exports._globalThis = typeof globalThis === 'object' ? globalThis : global; /***/ }), -/***/ 87200: +/***/ 33590: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -50774,12 +44732,12 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -__exportStar(__nccwpck_require__(89406), exports); +__exportStar(__nccwpck_require__(92825), exports); //# sourceMappingURL=index.js.map /***/ }), -/***/ 72368: +/***/ 87155: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -50823,7 +44781,7 @@ exports.NoopTextMapPropagator = NoopTextMapPropagator; /***/ }), -/***/ 80865: +/***/ 61407: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -50871,7 +44829,7 @@ exports.defaultTextMapSetter = { /***/ }), -/***/ 81462: +/***/ 12855: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -50893,7 +44851,7 @@ exports.defaultTextMapSetter = { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NonRecordingSpan = void 0; -var invalid_span_constants_1 = __nccwpck_require__(91760); +var invalid_span_constants_1 = __nccwpck_require__(22926); /** * The NonRecordingSpan is the default {@link Span} that is used when no Span * implementation is available. All operations are no-op including context @@ -50943,7 +44901,7 @@ exports.NonRecordingSpan = NonRecordingSpan; /***/ }), -/***/ 17606: +/***/ 15459: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -50965,10 +44923,10 @@ exports.NonRecordingSpan = NonRecordingSpan; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracer = void 0; -var context_1 = __nccwpck_require__(57171); -var context_utils_1 = __nccwpck_require__(23326); -var NonRecordingSpan_1 = __nccwpck_require__(81462); -var spancontext_utils_1 = __nccwpck_require__(49745); +var context_1 = __nccwpck_require__(43840); +var context_utils_1 = __nccwpck_require__(88612); +var NonRecordingSpan_1 = __nccwpck_require__(12855); +var spancontext_utils_1 = __nccwpck_require__(86095); var context = context_1.ContextAPI.getInstance(); /** * No-op implementations of {@link Tracer}. @@ -51028,7 +44986,7 @@ function isSpanContext(spanContext) { /***/ }), -/***/ 23259: +/***/ 80848: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -51050,7 +45008,7 @@ function isSpanContext(spanContext) { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracerProvider = void 0; -var NoopTracer_1 = __nccwpck_require__(17606); +var NoopTracer_1 = __nccwpck_require__(15459); /** * An implementation of the {@link TracerProvider} which returns an impotent * Tracer for all calls to `getTracer`. @@ -51070,7 +45028,7 @@ exports.NoopTracerProvider = NoopTracerProvider; /***/ }), -/***/ 43503: +/***/ 43866: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -51092,7 +45050,7 @@ exports.NoopTracerProvider = NoopTracerProvider; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracer = void 0; -var NoopTracer_1 = __nccwpck_require__(17606); +var NoopTracer_1 = __nccwpck_require__(15459); var NOOP_TRACER = new NoopTracer_1.NoopTracer(); /** * Proxy tracer provided by the proxy tracer provider @@ -51133,7 +45091,7 @@ exports.ProxyTracer = ProxyTracer; /***/ }), -/***/ 2285: +/***/ 76409: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -51155,8 +45113,8 @@ exports.ProxyTracer = ProxyTracer; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracerProvider = void 0; -var ProxyTracer_1 = __nccwpck_require__(43503); -var NoopTracerProvider_1 = __nccwpck_require__(23259); +var ProxyTracer_1 = __nccwpck_require__(43866); +var NoopTracerProvider_1 = __nccwpck_require__(80848); var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); /** * Tracer provider which provides {@link ProxyTracer}s. @@ -51197,7 +45155,7 @@ exports.ProxyTracerProvider = ProxyTracerProvider; /***/ }), -/***/ 19671: +/***/ 14310: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51222,7 +45180,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 33209: +/***/ 72560: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51245,6 +45203,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SamplingDecision = void 0; /** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. * A sampling decision that determines how a {@link Span} will be recorded * and collected. */ @@ -51270,7 +45229,7 @@ var SamplingDecision; /***/ }), -/***/ 20955: +/***/ 39240: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51295,7 +45254,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 57492: +/***/ 11926: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51320,7 +45279,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 23326: +/***/ 88612: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -51341,9 +45300,10 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getSpan = void 0; -var context_1 = __nccwpck_require__(78242); -var NonRecordingSpan_1 = __nccwpck_require__(81462); +exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0; +var context_1 = __nccwpck_require__(46565); +var NonRecordingSpan_1 = __nccwpck_require__(12855); +var context_2 = __nccwpck_require__(43840); /** * span key */ @@ -51357,6 +45317,13 @@ function getSpan(context) { return context.getValue(SPAN_KEY) || undefined; } exports.getSpan = getSpan; +/** + * Gets the span from the current context, if one exists. + */ +function getActiveSpan() { + return getSpan(context_2.ContextAPI.getInstance().active()); +} +exports.getActiveSpan = getActiveSpan; /** * Set the span on a context * @@ -51401,7 +45368,7 @@ exports.getSpanContext = getSpanContext; /***/ }), -/***/ 62110: +/***/ 85723: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -51423,7 +45390,7 @@ exports.getSpanContext = getSpanContext; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceStateImpl = void 0; -var tracestate_validators_1 = __nccwpck_require__(54864); +var tracestate_validators_1 = __nccwpck_require__(29305); var MAX_TRACE_STATE_ITEMS = 32; var MAX_TRACE_STATE_LEN = 512; var LIST_MEMBERS_SEPARATOR = ','; @@ -51513,7 +45480,7 @@ exports.TraceStateImpl = TraceStateImpl; /***/ }), -/***/ 54864: +/***/ 29305: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51566,7 +45533,7 @@ exports.validateValue = validateValue; /***/ }), -/***/ 32615: +/***/ 48088: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -51588,7 +45555,7 @@ exports.validateValue = validateValue; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createTraceState = void 0; -var tracestate_impl_1 = __nccwpck_require__(62110); +var tracestate_impl_1 = __nccwpck_require__(85723); function createTraceState(rawTraceState) { return new tracestate_impl_1.TraceStateImpl(rawTraceState); } @@ -51597,7 +45564,7 @@ exports.createTraceState = createTraceState; /***/ }), -/***/ 91760: +/***/ 22926: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -51619,7 +45586,7 @@ exports.createTraceState = createTraceState; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; -var trace_flags_1 = __nccwpck_require__(26905); +var trace_flags_1 = __nccwpck_require__(5683); exports.INVALID_SPANID = '0000000000000000'; exports.INVALID_TRACEID = '00000000000000000000000000000000'; exports.INVALID_SPAN_CONTEXT = { @@ -51631,7 +45598,7 @@ exports.INVALID_SPAN_CONTEXT = { /***/ }), -/***/ 44023: +/***/ 64072: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51656,7 +45623,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 4416: +/***/ 64750: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51681,7 +45648,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 15769: +/***/ 91613: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51706,7 +45673,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 31424: +/***/ 38423: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51759,7 +45726,7 @@ var SpanKind; /***/ }), -/***/ 49745: +/***/ 86095: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -51781,8 +45748,8 @@ exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = e * See the License for the specific language governing permissions and * limitations under the License. */ -var invalid_span_constants_1 = __nccwpck_require__(91760); -var NonRecordingSpan_1 = __nccwpck_require__(81462); +var invalid_span_constants_1 = __nccwpck_require__(22926); +var NonRecordingSpan_1 = __nccwpck_require__(12855); var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; function isValidTraceId(traceId) { @@ -51815,7 +45782,7 @@ exports.wrapSpanContext = wrapSpanContext; /***/ }), -/***/ 48845: +/***/ 8970: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51845,7 +45812,7 @@ var SpanStatusCode; /***/ }), -/***/ 26905: +/***/ 5683: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51878,7 +45845,7 @@ var TraceFlags; /***/ }), -/***/ 88384: +/***/ 66021: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51903,7 +45870,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 33168: +/***/ 92707: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51928,7 +45895,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 91823: +/***/ 90655: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51953,7 +45920,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 30891: +/***/ 22882: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51978,7 +45945,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 98996: +/***/ 87189: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -52001,25 +45968,25 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VERSION = void 0; // this is autogenerated file, see scripts/version-update.js -exports.VERSION = '1.1.0'; +exports.VERSION = '1.2.0'; //# sourceMappingURL=version.js.map /***/ }), -/***/ 14812: +/***/ 74324: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = { - parallel : __nccwpck_require__(8210), - serial : __nccwpck_require__(50445), - serialOrdered : __nccwpck_require__(3578) + parallel : __nccwpck_require__(18771), + serial : __nccwpck_require__(83218), + serialOrdered : __nccwpck_require__(62924) }; /***/ }), -/***/ 1700: +/***/ 53959: /***/ ((module) => { // API @@ -52055,10 +46022,10 @@ function clean(key) /***/ }), -/***/ 72794: +/***/ 3889: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var defer = __nccwpck_require__(15295); +var defer = __nccwpck_require__(7302); // API module.exports = async; @@ -52096,7 +46063,7 @@ function async(callback) /***/ }), -/***/ 15295: +/***/ 7302: /***/ ((module) => { module.exports = defer; @@ -52129,11 +46096,11 @@ function defer(fn) /***/ }), -/***/ 9023: +/***/ 81064: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var async = __nccwpck_require__(72794) - , abort = __nccwpck_require__(1700) +var async = __nccwpck_require__(3889) + , abort = __nccwpck_require__(53959) ; // API @@ -52211,7 +46178,7 @@ function runJob(iterator, key, item, callback) /***/ }), -/***/ 42474: +/***/ 27135: /***/ ((module) => { // API @@ -52255,11 +46222,11 @@ function state(list, sortMethod) /***/ }), -/***/ 37942: +/***/ 38534: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var abort = __nccwpck_require__(1700) - , async = __nccwpck_require__(72794) +var abort = __nccwpck_require__(53959) + , async = __nccwpck_require__(3889) ; // API @@ -52291,12 +46258,12 @@ function terminator(callback) /***/ }), -/***/ 8210: +/***/ 18771: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var iterate = __nccwpck_require__(9023) - , initState = __nccwpck_require__(42474) - , terminator = __nccwpck_require__(37942) +var iterate = __nccwpck_require__(81064) + , initState = __nccwpck_require__(27135) + , terminator = __nccwpck_require__(38534) ; // Public API @@ -52341,10 +46308,10 @@ function parallel(list, iterator, callback) /***/ }), -/***/ 50445: +/***/ 83218: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var serialOrdered = __nccwpck_require__(3578); +var serialOrdered = __nccwpck_require__(62924); // Public API module.exports = serial; @@ -52365,12 +46332,12 @@ function serial(list, iterator, callback) /***/ }), -/***/ 3578: +/***/ 62924: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var iterate = __nccwpck_require__(9023) - , initState = __nccwpck_require__(42474) - , terminator = __nccwpck_require__(37942) +var iterate = __nccwpck_require__(81064) + , initState = __nccwpck_require__(27135) + , terminator = __nccwpck_require__(38534) ; // Public API @@ -52447,7 +46414,7 @@ function descending(a, b) /***/ }), -/***/ 9417: +/***/ 39331: /***/ ((module) => { "use strict"; @@ -52517,12 +46484,12 @@ function range(a, b, str) { /***/ }), -/***/ 83682: +/***/ 79081: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var register = __nccwpck_require__(44670) -var addHook = __nccwpck_require__(5549) -var removeHook = __nccwpck_require__(6819) +var register = __nccwpck_require__(17334) +var addHook = __nccwpck_require__(81706) +var removeHook = __nccwpck_require__(400) // bind with array of arguments: https://stackoverflow.com/a/21792913 var bind = Function.bind @@ -52581,7 +46548,7 @@ module.exports.Collection = Hook.Collection /***/ }), -/***/ 5549: +/***/ 81706: /***/ ((module) => { module.exports = addHook; @@ -52634,7 +46601,7 @@ function addHook(state, kind, name, hook) { /***/ }), -/***/ 44670: +/***/ 17334: /***/ ((module) => { module.exports = register; @@ -52668,7 +46635,7 @@ function register(state, name, method, options) { /***/ }), -/***/ 6819: +/***/ 400: /***/ ((module) => { module.exports = removeHook; @@ -52694,7 +46661,7 @@ function removeHook(state, name, method) { /***/ }), -/***/ 44159: +/***/ 62744: /***/ ((module) => { module.exports = { @@ -52708,11 +46675,11 @@ module.exports = { /***/ }), -/***/ 33717: +/***/ 60909: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var concatMap = __nccwpck_require__(86891); -var balanced = __nccwpck_require__(9417); +var concatMap = __nccwpck_require__(23923); +var balanced = __nccwpck_require__(39331); module.exports = expandTop; @@ -52916,12 +46883,12 @@ function expand(str, isTop) { /***/ }), -/***/ 85443: +/***/ 59987: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var util = __nccwpck_require__(73837); var Stream = (__nccwpck_require__(12781).Stream); -var DelayedStream = __nccwpck_require__(18611); +var DelayedStream = __nccwpck_require__(40249); module.exports = CombinedStream; function CombinedStream() { @@ -53131,7 +47098,7 @@ CombinedStream.prototype._emitError = function(err) { /***/ }), -/***/ 86891: +/***/ 23923: /***/ ((module) => { module.exports = function (xs, fn) { @@ -53151,7 +47118,7 @@ var isArray = Array.isArray || function (xs) { /***/ }), -/***/ 80284: +/***/ 87586: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -53172,24 +47139,24 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stringify = exports.parse = exports.isTraversal = void 0; -__exportStar(__nccwpck_require__(98752), exports); -var parse_1 = __nccwpck_require__(67255); +__exportStar(__nccwpck_require__(26120), exports); +var parse_1 = __nccwpck_require__(15405); Object.defineProperty(exports, "isTraversal", ({ enumerable: true, get: function () { return parse_1.isTraversal; } })); Object.defineProperty(exports, "parse", ({ enumerable: true, get: function () { return parse_1.parse; } })); -var stringify_1 = __nccwpck_require__(19265); +var stringify_1 = __nccwpck_require__(11169); Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return stringify_1.stringify; } })); /***/ }), -/***/ 67255: +/***/ 15405: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parse = exports.isTraversal = void 0; -var types_1 = __nccwpck_require__(98752); +var types_1 = __nccwpck_require__(26120); var reName = /^[^\\#]?(?:\\(?:[\da-f]{1,6}\s?|.)|[\w\-\u00b0-\uFFFF])+/; var reEscape = /\\([\da-f]{1,6}\s?|(\s)|.)/gi; var actionTypes = new Map([ @@ -53615,7 +47582,7 @@ function parseSelector(subselects, selector, selectorIndex) { /***/ }), -/***/ 19265: +/***/ 11169: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -53631,7 +47598,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stringify = void 0; -var types_1 = __nccwpck_require__(98752); +var types_1 = __nccwpck_require__(26120); var attribValChars = ["\\", '"']; var pseudoValChars = __spreadArray(__spreadArray([], attribValChars, true), ["(", ")"], false); var charsToEscapeInAttributeValue = new Set(attribValChars.map(function (c) { return c.charCodeAt(0); })); @@ -53761,7 +47728,7 @@ function escapeName(str, charsToEscape) { /***/ }), -/***/ 98752: +/***/ 26120: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -53811,7 +47778,7 @@ var AttributeAction; /***/ }), -/***/ 58620: +/***/ 10750: /***/ ((module, exports) => { "use strict"; @@ -53837,7 +47804,7 @@ module.exports = exports.default; /***/ }), -/***/ 22631: +/***/ 49829: /***/ ((module, exports) => { "use strict"; @@ -53867,7 +47834,7 @@ module.exports = exports.default; /***/ }), -/***/ 17934: +/***/ 95051: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -53878,7 +47845,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = cloneObject; -var _index = _interopRequireDefault(__nccwpck_require__(22631)); +var _index = _interopRequireDefault(__nccwpck_require__(49829)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -53890,7 +47857,7 @@ module.exports = exports.default; /***/ }), -/***/ 618: +/***/ 57143: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -53901,7 +47868,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(31773)); +var _index = _interopRequireDefault(__nccwpck_require__(77553)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -53911,7 +47878,7 @@ module.exports = exports.default; /***/ }), -/***/ 79307: +/***/ 79115: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -53934,7 +47901,7 @@ function setDefaultOptions(newOptions) { /***/ }), -/***/ 69257: +/***/ 43324: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -53945,19 +47912,19 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(72966)); +var _index = _interopRequireDefault(__nccwpck_require__(76337)); -var _index2 = _interopRequireDefault(__nccwpck_require__(68493)); +var _index2 = _interopRequireDefault(__nccwpck_require__(82239)); -var _index3 = _interopRequireDefault(__nccwpck_require__(57170)); +var _index3 = _interopRequireDefault(__nccwpck_require__(60554)); -var _index4 = _interopRequireDefault(__nccwpck_require__(88761)); +var _index4 = _interopRequireDefault(__nccwpck_require__(73639)); -var _index5 = _interopRequireDefault(__nccwpck_require__(78050)); +var _index5 = _interopRequireDefault(__nccwpck_require__(5533)); -var _index6 = _interopRequireDefault(__nccwpck_require__(58620)); +var _index6 = _interopRequireDefault(__nccwpck_require__(10750)); -var _index7 = _interopRequireDefault(__nccwpck_require__(40289)); +var _index7 = _interopRequireDefault(__nccwpck_require__(31634)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -54825,7 +48792,7 @@ module.exports = exports.default; /***/ }), -/***/ 40289: +/***/ 31634: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -54836,7 +48803,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(58620)); +var _index = _interopRequireDefault(__nccwpck_require__(10750)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -54927,7 +48894,7 @@ module.exports = exports.default; /***/ }), -/***/ 78387: +/***/ 58676: /***/ ((module, exports) => { "use strict"; @@ -55039,7 +49006,7 @@ module.exports = exports.default; /***/ }), -/***/ 97032: +/***/ 8316: /***/ ((module, exports) => { "use strict"; @@ -55071,7 +49038,7 @@ module.exports = exports.default; /***/ }), -/***/ 72966: +/***/ 76337: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55082,9 +49049,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getUTCDayOfYear; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55105,7 +49072,7 @@ module.exports = exports.default; /***/ }), -/***/ 68493: +/***/ 82239: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55116,13 +49083,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getUTCISOWeek; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(13061)); +var _index2 = _interopRequireDefault(__nccwpck_require__(6099)); -var _index3 = _interopRequireDefault(__nccwpck_require__(11478)); +var _index3 = _interopRequireDefault(__nccwpck_require__(37889)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55142,7 +49109,7 @@ module.exports = exports.default; /***/ }), -/***/ 57170: +/***/ 60554: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55153,11 +49120,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getUTCISOWeekYear; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index3 = _interopRequireDefault(__nccwpck_require__(13061)); +var _index3 = _interopRequireDefault(__nccwpck_require__(6099)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55187,7 +49154,7 @@ module.exports = exports.default; /***/ }), -/***/ 88761: +/***/ 73639: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55198,13 +49165,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getUTCWeek; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82258)); +var _index2 = _interopRequireDefault(__nccwpck_require__(80694)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82629)); +var _index3 = _interopRequireDefault(__nccwpck_require__(86408)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55224,7 +49191,7 @@ module.exports = exports.default; /***/ }), -/***/ 78050: +/***/ 5533: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55235,15 +49202,15 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getUTCWeekYear; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82258)); +var _index3 = _interopRequireDefault(__nccwpck_require__(80694)); -var _index4 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index4 = _interopRequireDefault(__nccwpck_require__(35279)); -var _index5 = __nccwpck_require__(79307); +var _index5 = __nccwpck_require__(79115); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55282,7 +49249,7 @@ module.exports = exports.default; /***/ }), -/***/ 22509: +/***/ 29030: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -55319,7 +49286,7 @@ function throwProtectedError(token, format, input) { /***/ }), -/***/ 82063: +/***/ 76822: /***/ ((module, exports) => { "use strict"; @@ -55340,7 +49307,7 @@ module.exports = exports.default; /***/ }), -/***/ 58016: +/***/ 38860: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -55367,7 +49334,7 @@ function getRoundingMethod(method) { /***/ }), -/***/ 82694: +/***/ 98879: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55378,13 +49345,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = setUTCDay; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); -var _index4 = __nccwpck_require__(79307); +var _index4 = __nccwpck_require__(79115); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55413,7 +49380,7 @@ module.exports = exports.default; /***/ }), -/***/ 97985: +/***/ 39729: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55424,11 +49391,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = setUTCISODay; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55454,7 +49421,7 @@ module.exports = exports.default; /***/ }), -/***/ 88921: +/***/ 48694: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55465,13 +49432,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = setUTCISOWeek; -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index3 = _interopRequireDefault(__nccwpck_require__(68493)); +var _index3 = _interopRequireDefault(__nccwpck_require__(82239)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55488,7 +49455,7 @@ module.exports = exports.default; /***/ }), -/***/ 53285: +/***/ 51974: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55499,13 +49466,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = setUTCWeek; -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index3 = _interopRequireDefault(__nccwpck_require__(88761)); +var _index3 = _interopRequireDefault(__nccwpck_require__(73639)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55522,7 +49489,7 @@ module.exports = exports.default; /***/ }), -/***/ 13061: +/***/ 6099: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55533,9 +49500,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = startOfUTCISOWeek; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55554,7 +49521,7 @@ module.exports = exports.default; /***/ }), -/***/ 11478: +/***/ 37889: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55565,11 +49532,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = startOfUTCISOWeekYear; -var _index = _interopRequireDefault(__nccwpck_require__(57170)); +var _index = _interopRequireDefault(__nccwpck_require__(60554)); -var _index2 = _interopRequireDefault(__nccwpck_require__(13061)); +var _index2 = _interopRequireDefault(__nccwpck_require__(6099)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55587,7 +49554,7 @@ module.exports = exports.default; /***/ }), -/***/ 82258: +/***/ 80694: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55598,13 +49565,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = startOfUTCWeek; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); -var _index4 = __nccwpck_require__(79307); +var _index4 = __nccwpck_require__(79115); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55631,7 +49598,7 @@ module.exports = exports.default; /***/ }), -/***/ 82629: +/***/ 86408: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55642,15 +49609,15 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = startOfUTCWeekYear; -var _index = _interopRequireDefault(__nccwpck_require__(78050)); +var _index = _interopRequireDefault(__nccwpck_require__(5533)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82258)); +var _index3 = _interopRequireDefault(__nccwpck_require__(80694)); -var _index4 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index4 = _interopRequireDefault(__nccwpck_require__(35279)); -var _index5 = __nccwpck_require__(79307); +var _index5 = __nccwpck_require__(79115); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55672,7 +49639,7 @@ module.exports = exports.default; /***/ }), -/***/ 1985: +/***/ 35279: /***/ ((module, exports) => { "use strict"; @@ -55701,7 +49668,7 @@ module.exports = exports.default; /***/ }), -/***/ 96211: +/***/ 90623: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55712,15 +49679,15 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = add; -var _index = _interopRequireDefault(__nccwpck_require__(56227)); +var _index = _interopRequireDefault(__nccwpck_require__(53426)); -var _index2 = _interopRequireDefault(__nccwpck_require__(22995)); +var _index2 = _interopRequireDefault(__nccwpck_require__(71158)); -var _index3 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index3 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index5 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index5 = _interopRequireDefault(__nccwpck_require__(35279)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55790,7 +49757,7 @@ module.exports = exports.default; /***/ }), -/***/ 81727: +/***/ 96547: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55801,17 +49768,17 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = addBusinessDays; -var _index = _interopRequireDefault(__nccwpck_require__(40403)); +var _index = _interopRequireDefault(__nccwpck_require__(62564)); -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index5 = _interopRequireDefault(__nccwpck_require__(35852)); +var _index5 = _interopRequireDefault(__nccwpck_require__(6544)); -var _index6 = _interopRequireDefault(__nccwpck_require__(6308)); +var _index6 = _interopRequireDefault(__nccwpck_require__(49951)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55870,7 +49837,7 @@ module.exports = exports.default; /***/ }), -/***/ 56227: +/***/ 53426: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55881,11 +49848,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = addDays; -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55929,7 +49896,7 @@ module.exports = exports.default; /***/ }), -/***/ 59956: +/***/ 15856: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55940,11 +49907,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = addHours; -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index2 = _interopRequireDefault(__nccwpck_require__(30524)); +var _index2 = _interopRequireDefault(__nccwpck_require__(23734)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -55978,7 +49945,7 @@ module.exports = exports.default; /***/ }), -/***/ 75318: +/***/ 18809: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -55989,13 +49956,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = addISOWeekYears; -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index2 = _interopRequireDefault(__nccwpck_require__(86991)); +var _index2 = _interopRequireDefault(__nccwpck_require__(57869)); -var _index3 = _interopRequireDefault(__nccwpck_require__(50822)); +var _index3 = _interopRequireDefault(__nccwpck_require__(72593)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -56029,7 +49996,7 @@ module.exports = exports.default; /***/ }), -/***/ 30524: +/***/ 23734: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -56040,11 +50007,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = addMilliseconds; -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -56077,7 +50044,7 @@ module.exports = exports.default; /***/ }), -/***/ 15268: +/***/ 23232: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -56088,11 +50055,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = addMinutes; -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index2 = _interopRequireDefault(__nccwpck_require__(30524)); +var _index2 = _interopRequireDefault(__nccwpck_require__(23734)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -56126,7 +50093,7 @@ module.exports = exports.default; /***/ }), -/***/ 22995: +/***/ 71158: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -56137,11 +50104,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = addMonths; -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -56211,7 +50178,7 @@ module.exports = exports.default; /***/ }), -/***/ 25149: +/***/ 5341: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -56222,11 +50189,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = addQuarters; -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index2 = _interopRequireDefault(__nccwpck_require__(22995)); +var _index2 = _interopRequireDefault(__nccwpck_require__(71158)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -56259,7 +50226,7 @@ module.exports = exports.default; /***/ }), -/***/ 14112: +/***/ 97927: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -56270,11 +50237,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = addSeconds; -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index2 = _interopRequireDefault(__nccwpck_require__(30524)); +var _index2 = _interopRequireDefault(__nccwpck_require__(23734)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -56306,7 +50273,7 @@ module.exports = exports.default; /***/ }), -/***/ 97195: +/***/ 75214: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -56317,11 +50284,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = addWeeks; -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index2 = _interopRequireDefault(__nccwpck_require__(56227)); +var _index2 = _interopRequireDefault(__nccwpck_require__(53426)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -56354,7 +50321,7 @@ module.exports = exports.default; /***/ }), -/***/ 73367: +/***/ 91590: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -56365,11 +50332,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = addYears; -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index2 = _interopRequireDefault(__nccwpck_require__(22995)); +var _index2 = _interopRequireDefault(__nccwpck_require__(71158)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -56401,7 +50368,7 @@ module.exports = exports.default; /***/ }), -/***/ 32282: +/***/ 1577: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -56412,9 +50379,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = areIntervalsOverlapping; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -56495,7 +50462,7 @@ module.exports = exports.default; /***/ }), -/***/ 79660: +/***/ 19857: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -56506,11 +50473,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = clamp; -var _index = _interopRequireDefault(__nccwpck_require__(35815)); +var _index = _interopRequireDefault(__nccwpck_require__(44065)); -var _index2 = _interopRequireDefault(__nccwpck_require__(45310)); +var _index2 = _interopRequireDefault(__nccwpck_require__(18163)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -56551,7 +50518,7 @@ module.exports = exports.default; /***/ }), -/***/ 62264: +/***/ 20819: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -56562,9 +50529,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = closestIndexTo; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -56632,7 +50599,7 @@ module.exports = exports.default; /***/ }), -/***/ 42013: +/***/ 15102: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -56643,9 +50610,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = closestTo; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -56711,7 +50678,7 @@ module.exports = exports.default; /***/ }), -/***/ 29818: +/***/ 79504: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -56722,9 +50689,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = compareAsc; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -56779,7 +50746,7 @@ module.exports = exports.default; /***/ }), -/***/ 57783: +/***/ 9642: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -56790,9 +50757,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = compareDesc; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -56847,7 +50814,7 @@ module.exports = exports.default; /***/ }), -/***/ 25756: +/***/ 24665: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -57062,7 +51029,7 @@ exports.secondsInQuarter = secondsInQuarter; /***/ }), -/***/ 56237: +/***/ 58105: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -57073,9 +51040,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = daysToWeeks; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = __nccwpck_require__(25756); +var _index2 = __nccwpck_require__(24665); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -57112,7 +51079,7 @@ module.exports = exports.default; /***/ }), -/***/ 34734: +/***/ 14706: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -57123,21 +51090,21 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInBusinessDays; -var _index = _interopRequireDefault(__nccwpck_require__(56227)); +var _index = _interopRequireDefault(__nccwpck_require__(53426)); -var _index2 = _interopRequireDefault(__nccwpck_require__(3086)); +var _index2 = _interopRequireDefault(__nccwpck_require__(68607)); -var _index3 = _interopRequireDefault(__nccwpck_require__(52154)); +var _index3 = _interopRequireDefault(__nccwpck_require__(17150)); -var _index4 = _interopRequireDefault(__nccwpck_require__(59920)); +var _index4 = _interopRequireDefault(__nccwpck_require__(60435)); -var _index5 = _interopRequireDefault(__nccwpck_require__(40403)); +var _index5 = _interopRequireDefault(__nccwpck_require__(62564)); -var _index6 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index6 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index7 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index7 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index8 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index8 = _interopRequireDefault(__nccwpck_require__(35279)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -57214,7 +51181,7 @@ module.exports = exports.default; /***/ }), -/***/ 3086: +/***/ 68607: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -57225,11 +51192,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInCalendarDays; -var _index = _interopRequireDefault(__nccwpck_require__(97032)); +var _index = _interopRequireDefault(__nccwpck_require__(8316)); -var _index2 = _interopRequireDefault(__nccwpck_require__(61868)); +var _index2 = _interopRequireDefault(__nccwpck_require__(72287)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -57281,7 +51248,7 @@ module.exports = exports.default; /***/ }), -/***/ 36778: +/***/ 36638: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -57292,9 +51259,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInCalendarISOWeekYears; -var _index = _interopRequireDefault(__nccwpck_require__(86991)); +var _index = _interopRequireDefault(__nccwpck_require__(57869)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -57330,7 +51297,7 @@ module.exports = exports.default; /***/ }), -/***/ 1656: +/***/ 87184: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -57341,11 +51308,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInCalendarISOWeeks; -var _index = _interopRequireDefault(__nccwpck_require__(97032)); +var _index = _interopRequireDefault(__nccwpck_require__(8316)); -var _index2 = _interopRequireDefault(__nccwpck_require__(56307)); +var _index2 = _interopRequireDefault(__nccwpck_require__(25093)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -57390,7 +51357,7 @@ module.exports = exports.default; /***/ }), -/***/ 95536: +/***/ 98906: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -57401,9 +51368,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInCalendarMonths; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -57441,7 +51408,7 @@ module.exports = exports.default; /***/ }), -/***/ 22342: +/***/ 50343: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -57452,11 +51419,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInCalendarQuarters; -var _index = _interopRequireDefault(__nccwpck_require__(34523)); +var _index = _interopRequireDefault(__nccwpck_require__(91537)); -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -57494,7 +51461,7 @@ module.exports = exports.default; /***/ }), -/***/ 8620: +/***/ 81774: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -57505,11 +51472,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInCalendarWeeks; -var _index = _interopRequireDefault(__nccwpck_require__(29813)); +var _index = _interopRequireDefault(__nccwpck_require__(38599)); -var _index2 = _interopRequireDefault(__nccwpck_require__(97032)); +var _index2 = _interopRequireDefault(__nccwpck_require__(8316)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -57566,7 +51533,7 @@ module.exports = exports.default; /***/ }), -/***/ 45237: +/***/ 56211: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -57577,9 +51544,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInCalendarYears; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -57615,7 +51582,7 @@ module.exports = exports.default; /***/ }), -/***/ 16311: +/***/ 81684: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -57626,11 +51593,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInDays; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(3086)); +var _index2 = _interopRequireDefault(__nccwpck_require__(68607)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -57719,7 +51686,7 @@ module.exports = exports.default; /***/ }), -/***/ 88740: +/***/ 44071: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -57730,13 +51697,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInHours; -var _index = __nccwpck_require__(25756); +var _index = __nccwpck_require__(24665); -var _index2 = _interopRequireDefault(__nccwpck_require__(92288)); +var _index2 = _interopRequireDefault(__nccwpck_require__(15554)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index4 = __nccwpck_require__(58016); +var _index4 = __nccwpck_require__(38860); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -57775,7 +51742,7 @@ module.exports = exports.default; /***/ }), -/***/ 98815: +/***/ 35515: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -57786,15 +51753,15 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInISOWeekYears; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(36778)); +var _index2 = _interopRequireDefault(__nccwpck_require__(36638)); -var _index3 = _interopRequireDefault(__nccwpck_require__(29818)); +var _index3 = _interopRequireDefault(__nccwpck_require__(79504)); -var _index4 = _interopRequireDefault(__nccwpck_require__(33925)); +var _index4 = _interopRequireDefault(__nccwpck_require__(34148)); -var _index5 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index5 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -57841,7 +51808,7 @@ module.exports = exports.default; /***/ }), -/***/ 92288: +/***/ 15554: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -57852,9 +51819,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInMilliseconds; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -57889,7 +51856,7 @@ module.exports = exports.default; /***/ }), -/***/ 63842: +/***/ 17722: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -57900,13 +51867,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInMinutes; -var _index = __nccwpck_require__(25756); +var _index = __nccwpck_require__(24665); -var _index2 = _interopRequireDefault(__nccwpck_require__(92288)); +var _index2 = _interopRequireDefault(__nccwpck_require__(15554)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index4 = __nccwpck_require__(58016); +var _index4 = __nccwpck_require__(38860); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -57953,7 +51920,7 @@ module.exports = exports.default; /***/ }), -/***/ 12713: +/***/ 36775: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -57964,15 +51931,15 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInMonths; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(95536)); +var _index2 = _interopRequireDefault(__nccwpck_require__(98906)); -var _index3 = _interopRequireDefault(__nccwpck_require__(29818)); +var _index3 = _interopRequireDefault(__nccwpck_require__(79504)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index5 = _interopRequireDefault(__nccwpck_require__(48506)); +var _index5 = _interopRequireDefault(__nccwpck_require__(5263)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -58031,7 +51998,7 @@ module.exports = exports.default; /***/ }), -/***/ 87074: +/***/ 48502: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -58042,11 +52009,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInQuarters; -var _index = _interopRequireDefault(__nccwpck_require__(12713)); +var _index = _interopRequireDefault(__nccwpck_require__(36775)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index3 = __nccwpck_require__(58016); +var _index3 = __nccwpck_require__(38860); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -58080,7 +52047,7 @@ module.exports = exports.default; /***/ }), -/***/ 89448: +/***/ 96785: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -58091,11 +52058,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInSeconds; -var _index = _interopRequireDefault(__nccwpck_require__(92288)); +var _index = _interopRequireDefault(__nccwpck_require__(15554)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index3 = __nccwpck_require__(58016); +var _index3 = __nccwpck_require__(38860); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -58133,7 +52100,7 @@ module.exports = exports.default; /***/ }), -/***/ 42701: +/***/ 67737: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -58144,11 +52111,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInWeeks; -var _index = _interopRequireDefault(__nccwpck_require__(16311)); +var _index = _interopRequireDefault(__nccwpck_require__(81684)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index3 = __nccwpck_require__(58016); +var _index3 = __nccwpck_require__(38860); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -58203,7 +52170,7 @@ module.exports = exports.default; /***/ }), -/***/ 13959: +/***/ 70112: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -58214,13 +52181,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = differenceInYears; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(45237)); +var _index2 = _interopRequireDefault(__nccwpck_require__(56211)); -var _index3 = _interopRequireDefault(__nccwpck_require__(29818)); +var _index3 = _interopRequireDefault(__nccwpck_require__(79504)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -58264,7 +52231,7 @@ module.exports = exports.default; /***/ }), -/***/ 56545: +/***/ 23952: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -58275,9 +52242,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = eachDayOfInterval; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -58344,7 +52311,7 @@ module.exports = exports.default; /***/ }), -/***/ 66802: +/***/ 11201: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -58355,11 +52322,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = eachHourOfInterval; -var _index = _interopRequireDefault(__nccwpck_require__(59956)); +var _index = _interopRequireDefault(__nccwpck_require__(15856)); -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -58425,7 +52392,7 @@ module.exports = exports.default; /***/ }), -/***/ 62029: +/***/ 48199: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -58436,13 +52403,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = eachMinuteOfInterval; -var _index = _interopRequireDefault(__nccwpck_require__(15268)); +var _index = _interopRequireDefault(__nccwpck_require__(23232)); -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index3 = _interopRequireDefault(__nccwpck_require__(48567)); +var _index3 = _interopRequireDefault(__nccwpck_require__(10749)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -58506,7 +52473,7 @@ module.exports = exports.default; /***/ }), -/***/ 25879: +/***/ 69689: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -58517,9 +52484,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = eachMonthOfInterval; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -58581,7 +52548,7 @@ module.exports = exports.default; /***/ }), -/***/ 36516: +/***/ 91338: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -58592,13 +52559,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = eachQuarterOfInterval; -var _index = _interopRequireDefault(__nccwpck_require__(25149)); +var _index = _interopRequireDefault(__nccwpck_require__(5341)); -var _index2 = _interopRequireDefault(__nccwpck_require__(92932)); +var _index2 = _interopRequireDefault(__nccwpck_require__(44860)); -var _index3 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index3 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -58657,7 +52624,7 @@ module.exports = exports.default; /***/ }), -/***/ 95994: +/***/ 14348: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -58668,13 +52635,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = eachWeekOfInterval; -var _index = _interopRequireDefault(__nccwpck_require__(97195)); +var _index = _interopRequireDefault(__nccwpck_require__(75214)); -var _index2 = _interopRequireDefault(__nccwpck_require__(29813)); +var _index2 = _interopRequireDefault(__nccwpck_require__(38599)); -var _index3 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index3 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -58747,7 +52714,7 @@ module.exports = exports.default; /***/ }), -/***/ 51944: +/***/ 88164: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -58758,13 +52725,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = eachWeekendOfInterval; -var _index = _interopRequireDefault(__nccwpck_require__(56545)); +var _index = _interopRequireDefault(__nccwpck_require__(23952)); -var _index2 = _interopRequireDefault(__nccwpck_require__(35852)); +var _index2 = _interopRequireDefault(__nccwpck_require__(6544)); -var _index3 = _interopRequireDefault(__nccwpck_require__(40403)); +var _index3 = _interopRequireDefault(__nccwpck_require__(62564)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -58817,7 +52784,7 @@ module.exports = exports.default; /***/ }), -/***/ 3973: +/***/ 75054: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -58828,13 +52795,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = eachWeekendOfMonth; -var _index = _interopRequireDefault(__nccwpck_require__(51944)); +var _index = _interopRequireDefault(__nccwpck_require__(88164)); -var _index2 = _interopRequireDefault(__nccwpck_require__(97182)); +var _index2 = _interopRequireDefault(__nccwpck_require__(12081)); -var _index3 = _interopRequireDefault(__nccwpck_require__(12621)); +var _index3 = _interopRequireDefault(__nccwpck_require__(60349)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -58880,7 +52847,7 @@ module.exports = exports.default; /***/ }), -/***/ 7961: +/***/ 47937: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -58891,13 +52858,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = eachWeekendOfYear; -var _index = _interopRequireDefault(__nccwpck_require__(51944)); +var _index = _interopRequireDefault(__nccwpck_require__(88164)); -var _index2 = _interopRequireDefault(__nccwpck_require__(67079)); +var _index2 = _interopRequireDefault(__nccwpck_require__(43530)); -var _index3 = _interopRequireDefault(__nccwpck_require__(88225)); +var _index3 = _interopRequireDefault(__nccwpck_require__(71986)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -58939,7 +52906,7 @@ module.exports = exports.default; /***/ }), -/***/ 56525: +/***/ 89542: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -58950,9 +52917,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = eachYearOfInterval; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -59011,7 +52978,7 @@ module.exports = exports.default; /***/ }), -/***/ 8569: +/***/ 83055: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -59022,9 +52989,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = endOfDay; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -59057,7 +53024,7 @@ module.exports = exports.default; /***/ }), -/***/ 21517: +/***/ 84209: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -59068,9 +53035,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = endOfDecade; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -59108,7 +53075,7 @@ module.exports = exports.default; /***/ }), -/***/ 81894: +/***/ 79994: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -59119,9 +53086,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = endOfHour; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -59154,7 +53121,7 @@ module.exports = exports.default; /***/ }), -/***/ 1920: +/***/ 97771: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -59165,9 +53132,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = endOfISOWeek; -var _index = _interopRequireDefault(__nccwpck_require__(85218)); +var _index = _interopRequireDefault(__nccwpck_require__(12212)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -59202,7 +53169,7 @@ module.exports = exports.default; /***/ }), -/***/ 79731: +/***/ 94596: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -59213,11 +53180,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = endOfISOWeekYear; -var _index = _interopRequireDefault(__nccwpck_require__(86991)); +var _index = _interopRequireDefault(__nccwpck_require__(57869)); -var _index2 = _interopRequireDefault(__nccwpck_require__(56307)); +var _index2 = _interopRequireDefault(__nccwpck_require__(25093)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -59257,7 +53224,7 @@ module.exports = exports.default; /***/ }), -/***/ 71389: +/***/ 84813: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -59268,9 +53235,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = endOfMinute; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -59303,7 +53270,7 @@ module.exports = exports.default; /***/ }), -/***/ 12621: +/***/ 60349: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -59314,9 +53281,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = endOfMonth; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -59351,7 +53318,7 @@ module.exports = exports.default; /***/ }), -/***/ 35596: +/***/ 18458: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -59362,9 +53329,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = endOfQuarter; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -59400,7 +53367,7 @@ module.exports = exports.default; /***/ }), -/***/ 66121: +/***/ 75398: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -59411,9 +53378,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = endOfSecond; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -59446,7 +53413,7 @@ module.exports = exports.default; /***/ }), -/***/ 95700: +/***/ 24971: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -59457,7 +53424,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = endOfToday; -var _index = _interopRequireDefault(__nccwpck_require__(8569)); +var _index = _interopRequireDefault(__nccwpck_require__(83055)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -59488,7 +53455,7 @@ module.exports = exports.default; /***/ }), -/***/ 6935: +/***/ 22592: /***/ ((module, exports) => { "use strict"; @@ -59533,7 +53500,7 @@ module.exports = exports.default; /***/ }), -/***/ 85218: +/***/ 12212: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -59544,13 +53511,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = endOfWeek; -var _index = __nccwpck_require__(79307); +var _index = __nccwpck_require__(79115); -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -59604,7 +53571,7 @@ module.exports = exports.default; /***/ }), -/***/ 67079: +/***/ 43530: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -59615,9 +53582,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = endOfYear; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -59652,7 +53619,7 @@ module.exports = exports.default; /***/ }), -/***/ 50066: +/***/ 20658: /***/ ((module, exports) => { "use strict"; @@ -59697,7 +53664,7 @@ module.exports = exports.default; /***/ }), -/***/ 42168: +/***/ 17842: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -59708,27 +53675,27 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = format; -var _index = _interopRequireDefault(__nccwpck_require__(59920)); +var _index = _interopRequireDefault(__nccwpck_require__(60435)); -var _index2 = _interopRequireDefault(__nccwpck_require__(97923)); +var _index2 = _interopRequireDefault(__nccwpck_require__(88874)); -var _index3 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index3 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index4 = _interopRequireDefault(__nccwpck_require__(69257)); +var _index4 = _interopRequireDefault(__nccwpck_require__(43324)); -var _index5 = _interopRequireDefault(__nccwpck_require__(78387)); +var _index5 = _interopRequireDefault(__nccwpck_require__(58676)); -var _index6 = _interopRequireDefault(__nccwpck_require__(97032)); +var _index6 = _interopRequireDefault(__nccwpck_require__(8316)); -var _index7 = __nccwpck_require__(22509); +var _index7 = __nccwpck_require__(29030); -var _index8 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index8 = _interopRequireDefault(__nccwpck_require__(35279)); -var _index9 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index9 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index10 = __nccwpck_require__(79307); +var _index10 = __nccwpck_require__(79115); -var _index11 = _interopRequireDefault(__nccwpck_require__(618)); +var _index11 = _interopRequireDefault(__nccwpck_require__(57143)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -60144,7 +54111,7 @@ module.exports = exports.default; /***/ }), -/***/ 48149: +/***/ 76771: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -60155,25 +54122,25 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = formatDistance; -var _index = __nccwpck_require__(79307); +var _index = __nccwpck_require__(79115); -var _index2 = _interopRequireDefault(__nccwpck_require__(29818)); +var _index2 = _interopRequireDefault(__nccwpck_require__(79504)); -var _index3 = _interopRequireDefault(__nccwpck_require__(12713)); +var _index3 = _interopRequireDefault(__nccwpck_require__(36775)); -var _index4 = _interopRequireDefault(__nccwpck_require__(89448)); +var _index4 = _interopRequireDefault(__nccwpck_require__(96785)); -var _index5 = _interopRequireDefault(__nccwpck_require__(618)); +var _index5 = _interopRequireDefault(__nccwpck_require__(57143)); -var _index6 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index6 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index7 = _interopRequireDefault(__nccwpck_require__(17934)); +var _index7 = _interopRequireDefault(__nccwpck_require__(95051)); -var _index8 = _interopRequireDefault(__nccwpck_require__(22631)); +var _index8 = _interopRequireDefault(__nccwpck_require__(49829)); -var _index9 = _interopRequireDefault(__nccwpck_require__(97032)); +var _index9 = _interopRequireDefault(__nccwpck_require__(8316)); -var _index10 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index10 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -60362,7 +54329,7 @@ module.exports = exports.default; /***/ }), -/***/ 97128: +/***/ 79671: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -60373,21 +54340,21 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = formatDistanceStrict; -var _index = __nccwpck_require__(79307); +var _index = __nccwpck_require__(79115); -var _index2 = _interopRequireDefault(__nccwpck_require__(97032)); +var _index2 = _interopRequireDefault(__nccwpck_require__(8316)); -var _index3 = _interopRequireDefault(__nccwpck_require__(29818)); +var _index3 = _interopRequireDefault(__nccwpck_require__(79504)); -var _index4 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index4 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index5 = _interopRequireDefault(__nccwpck_require__(17934)); +var _index5 = _interopRequireDefault(__nccwpck_require__(95051)); -var _index6 = _interopRequireDefault(__nccwpck_require__(22631)); +var _index6 = _interopRequireDefault(__nccwpck_require__(49829)); -var _index7 = _interopRequireDefault(__nccwpck_require__(618)); +var _index7 = _interopRequireDefault(__nccwpck_require__(57143)); -var _index8 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index8 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -60577,7 +54544,7 @@ module.exports = exports.default; /***/ }), -/***/ 71163: +/***/ 11405: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -60588,9 +54555,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = formatDistanceToNow; -var _index = _interopRequireDefault(__nccwpck_require__(48149)); +var _index = _interopRequireDefault(__nccwpck_require__(76771)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -60689,7 +54656,7 @@ module.exports = exports.default; /***/ }), -/***/ 84741: +/***/ 3737: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -60700,9 +54667,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = formatDistanceToNowStrict; -var _index = _interopRequireDefault(__nccwpck_require__(97128)); +var _index = _interopRequireDefault(__nccwpck_require__(79671)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -60789,7 +54756,7 @@ module.exports = exports.default; /***/ }), -/***/ 68917: +/***/ 18293: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -60800,9 +54767,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = formatDuration; -var _index = __nccwpck_require__(79307); +var _index = __nccwpck_require__(79115); -var _index2 = _interopRequireDefault(__nccwpck_require__(618)); +var _index2 = _interopRequireDefault(__nccwpck_require__(57143)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -60906,7 +54873,7 @@ module.exports = exports.default; /***/ }), -/***/ 93385: +/***/ 71048: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -60917,11 +54884,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = formatISO; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(58620)); +var _index2 = _interopRequireDefault(__nccwpck_require__(10750)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -61031,7 +54998,7 @@ module.exports = exports.default; /***/ }), -/***/ 5296: +/***/ 90046: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -61042,11 +55009,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = formatISO9075; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(59920)); +var _index2 = _interopRequireDefault(__nccwpck_require__(60435)); -var _index3 = _interopRequireDefault(__nccwpck_require__(58620)); +var _index3 = _interopRequireDefault(__nccwpck_require__(10750)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -61142,7 +55109,7 @@ module.exports = exports.default; /***/ }), -/***/ 32448: +/***/ 689: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -61153,7 +55120,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = formatISODuration; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -61205,7 +55172,7 @@ module.exports = exports.default; /***/ }), -/***/ 34182: +/***/ 95493: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -61216,13 +55183,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = formatRFC3339; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(59920)); +var _index2 = _interopRequireDefault(__nccwpck_require__(60435)); -var _index3 = _interopRequireDefault(__nccwpck_require__(58620)); +var _index3 = _interopRequireDefault(__nccwpck_require__(10750)); -var _index4 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index4 = _interopRequireDefault(__nccwpck_require__(35279)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -61311,7 +55278,7 @@ module.exports = exports.default; /***/ }), -/***/ 60402: +/***/ 42443: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -61322,11 +55289,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = formatRFC7231; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(59920)); +var _index2 = _interopRequireDefault(__nccwpck_require__(60435)); -var _index3 = _interopRequireDefault(__nccwpck_require__(58620)); +var _index3 = _interopRequireDefault(__nccwpck_require__(10750)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -61378,7 +55345,7 @@ module.exports = exports.default; /***/ }), -/***/ 90675: +/***/ 60402: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -61389,23 +55356,23 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = formatRelative; -var _index = __nccwpck_require__(79307); +var _index = __nccwpck_require__(79115); -var _index2 = _interopRequireDefault(__nccwpck_require__(3086)); +var _index2 = _interopRequireDefault(__nccwpck_require__(68607)); -var _index3 = _interopRequireDefault(__nccwpck_require__(42168)); +var _index3 = _interopRequireDefault(__nccwpck_require__(17842)); -var _index4 = _interopRequireDefault(__nccwpck_require__(618)); +var _index4 = _interopRequireDefault(__nccwpck_require__(57143)); -var _index5 = _interopRequireDefault(__nccwpck_require__(97923)); +var _index5 = _interopRequireDefault(__nccwpck_require__(88874)); -var _index6 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index6 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index7 = _interopRequireDefault(__nccwpck_require__(97032)); +var _index7 = _interopRequireDefault(__nccwpck_require__(8316)); -var _index8 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index8 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index9 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index9 = _interopRequireDefault(__nccwpck_require__(35279)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -61507,7 +55474,7 @@ module.exports = exports.default; /***/ }), -/***/ 74897: +/***/ 74707: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -61518,11 +55485,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = fromUnixTime; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index2 = _interopRequireDefault(__nccwpck_require__(35279)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -61553,7 +55520,7 @@ module.exports = exports.default; /***/ }), -/***/ 7626: +/***/ 6655: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -61564,9 +55531,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getDate; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -61598,7 +55565,7 @@ module.exports = exports.default; /***/ }), -/***/ 9361: +/***/ 99950: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -61609,9 +55576,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getDay; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -61643,7 +55610,7 @@ module.exports = exports.default; /***/ }), -/***/ 67468: +/***/ 5041: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -61654,13 +55621,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getDayOfYear; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(88225)); +var _index2 = _interopRequireDefault(__nccwpck_require__(71986)); -var _index3 = _interopRequireDefault(__nccwpck_require__(3086)); +var _index3 = _interopRequireDefault(__nccwpck_require__(68607)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -61693,7 +55660,7 @@ module.exports = exports.default; /***/ }), -/***/ 97573: +/***/ 19768: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -61704,9 +55671,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getDaysInMonth; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -61742,7 +55709,7 @@ module.exports = exports.default; /***/ }), -/***/ 42784: +/***/ 19281: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -61753,11 +55720,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getDaysInYear; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(90074)); +var _index2 = _interopRequireDefault(__nccwpck_require__(94274)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -61793,7 +55760,7 @@ module.exports = exports.default; /***/ }), -/***/ 9322: +/***/ 36643: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -61804,9 +55771,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getDecade; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -61839,7 +55806,7 @@ module.exports = exports.default; /***/ }), -/***/ 65795: +/***/ 47987: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -61850,9 +55817,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getDefaultOptions; -var _index = __nccwpck_require__(79307); +var _index = __nccwpck_require__(79115); -var _index2 = _interopRequireDefault(__nccwpck_require__(22631)); +var _index2 = _interopRequireDefault(__nccwpck_require__(49829)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -61888,7 +55855,7 @@ module.exports = exports.default; /***/ }), -/***/ 27941: +/***/ 48572: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -61899,9 +55866,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getHours; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -61933,7 +55900,7 @@ module.exports = exports.default; /***/ }), -/***/ 98313: +/***/ 40321: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -61944,9 +55911,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getISODay; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -61986,7 +55953,7 @@ module.exports = exports.default; /***/ }), -/***/ 19894: +/***/ 67374: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -61997,13 +55964,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getISOWeek; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(56307)); +var _index2 = _interopRequireDefault(__nccwpck_require__(25093)); -var _index3 = _interopRequireDefault(__nccwpck_require__(60776)); +var _index3 = _interopRequireDefault(__nccwpck_require__(34855)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62042,7 +56009,7 @@ module.exports = exports.default; /***/ }), -/***/ 86991: +/***/ 57869: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62053,11 +56020,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getISOWeekYear; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(56307)); +var _index2 = _interopRequireDefault(__nccwpck_require__(25093)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62107,7 +56074,7 @@ module.exports = exports.default; /***/ }), -/***/ 35438: +/***/ 20326: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62118,11 +56085,11 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getISOWeeksInYear; -var _index = _interopRequireDefault(__nccwpck_require__(60776)); +var _index = _interopRequireDefault(__nccwpck_require__(34855)); -var _index2 = _interopRequireDefault(__nccwpck_require__(97195)); +var _index2 = _interopRequireDefault(__nccwpck_require__(75214)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62162,7 +56129,7 @@ module.exports = exports.default; /***/ }), -/***/ 67560: +/***/ 54251: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62173,9 +56140,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getMilliseconds; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62207,7 +56174,7 @@ module.exports = exports.default; /***/ }), -/***/ 7030: +/***/ 19644: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62218,9 +56185,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getMinutes; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62252,7 +56219,7 @@ module.exports = exports.default; /***/ }), -/***/ 2194: +/***/ 27216: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62263,9 +56230,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getMonth; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62297,7 +56264,7 @@ module.exports = exports.default; /***/ }), -/***/ 57647: +/***/ 80357: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62308,9 +56275,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getOverlappingDaysInIntervals; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62376,7 +56343,7 @@ module.exports = exports.default; /***/ }), -/***/ 34523: +/***/ 91537: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62387,9 +56354,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getQuarter; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62421,7 +56388,7 @@ module.exports = exports.default; /***/ }), -/***/ 48755: +/***/ 99521: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62432,9 +56399,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getSeconds; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62466,7 +56433,7 @@ module.exports = exports.default; /***/ }), -/***/ 85052: +/***/ 35916: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62477,9 +56444,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getTime; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62511,7 +56478,7 @@ module.exports = exports.default; /***/ }), -/***/ 66476: +/***/ 84004: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62522,9 +56489,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getUnixTime; -var _index = _interopRequireDefault(__nccwpck_require__(85052)); +var _index = _interopRequireDefault(__nccwpck_require__(35916)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62554,7 +56521,7 @@ module.exports = exports.default; /***/ }), -/***/ 81: +/***/ 21090: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62565,13 +56532,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getWeek; -var _index = _interopRequireDefault(__nccwpck_require__(29813)); +var _index = _interopRequireDefault(__nccwpck_require__(38599)); -var _index2 = _interopRequireDefault(__nccwpck_require__(18014)); +var _index2 = _interopRequireDefault(__nccwpck_require__(53392)); -var _index3 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index3 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62629,7 +56596,7 @@ module.exports = exports.default; /***/ }), -/***/ 39229: +/***/ 89885: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62640,17 +56607,17 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getWeekOfMonth; -var _index = __nccwpck_require__(79307); +var _index = __nccwpck_require__(79115); -var _index2 = _interopRequireDefault(__nccwpck_require__(7626)); +var _index2 = _interopRequireDefault(__nccwpck_require__(6655)); -var _index3 = _interopRequireDefault(__nccwpck_require__(9361)); +var _index3 = _interopRequireDefault(__nccwpck_require__(99950)); -var _index4 = _interopRequireDefault(__nccwpck_require__(97182)); +var _index4 = _interopRequireDefault(__nccwpck_require__(12081)); -var _index5 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index5 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index6 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index6 = _interopRequireDefault(__nccwpck_require__(35279)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62699,7 +56666,7 @@ module.exports = exports.default; /***/ }), -/***/ 33494: +/***/ 51354: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62710,15 +56677,15 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getWeekYear; -var _index = _interopRequireDefault(__nccwpck_require__(29813)); +var _index = _interopRequireDefault(__nccwpck_require__(38599)); -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index5 = __nccwpck_require__(79307); +var _index5 = __nccwpck_require__(79115); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62796,7 +56763,7 @@ module.exports = exports.default; /***/ }), -/***/ 89482: +/***/ 17573: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62807,13 +56774,13 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getWeeksInMonth; -var _index = _interopRequireDefault(__nccwpck_require__(8620)); +var _index = _interopRequireDefault(__nccwpck_require__(81774)); -var _index2 = _interopRequireDefault(__nccwpck_require__(43346)); +var _index2 = _interopRequireDefault(__nccwpck_require__(62700)); -var _index3 = _interopRequireDefault(__nccwpck_require__(97182)); +var _index3 = _interopRequireDefault(__nccwpck_require__(12081)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62853,7 +56820,7 @@ module.exports = exports.default; /***/ }), -/***/ 25714: +/***/ 88641: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62864,9 +56831,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = getYear; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62896,7 +56863,7 @@ module.exports = exports.default; /***/ }), -/***/ 83895: +/***/ 64266: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62907,9 +56874,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = hoursToMilliseconds; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = __nccwpck_require__(25756); +var _index2 = __nccwpck_require__(24665); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62940,7 +56907,7 @@ module.exports = exports.default; /***/ }), -/***/ 72449: +/***/ 61156: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62951,9 +56918,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = hoursToMinutes; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = __nccwpck_require__(25756); +var _index2 = __nccwpck_require__(24665); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -62984,7 +56951,7 @@ module.exports = exports.default; /***/ }), -/***/ 775: +/***/ 34331: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -62995,9 +56962,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = hoursToSeconds; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = __nccwpck_require__(25756); +var _index2 = __nccwpck_require__(24665); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -63028,7 +56995,7 @@ module.exports = exports.default; /***/ }), -/***/ 73314: +/***/ 80541: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -64646,569 +58613,2923 @@ Object.defineProperty(exports, "subISOWeekYears", ({ return _index228.default; } })); -Object.defineProperty(exports, "subMilliseconds", ({ - enumerable: true, - get: function () { - return _index229.default; +Object.defineProperty(exports, "subMilliseconds", ({ + enumerable: true, + get: function () { + return _index229.default; + } +})); +Object.defineProperty(exports, "subMinutes", ({ + enumerable: true, + get: function () { + return _index230.default; + } +})); +Object.defineProperty(exports, "subMonths", ({ + enumerable: true, + get: function () { + return _index231.default; + } +})); +Object.defineProperty(exports, "subQuarters", ({ + enumerable: true, + get: function () { + return _index232.default; + } +})); +Object.defineProperty(exports, "subSeconds", ({ + enumerable: true, + get: function () { + return _index233.default; + } +})); +Object.defineProperty(exports, "subWeeks", ({ + enumerable: true, + get: function () { + return _index234.default; + } +})); +Object.defineProperty(exports, "subYears", ({ + enumerable: true, + get: function () { + return _index235.default; + } +})); +Object.defineProperty(exports, "toDate", ({ + enumerable: true, + get: function () { + return _index236.default; + } +})); +Object.defineProperty(exports, "weeksToDays", ({ + enumerable: true, + get: function () { + return _index237.default; + } +})); +Object.defineProperty(exports, "yearsToMonths", ({ + enumerable: true, + get: function () { + return _index238.default; + } +})); +Object.defineProperty(exports, "yearsToQuarters", ({ + enumerable: true, + get: function () { + return _index239.default; + } +})); + +var _index = _interopRequireDefault(__nccwpck_require__(90623)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(96547)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(53426)); + +var _index4 = _interopRequireDefault(__nccwpck_require__(15856)); + +var _index5 = _interopRequireDefault(__nccwpck_require__(18809)); + +var _index6 = _interopRequireDefault(__nccwpck_require__(23734)); + +var _index7 = _interopRequireDefault(__nccwpck_require__(23232)); + +var _index8 = _interopRequireDefault(__nccwpck_require__(71158)); + +var _index9 = _interopRequireDefault(__nccwpck_require__(5341)); + +var _index10 = _interopRequireDefault(__nccwpck_require__(97927)); + +var _index11 = _interopRequireDefault(__nccwpck_require__(75214)); + +var _index12 = _interopRequireDefault(__nccwpck_require__(91590)); + +var _index13 = _interopRequireDefault(__nccwpck_require__(1577)); + +var _index14 = _interopRequireDefault(__nccwpck_require__(19857)); + +var _index15 = _interopRequireDefault(__nccwpck_require__(20819)); + +var _index16 = _interopRequireDefault(__nccwpck_require__(15102)); + +var _index17 = _interopRequireDefault(__nccwpck_require__(79504)); + +var _index18 = _interopRequireDefault(__nccwpck_require__(9642)); + +var _index19 = _interopRequireDefault(__nccwpck_require__(58105)); + +var _index20 = _interopRequireDefault(__nccwpck_require__(14706)); + +var _index21 = _interopRequireDefault(__nccwpck_require__(68607)); + +var _index22 = _interopRequireDefault(__nccwpck_require__(36638)); + +var _index23 = _interopRequireDefault(__nccwpck_require__(87184)); + +var _index24 = _interopRequireDefault(__nccwpck_require__(98906)); + +var _index25 = _interopRequireDefault(__nccwpck_require__(50343)); + +var _index26 = _interopRequireDefault(__nccwpck_require__(81774)); + +var _index27 = _interopRequireDefault(__nccwpck_require__(56211)); + +var _index28 = _interopRequireDefault(__nccwpck_require__(81684)); + +var _index29 = _interopRequireDefault(__nccwpck_require__(44071)); + +var _index30 = _interopRequireDefault(__nccwpck_require__(35515)); + +var _index31 = _interopRequireDefault(__nccwpck_require__(15554)); + +var _index32 = _interopRequireDefault(__nccwpck_require__(17722)); + +var _index33 = _interopRequireDefault(__nccwpck_require__(36775)); + +var _index34 = _interopRequireDefault(__nccwpck_require__(48502)); + +var _index35 = _interopRequireDefault(__nccwpck_require__(96785)); + +var _index36 = _interopRequireDefault(__nccwpck_require__(67737)); + +var _index37 = _interopRequireDefault(__nccwpck_require__(70112)); + +var _index38 = _interopRequireDefault(__nccwpck_require__(23952)); + +var _index39 = _interopRequireDefault(__nccwpck_require__(11201)); + +var _index40 = _interopRequireDefault(__nccwpck_require__(48199)); + +var _index41 = _interopRequireDefault(__nccwpck_require__(69689)); + +var _index42 = _interopRequireDefault(__nccwpck_require__(91338)); + +var _index43 = _interopRequireDefault(__nccwpck_require__(14348)); + +var _index44 = _interopRequireDefault(__nccwpck_require__(88164)); + +var _index45 = _interopRequireDefault(__nccwpck_require__(75054)); + +var _index46 = _interopRequireDefault(__nccwpck_require__(47937)); + +var _index47 = _interopRequireDefault(__nccwpck_require__(89542)); + +var _index48 = _interopRequireDefault(__nccwpck_require__(83055)); + +var _index49 = _interopRequireDefault(__nccwpck_require__(84209)); + +var _index50 = _interopRequireDefault(__nccwpck_require__(79994)); + +var _index51 = _interopRequireDefault(__nccwpck_require__(97771)); + +var _index52 = _interopRequireDefault(__nccwpck_require__(94596)); + +var _index53 = _interopRequireDefault(__nccwpck_require__(84813)); + +var _index54 = _interopRequireDefault(__nccwpck_require__(60349)); + +var _index55 = _interopRequireDefault(__nccwpck_require__(18458)); + +var _index56 = _interopRequireDefault(__nccwpck_require__(75398)); + +var _index57 = _interopRequireDefault(__nccwpck_require__(24971)); + +var _index58 = _interopRequireDefault(__nccwpck_require__(22592)); + +var _index59 = _interopRequireDefault(__nccwpck_require__(12212)); + +var _index60 = _interopRequireDefault(__nccwpck_require__(43530)); + +var _index61 = _interopRequireDefault(__nccwpck_require__(20658)); + +var _index62 = _interopRequireDefault(__nccwpck_require__(17842)); + +var _index63 = _interopRequireDefault(__nccwpck_require__(76771)); + +var _index64 = _interopRequireDefault(__nccwpck_require__(79671)); + +var _index65 = _interopRequireDefault(__nccwpck_require__(11405)); + +var _index66 = _interopRequireDefault(__nccwpck_require__(3737)); + +var _index67 = _interopRequireDefault(__nccwpck_require__(18293)); + +var _index68 = _interopRequireDefault(__nccwpck_require__(71048)); + +var _index69 = _interopRequireDefault(__nccwpck_require__(90046)); + +var _index70 = _interopRequireDefault(__nccwpck_require__(689)); + +var _index71 = _interopRequireDefault(__nccwpck_require__(95493)); + +var _index72 = _interopRequireDefault(__nccwpck_require__(42443)); + +var _index73 = _interopRequireDefault(__nccwpck_require__(60402)); + +var _index74 = _interopRequireDefault(__nccwpck_require__(74707)); + +var _index75 = _interopRequireDefault(__nccwpck_require__(6655)); + +var _index76 = _interopRequireDefault(__nccwpck_require__(99950)); + +var _index77 = _interopRequireDefault(__nccwpck_require__(5041)); + +var _index78 = _interopRequireDefault(__nccwpck_require__(19768)); + +var _index79 = _interopRequireDefault(__nccwpck_require__(19281)); + +var _index80 = _interopRequireDefault(__nccwpck_require__(36643)); + +var _index81 = _interopRequireDefault(__nccwpck_require__(47987)); + +var _index82 = _interopRequireDefault(__nccwpck_require__(48572)); + +var _index83 = _interopRequireDefault(__nccwpck_require__(40321)); + +var _index84 = _interopRequireDefault(__nccwpck_require__(67374)); + +var _index85 = _interopRequireDefault(__nccwpck_require__(57869)); + +var _index86 = _interopRequireDefault(__nccwpck_require__(20326)); + +var _index87 = _interopRequireDefault(__nccwpck_require__(54251)); + +var _index88 = _interopRequireDefault(__nccwpck_require__(19644)); + +var _index89 = _interopRequireDefault(__nccwpck_require__(27216)); + +var _index90 = _interopRequireDefault(__nccwpck_require__(80357)); + +var _index91 = _interopRequireDefault(__nccwpck_require__(91537)); + +var _index92 = _interopRequireDefault(__nccwpck_require__(99521)); + +var _index93 = _interopRequireDefault(__nccwpck_require__(35916)); + +var _index94 = _interopRequireDefault(__nccwpck_require__(84004)); + +var _index95 = _interopRequireDefault(__nccwpck_require__(21090)); + +var _index96 = _interopRequireDefault(__nccwpck_require__(89885)); + +var _index97 = _interopRequireDefault(__nccwpck_require__(51354)); + +var _index98 = _interopRequireDefault(__nccwpck_require__(17573)); + +var _index99 = _interopRequireDefault(__nccwpck_require__(88641)); + +var _index100 = _interopRequireDefault(__nccwpck_require__(64266)); + +var _index101 = _interopRequireDefault(__nccwpck_require__(61156)); + +var _index102 = _interopRequireDefault(__nccwpck_require__(34331)); + +var _index103 = _interopRequireDefault(__nccwpck_require__(24545)); + +var _index104 = _interopRequireDefault(__nccwpck_require__(25979)); + +var _index105 = _interopRequireDefault(__nccwpck_require__(93869)); + +var _index106 = _interopRequireDefault(__nccwpck_require__(99415)); + +var _index107 = _interopRequireDefault(__nccwpck_require__(55678)); + +var _index108 = _interopRequireDefault(__nccwpck_require__(19410)); + +var _index109 = _interopRequireDefault(__nccwpck_require__(41804)); + +var _index110 = _interopRequireDefault(__nccwpck_require__(77621)); + +var _index111 = _interopRequireDefault(__nccwpck_require__(4627)); + +var _index112 = _interopRequireDefault(__nccwpck_require__(82372)); + +var _index113 = _interopRequireDefault(__nccwpck_require__(55371)); + +var _index114 = _interopRequireDefault(__nccwpck_require__(5263)); + +var _index115 = _interopRequireDefault(__nccwpck_require__(94274)); + +var _index116 = _interopRequireDefault(__nccwpck_require__(95440)); + +var _index117 = _interopRequireDefault(__nccwpck_require__(21095)); + +var _index118 = _interopRequireDefault(__nccwpck_require__(39886)); + +var _index119 = _interopRequireDefault(__nccwpck_require__(17150)); + +var _index120 = _interopRequireDefault(__nccwpck_require__(88687)); + +var _index121 = _interopRequireDefault(__nccwpck_require__(49846)); + +var _index122 = _interopRequireDefault(__nccwpck_require__(96303)); + +var _index123 = _interopRequireDefault(__nccwpck_require__(76570)); + +var _index124 = _interopRequireDefault(__nccwpck_require__(32603)); + +var _index125 = _interopRequireDefault(__nccwpck_require__(16063)); + +var _index126 = _interopRequireDefault(__nccwpck_require__(969)); + +var _index127 = _interopRequireDefault(__nccwpck_require__(30876)); + +var _index128 = _interopRequireDefault(__nccwpck_require__(1050)); + +var _index129 = _interopRequireDefault(__nccwpck_require__(49951)); + +var _index130 = _interopRequireDefault(__nccwpck_require__(6544)); + +var _index131 = _interopRequireDefault(__nccwpck_require__(48897)); + +var _index132 = _interopRequireDefault(__nccwpck_require__(11887)); + +var _index133 = _interopRequireDefault(__nccwpck_require__(62182)); + +var _index134 = _interopRequireDefault(__nccwpck_require__(88738)); + +var _index135 = _interopRequireDefault(__nccwpck_require__(89872)); + +var _index136 = _interopRequireDefault(__nccwpck_require__(30671)); + +var _index137 = _interopRequireDefault(__nccwpck_require__(2376)); + +var _index138 = _interopRequireDefault(__nccwpck_require__(88807)); + +var _index139 = _interopRequireDefault(__nccwpck_require__(1815)); + +var _index140 = _interopRequireDefault(__nccwpck_require__(8566)); + +var _index141 = _interopRequireDefault(__nccwpck_require__(60450)); + +var _index142 = _interopRequireDefault(__nccwpck_require__(67611)); + +var _index143 = _interopRequireDefault(__nccwpck_require__(60435)); + +var _index144 = _interopRequireDefault(__nccwpck_require__(99651)); + +var _index145 = _interopRequireDefault(__nccwpck_require__(62564)); + +var _index146 = _interopRequireDefault(__nccwpck_require__(11557)); + +var _index147 = _interopRequireDefault(__nccwpck_require__(59054)); + +var _index148 = _interopRequireDefault(__nccwpck_require__(61311)); + +var _index149 = _interopRequireDefault(__nccwpck_require__(15619)); + +var _index150 = _interopRequireDefault(__nccwpck_require__(73205)); + +var _index151 = _interopRequireDefault(__nccwpck_require__(62700)); + +var _index152 = _interopRequireDefault(__nccwpck_require__(26886)); + +var _index153 = _interopRequireDefault(__nccwpck_require__(39013)); + +var _index154 = _interopRequireDefault(__nccwpck_require__(87819)); + +var _index155 = _interopRequireDefault(__nccwpck_require__(28655)); + +var _index156 = _interopRequireDefault(__nccwpck_require__(44065)); + +var _index157 = _interopRequireDefault(__nccwpck_require__(30003)); + +var _index158 = _interopRequireDefault(__nccwpck_require__(96570)); + +var _index159 = _interopRequireDefault(__nccwpck_require__(84493)); + +var _index160 = _interopRequireDefault(__nccwpck_require__(21594)); + +var _index161 = _interopRequireDefault(__nccwpck_require__(18163)); + +var _index162 = _interopRequireDefault(__nccwpck_require__(32070)); + +var _index163 = _interopRequireDefault(__nccwpck_require__(12478)); + +var _index164 = _interopRequireDefault(__nccwpck_require__(45947)); + +var _index165 = _interopRequireDefault(__nccwpck_require__(5806)); + +var _index166 = _interopRequireDefault(__nccwpck_require__(76230)); + +var _index167 = _interopRequireDefault(__nccwpck_require__(59894)); + +var _index168 = _interopRequireDefault(__nccwpck_require__(42082)); + +var _index169 = _interopRequireDefault(__nccwpck_require__(4311)); + +var _index170 = _interopRequireDefault(__nccwpck_require__(413)); + +var _index171 = _interopRequireDefault(__nccwpck_require__(25033)); + +var _index172 = _interopRequireDefault(__nccwpck_require__(49691)); + +var _index173 = _interopRequireDefault(__nccwpck_require__(39621)); + +var _index174 = _interopRequireDefault(__nccwpck_require__(39608)); + +var _index175 = _interopRequireDefault(__nccwpck_require__(10435)); + +var _index176 = _interopRequireDefault(__nccwpck_require__(78081)); + +var _index177 = _interopRequireDefault(__nccwpck_require__(45183)); + +var _index178 = _interopRequireDefault(__nccwpck_require__(95896)); + +var _index179 = _interopRequireDefault(__nccwpck_require__(58048)); + +var _index180 = _interopRequireDefault(__nccwpck_require__(57101)); + +var _index181 = _interopRequireDefault(__nccwpck_require__(50572)); + +var _index182 = _interopRequireDefault(__nccwpck_require__(71757)); + +var _index183 = _interopRequireDefault(__nccwpck_require__(89817)); + +var _index184 = _interopRequireDefault(__nccwpck_require__(7721)); + +var _index185 = _interopRequireDefault(__nccwpck_require__(90754)); + +var _index186 = _interopRequireDefault(__nccwpck_require__(62381)); + +var _index187 = _interopRequireDefault(__nccwpck_require__(97483)); + +var _index188 = _interopRequireDefault(__nccwpck_require__(13854)); + +var _index189 = _interopRequireDefault(__nccwpck_require__(79595)); + +var _index190 = _interopRequireDefault(__nccwpck_require__(11499)); + +var _index191 = _interopRequireDefault(__nccwpck_require__(15559)); + +var _index192 = _interopRequireDefault(__nccwpck_require__(67142)); + +var _index193 = _interopRequireDefault(__nccwpck_require__(760)); + +var _index194 = _interopRequireDefault(__nccwpck_require__(25247)); + +var _index195 = _interopRequireDefault(__nccwpck_require__(31003)); + +var _index196 = _interopRequireDefault(__nccwpck_require__(44604)); + +var _index197 = _interopRequireDefault(__nccwpck_require__(42664)); + +var _index198 = _interopRequireDefault(__nccwpck_require__(50193)); + +var _index199 = _interopRequireDefault(__nccwpck_require__(41744)); + +var _index200 = _interopRequireDefault(__nccwpck_require__(72593)); + +var _index201 = _interopRequireDefault(__nccwpck_require__(29973)); + +var _index202 = _interopRequireDefault(__nccwpck_require__(88434)); + +var _index203 = _interopRequireDefault(__nccwpck_require__(70029)); + +var _index204 = _interopRequireDefault(__nccwpck_require__(12973)); + +var _index205 = _interopRequireDefault(__nccwpck_require__(74275)); + +var _index206 = _interopRequireDefault(__nccwpck_require__(19966)); + +var _index207 = _interopRequireDefault(__nccwpck_require__(43844)); + +var _index208 = _interopRequireDefault(__nccwpck_require__(16313)); + +var _index209 = _interopRequireDefault(__nccwpck_require__(72287)); + +var _index210 = _interopRequireDefault(__nccwpck_require__(20343)); + +var _index211 = _interopRequireDefault(__nccwpck_require__(46561)); + +var _index212 = _interopRequireDefault(__nccwpck_require__(25093)); + +var _index213 = _interopRequireDefault(__nccwpck_require__(34855)); + +var _index214 = _interopRequireDefault(__nccwpck_require__(10749)); + +var _index215 = _interopRequireDefault(__nccwpck_require__(12081)); + +var _index216 = _interopRequireDefault(__nccwpck_require__(44860)); + +var _index217 = _interopRequireDefault(__nccwpck_require__(20740)); + +var _index218 = _interopRequireDefault(__nccwpck_require__(89912)); + +var _index219 = _interopRequireDefault(__nccwpck_require__(25713)); + +var _index220 = _interopRequireDefault(__nccwpck_require__(38599)); + +var _index221 = _interopRequireDefault(__nccwpck_require__(53392)); + +var _index222 = _interopRequireDefault(__nccwpck_require__(71986)); + +var _index223 = _interopRequireDefault(__nccwpck_require__(3610)); + +var _index224 = _interopRequireDefault(__nccwpck_require__(79395)); + +var _index225 = _interopRequireDefault(__nccwpck_require__(569)); + +var _index226 = _interopRequireDefault(__nccwpck_require__(80289)); + +var _index227 = _interopRequireDefault(__nccwpck_require__(51423)); + +var _index228 = _interopRequireDefault(__nccwpck_require__(34148)); + +var _index229 = _interopRequireDefault(__nccwpck_require__(88874)); + +var _index230 = _interopRequireDefault(__nccwpck_require__(27350)); + +var _index231 = _interopRequireDefault(__nccwpck_require__(54591)); + +var _index232 = _interopRequireDefault(__nccwpck_require__(98728)); + +var _index233 = _interopRequireDefault(__nccwpck_require__(29133)); + +var _index234 = _interopRequireDefault(__nccwpck_require__(47076)); + +var _index235 = _interopRequireDefault(__nccwpck_require__(61751)); + +var _index236 = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index237 = _interopRequireDefault(__nccwpck_require__(61287)); + +var _index238 = _interopRequireDefault(__nccwpck_require__(28436)); + +var _index239 = _interopRequireDefault(__nccwpck_require__(55738)); + +var _index240 = __nccwpck_require__(24665); + +Object.keys(_index240).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _index240[key]; + } + }); +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/***/ }), + +/***/ 24545: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = intervalToDuration; + +var _index = _interopRequireDefault(__nccwpck_require__(79504)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(90623)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(81684)); + +var _index4 = _interopRequireDefault(__nccwpck_require__(44071)); + +var _index5 = _interopRequireDefault(__nccwpck_require__(17722)); + +var _index6 = _interopRequireDefault(__nccwpck_require__(36775)); + +var _index7 = _interopRequireDefault(__nccwpck_require__(96785)); + +var _index8 = _interopRequireDefault(__nccwpck_require__(70112)); + +var _index9 = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index10 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name intervalToDuration + * @category Common Helpers + * @summary Convert interval to duration + * + * @description + * Convert a interval object to a duration object. + * + * @param {Interval} interval - the interval to convert to duration + * + * @returns {Duration} The duration Object + * @throws {TypeError} Requires 2 arguments + * @throws {RangeError} `start` must not be Invalid Date + * @throws {RangeError} `end` must not be Invalid Date + * + * @example + * // Get the duration between January 15, 1929 and April 4, 1968. + * intervalToDuration({ + * start: new Date(1929, 0, 15, 12, 0, 0), + * end: new Date(1968, 3, 4, 19, 5, 0) + * }) + * // => { years: 39, months: 2, days: 20, hours: 7, minutes: 5, seconds: 0 } + */ +function intervalToDuration(interval) { + (0, _index10.default)(1, arguments); + var start = (0, _index9.default)(interval.start); + var end = (0, _index9.default)(interval.end); + if (isNaN(start.getTime())) throw new RangeError('Start Date is invalid'); + if (isNaN(end.getTime())) throw new RangeError('End Date is invalid'); + var duration = {}; + duration.years = Math.abs((0, _index8.default)(end, start)); + var sign = (0, _index.default)(end, start); + var remainingMonths = (0, _index2.default)(start, { + years: sign * duration.years + }); + duration.months = Math.abs((0, _index6.default)(end, remainingMonths)); + var remainingDays = (0, _index2.default)(remainingMonths, { + months: sign * duration.months + }); + duration.days = Math.abs((0, _index3.default)(end, remainingDays)); + var remainingHours = (0, _index2.default)(remainingDays, { + days: sign * duration.days + }); + duration.hours = Math.abs((0, _index4.default)(end, remainingHours)); + var remainingMinutes = (0, _index2.default)(remainingHours, { + hours: sign * duration.hours + }); + duration.minutes = Math.abs((0, _index5.default)(end, remainingMinutes)); + var remainingSeconds = (0, _index2.default)(remainingMinutes, { + minutes: sign * duration.minutes + }); + duration.seconds = Math.abs((0, _index7.default)(end, remainingSeconds)); + return duration; +} + +module.exports = exports.default; + +/***/ }), + +/***/ 25979: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = intlFormat; + +var _index = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name intlFormat + * @category Common Helpers + * @summary Format the date with Intl.DateTimeFormat (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat). + * + * @description + * Return the formatted date string in the given format. + * The method uses [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) inside. + * formatOptions are the same as [`Intl.DateTimeFormat` options](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat#using_options) + * + * > ⚠️ Please note that before Node version 13.0.0, only the locale data for en-US is available by default. + * + * @param {Date|Number} argument - the original date. + * @param {Object} [formatOptions] - an object with options. + * @param {'lookup'|'best fit'} [formatOptions.localeMatcher='best fit'] - locale selection algorithm. + * @param {'narrow'|'short'|'long'} [formatOptions.weekday] - representation the days of the week. + * @param {'narrow'|'short'|'long'} [formatOptions.era] - representation of eras. + * @param {'numeric'|'2-digit'} [formatOptions.year] - representation of years. + * @param {'numeric'|'2-digit'|'narrow'|'short'|'long'} [formatOptions.month='numeric'] - representation of month. + * @param {'numeric'|'2-digit'} [formatOptions.day='numeric'] - representation of day. + * @param {'numeric'|'2-digit'} [formatOptions.hour='numeric'] - representation of hours. + * @param {'numeric'|'2-digit'} [formatOptions.minute] - representation of minutes. + * @param {'numeric'|'2-digit'} [formatOptions.second] - representation of seconds. + * @param {'short'|'long'} [formatOptions.timeZoneName] - representation of names of time zones. + * @param {'basic'|'best fit'} [formatOptions.formatMatcher='best fit'] - format selection algorithm. + * @param {Boolean} [formatOptions.hour12] - determines whether to use 12-hour time format. + * @param {String} [formatOptions.timeZone] - the time zone to use. + * @param {Object} [localeOptions] - an object with locale. + * @param {String|String[]} [localeOptions.locale] - the locale code + * @returns {String} the formatted date string. + * @throws {TypeError} 1 argument required. + * @throws {RangeError} `date` must not be Invalid Date + * + * @example + * // Represent 10 October 2019 in German. + * // Convert the date with format's options and locale's options. + * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456), { + * weekday: 'long', + * year: 'numeric', + * month: 'long', + * day: 'numeric', + * }, { + * locale: 'de-DE', + * }) + * //=> Freitag, 4. Oktober 2019 + * + * @example + * // Represent 10 October 2019. + * // Convert the date with format's options. + * const result = intlFormat.default(new Date(2019, 9, 4, 12, 30, 13, 456), { + * year: 'numeric', + * month: 'numeric', + * day: 'numeric', + * hour: 'numeric', + * }) + * //=> 10/4/2019, 12 PM + * + * @example + * // Represent 10 October 2019 in Korean. + * // Convert the date with locale's options. + * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456), { + * locale: 'ko-KR', + * }) + * //=> 2019. 10. 4. + * + * @example + * // Represent 10 October 2019 in middle-endian format: + * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456)) + * //=> 10/4/2019 + */ +function intlFormat(date, formatOrLocale, localeOptions) { + var _localeOptions; + + (0, _index.default)(1, arguments); + var formatOptions; + + if (isFormatOptions(formatOrLocale)) { + formatOptions = formatOrLocale; + } else { + localeOptions = formatOrLocale; } + + return new Intl.DateTimeFormat((_localeOptions = localeOptions) === null || _localeOptions === void 0 ? void 0 : _localeOptions.locale, formatOptions).format(date); +} + +function isFormatOptions(opts) { + return opts !== undefined && !('locale' in opts); +} + +module.exports = exports.default; + +/***/ }), + +/***/ 93869: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true })); -Object.defineProperty(exports, "subMinutes", ({ - enumerable: true, - get: function () { - return _index230.default; +exports["default"] = intlFormatDistance; + +var _index = __nccwpck_require__(24665); + +var _index2 = _interopRequireDefault(__nccwpck_require__(68607)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(98906)); + +var _index4 = _interopRequireDefault(__nccwpck_require__(50343)); + +var _index5 = _interopRequireDefault(__nccwpck_require__(81774)); + +var _index6 = _interopRequireDefault(__nccwpck_require__(56211)); + +var _index7 = _interopRequireDefault(__nccwpck_require__(44071)); + +var _index8 = _interopRequireDefault(__nccwpck_require__(17722)); + +var _index9 = _interopRequireDefault(__nccwpck_require__(96785)); + +var _index10 = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index11 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name intlFormatDistance + * @category Common Helpers + * @summary Formats distance between two dates in a human-readable format + * @description + * The function calculates the difference between two dates and formats it as a human-readable string. + * + * The function will pick the most appropriate unit depending on the distance between dates. For example, if the distance is a few hours, it might return `x hours`. If the distance is a few months, it might return `x months`. + * + * You can also specify a unit to force using it regardless of the distance to get a result like `123456 hours`. + * + * See the table below for the unit picking logic: + * + * | Distance between dates | Result (past) | Result (future) | + * | ---------------------- | -------------- | --------------- | + * | 0 seconds | now | now | + * | 1-59 seconds | X seconds ago | in X seconds | + * | 1-59 minutes | X minutes ago | in X minutes | + * | 1-23 hours | X hours ago | in X hours | + * | 1 day | yesterday | tomorrow | + * | 2-6 days | X days ago | in X days | + * | 7 days | last week | next week | + * | 8 days-1 month | X weeks ago | in X weeks | + * | 1 month | last month | next month | + * | 2-3 months | X months ago | in X months | + * | 1 quarter | last quarter | next quarter | + * | 2-3 quarters | X quarters ago | in X quarters | + * | 1 year | last year | next year | + * | 2+ years | X years ago | in X years | + * + * @param {Date|Number} date - the date + * @param {Date|Number} baseDate - the date to compare with. + * @param {Object} [options] - an object with options. + * @param {String} [options.unit] - formats the distance with the given unit ('year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'). + * @param {String|String[]} [options.locale] - the locale to use. + * @param {String} [options.localeMatcher='best fit'] - the locale matching algorithm to use. Other value: 'lookup'. + * See MDN for details [Locale identification and negotiation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation) + * @param {String} [options.numeric='auto'] - the output message format. The values are 'auto' (e.g. `yesterday`), 'always'(e.g. `1 day ago`). + * @param {String} [options.style='long'] - the length of the result. The values are: 'long' (e.g. `1 month`), 'short' (e.g. 'in 1 mo.'), 'narrow' (e.g. 'in 1 mo.'). + * The narrow one could be similar to the short one for some locales. + * @returns {String} the distance in words according to language-sensitive relative time formatting. + * @throws {TypeError} 2 arguments required + * @throws {RangeError} `date` must not be Invalid Date + * @throws {RangeError} `baseDate` must not be Invalid Date + * @throws {RangeError} `options.unit` must not be invalid Unit + * @throws {RangeError} `options.locale` must not be invalid locale + * @throws {RangeError} `options.localeMatcher` must not be invalid localeMatcher + * @throws {RangeError} `options.numeric` must not be invalid numeric + * @throws {RangeError} `options.style` must not be invalid style + * + * @example + * // What is the distance between the dates when the fist date is after the second? + * intlFormatDistance( + * new Date(1986, 3, 4, 11, 30, 0), + * new Date(1986, 3, 4, 10, 30, 0) + * ) + * //=> 'in 1 hour' + * + * // What is the distance between the dates when the fist date is before the second? + * intlFormatDistance( + * new Date(1986, 3, 4, 10, 30, 0), + * new Date(1986, 3, 4, 11, 30, 0) + * ) + * //=> '1 hour ago' + * + * @example + * // Use the unit option to force the function to output the result in quarters. Without setting it, the example would return "next year" + * intlFormatDistance( + * new Date(1987, 6, 4, 10, 30, 0), + * new Date(1986, 3, 4, 10, 30, 0), + * { unit: 'quarter' } + * ) + * //=> 'in 5 quarters' + * + * @example + * // Use the locale option to get the result in Spanish. Without setting it, the example would return "in 1 hour". + * intlFormatDistance( + * new Date(1986, 3, 4, 11, 30, 0), + * new Date(1986, 3, 4, 10, 30, 0), + * { locale: 'es' } + * ) + * //=> 'dentro de 1 hora' + * + * @example + * // Use the numeric option to force the function to use numeric values. Without setting it, the example would return "tomorrow". + * intlFormatDistance( + * new Date(1986, 3, 5, 11, 30, 0), + * new Date(1986, 3, 4, 11, 30, 0), + * { numeric: 'always' } + * ) + * //=> 'in 1 day' + * + * @example + * // Use the style option to force the function to use short values. Without setting it, the example would return "in 2 years". + * intlFormatDistance( + * new Date(1988, 3, 4, 11, 30, 0), + * new Date(1986, 3, 4, 11, 30, 0), + * { style: 'short' } + * ) + * //=> 'in 2 yr' + */ +function intlFormatDistance(date, baseDate, options) { + (0, _index11.default)(2, arguments); + var value = 0; + var unit; + var dateLeft = (0, _index10.default)(date); + var dateRight = (0, _index10.default)(baseDate); + + if (!(options !== null && options !== void 0 && options.unit)) { + // Get the unit based on diffInSeconds calculations if no unit is specified + var diffInSeconds = (0, _index9.default)(dateLeft, dateRight); // The smallest unit + + if (Math.abs(diffInSeconds) < _index.secondsInMinute) { + value = (0, _index9.default)(dateLeft, dateRight); + unit = 'second'; + } else if (Math.abs(diffInSeconds) < _index.secondsInHour) { + value = (0, _index8.default)(dateLeft, dateRight); + unit = 'minute'; + } else if (Math.abs(diffInSeconds) < _index.secondsInDay && Math.abs((0, _index2.default)(dateLeft, dateRight)) < 1) { + value = (0, _index7.default)(dateLeft, dateRight); + unit = 'hour'; + } else if (Math.abs(diffInSeconds) < _index.secondsInWeek && (value = (0, _index2.default)(dateLeft, dateRight)) && Math.abs(value) < 7) { + unit = 'day'; + } else if (Math.abs(diffInSeconds) < _index.secondsInMonth) { + value = (0, _index5.default)(dateLeft, dateRight); + unit = 'week'; + } else if (Math.abs(diffInSeconds) < _index.secondsInQuarter) { + value = (0, _index3.default)(dateLeft, dateRight); + unit = 'month'; + } else if (Math.abs(diffInSeconds) < _index.secondsInYear) { + if ((0, _index4.default)(dateLeft, dateRight) < 4) { + // To filter out cases that are less than a year but match 4 quarters + value = (0, _index4.default)(dateLeft, dateRight); + unit = 'quarter'; + } else { + value = (0, _index6.default)(dateLeft, dateRight); + unit = 'year'; + } + } else { + value = (0, _index6.default)(dateLeft, dateRight); + unit = 'year'; + } + } else { + // Get the value if unit is specified + unit = options === null || options === void 0 ? void 0 : options.unit; + + if (unit === 'second') { + value = (0, _index9.default)(dateLeft, dateRight); + } else if (unit === 'minute') { + value = (0, _index8.default)(dateLeft, dateRight); + } else if (unit === 'hour') { + value = (0, _index7.default)(dateLeft, dateRight); + } else if (unit === 'day') { + value = (0, _index2.default)(dateLeft, dateRight); + } else if (unit === 'week') { + value = (0, _index5.default)(dateLeft, dateRight); + } else if (unit === 'month') { + value = (0, _index3.default)(dateLeft, dateRight); + } else if (unit === 'quarter') { + value = (0, _index4.default)(dateLeft, dateRight); + } else if (unit === 'year') { + value = (0, _index6.default)(dateLeft, dateRight); + } } + + var rtf = new Intl.RelativeTimeFormat(options === null || options === void 0 ? void 0 : options.locale, { + localeMatcher: options === null || options === void 0 ? void 0 : options.localeMatcher, + numeric: (options === null || options === void 0 ? void 0 : options.numeric) || 'auto', + style: options === null || options === void 0 ? void 0 : options.style + }); + return rtf.format(value, unit); +} + +module.exports = exports.default; + +/***/ }), + +/***/ 99415: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true })); -Object.defineProperty(exports, "subMonths", ({ - enumerable: true, - get: function () { - return _index231.default; - } +exports["default"] = isAfter; + +var _index = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name isAfter + * @category Common Helpers + * @summary Is the first date after the second one? + * + * @description + * Is the first date after the second one? + * + * @param {Date|Number} date - the date that should be after the other one to return true + * @param {Date|Number} dateToCompare - the date to compare with + * @returns {Boolean} the first date is after the second date + * @throws {TypeError} 2 arguments required + * + * @example + * // Is 10 July 1989 after 11 February 1987? + * const result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11)) + * //=> true + */ +function isAfter(dirtyDate, dirtyDateToCompare) { + (0, _index2.default)(2, arguments); + var date = (0, _index.default)(dirtyDate); + var dateToCompare = (0, _index.default)(dirtyDateToCompare); + return date.getTime() > dateToCompare.getTime(); +} + +module.exports = exports.default; + +/***/ }), + +/***/ 55678: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true })); -Object.defineProperty(exports, "subQuarters", ({ - enumerable: true, - get: function () { - return _index232.default; - } +exports["default"] = isBefore; + +var _index = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name isBefore + * @category Common Helpers + * @summary Is the first date before the second one? + * + * @description + * Is the first date before the second one? + * + * @param {Date|Number} date - the date that should be before the other one to return true + * @param {Date|Number} dateToCompare - the date to compare with + * @returns {Boolean} the first date is before the second date + * @throws {TypeError} 2 arguments required + * + * @example + * // Is 10 July 1989 before 11 February 1987? + * const result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11)) + * //=> false + */ +function isBefore(dirtyDate, dirtyDateToCompare) { + (0, _index2.default)(2, arguments); + var date = (0, _index.default)(dirtyDate); + var dateToCompare = (0, _index.default)(dirtyDateToCompare); + return date.getTime() < dateToCompare.getTime(); +} + +module.exports = exports.default; + +/***/ }), + +/***/ 19410: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true })); -Object.defineProperty(exports, "subSeconds", ({ - enumerable: true, - get: function () { - return _index233.default; - } +exports["default"] = isDate; + +var _index = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name isDate + * @category Common Helpers + * @summary Is the given value a date? + * + * @description + * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes. + * + * @param {*} value - the value to check + * @returns {boolean} true if the given value is a date + * @throws {TypeError} 1 arguments required + * + * @example + * // For a valid date: + * const result = isDate(new Date()) + * //=> true + * + * @example + * // For an invalid date: + * const result = isDate(new Date(NaN)) + * //=> true + * + * @example + * // For some value: + * const result = isDate('2014-02-31') + * //=> false + * + * @example + * // For an object: + * const result = isDate({}) + * //=> false + */ +function isDate(value) { + (0, _index.default)(1, arguments); + return value instanceof Date || typeof value === 'object' && Object.prototype.toString.call(value) === '[object Date]'; +} + +module.exports = exports.default; + +/***/ }), + +/***/ 41804: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true })); -Object.defineProperty(exports, "subWeeks", ({ - enumerable: true, - get: function () { - return _index234.default; - } +exports["default"] = isEqual; + +var _index = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name isEqual + * @category Common Helpers + * @summary Are the given dates equal? + * + * @description + * Are the given dates equal? + * + * @param {Date|Number} dateLeft - the first date to compare + * @param {Date|Number} dateRight - the second date to compare + * @returns {Boolean} the dates are equal + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal? + * const result = isEqual( + * new Date(2014, 6, 2, 6, 30, 45, 0), + * new Date(2014, 6, 2, 6, 30, 45, 500) + * ) + * //=> false + */ +function isEqual(dirtyLeftDate, dirtyRightDate) { + (0, _index2.default)(2, arguments); + var dateLeft = (0, _index.default)(dirtyLeftDate); + var dateRight = (0, _index.default)(dirtyRightDate); + return dateLeft.getTime() === dateRight.getTime(); +} + +module.exports = exports.default; + +/***/ }), + +/***/ 77621: +/***/ ((module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true })); -Object.defineProperty(exports, "subYears", ({ - enumerable: true, - get: function () { - return _index235.default; +exports["default"] = isExists; + +/** + * @name isExists + * @category Common Helpers + * @summary Is the given date exists? + * + * @description + * Checks if the given arguments convert to an existing date. + * + * @param {Number} year of the date to check + * @param {Number} month of the date to check + * @param {Number} day of the date to check + * @returns {Boolean} the date exists + * @throws {TypeError} 3 arguments required + * + * @example + * // For the valid date: + * const result = isExists(2018, 0, 31) + * //=> true + * + * @example + * // For the invalid date: + * const result = isExists(2018, 1, 31) + * //=> false + */ +function isExists(year, month, day) { + if (arguments.length < 3) { + throw new TypeError('3 argument required, but only ' + arguments.length + ' present'); } + + var date = new Date(year, month, day); + return date.getFullYear() === year && date.getMonth() === month && date.getDate() === day; +} + +module.exports = exports.default; + +/***/ }), + +/***/ 4627: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true })); -Object.defineProperty(exports, "toDate", ({ - enumerable: true, - get: function () { - return _index236.default; - } +exports["default"] = isFirstDayOfMonth; + +var _index = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name isFirstDayOfMonth + * @category Month Helpers + * @summary Is the given date the first day of a month? + * + * @description + * Is the given date the first day of a month? + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is the first day of a month + * @throws {TypeError} 1 argument required + * + * @example + * // Is 1 September 2014 the first day of a month? + * const result = isFirstDayOfMonth(new Date(2014, 8, 1)) + * //=> true + */ +function isFirstDayOfMonth(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate).getDate() === 1; +} + +module.exports = exports.default; + +/***/ }), + +/***/ 82372: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true })); -Object.defineProperty(exports, "weeksToDays", ({ - enumerable: true, - get: function () { - return _index237.default; - } +exports["default"] = isFriday; + +var _index = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name isFriday + * @category Weekday Helpers + * @summary Is the given date Friday? + * + * @description + * Is the given date Friday? + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is Friday + * @throws {TypeError} 1 argument required + * + * @example + * // Is 26 September 2014 Friday? + * const result = isFriday(new Date(2014, 8, 26)) + * //=> true + */ +function isFriday(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate).getDay() === 5; +} + +module.exports = exports.default; + +/***/ }), + +/***/ 55371: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true })); -Object.defineProperty(exports, "yearsToMonths", ({ - enumerable: true, - get: function () { - return _index238.default; - } +exports["default"] = isFuture; + +var _index = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name isFuture + * @category Common Helpers + * @summary Is the given date in the future? + * @pure false + * + * @description + * Is the given date in the future? + * + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `Date.now()` internally hence impure and can't be safely curried. + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is in the future + * @throws {TypeError} 1 argument required + * + * @example + * // If today is 6 October 2014, is 31 December 2014 in the future? + * const result = isFuture(new Date(2014, 11, 31)) + * //=> true + */ +function isFuture(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate).getTime() > Date.now(); +} + +module.exports = exports.default; + +/***/ }), + +/***/ 5263: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true })); -Object.defineProperty(exports, "yearsToQuarters", ({ - enumerable: true, - get: function () { - return _index239.default; - } +exports["default"] = isLastDayOfMonth; + +var _index = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(83055)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(60349)); + +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name isLastDayOfMonth + * @category Month Helpers + * @summary Is the given date the last day of a month? + * + * @description + * Is the given date the last day of a month? + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is the last day of a month + * @throws {TypeError} 1 argument required + * + * @example + * // Is 28 February 2014 the last day of a month? + * const result = isLastDayOfMonth(new Date(2014, 1, 28)) + * //=> true + */ +function isLastDayOfMonth(dirtyDate) { + (0, _index4.default)(1, arguments); + var date = (0, _index.default)(dirtyDate); + return (0, _index2.default)(date).getTime() === (0, _index3.default)(date).getTime(); +} + +module.exports = exports.default; + +/***/ }), + +/***/ 94274: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true })); +exports["default"] = isLeapYear; + +var _index = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name isLeapYear + * @category Year Helpers + * @summary Is the given date in the leap year? + * + * @description + * Is the given date in the leap year? + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is in the leap year + * @throws {TypeError} 1 argument required + * + * @example + * // Is 1 September 2012 in the leap year? + * const result = isLeapYear(new Date(2012, 8, 1)) + * //=> true + */ +function isLeapYear(dirtyDate) { + (0, _index2.default)(1, arguments); + var date = (0, _index.default)(dirtyDate); + var year = date.getFullYear(); + return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0; +} -var _index = _interopRequireDefault(__nccwpck_require__(96211)); +module.exports = exports.default; -var _index2 = _interopRequireDefault(__nccwpck_require__(81727)); +/***/ }), -var _index3 = _interopRequireDefault(__nccwpck_require__(56227)); +/***/ 95440: +/***/ ((module, exports, __nccwpck_require__) => { -var _index4 = _interopRequireDefault(__nccwpck_require__(59956)); +"use strict"; -var _index5 = _interopRequireDefault(__nccwpck_require__(75318)); -var _index6 = _interopRequireDefault(__nccwpck_require__(30524)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isMatch; -var _index7 = _interopRequireDefault(__nccwpck_require__(15268)); +var _index = _interopRequireDefault(__nccwpck_require__(10435)); -var _index8 = _interopRequireDefault(__nccwpck_require__(22995)); +var _index2 = _interopRequireDefault(__nccwpck_require__(60435)); -var _index9 = _interopRequireDefault(__nccwpck_require__(25149)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index10 = _interopRequireDefault(__nccwpck_require__(14112)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index11 = _interopRequireDefault(__nccwpck_require__(97195)); +/** + * @name isMatch + * @category Common Helpers + * @summary validates the date string against given formats + * + * @description + * Return the true if given date is string correct against the given format else + * will return false. + * + * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries. + * > See: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * The characters in the format string wrapped between two single quotes characters (') are escaped. + * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. + * + * Format of the format string is based on Unicode Technical Standard #35: + * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table + * with a few additions (see note 5 below the table). + * + * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited + * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception: + * + * ```javascript + * isMatch('23 AM', 'HH a') + * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time + * ``` + * + * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true + * + * Accepted format string patterns: + * | Unit |Prior| Pattern | Result examples | Notes | + * |---------------------------------|-----|---------|-----------------------------------|-------| + * | Era | 140 | G..GGG | AD, BC | | + * | | | GGGG | Anno Domini, Before Christ | 2 | + * | | | GGGGG | A, B | | + * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 | + * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 | + * | | | yy | 44, 01, 00, 17 | 4 | + * | | | yyy | 044, 001, 123, 999 | 4 | + * | | | yyyy | 0044, 0001, 1900, 2017 | 4 | + * | | | yyyyy | ... | 2,4 | + * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 | + * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 | + * | | | YY | 44, 01, 00, 17 | 4,6 | + * | | | YYY | 044, 001, 123, 999 | 4 | + * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 | + * | | | YYYYY | ... | 2,4 | + * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 | + * | | | RR | -43, 01, 00, 17 | 4,5 | + * | | | RRR | -043, 001, 123, 999, -999 | 4,5 | + * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 | + * | | | RRRRR | ... | 2,4,5 | + * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 | + * | | | uu | -43, 01, 99, -99 | 4 | + * | | | uuu | -043, 001, 123, 999, -999 | 4 | + * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 | + * | | | uuuuu | ... | 2,4 | + * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | | + * | | | Qo | 1st, 2nd, 3rd, 4th | 5 | + * | | | QQ | 01, 02, 03, 04 | | + * | | | QQQ | Q1, Q2, Q3, Q4 | | + * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 | + * | | | QQQQQ | 1, 2, 3, 4 | 4 | + * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | | + * | | | qo | 1st, 2nd, 3rd, 4th | 5 | + * | | | qq | 01, 02, 03, 04 | | + * | | | qqq | Q1, Q2, Q3, Q4 | | + * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 | + * | | | qqqqq | 1, 2, 3, 4 | 3 | + * | Month (formatting) | 110 | M | 1, 2, ..., 12 | | + * | | | Mo | 1st, 2nd, ..., 12th | 5 | + * | | | MM | 01, 02, ..., 12 | | + * | | | MMM | Jan, Feb, ..., Dec | | + * | | | MMMM | January, February, ..., December | 2 | + * | | | MMMMM | J, F, ..., D | | + * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | | + * | | | Lo | 1st, 2nd, ..., 12th | 5 | + * | | | LL | 01, 02, ..., 12 | | + * | | | LLL | Jan, Feb, ..., Dec | | + * | | | LLLL | January, February, ..., December | 2 | + * | | | LLLLL | J, F, ..., D | | + * | Local week of year | 100 | w | 1, 2, ..., 53 | | + * | | | wo | 1st, 2nd, ..., 53th | 5 | + * | | | ww | 01, 02, ..., 53 | | + * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 | + * | | | Io | 1st, 2nd, ..., 53th | 5 | + * | | | II | 01, 02, ..., 53 | 5 | + * | Day of month | 90 | d | 1, 2, ..., 31 | | + * | | | do | 1st, 2nd, ..., 31st | 5 | + * | | | dd | 01, 02, ..., 31 | | + * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 | + * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 | + * | | | DD | 01, 02, ..., 365, 366 | 7 | + * | | | DDD | 001, 002, ..., 365, 366 | | + * | | | DDDD | ... | 2 | + * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Su | | + * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 | + * | | | EEEEE | M, T, W, T, F, S, S | | + * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | | + * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 | + * | | | io | 1st, 2nd, ..., 7th | 5 | + * | | | ii | 01, 02, ..., 07 | 5 | + * | | | iii | Mon, Tue, Wed, ..., Su | 5 | + * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 | + * | | | iiiii | M, T, W, T, F, S, S | 5 | + * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 | + * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | | + * | | | eo | 2nd, 3rd, ..., 1st | 5 | + * | | | ee | 02, 03, ..., 01 | | + * | | | eee | Mon, Tue, Wed, ..., Su | | + * | | | eeee | Monday, Tuesday, ..., Sunday | 2 | + * | | | eeeee | M, T, W, T, F, S, S | | + * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | | + * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | | + * | | | co | 2nd, 3rd, ..., 1st | 5 | + * | | | cc | 02, 03, ..., 01 | | + * | | | ccc | Mon, Tue, Wed, ..., Su | | + * | | | cccc | Monday, Tuesday, ..., Sunday | 2 | + * | | | ccccc | M, T, W, T, F, S, S | | + * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | | + * | AM, PM | 80 | a..aaa | AM, PM | | + * | | | aaaa | a.m., p.m. | 2 | + * | | | aaaaa | a, p | | + * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | | + * | | | bbbb | a.m., p.m., noon, midnight | 2 | + * | | | bbbbb | a, p, n, mi | | + * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | | + * | | | BBBB | at night, in the morning, ... | 2 | + * | | | BBBBB | at night, in the morning, ... | | + * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | | + * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 | + * | | | hh | 01, 02, ..., 11, 12 | | + * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | | + * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 | + * | | | HH | 00, 01, 02, ..., 23 | | + * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | | + * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 | + * | | | KK | 01, 02, ..., 11, 00 | | + * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | | + * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 | + * | | | kk | 24, 01, 02, ..., 23 | | + * | Minute | 60 | m | 0, 1, ..., 59 | | + * | | | mo | 0th, 1st, ..., 59th | 5 | + * | | | mm | 00, 01, ..., 59 | | + * | Second | 50 | s | 0, 1, ..., 59 | | + * | | | so | 0th, 1st, ..., 59th | 5 | + * | | | ss | 00, 01, ..., 59 | | + * | Seconds timestamp | 40 | t | 512969520 | | + * | | | tt | ... | 2 | + * | Fraction of second | 30 | S | 0, 1, ..., 9 | | + * | | | SS | 00, 01, ..., 99 | | + * | | | SSS | 000, 001, ..., 999 | | + * | | | SSSS | ... | 2 | + * | Milliseconds timestamp | 20 | T | 512969520900 | | + * | | | TT | ... | 2 | + * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | | + * | | | XX | -0800, +0530, Z | | + * | | | XXX | -08:00, +05:30, Z | | + * | | | XXXX | -0800, +0530, Z, +123456 | 2 | + * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | | + * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | | + * | | | xx | -0800, +0530, +0000 | | + * | | | xxx | -08:00, +05:30, +00:00 | 2 | + * | | | xxxx | -0800, +0530, +0000, +123456 | | + * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | | + * | Long localized date | NA | P | 05/29/1453 | 5,8 | + * | | | PP | May 29, 1453 | | + * | | | PPP | May 29th, 1453 | | + * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 | + * | Long localized time | NA | p | 12:00 AM | 5,8 | + * | | | pp | 12:00:00 AM | | + * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | | + * | | | PPpp | May 29, 1453, 12:00:00 AM | | + * | | | PPPpp | May 29th, 1453 at ... | | + * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 | + * Notes: + * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale + * are the same as "stand-alone" units, but are different in some languages. + * "Formatting" units are declined according to the rules of the language + * in the context of a date. "Stand-alone" units are always nominative singular. + * In `format` function, they will produce different result: + * + * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'` + * + * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'` + * + * `isMatch` will try to match both formatting and stand-alone units interchangably. + * + * 2. Any sequence of the identical letters is a pattern, unless it is escaped by + * the single quote characters (see below). + * If the sequence is longer than listed in table: + * - for numerical units (`yyyyyyyy`) `isMatch` will try to match a number + * as wide as the sequence + * - for text units (`MMMMMMMM`) `isMatch` will try to match the widest variation of the unit. + * These variations are marked with "2" in the last column of the table. + * + * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales. + * These tokens represent the shortest form of the quarter. + * + * 4. The main difference between `y` and `u` patterns are B.C. years: + * + * | Year | `y` | `u` | + * |------|-----|-----| + * | AC 1 | 1 | 1 | + * | BC 1 | 1 | 0 | + * | BC 2 | 2 | -1 | + * + * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`: + * + * `isMatch('50', 'yy') //=> true` + * + * `isMatch('75', 'yy') //=> true` + * + * while `uu` will use the year as is: + * + * `isMatch('50', 'uu') //=> true` + * + * `isMatch('75', 'uu') //=> true` + * + * The same difference is true for local and ISO week-numbering years (`Y` and `R`), + * except local week-numbering years are dependent on `options.weekStartsOn` + * and `options.firstWeekContainsDate` (compare [setISOWeekYear]{@link https://date-fns.org/docs/setISOWeekYear} + * and [setWeekYear]{@link https://date-fns.org/docs/setWeekYear}). + * + * 5. These patterns are not in the Unicode Technical Standard #35: + * - `i`: ISO day of week + * - `I`: ISO week of year + * - `R`: ISO week-numbering year + * - `o`: ordinal number modifier + * - `P`: long localized date + * - `p`: long localized time + * + * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years. + * You should enable `options.useAdditionalWeekYearTokens` to use them. See: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * 7. `D` and `DD` tokens represent days of the year but they are ofthen confused with days of the month. + * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based + * on the given locale. + * + * using `en-US` locale: `P` => `MM/dd/yyyy` + * using `en-US` locale: `p` => `hh:mm a` + * using `pt-BR` locale: `P` => `dd/MM/yyyy` + * using `pt-BR` locale: `p` => `HH:mm` + * + * Values will be checked in the descending order of its unit's priority. + * Units of an equal priority overwrite each other in the order of appearance. + * + * If no values of higher priority are matched (e.g. when matching string 'January 1st' without a year), + * the values will be taken from today's using `new Date()` date which works as a context of parsing. + * + * The result may vary by locale. + * + * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned. + * + * + * + * @param {String} dateString - the date string to verify + * @param {String} formatString - the string of tokens + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year + * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`; + * see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`; + * see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @returns {Boolean} + * @throws {TypeError} 2 arguments required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 + * @throws {RangeError} `options.locale` must contain `match` property + * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years; see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `yy` instead of `YY` for formatting years; see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `d` instead of `D` for formatting days of the month; see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month; see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} format string contains an unescaped latin alphabet character + * + * @example + * // Match 11 February 2014 from middle-endian format: + * const result = isMatch('02/11/2014', 'MM/dd/yyyy') + * //=> true + * + * @example + * // Match 28th of February in Esperanto locale in the context of 2010 year: + * import eo from 'date-fns/locale/eo' + * const result = isMatch('28-a de februaro', "do 'de' MMMM", { + * locale: eo + * }) + * //=> true + */ +function isMatch(dateString, formatString, options) { + (0, _index3.default)(2, arguments); + return (0, _index2.default)((0, _index.default)(dateString, formatString, new Date(), options)); +} -var _index12 = _interopRequireDefault(__nccwpck_require__(73367)); +module.exports = exports.default; -var _index13 = _interopRequireDefault(__nccwpck_require__(32282)); +/***/ }), -var _index14 = _interopRequireDefault(__nccwpck_require__(79660)); +/***/ 21095: +/***/ ((module, exports, __nccwpck_require__) => { -var _index15 = _interopRequireDefault(__nccwpck_require__(62264)); +"use strict"; -var _index16 = _interopRequireDefault(__nccwpck_require__(42013)); -var _index17 = _interopRequireDefault(__nccwpck_require__(29818)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isMonday; -var _index18 = _interopRequireDefault(__nccwpck_require__(57783)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index19 = _interopRequireDefault(__nccwpck_require__(56237)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index20 = _interopRequireDefault(__nccwpck_require__(34734)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index21 = _interopRequireDefault(__nccwpck_require__(3086)); +/** + * @name isMonday + * @category Weekday Helpers + * @summary Is the given date Monday? + * + * @description + * Is the given date Monday? + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is Monday + * @throws {TypeError} 1 argument required + * + * @example + * // Is 22 September 2014 Monday? + * const result = isMonday(new Date(2014, 8, 22)) + * //=> true + */ +function isMonday(date) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(date).getDay() === 1; +} -var _index22 = _interopRequireDefault(__nccwpck_require__(36778)); +module.exports = exports.default; -var _index23 = _interopRequireDefault(__nccwpck_require__(1656)); +/***/ }), -var _index24 = _interopRequireDefault(__nccwpck_require__(95536)); +/***/ 39886: +/***/ ((module, exports, __nccwpck_require__) => { -var _index25 = _interopRequireDefault(__nccwpck_require__(22342)); +"use strict"; -var _index26 = _interopRequireDefault(__nccwpck_require__(8620)); -var _index27 = _interopRequireDefault(__nccwpck_require__(45237)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isPast; -var _index28 = _interopRequireDefault(__nccwpck_require__(16311)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index29 = _interopRequireDefault(__nccwpck_require__(88740)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index30 = _interopRequireDefault(__nccwpck_require__(98815)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index31 = _interopRequireDefault(__nccwpck_require__(92288)); +/** + * @name isPast + * @category Common Helpers + * @summary Is the given date in the past? + * @pure false + * + * @description + * Is the given date in the past? + * + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `Date.now()` internally hence impure and can't be safely curried. + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is in the past + * @throws {TypeError} 1 argument required + * + * @example + * // If today is 6 October 2014, is 2 July 2014 in the past? + * const result = isPast(new Date(2014, 6, 2)) + * //=> true + */ +function isPast(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate).getTime() < Date.now(); +} -var _index32 = _interopRequireDefault(__nccwpck_require__(63842)); +module.exports = exports.default; -var _index33 = _interopRequireDefault(__nccwpck_require__(12713)); +/***/ }), -var _index34 = _interopRequireDefault(__nccwpck_require__(87074)); +/***/ 17150: +/***/ ((module, exports, __nccwpck_require__) => { -var _index35 = _interopRequireDefault(__nccwpck_require__(89448)); +"use strict"; -var _index36 = _interopRequireDefault(__nccwpck_require__(42701)); -var _index37 = _interopRequireDefault(__nccwpck_require__(13959)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isSameDay; -var _index38 = _interopRequireDefault(__nccwpck_require__(56545)); +var _index = _interopRequireDefault(__nccwpck_require__(72287)); -var _index39 = _interopRequireDefault(__nccwpck_require__(66802)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index40 = _interopRequireDefault(__nccwpck_require__(62029)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index41 = _interopRequireDefault(__nccwpck_require__(25879)); +/** + * @name isSameDay + * @category Day Helpers + * @summary Are the given dates in the same day (and year and month)? + * + * @description + * Are the given dates in the same day (and year and month)? + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @returns {Boolean} the dates are in the same day (and year and month) + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day? + * const result = isSameDay(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 18, 0)) + * //=> true + * + * @example + * // Are 4 September and 4 October in the same day? + * const result = isSameDay(new Date(2014, 8, 4), new Date(2014, 9, 4)) + * //=> false + * + * @example + * // Are 4 September, 2014 and 4 September, 2015 in the same day? + * const result = isSameDay(new Date(2014, 8, 4), new Date(2015, 8, 4)) + * //=> false + */ +function isSameDay(dirtyDateLeft, dirtyDateRight) { + (0, _index2.default)(2, arguments); + var dateLeftStartOfDay = (0, _index.default)(dirtyDateLeft); + var dateRightStartOfDay = (0, _index.default)(dirtyDateRight); + return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime(); +} -var _index42 = _interopRequireDefault(__nccwpck_require__(36516)); +module.exports = exports.default; -var _index43 = _interopRequireDefault(__nccwpck_require__(95994)); +/***/ }), -var _index44 = _interopRequireDefault(__nccwpck_require__(51944)); +/***/ 88687: +/***/ ((module, exports, __nccwpck_require__) => { -var _index45 = _interopRequireDefault(__nccwpck_require__(3973)); +"use strict"; -var _index46 = _interopRequireDefault(__nccwpck_require__(7961)); -var _index47 = _interopRequireDefault(__nccwpck_require__(56525)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isSameHour; -var _index48 = _interopRequireDefault(__nccwpck_require__(8569)); +var _index = _interopRequireDefault(__nccwpck_require__(46561)); -var _index49 = _interopRequireDefault(__nccwpck_require__(21517)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index50 = _interopRequireDefault(__nccwpck_require__(81894)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index51 = _interopRequireDefault(__nccwpck_require__(1920)); +/** + * @name isSameHour + * @category Hour Helpers + * @summary Are the given dates in the same hour (and same day)? + * + * @description + * Are the given dates in the same hour (and same day)? + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @returns {Boolean} the dates are in the same hour (and same day) + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 4 September 2014 06:00:00 and 4 September 06:30:00 in the same hour? + * const result = isSameHour(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 6, 30)) + * //=> true + * + * @example + * // Are 4 September 2014 06:00:00 and 5 September 06:00:00 in the same hour? + * const result = isSameHour(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 5, 6, 0)) + * //=> false + */ +function isSameHour(dirtyDateLeft, dirtyDateRight) { + (0, _index2.default)(2, arguments); + var dateLeftStartOfHour = (0, _index.default)(dirtyDateLeft); + var dateRightStartOfHour = (0, _index.default)(dirtyDateRight); + return dateLeftStartOfHour.getTime() === dateRightStartOfHour.getTime(); +} -var _index52 = _interopRequireDefault(__nccwpck_require__(79731)); +module.exports = exports.default; -var _index53 = _interopRequireDefault(__nccwpck_require__(71389)); +/***/ }), -var _index54 = _interopRequireDefault(__nccwpck_require__(12621)); +/***/ 49846: +/***/ ((module, exports, __nccwpck_require__) => { -var _index55 = _interopRequireDefault(__nccwpck_require__(35596)); +"use strict"; -var _index56 = _interopRequireDefault(__nccwpck_require__(66121)); -var _index57 = _interopRequireDefault(__nccwpck_require__(95700)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isSameISOWeek; -var _index58 = _interopRequireDefault(__nccwpck_require__(6935)); +var _index = _interopRequireDefault(__nccwpck_require__(30876)); -var _index59 = _interopRequireDefault(__nccwpck_require__(85218)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index60 = _interopRequireDefault(__nccwpck_require__(67079)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index61 = _interopRequireDefault(__nccwpck_require__(50066)); +/** + * @name isSameISOWeek + * @category ISO Week Helpers + * @summary Are the given dates in the same ISO week (and year)? + * + * @description + * Are the given dates in the same ISO week (and year)? + * + * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @returns {Boolean} the dates are in the same ISO week (and year) + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 1 September 2014 and 7 September 2014 in the same ISO week? + * const result = isSameISOWeek(new Date(2014, 8, 1), new Date(2014, 8, 7)) + * //=> true + * + * @example + * // Are 1 September 2014 and 1 September 2015 in the same ISO week? + * const result = isSameISOWeek(new Date(2014, 8, 1), new Date(2015, 8, 1)) + * //=> false + */ +function isSameISOWeek(dirtyDateLeft, dirtyDateRight) { + (0, _index2.default)(2, arguments); + return (0, _index.default)(dirtyDateLeft, dirtyDateRight, { + weekStartsOn: 1 + }); +} -var _index62 = _interopRequireDefault(__nccwpck_require__(42168)); +module.exports = exports.default; -var _index63 = _interopRequireDefault(__nccwpck_require__(48149)); +/***/ }), -var _index64 = _interopRequireDefault(__nccwpck_require__(97128)); +/***/ 96303: +/***/ ((module, exports, __nccwpck_require__) => { -var _index65 = _interopRequireDefault(__nccwpck_require__(71163)); +"use strict"; -var _index66 = _interopRequireDefault(__nccwpck_require__(84741)); -var _index67 = _interopRequireDefault(__nccwpck_require__(68917)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isSameISOWeekYear; -var _index68 = _interopRequireDefault(__nccwpck_require__(93385)); +var _index = _interopRequireDefault(__nccwpck_require__(34855)); -var _index69 = _interopRequireDefault(__nccwpck_require__(5296)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index70 = _interopRequireDefault(__nccwpck_require__(32448)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index71 = _interopRequireDefault(__nccwpck_require__(34182)); +/** + * @name isSameISOWeekYear + * @category ISO Week-Numbering Year Helpers + * @summary Are the given dates in the same ISO week-numbering year? + * + * @description + * Are the given dates in the same ISO week-numbering year? + * + * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @returns {Boolean} the dates are in the same ISO week-numbering year + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 29 December 2003 and 2 January 2005 in the same ISO week-numbering year? + * const result = isSameISOWeekYear(new Date(2003, 11, 29), new Date(2005, 0, 2)) + * //=> true + */ +function isSameISOWeekYear(dirtyDateLeft, dirtyDateRight) { + (0, _index2.default)(2, arguments); + var dateLeftStartOfYear = (0, _index.default)(dirtyDateLeft); + var dateRightStartOfYear = (0, _index.default)(dirtyDateRight); + return dateLeftStartOfYear.getTime() === dateRightStartOfYear.getTime(); +} -var _index72 = _interopRequireDefault(__nccwpck_require__(60402)); +module.exports = exports.default; -var _index73 = _interopRequireDefault(__nccwpck_require__(90675)); +/***/ }), -var _index74 = _interopRequireDefault(__nccwpck_require__(74897)); +/***/ 76570: +/***/ ((module, exports, __nccwpck_require__) => { -var _index75 = _interopRequireDefault(__nccwpck_require__(7626)); +"use strict"; -var _index76 = _interopRequireDefault(__nccwpck_require__(9361)); -var _index77 = _interopRequireDefault(__nccwpck_require__(67468)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isSameMinute; -var _index78 = _interopRequireDefault(__nccwpck_require__(97573)); +var _index = _interopRequireDefault(__nccwpck_require__(10749)); -var _index79 = _interopRequireDefault(__nccwpck_require__(42784)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index80 = _interopRequireDefault(__nccwpck_require__(9322)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index81 = _interopRequireDefault(__nccwpck_require__(65795)); +/** + * @name isSameMinute + * @category Minute Helpers + * @summary Are the given dates in the same minute (and hour and day)? + * + * @description + * Are the given dates in the same minute (and hour and day)? + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @returns {Boolean} the dates are in the same minute (and hour and day) + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 4 September 2014 06:30:00 and 4 September 2014 06:30:15 in the same minute? + * const result = isSameMinute( + * new Date(2014, 8, 4, 6, 30), + * new Date(2014, 8, 4, 6, 30, 15) + * ) + * //=> true + * + * @example + * // Are 4 September 2014 06:30:00 and 5 September 2014 06:30:00 in the same minute? + * const result = isSameMinute( + * new Date(2014, 8, 4, 6, 30), + * new Date(2014, 8, 5, 6, 30) + * ) + * //=> false + */ +function isSameMinute(dirtyDateLeft, dirtyDateRight) { + (0, _index2.default)(2, arguments); + var dateLeftStartOfMinute = (0, _index.default)(dirtyDateLeft); + var dateRightStartOfMinute = (0, _index.default)(dirtyDateRight); + return dateLeftStartOfMinute.getTime() === dateRightStartOfMinute.getTime(); +} -var _index82 = _interopRequireDefault(__nccwpck_require__(27941)); +module.exports = exports.default; -var _index83 = _interopRequireDefault(__nccwpck_require__(98313)); +/***/ }), -var _index84 = _interopRequireDefault(__nccwpck_require__(19894)); +/***/ 32603: +/***/ ((module, exports, __nccwpck_require__) => { -var _index85 = _interopRequireDefault(__nccwpck_require__(86991)); +"use strict"; -var _index86 = _interopRequireDefault(__nccwpck_require__(35438)); -var _index87 = _interopRequireDefault(__nccwpck_require__(67560)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isSameMonth; -var _index88 = _interopRequireDefault(__nccwpck_require__(7030)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index89 = _interopRequireDefault(__nccwpck_require__(2194)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index90 = _interopRequireDefault(__nccwpck_require__(57647)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index91 = _interopRequireDefault(__nccwpck_require__(34523)); +/** + * @name isSameMonth + * @category Month Helpers + * @summary Are the given dates in the same month (and year)? + * + * @description + * Are the given dates in the same month (and year)? + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @returns {Boolean} the dates are in the same month (and year) + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 2 September 2014 and 25 September 2014 in the same month? + * const result = isSameMonth(new Date(2014, 8, 2), new Date(2014, 8, 25)) + * //=> true + * + * @example + * // Are 2 September 2014 and 25 September 2015 in the same month? + * const result = isSameMonth(new Date(2014, 8, 2), new Date(2015, 8, 25)) + * //=> false + */ +function isSameMonth(dirtyDateLeft, dirtyDateRight) { + (0, _index2.default)(2, arguments); + var dateLeft = (0, _index.default)(dirtyDateLeft); + var dateRight = (0, _index.default)(dirtyDateRight); + return dateLeft.getFullYear() === dateRight.getFullYear() && dateLeft.getMonth() === dateRight.getMonth(); +} -var _index92 = _interopRequireDefault(__nccwpck_require__(48755)); +module.exports = exports.default; -var _index93 = _interopRequireDefault(__nccwpck_require__(85052)); +/***/ }), -var _index94 = _interopRequireDefault(__nccwpck_require__(66476)); +/***/ 16063: +/***/ ((module, exports, __nccwpck_require__) => { -var _index95 = _interopRequireDefault(__nccwpck_require__(81)); +"use strict"; -var _index96 = _interopRequireDefault(__nccwpck_require__(39229)); -var _index97 = _interopRequireDefault(__nccwpck_require__(33494)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isSameQuarter; -var _index98 = _interopRequireDefault(__nccwpck_require__(89482)); +var _index = _interopRequireDefault(__nccwpck_require__(44860)); -var _index99 = _interopRequireDefault(__nccwpck_require__(25714)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index100 = _interopRequireDefault(__nccwpck_require__(83895)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index101 = _interopRequireDefault(__nccwpck_require__(72449)); +/** + * @name isSameQuarter + * @category Quarter Helpers + * @summary Are the given dates in the same quarter (and year)? + * + * @description + * Are the given dates in the same quarter (and year)? + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @returns {Boolean} the dates are in the same quarter (and year) + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 1 January 2014 and 8 March 2014 in the same quarter? + * const result = isSameQuarter(new Date(2014, 0, 1), new Date(2014, 2, 8)) + * //=> true + * + * @example + * // Are 1 January 2014 and 1 January 2015 in the same quarter? + * const result = isSameQuarter(new Date(2014, 0, 1), new Date(2015, 0, 1)) + * //=> false + */ +function isSameQuarter(dirtyDateLeft, dirtyDateRight) { + (0, _index2.default)(2, arguments); + var dateLeftStartOfQuarter = (0, _index.default)(dirtyDateLeft); + var dateRightStartOfQuarter = (0, _index.default)(dirtyDateRight); + return dateLeftStartOfQuarter.getTime() === dateRightStartOfQuarter.getTime(); +} -var _index102 = _interopRequireDefault(__nccwpck_require__(775)); +module.exports = exports.default; -var _index103 = _interopRequireDefault(__nccwpck_require__(32079)); +/***/ }), -var _index104 = _interopRequireDefault(__nccwpck_require__(51982)); +/***/ 969: +/***/ ((module, exports, __nccwpck_require__) => { -var _index105 = _interopRequireDefault(__nccwpck_require__(73858)); +"use strict"; -var _index106 = _interopRequireDefault(__nccwpck_require__(2755)); -var _index107 = _interopRequireDefault(__nccwpck_require__(89369)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isSameSecond; -var _index108 = _interopRequireDefault(__nccwpck_require__(6801)); +var _index = _interopRequireDefault(__nccwpck_require__(20740)); -var _index109 = _interopRequireDefault(__nccwpck_require__(44669)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index110 = _interopRequireDefault(__nccwpck_require__(97352)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index111 = _interopRequireDefault(__nccwpck_require__(15387)); +/** + * @name isSameSecond + * @category Second Helpers + * @summary Are the given dates in the same second (and hour and day)? + * + * @description + * Are the given dates in the same second (and hour and day)? + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @returns {Boolean} the dates are in the same second (and hour and day) + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 4 September 2014 06:30:15.000 and 4 September 2014 06:30.15.500 in the same second? + * const result = isSameSecond( + * new Date(2014, 8, 4, 6, 30, 15), + * new Date(2014, 8, 4, 6, 30, 15, 500) + * ) + * //=> true + * + * @example + * // Are 4 September 2014 06:00:15.000 and 4 September 2014 06:01.15.000 in the same second? + * const result = isSameSecond( + * new Date(2014, 8, 4, 6, 0, 15), + * new Date(2014, 8, 4, 6, 1, 15) + * ) + * //=> false + * + * @example + * // Are 4 September 2014 06:00:15.000 and 5 September 2014 06:00.15.000 in the same second? + * const result = isSameSecond( + * new Date(2014, 8, 4, 6, 0, 15), + * new Date(2014, 8, 5, 6, 0, 15) + * ) + * //=> false + */ +function isSameSecond(dirtyDateLeft, dirtyDateRight) { + (0, _index2.default)(2, arguments); + var dateLeftStartOfSecond = (0, _index.default)(dirtyDateLeft); + var dateRightStartOfSecond = (0, _index.default)(dirtyDateRight); + return dateLeftStartOfSecond.getTime() === dateRightStartOfSecond.getTime(); +} -var _index112 = _interopRequireDefault(__nccwpck_require__(81758)); +module.exports = exports.default; -var _index113 = _interopRequireDefault(__nccwpck_require__(36803)); +/***/ }), -var _index114 = _interopRequireDefault(__nccwpck_require__(48506)); +/***/ 30876: +/***/ ((module, exports, __nccwpck_require__) => { -var _index115 = _interopRequireDefault(__nccwpck_require__(90074)); +"use strict"; -var _index116 = _interopRequireDefault(__nccwpck_require__(90525)); -var _index117 = _interopRequireDefault(__nccwpck_require__(16030)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isSameWeek; -var _index118 = _interopRequireDefault(__nccwpck_require__(89543)); +var _index = _interopRequireDefault(__nccwpck_require__(38599)); -var _index119 = _interopRequireDefault(__nccwpck_require__(52154)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index120 = _interopRequireDefault(__nccwpck_require__(42489)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index121 = _interopRequireDefault(__nccwpck_require__(89852)); +/** + * @name isSameWeek + * @category Week Helpers + * @summary Are the given dates in the same week (and month and year)? + * + * @description + * Are the given dates in the same week (and month and year)? + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @returns {Boolean} the dates are in the same week (and month and year) + * @throws {TypeError} 2 arguments required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * + * @example + * // Are 31 August 2014 and 4 September 2014 in the same week? + * const result = isSameWeek(new Date(2014, 7, 31), new Date(2014, 8, 4)) + * //=> true + * + * @example + * // If week starts with Monday, + * // are 31 August 2014 and 4 September 2014 in the same week? + * const result = isSameWeek(new Date(2014, 7, 31), new Date(2014, 8, 4), { + * weekStartsOn: 1 + * }) + * //=> false + * + * @example + * // Are 1 January 2014 and 1 January 2015 in the same week? + * const result = isSameWeek(new Date(2014, 0, 1), new Date(2015, 0, 1)) + * //=> false + */ +function isSameWeek(dirtyDateLeft, dirtyDateRight, options) { + (0, _index2.default)(2, arguments); + var dateLeftStartOfWeek = (0, _index.default)(dirtyDateLeft, options); + var dateRightStartOfWeek = (0, _index.default)(dirtyDateRight, options); + return dateLeftStartOfWeek.getTime() === dateRightStartOfWeek.getTime(); +} -var _index122 = _interopRequireDefault(__nccwpck_require__(73944)); +module.exports = exports.default; -var _index123 = _interopRequireDefault(__nccwpck_require__(66)); +/***/ }), -var _index124 = _interopRequireDefault(__nccwpck_require__(65421)); +/***/ 1050: +/***/ ((module, exports, __nccwpck_require__) => { -var _index125 = _interopRequireDefault(__nccwpck_require__(40938)); +"use strict"; -var _index126 = _interopRequireDefault(__nccwpck_require__(51988)); -var _index127 = _interopRequireDefault(__nccwpck_require__(7013)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isSameYear; -var _index128 = _interopRequireDefault(__nccwpck_require__(99821)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index129 = _interopRequireDefault(__nccwpck_require__(6308)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index130 = _interopRequireDefault(__nccwpck_require__(35852)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index131 = _interopRequireDefault(__nccwpck_require__(84078)); +/** + * @name isSameYear + * @category Year Helpers + * @summary Are the given dates in the same year? + * + * @description + * Are the given dates in the same year? + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @returns {Boolean} the dates are in the same year + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 2 September 2014 and 25 September 2014 in the same year? + * const result = isSameYear(new Date(2014, 8, 2), new Date(2014, 8, 25)) + * //=> true + */ +function isSameYear(dirtyDateLeft, dirtyDateRight) { + (0, _index2.default)(2, arguments); + var dateLeft = (0, _index.default)(dirtyDateLeft); + var dateRight = (0, _index.default)(dirtyDateRight); + return dateLeft.getFullYear() === dateRight.getFullYear(); +} -var _index132 = _interopRequireDefault(__nccwpck_require__(6065)); +module.exports = exports.default; -var _index133 = _interopRequireDefault(__nccwpck_require__(33413)); +/***/ }), -var _index134 = _interopRequireDefault(__nccwpck_require__(51157)); +/***/ 49951: +/***/ ((module, exports, __nccwpck_require__) => { -var _index135 = _interopRequireDefault(__nccwpck_require__(25122)); +"use strict"; -var _index136 = _interopRequireDefault(__nccwpck_require__(34641)); -var _index137 = _interopRequireDefault(__nccwpck_require__(32373)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isSaturday; -var _index138 = _interopRequireDefault(__nccwpck_require__(60856)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index139 = _interopRequireDefault(__nccwpck_require__(74350)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index140 = _interopRequireDefault(__nccwpck_require__(97185)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index141 = _interopRequireDefault(__nccwpck_require__(13014)); +/** + * @name isSaturday + * @category Weekday Helpers + * @summary Is the given date Saturday? + * + * @description + * Is the given date Saturday? + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is Saturday + * @throws {TypeError} 1 argument required + * + * @example + * // Is 27 September 2014 Saturday? + * const result = isSaturday(new Date(2014, 8, 27)) + * //=> true + */ +function isSaturday(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate).getDay() === 6; +} -var _index142 = _interopRequireDefault(__nccwpck_require__(88235)); +module.exports = exports.default; -var _index143 = _interopRequireDefault(__nccwpck_require__(59920)); +/***/ }), -var _index144 = _interopRequireDefault(__nccwpck_require__(29218)); +/***/ 6544: +/***/ ((module, exports, __nccwpck_require__) => { -var _index145 = _interopRequireDefault(__nccwpck_require__(40403)); +"use strict"; -var _index146 = _interopRequireDefault(__nccwpck_require__(14419)); -var _index147 = _interopRequireDefault(__nccwpck_require__(9583)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isSunday; -var _index148 = _interopRequireDefault(__nccwpck_require__(94864)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index149 = _interopRequireDefault(__nccwpck_require__(17692)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index150 = _interopRequireDefault(__nccwpck_require__(20217)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index151 = _interopRequireDefault(__nccwpck_require__(43346)); +/** + * @name isSunday + * @category Weekday Helpers + * @summary Is the given date Sunday? + * + * @description + * Is the given date Sunday? + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is Sunday + * @throws {TypeError} 1 argument required + * + * @example + * // Is 21 September 2014 Sunday? + * const result = isSunday(new Date(2014, 8, 21)) + * //=> true + */ +function isSunday(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate).getDay() === 0; +} -var _index152 = _interopRequireDefault(__nccwpck_require__(98635)); +module.exports = exports.default; -var _index153 = _interopRequireDefault(__nccwpck_require__(20666)); +/***/ }), -var _index154 = _interopRequireDefault(__nccwpck_require__(79771)); +/***/ 48897: +/***/ ((module, exports, __nccwpck_require__) => { -var _index155 = _interopRequireDefault(__nccwpck_require__(24018)); +"use strict"; -var _index156 = _interopRequireDefault(__nccwpck_require__(35815)); -var _index157 = _interopRequireDefault(__nccwpck_require__(96133)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isThisHour; -var _index158 = _interopRequireDefault(__nccwpck_require__(89571)); +var _index = _interopRequireDefault(__nccwpck_require__(88687)); -var _index159 = _interopRequireDefault(__nccwpck_require__(5419)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index160 = _interopRequireDefault(__nccwpck_require__(42294)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index161 = _interopRequireDefault(__nccwpck_require__(45310)); +/** + * @name isThisHour + * @category Hour Helpers + * @summary Is the given date in the same hour as the current date? + * @pure false + * + * @description + * Is the given date in the same hour as the current date? + * + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `Date.now()` internally hence impure and can't be safely curried. + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is in this hour + * @throws {TypeError} 1 argument required + * + * @example + * // If now is 25 September 2014 18:30:15.500, + * // is 25 September 2014 18:00:00 in this hour? + * const result = isThisHour(new Date(2014, 8, 25, 18)) + * //=> true + */ +function isThisHour(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(Date.now(), dirtyDate); +} -var _index162 = _interopRequireDefault(__nccwpck_require__(52516)); +module.exports = exports.default; -var _index163 = _interopRequireDefault(__nccwpck_require__(71886)); +/***/ }), -var _index164 = _interopRequireDefault(__nccwpck_require__(48192)); +/***/ 11887: +/***/ ((module, exports, __nccwpck_require__) => { -var _index165 = _interopRequireDefault(__nccwpck_require__(91142)); +"use strict"; -var _index166 = _interopRequireDefault(__nccwpck_require__(73757)); -var _index167 = _interopRequireDefault(__nccwpck_require__(46771)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isThisISOWeek; -var _index168 = _interopRequireDefault(__nccwpck_require__(61491)); +var _index = _interopRequireDefault(__nccwpck_require__(49846)); -var _index169 = _interopRequireDefault(__nccwpck_require__(25947)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index170 = _interopRequireDefault(__nccwpck_require__(363)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index171 = _interopRequireDefault(__nccwpck_require__(17266)); +/** + * @name isThisISOWeek + * @category ISO Week Helpers + * @summary Is the given date in the same ISO week as the current date? + * @pure false + * + * @description + * Is the given date in the same ISO week as the current date? + * + * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date + * + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `Date.now()` internally hence impure and can't be safely curried. + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is in this ISO week + * @throws {TypeError} 1 argument required + * + * @example + * // If today is 25 September 2014, is 22 September 2014 in this ISO week? + * const result = isThisISOWeek(new Date(2014, 8, 22)) + * //=> true + */ +function isThisISOWeek(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate, Date.now()); +} -var _index172 = _interopRequireDefault(__nccwpck_require__(9457)); +module.exports = exports.default; -var _index173 = _interopRequireDefault(__nccwpck_require__(7894)); +/***/ }), -var _index174 = _interopRequireDefault(__nccwpck_require__(70029)); +/***/ 62182: +/***/ ((module, exports, __nccwpck_require__) => { -var _index175 = _interopRequireDefault(__nccwpck_require__(71287)); +"use strict"; -var _index176 = _interopRequireDefault(__nccwpck_require__(33390)); -var _index177 = _interopRequireDefault(__nccwpck_require__(28159)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isThisMinute; -var _index178 = _interopRequireDefault(__nccwpck_require__(68756)); +var _index = _interopRequireDefault(__nccwpck_require__(76570)); -var _index179 = _interopRequireDefault(__nccwpck_require__(9558)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index180 = _interopRequireDefault(__nccwpck_require__(48386)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index181 = _interopRequireDefault(__nccwpck_require__(94834)); +/** + * @name isThisMinute + * @category Minute Helpers + * @summary Is the given date in the same minute as the current date? + * @pure false + * + * @description + * Is the given date in the same minute as the current date? + * + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `Date.now()` internally hence impure and can't be safely curried. + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is in this minute + * @throws {TypeError} 1 argument required + * + * @example + * // If now is 25 September 2014 18:30:15.500, + * // is 25 September 2014 18:30:00 in this minute? + * const result = isThisMinute(new Date(2014, 8, 25, 18, 30)) + * //=> true + */ +function isThisMinute(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(Date.now(), dirtyDate); +} -var _index182 = _interopRequireDefault(__nccwpck_require__(60264)); +module.exports = exports.default; -var _index183 = _interopRequireDefault(__nccwpck_require__(70019)); +/***/ }), -var _index184 = _interopRequireDefault(__nccwpck_require__(3294)); +/***/ 88738: +/***/ ((module, exports, __nccwpck_require__) => { -var _index185 = _interopRequireDefault(__nccwpck_require__(48630)); +"use strict"; -var _index186 = _interopRequireDefault(__nccwpck_require__(78995)); -var _index187 = _interopRequireDefault(__nccwpck_require__(40883)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isThisMonth; -var _index188 = _interopRequireDefault(__nccwpck_require__(75515)); +var _index = _interopRequireDefault(__nccwpck_require__(32603)); -var _index189 = _interopRequireDefault(__nccwpck_require__(60594)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index190 = _interopRequireDefault(__nccwpck_require__(26779)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index191 = _interopRequireDefault(__nccwpck_require__(78438)); +/** + * @name isThisMonth + * @category Month Helpers + * @summary Is the given date in the same month as the current date? + * @pure false + * + * @description + * Is the given date in the same month as the current date? + * + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `Date.now()` internally hence impure and can't be safely curried. + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is in this month + * @throws {TypeError} 1 argument required + * + * @example + * // If today is 25 September 2014, is 15 September 2014 in this month? + * const result = isThisMonth(new Date(2014, 8, 15)) + * //=> true + */ +function isThisMonth(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(Date.now(), dirtyDate); +} -var _index192 = _interopRequireDefault(__nccwpck_require__(32031)); +module.exports = exports.default; -var _index193 = _interopRequireDefault(__nccwpck_require__(68760)); +/***/ }), -var _index194 = _interopRequireDefault(__nccwpck_require__(89540)); +/***/ 89872: +/***/ ((module, exports, __nccwpck_require__) => { -var _index195 = _interopRequireDefault(__nccwpck_require__(34002)); +"use strict"; -var _index196 = _interopRequireDefault(__nccwpck_require__(30054)); -var _index197 = _interopRequireDefault(__nccwpck_require__(96355)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isThisQuarter; -var _index198 = _interopRequireDefault(__nccwpck_require__(23705)); +var _index = _interopRequireDefault(__nccwpck_require__(16063)); -var _index199 = _interopRequireDefault(__nccwpck_require__(33035)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index200 = _interopRequireDefault(__nccwpck_require__(50822)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index201 = _interopRequireDefault(__nccwpck_require__(59105)); +/** + * @name isThisQuarter + * @category Quarter Helpers + * @summary Is the given date in the same quarter as the current date? + * @pure false + * + * @description + * Is the given date in the same quarter as the current date? + * + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `Date.now()` internally hence impure and can't be safely curried. + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is in this quarter + * @throws {TypeError} 1 argument required + * + * @example + * // If today is 25 September 2014, is 2 July 2014 in this quarter? + * const result = isThisQuarter(new Date(2014, 6, 2)) + * //=> true + */ +function isThisQuarter(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(Date.now(), dirtyDate); +} -var _index202 = _interopRequireDefault(__nccwpck_require__(49207)); +module.exports = exports.default; -var _index203 = _interopRequireDefault(__nccwpck_require__(80847)); +/***/ }), -var _index204 = _interopRequireDefault(__nccwpck_require__(10621)); +/***/ 30671: +/***/ ((module, exports, __nccwpck_require__) => { -var _index205 = _interopRequireDefault(__nccwpck_require__(61346)); +"use strict"; -var _index206 = _interopRequireDefault(__nccwpck_require__(22664)); -var _index207 = _interopRequireDefault(__nccwpck_require__(43438)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isThisSecond; -var _index208 = _interopRequireDefault(__nccwpck_require__(6212)); +var _index = _interopRequireDefault(__nccwpck_require__(969)); -var _index209 = _interopRequireDefault(__nccwpck_require__(61868)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index210 = _interopRequireDefault(__nccwpck_require__(52025)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index211 = _interopRequireDefault(__nccwpck_require__(46277)); +/** + * @name isThisSecond + * @category Second Helpers + * @summary Is the given date in the same second as the current date? + * @pure false + * + * @description + * Is the given date in the same second as the current date? + * + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `Date.now()` internally hence impure and can't be safely curried. + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is in this second + * @throws {TypeError} 1 argument required + * + * @example + * // If now is 25 September 2014 18:30:15.500, + * // is 25 September 2014 18:30:15.000 in this second? + * const result = isThisSecond(new Date(2014, 8, 25, 18, 30, 15)) + * //=> true + */ +function isThisSecond(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(Date.now(), dirtyDate); +} -var _index212 = _interopRequireDefault(__nccwpck_require__(56307)); +module.exports = exports.default; -var _index213 = _interopRequireDefault(__nccwpck_require__(60776)); +/***/ }), -var _index214 = _interopRequireDefault(__nccwpck_require__(48567)); +/***/ 2376: +/***/ ((module, exports, __nccwpck_require__) => { -var _index215 = _interopRequireDefault(__nccwpck_require__(97182)); +"use strict"; -var _index216 = _interopRequireDefault(__nccwpck_require__(92932)); -var _index217 = _interopRequireDefault(__nccwpck_require__(86738)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isThisWeek; -var _index218 = _interopRequireDefault(__nccwpck_require__(35516)); +var _index = _interopRequireDefault(__nccwpck_require__(30876)); -var _index219 = _interopRequireDefault(__nccwpck_require__(12442)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index220 = _interopRequireDefault(__nccwpck_require__(29813)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index221 = _interopRequireDefault(__nccwpck_require__(18014)); +/** + * @name isThisWeek + * @category Week Helpers + * @summary Is the given date in the same week as the current date? + * @pure false + * + * @description + * Is the given date in the same week as the current date? + * + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `Date.now()` internally hence impure and can't be safely curried. + * + * @param {Date|Number} date - the date to check + * @param {Object} [options] - the object with options + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @returns {Boolean} the date is in this week + * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * + * @example + * // If today is 25 September 2014, is 21 September 2014 in this week? + * const result = isThisWeek(new Date(2014, 8, 21)) + * //=> true + * + * @example + * // If today is 25 September 2014 and week starts with Monday + * // is 21 September 2014 in this week? + * const result = isThisWeek(new Date(2014, 8, 21), { weekStartsOn: 1 }) + * //=> false + */ +function isThisWeek(dirtyDate, options) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate, Date.now(), options); +} -var _index222 = _interopRequireDefault(__nccwpck_require__(88225)); +module.exports = exports.default; -var _index223 = _interopRequireDefault(__nccwpck_require__(81672)); +/***/ }), -var _index224 = _interopRequireDefault(__nccwpck_require__(63875)); +/***/ 88807: +/***/ ((module, exports, __nccwpck_require__) => { -var _index225 = _interopRequireDefault(__nccwpck_require__(71952)); +"use strict"; -var _index226 = _interopRequireDefault(__nccwpck_require__(50970)); -var _index227 = _interopRequireDefault(__nccwpck_require__(22481)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isThisYear; -var _index228 = _interopRequireDefault(__nccwpck_require__(33925)); +var _index = _interopRequireDefault(__nccwpck_require__(1050)); -var _index229 = _interopRequireDefault(__nccwpck_require__(97923)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index230 = _interopRequireDefault(__nccwpck_require__(67535)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index231 = _interopRequireDefault(__nccwpck_require__(6752)); +/** + * @name isThisYear + * @category Year Helpers + * @summary Is the given date in the same year as the current date? + * @pure false + * + * @description + * Is the given date in the same year as the current date? + * + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `Date.now()` internally hence impure and can't be safely curried. + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is in this year + * @throws {TypeError} 1 argument required + * + * @example + * // If today is 25 September 2014, is 2 July 2014 in this year? + * const result = isThisYear(new Date(2014, 6, 2)) + * //=> true + */ +function isThisYear(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate, Date.now()); +} -var _index232 = _interopRequireDefault(__nccwpck_require__(23139)); +module.exports = exports.default; -var _index233 = _interopRequireDefault(__nccwpck_require__(40138)); +/***/ }), -var _index234 = _interopRequireDefault(__nccwpck_require__(45504)); +/***/ 1815: +/***/ ((module, exports, __nccwpck_require__) => { -var _index235 = _interopRequireDefault(__nccwpck_require__(80843)); +"use strict"; -var _index236 = _interopRequireDefault(__nccwpck_require__(26477)); -var _index237 = _interopRequireDefault(__nccwpck_require__(56812)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isThursday; -var _index238 = _interopRequireDefault(__nccwpck_require__(34616)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index239 = _interopRequireDefault(__nccwpck_require__(97384)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index240 = __nccwpck_require__(25756); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -Object.keys(_index240).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _index240[key]; - } - }); -}); +/** + * @name isThursday + * @category Weekday Helpers + * @summary Is the given date Thursday? + * + * @description + * Is the given date Thursday? + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is Thursday + * @throws {TypeError} 1 argument required + * + * @example + * // Is 25 September 2014 Thursday? + * const result = isThursday(new Date(2014, 8, 25)) + * //=> true + */ +function isThursday(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate).getDay() === 4; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +module.exports = exports.default; /***/ }), -/***/ 32079: +/***/ 8566: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -65217,90 +61538,94 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = intervalToDuration; +exports["default"] = isToday; + +var _index = _interopRequireDefault(__nccwpck_require__(17150)); -var _index = _interopRequireDefault(__nccwpck_require__(29818)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name isToday + * @category Day Helpers + * @summary Is the given date today? + * @pure false + * + * @description + * Is the given date today? + * + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `Date.now()` internally hence impure and can't be safely curried. + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is today + * @throws {TypeError} 1 argument required + * + * @example + * // If today is 6 October 2014, is 6 October 14:00:00 today? + * const result = isToday(new Date(2014, 9, 6, 14, 0)) + * //=> true + */ +function isToday(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate, Date.now()); +} -var _index2 = _interopRequireDefault(__nccwpck_require__(96211)); +module.exports = exports.default; -var _index3 = _interopRequireDefault(__nccwpck_require__(16311)); +/***/ }), -var _index4 = _interopRequireDefault(__nccwpck_require__(88740)); +/***/ 60450: +/***/ ((module, exports, __nccwpck_require__) => { -var _index5 = _interopRequireDefault(__nccwpck_require__(63842)); +"use strict"; -var _index6 = _interopRequireDefault(__nccwpck_require__(12713)); -var _index7 = _interopRequireDefault(__nccwpck_require__(89448)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = isTomorrow; -var _index8 = _interopRequireDefault(__nccwpck_require__(13959)); +var _index = _interopRequireDefault(__nccwpck_require__(53426)); -var _index9 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index2 = _interopRequireDefault(__nccwpck_require__(17150)); -var _index10 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name intervalToDuration - * @category Common Helpers - * @summary Convert interval to duration + * @name isTomorrow + * @category Day Helpers + * @summary Is the given date tomorrow? + * @pure false * * @description - * Convert a interval object to a duration object. + * Is the given date tomorrow? * - * @param {Interval} interval - the interval to convert to duration + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `Date.now()` internally hence impure and can't be safely curried. * - * @returns {Duration} The duration Object - * @throws {TypeError} Requires 2 arguments - * @throws {RangeError} `start` must not be Invalid Date - * @throws {RangeError} `end` must not be Invalid Date + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is tomorrow + * @throws {TypeError} 1 argument required * * @example - * // Get the duration between January 15, 1929 and April 4, 1968. - * intervalToDuration({ - * start: new Date(1929, 0, 15, 12, 0, 0), - * end: new Date(1968, 3, 4, 19, 5, 0) - * }) - * // => { years: 39, months: 2, days: 20, hours: 7, minutes: 5, seconds: 0 } - */ -function intervalToDuration(interval) { - (0, _index10.default)(1, arguments); - var start = (0, _index9.default)(interval.start); - var end = (0, _index9.default)(interval.end); - if (isNaN(start.getTime())) throw new RangeError('Start Date is invalid'); - if (isNaN(end.getTime())) throw new RangeError('End Date is invalid'); - var duration = {}; - duration.years = Math.abs((0, _index8.default)(end, start)); - var sign = (0, _index.default)(end, start); - var remainingMonths = (0, _index2.default)(start, { - years: sign * duration.years - }); - duration.months = Math.abs((0, _index6.default)(end, remainingMonths)); - var remainingDays = (0, _index2.default)(remainingMonths, { - months: sign * duration.months - }); - duration.days = Math.abs((0, _index3.default)(end, remainingDays)); - var remainingHours = (0, _index2.default)(remainingDays, { - days: sign * duration.days - }); - duration.hours = Math.abs((0, _index4.default)(end, remainingHours)); - var remainingMinutes = (0, _index2.default)(remainingHours, { - hours: sign * duration.hours - }); - duration.minutes = Math.abs((0, _index5.default)(end, remainingMinutes)); - var remainingSeconds = (0, _index2.default)(remainingMinutes, { - minutes: sign * duration.minutes - }); - duration.seconds = Math.abs((0, _index7.default)(end, remainingSeconds)); - return duration; + * // If today is 6 October 2014, is 7 October 14:00:00 tomorrow? + * const result = isTomorrow(new Date(2014, 9, 7, 14, 0)) + * //=> true + */ +function isTomorrow(dirtyDate) { + (0, _index3.default)(1, arguments); + return (0, _index2.default)(dirtyDate, (0, _index.default)(Date.now(), 1)); } module.exports = exports.default; /***/ }), -/***/ 51982: +/***/ 67611: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -65309,106 +61634,41 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = intlFormat; +exports["default"] = isTuesday; + +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name intlFormat - * @category Common Helpers - * @summary Format the date with Intl.DateTimeFormat (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat). + * @name isTuesday + * @category Weekday Helpers + * @summary Is the given date Tuesday? * * @description - * Return the formatted date string in the given format. - * The method uses [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) inside. - * formatOptions are the same as [`Intl.DateTimeFormat` options](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat#using_options) - * - * > ⚠️ Please note that before Node version 13.0.0, only the locale data for en-US is available by default. - * - * @param {Date|Number} argument - the original date. - * @param {Object} [formatOptions] - an object with options. - * @param {'lookup'|'best fit'} [formatOptions.localeMatcher='best fit'] - locale selection algorithm. - * @param {'narrow'|'short'|'long'} [formatOptions.weekday] - representation the days of the week. - * @param {'narrow'|'short'|'long'} [formatOptions.era] - representation of eras. - * @param {'numeric'|'2-digit'} [formatOptions.year] - representation of years. - * @param {'numeric'|'2-digit'|'narrow'|'short'|'long'} [formatOptions.month='numeric'] - representation of month. - * @param {'numeric'|'2-digit'} [formatOptions.day='numeric'] - representation of day. - * @param {'numeric'|'2-digit'} [formatOptions.hour='numeric'] - representation of hours. - * @param {'numeric'|'2-digit'} [formatOptions.minute] - representation of minutes. - * @param {'numeric'|'2-digit'} [formatOptions.second] - representation of seconds. - * @param {'short'|'long'} [formatOptions.timeZoneName] - representation of names of time zones. - * @param {'basic'|'best fit'} [formatOptions.formatMatcher='best fit'] - format selection algorithm. - * @param {Boolean} [formatOptions.hour12] - determines whether to use 12-hour time format. - * @param {String} [formatOptions.timeZone] - the time zone to use. - * @param {Object} [localeOptions] - an object with locale. - * @param {String|String[]} [localeOptions.locale] - the locale code - * @returns {String} the formatted date string. - * @throws {TypeError} 1 argument required. - * @throws {RangeError} `date` must not be Invalid Date - * - * @example - * // Represent 10 October 2019 in German. - * // Convert the date with format's options and locale's options. - * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456), { - * weekday: 'long', - * year: 'numeric', - * month: 'long', - * day: 'numeric', - * }, { - * locale: 'de-DE', - * }) - * //=> Freitag, 4. Oktober 2019 - * - * @example - * // Represent 10 October 2019. - * // Convert the date with format's options. - * const result = intlFormat.default(new Date(2019, 9, 4, 12, 30, 13, 456), { - * year: 'numeric', - * month: 'numeric', - * day: 'numeric', - * hour: 'numeric', - * }) - * //=> 10/4/2019, 12 PM + * Is the given date Tuesday? * - * @example - * // Represent 10 October 2019 in Korean. - * // Convert the date with locale's options. - * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456), { - * locale: 'ko-KR', - * }) - * //=> 2019. 10. 4. + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is Tuesday + * @throws {TypeError} 1 argument required * * @example - * // Represent 10 October 2019 in middle-endian format: - * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456)) - * //=> 10/4/2019 + * // Is 23 September 2014 Tuesday? + * const result = isTuesday(new Date(2014, 8, 23)) + * //=> true */ -function intlFormat(date, formatOrLocale, localeOptions) { - var _localeOptions; - - (0, _index.default)(1, arguments); - var formatOptions; - - if (isFormatOptions(formatOrLocale)) { - formatOptions = formatOrLocale; - } else { - localeOptions = formatOrLocale; - } - - return new Intl.DateTimeFormat((_localeOptions = localeOptions) === null || _localeOptions === void 0 ? void 0 : _localeOptions.locale, formatOptions).format(date); -} - -function isFormatOptions(opts) { - return opts !== undefined && !('locale' in opts); +function isTuesday(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate).getDay() === 2; } module.exports = exports.default; /***/ }), -/***/ 73858: +/***/ 60435: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -65417,210 +61677,63 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = intlFormatDistance; - -var _index = __nccwpck_require__(25756); - -var _index2 = _interopRequireDefault(__nccwpck_require__(3086)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(95536)); - -var _index4 = _interopRequireDefault(__nccwpck_require__(22342)); - -var _index5 = _interopRequireDefault(__nccwpck_require__(8620)); - -var _index6 = _interopRequireDefault(__nccwpck_require__(45237)); - -var _index7 = _interopRequireDefault(__nccwpck_require__(88740)); - -var _index8 = _interopRequireDefault(__nccwpck_require__(63842)); +exports["default"] = isValid; -var _index9 = _interopRequireDefault(__nccwpck_require__(89448)); +var _index = _interopRequireDefault(__nccwpck_require__(19410)); -var _index10 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index11 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name intlFormatDistance + * @name isValid * @category Common Helpers - * @summary Formats distance between two dates in a human-readable format - * @description - * The function calculates the difference between two dates and formats it as a human-readable string. - * - * The function will pick the most appropriate unit depending on the distance between dates. For example, if the distance is a few hours, it might return `x hours`. If the distance is a few months, it might return `x months`. - * - * You can also specify a unit to force using it regardless of the distance to get a result like `123456 hours`. - * - * See the table below for the unit picking logic: - * - * | Distance between dates | Result (past) | Result (future) | - * | ---------------------- | -------------- | --------------- | - * | 0 seconds | now | now | - * | 1-59 seconds | X seconds ago | in X seconds | - * | 1-59 minutes | X minutes ago | in X minutes | - * | 1-23 hours | X hours ago | in X hours | - * | 1 day | yesterday | tomorrow | - * | 2-6 days | X days ago | in X days | - * | 7 days | last week | next week | - * | 8 days-1 month | X weeks ago | in X weeks | - * | 1 month | last month | next month | - * | 2-3 months | X months ago | in X months | - * | 1 quarter | last quarter | next quarter | - * | 2-3 quarters | X quarters ago | in X quarters | - * | 1 year | last year | next year | - * | 2+ years | X years ago | in X years | - * - * @param {Date|Number} date - the date - * @param {Date|Number} baseDate - the date to compare with. - * @param {Object} [options] - an object with options. - * @param {String} [options.unit] - formats the distance with the given unit ('year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'). - * @param {String|String[]} [options.locale] - the locale to use. - * @param {String} [options.localeMatcher='best fit'] - the locale matching algorithm to use. Other value: 'lookup'. - * See MDN for details [Locale identification and negotiation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation) - * @param {String} [options.numeric='auto'] - the output message format. The values are 'auto' (e.g. `yesterday`), 'always'(e.g. `1 day ago`). - * @param {String} [options.style='long'] - the length of the result. The values are: 'long' (e.g. `1 month`), 'short' (e.g. 'in 1 mo.'), 'narrow' (e.g. 'in 1 mo.'). - * The narrow one could be similar to the short one for some locales. - * @returns {String} the distance in words according to language-sensitive relative time formatting. - * @throws {TypeError} 2 arguments required - * @throws {RangeError} `date` must not be Invalid Date - * @throws {RangeError} `baseDate` must not be Invalid Date - * @throws {RangeError} `options.unit` must not be invalid Unit - * @throws {RangeError} `options.locale` must not be invalid locale - * @throws {RangeError} `options.localeMatcher` must not be invalid localeMatcher - * @throws {RangeError} `options.numeric` must not be invalid numeric - * @throws {RangeError} `options.style` must not be invalid style + * @summary Is the given date valid? * - * @example - * // What is the distance between the dates when the fist date is after the second? - * intlFormatDistance( - * new Date(1986, 3, 4, 11, 30, 0), - * new Date(1986, 3, 4, 10, 30, 0) - * ) - * //=> 'in 1 hour' + * @description + * Returns false if argument is Invalid Date and true otherwise. + * Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate} + * Invalid Date is a Date, whose time value is NaN. * - * // What is the distance between the dates when the fist date is before the second? - * intlFormatDistance( - * new Date(1986, 3, 4, 10, 30, 0), - * new Date(1986, 3, 4, 11, 30, 0) - * ) - * //=> '1 hour ago' + * Time value of Date: http://es5.github.io/#x15.9.1.1 * - * @example - * // Use the unit option to force the function to output the result in quarters. Without setting it, the example would return "next year" - * intlFormatDistance( - * new Date(1987, 6, 4, 10, 30, 0), - * new Date(1986, 3, 4, 10, 30, 0), - * { unit: 'quarter' } - * ) - * //=> 'in 5 quarters' + * @param {*} date - the date to check + * @returns {Boolean} the date is valid + * @throws {TypeError} 1 argument required * * @example - * // Use the locale option to get the result in Spanish. Without setting it, the example would return "in 1 hour". - * intlFormatDistance( - * new Date(1986, 3, 4, 11, 30, 0), - * new Date(1986, 3, 4, 10, 30, 0), - * { locale: 'es' } - * ) - * //=> 'dentro de 1 hora' + * // For the valid date: + * const result = isValid(new Date(2014, 1, 31)) + * //=> true * * @example - * // Use the numeric option to force the function to use numeric values. Without setting it, the example would return "tomorrow". - * intlFormatDistance( - * new Date(1986, 3, 5, 11, 30, 0), - * new Date(1986, 3, 4, 11, 30, 0), - * { numeric: 'always' } - * ) - * //=> 'in 1 day' + * // For the value, convertable into a date: + * const result = isValid(1393804800000) + * //=> true * * @example - * // Use the style option to force the function to use short values. Without setting it, the example would return "in 2 years". - * intlFormatDistance( - * new Date(1988, 3, 4, 11, 30, 0), - * new Date(1986, 3, 4, 11, 30, 0), - * { style: 'short' } - * ) - * //=> 'in 2 yr' + * // For the invalid date: + * const result = isValid(new Date('')) + * //=> false */ -function intlFormatDistance(date, baseDate, options) { - (0, _index11.default)(2, arguments); - var value = 0; - var unit; - var dateLeft = (0, _index10.default)(date); - var dateRight = (0, _index10.default)(baseDate); - - if (!(options !== null && options !== void 0 && options.unit)) { - // Get the unit based on diffInSeconds calculations if no unit is specified - var diffInSeconds = (0, _index9.default)(dateLeft, dateRight); // The smallest unit - - if (Math.abs(diffInSeconds) < _index.secondsInMinute) { - value = (0, _index9.default)(dateLeft, dateRight); - unit = 'second'; - } else if (Math.abs(diffInSeconds) < _index.secondsInHour) { - value = (0, _index8.default)(dateLeft, dateRight); - unit = 'minute'; - } else if (Math.abs(diffInSeconds) < _index.secondsInDay && Math.abs((0, _index2.default)(dateLeft, dateRight)) < 1) { - value = (0, _index7.default)(dateLeft, dateRight); - unit = 'hour'; - } else if (Math.abs(diffInSeconds) < _index.secondsInWeek && (value = (0, _index2.default)(dateLeft, dateRight)) && Math.abs(value) < 7) { - unit = 'day'; - } else if (Math.abs(diffInSeconds) < _index.secondsInMonth) { - value = (0, _index5.default)(dateLeft, dateRight); - unit = 'week'; - } else if (Math.abs(diffInSeconds) < _index.secondsInQuarter) { - value = (0, _index3.default)(dateLeft, dateRight); - unit = 'month'; - } else if (Math.abs(diffInSeconds) < _index.secondsInYear) { - if ((0, _index4.default)(dateLeft, dateRight) < 4) { - // To filter out cases that are less than a year but match 4 quarters - value = (0, _index4.default)(dateLeft, dateRight); - unit = 'quarter'; - } else { - value = (0, _index6.default)(dateLeft, dateRight); - unit = 'year'; - } - } else { - value = (0, _index6.default)(dateLeft, dateRight); - unit = 'year'; - } - } else { - // Get the value if unit is specified - unit = options === null || options === void 0 ? void 0 : options.unit; +function isValid(dirtyDate) { + (0, _index3.default)(1, arguments); - if (unit === 'second') { - value = (0, _index9.default)(dateLeft, dateRight); - } else if (unit === 'minute') { - value = (0, _index8.default)(dateLeft, dateRight); - } else if (unit === 'hour') { - value = (0, _index7.default)(dateLeft, dateRight); - } else if (unit === 'day') { - value = (0, _index2.default)(dateLeft, dateRight); - } else if (unit === 'week') { - value = (0, _index5.default)(dateLeft, dateRight); - } else if (unit === 'month') { - value = (0, _index3.default)(dateLeft, dateRight); - } else if (unit === 'quarter') { - value = (0, _index4.default)(dateLeft, dateRight); - } else if (unit === 'year') { - value = (0, _index6.default)(dateLeft, dateRight); - } + if (!(0, _index.default)(dirtyDate) && typeof dirtyDate !== 'number') { + return false; } - var rtf = new Intl.RelativeTimeFormat(options === null || options === void 0 ? void 0 : options.locale, { - localeMatcher: options === null || options === void 0 ? void 0 : options.localeMatcher, - numeric: (options === null || options === void 0 ? void 0 : options.numeric) || 'auto', - style: options === null || options === void 0 ? void 0 : options.style - }); - return rtf.format(value, unit); + var date = (0, _index2.default)(dirtyDate); + return !isNaN(Number(date)); } module.exports = exports.default; /***/ }), -/***/ 2755: +/***/ 99651: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -65629,44 +61742,41 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isAfter; +exports["default"] = isWednesday; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isAfter - * @category Common Helpers - * @summary Is the first date after the second one? + * @name isWednesday + * @category Weekday Helpers + * @summary Is the given date Wednesday? * * @description - * Is the first date after the second one? + * Is the given date Wednesday? * - * @param {Date|Number} date - the date that should be after the other one to return true - * @param {Date|Number} dateToCompare - the date to compare with - * @returns {Boolean} the first date is after the second date - * @throws {TypeError} 2 arguments required + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is Wednesday + * @throws {TypeError} 1 argument required * * @example - * // Is 10 July 1989 after 11 February 1987? - * const result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11)) + * // Is 24 September 2014 Wednesday? + * const result = isWednesday(new Date(2014, 8, 24)) * //=> true */ -function isAfter(dirtyDate, dirtyDateToCompare) { - (0, _index2.default)(2, arguments); - var date = (0, _index.default)(dirtyDate); - var dateToCompare = (0, _index.default)(dirtyDateToCompare); - return date.getTime() > dateToCompare.getTime(); +function isWednesday(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate).getDay() === 3; } module.exports = exports.default; /***/ }), -/***/ 89369: +/***/ 62564: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -65675,44 +61785,43 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isBefore; +exports["default"] = isWeekend; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isBefore - * @category Common Helpers - * @summary Is the first date before the second one? + * @name isWeekend + * @category Weekday Helpers + * @summary Does the given date fall on a weekend? * * @description - * Is the first date before the second one? + * Does the given date fall on a weekend? * - * @param {Date|Number} date - the date that should be before the other one to return true - * @param {Date|Number} dateToCompare - the date to compare with - * @returns {Boolean} the first date is before the second date - * @throws {TypeError} 2 arguments required + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date falls on a weekend + * @throws {TypeError} 1 argument required * * @example - * // Is 10 July 1989 before 11 February 1987? - * const result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11)) - * //=> false + * // Does 5 October 2014 fall on a weekend? + * const result = isWeekend(new Date(2014, 9, 5)) + * //=> true */ -function isBefore(dirtyDate, dirtyDateToCompare) { - (0, _index2.default)(2, arguments); +function isWeekend(dirtyDate) { + (0, _index2.default)(1, arguments); var date = (0, _index.default)(dirtyDate); - var dateToCompare = (0, _index.default)(dirtyDateToCompare); - return date.getTime() < dateToCompare.getTime(); + var day = date.getDay(); + return day === 0 || day === 6; } module.exports = exports.default; /***/ }), -/***/ 6801: +/***/ 11557: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -65721,54 +61830,71 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isDate; +exports["default"] = isWithinInterval; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isDate - * @category Common Helpers - * @summary Is the given value a date? + * @name isWithinInterval + * @category Interval Helpers + * @summary Is the given date within the interval? * * @description - * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes. + * Is the given date within the interval? (Including start and end.) * - * @param {*} value - the value to check - * @returns {boolean} true if the given value is a date - * @throws {TypeError} 1 arguments required + * @param {Date|Number} date - the date to check + * @param {Interval} interval - the interval to check + * @returns {Boolean} the date is within the interval + * @throws {TypeError} 2 arguments required + * @throws {RangeError} The start of an interval cannot be after its end + * @throws {RangeError} Date in interval cannot be `Invalid Date` * * @example - * // For a valid date: - * const result = isDate(new Date()) + * // For the date within the interval: + * isWithinInterval(new Date(2014, 0, 3), { + * start: new Date(2014, 0, 1), + * end: new Date(2014, 0, 7) + * }) * //=> true * * @example - * // For an invalid date: - * const result = isDate(new Date(NaN)) - * //=> true + * // For the date outside of the interval: + * isWithinInterval(new Date(2014, 0, 10), { + * start: new Date(2014, 0, 1), + * end: new Date(2014, 0, 7) + * }) + * //=> false * * @example - * // For some value: - * const result = isDate('2014-02-31') - * //=> false + * // For date equal to interval start: + * isWithinInterval(date, { start, end: date }) // => true * * @example - * // For an object: - * const result = isDate({}) - * //=> false + * // For date equal to interval end: + * isWithinInterval(date, { start: date, end }) // => true */ -function isDate(value) { - (0, _index.default)(1, arguments); - return value instanceof Date || typeof value === 'object' && Object.prototype.toString.call(value) === '[object Date]'; +function isWithinInterval(dirtyDate, interval) { + (0, _index2.default)(2, arguments); + var time = (0, _index.default)(dirtyDate).getTime(); + var startTime = (0, _index.default)(interval.start).getTime(); + var endTime = (0, _index.default)(interval.end).getTime(); // Throw an exception if start date is after end date or if any date is `Invalid Date` + + if (!(startTime <= endTime)) { + throw new RangeError('Invalid interval'); + } + + return time >= startTime && time <= endTime; } module.exports = exports.default; /***/ }), -/***/ 44669: +/***/ 59054: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -65777,48 +61903,48 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isEqual; +exports["default"] = isYesterday; + +var _index = _interopRequireDefault(__nccwpck_require__(17150)); -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index2 = _interopRequireDefault(__nccwpck_require__(80289)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isEqual - * @category Common Helpers - * @summary Are the given dates equal? + * @name isYesterday + * @category Day Helpers + * @summary Is the given date yesterday? + * @pure false * * @description - * Are the given dates equal? + * Is the given date yesterday? * - * @param {Date|Number} dateLeft - the first date to compare - * @param {Date|Number} dateRight - the second date to compare - * @returns {Boolean} the dates are equal - * @throws {TypeError} 2 arguments required + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `Date.now()` internally hence impure and can't be safely curried. + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is yesterday + * @throws {TypeError} 1 argument required * * @example - * // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal? - * const result = isEqual( - * new Date(2014, 6, 2, 6, 30, 45, 0), - * new Date(2014, 6, 2, 6, 30, 45, 500) - * ) - * //=> false + * // If today is 6 October 2014, is 5 October 14:00:00 yesterday? + * const result = isYesterday(new Date(2014, 9, 5, 14, 0)) + * //=> true */ -function isEqual(dirtyLeftDate, dirtyRightDate) { - (0, _index2.default)(2, arguments); - var dateLeft = (0, _index.default)(dirtyLeftDate); - var dateRight = (0, _index.default)(dirtyRightDate); - return dateLeft.getTime() === dateRight.getTime(); +function isYesterday(dirtyDate) { + (0, _index3.default)(1, arguments); + return (0, _index.default)(dirtyDate, (0, _index2.default)(Date.now(), 1)); } module.exports = exports.default; /***/ }), -/***/ 97352: -/***/ ((module, exports) => { +/***/ 61311: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -65826,46 +61952,94 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isExists; +exports["default"] = lastDayOfDecade; + +var _index = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isExists - * @category Common Helpers - * @summary Is the given date exists? + * @name lastDayOfDecade + * @category Decade Helpers + * @summary Return the last day of a decade for the given date. + * + * @description + * Return the last day of a decade for the given date. + * + * @param {Date|Number} date - the original date + * @returns {Date} the last day of a decade + * @throws {TypeError} 1 argument required + * + * @example + * // The last day of a decade for 21 December 2012 21:12:00: + * const result = lastDayOfDecade(new Date(2012, 11, 21, 21, 12, 00)) + * //=> Wed Dec 31 2019 00:00:00 + */ +function lastDayOfDecade(dirtyDate) { + (0, _index2.default)(1, arguments); + var date = (0, _index.default)(dirtyDate); + var year = date.getFullYear(); + var decade = 9 + Math.floor(year / 10) * 10; + date.setFullYear(decade + 1, 0, 0); + date.setHours(0, 0, 0, 0); + return date; +} + +module.exports = exports.default; + +/***/ }), + +/***/ 15619: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = lastDayOfISOWeek; + +var _index = _interopRequireDefault(__nccwpck_require__(39013)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name lastDayOfISOWeek + * @category ISO Week Helpers + * @summary Return the last day of an ISO week for the given date. * * @description - * Checks if the given arguments convert to an existing date. + * Return the last day of an ISO week for the given date. + * The result will be in the local timezone. * - * @param {Number} year of the date to check - * @param {Number} month of the date to check - * @param {Number} day of the date to check - * @returns {Boolean} the date exists - * @throws {TypeError} 3 arguments required + * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date * - * @example - * // For the valid date: - * const result = isExists(2018, 0, 31) - * //=> true + * @param {Date|Number} date - the original date + * @returns {Date} the last day of an ISO week + * @throws {TypeError} 1 argument required * * @example - * // For the invalid date: - * const result = isExists(2018, 1, 31) - * //=> false + * // The last day of an ISO week for 2 September 2014 11:55:00: + * const result = lastDayOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Sun Sep 07 2014 00:00:00 */ -function isExists(year, month, day) { - if (arguments.length < 3) { - throw new TypeError('3 argument required, but only ' + arguments.length + ' present'); - } - - var date = new Date(year, month, day); - return date.getFullYear() === year && date.getMonth() === month && date.getDate() === day; +function lastDayOfISOWeek(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate, { + weekStartsOn: 1 + }); } module.exports = exports.default; /***/ }), -/***/ 15387: +/***/ 73205: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -65874,41 +62048,53 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isFirstDayOfMonth; +exports["default"] = lastDayOfISOWeekYear; + +var _index = _interopRequireDefault(__nccwpck_require__(57869)); -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index2 = _interopRequireDefault(__nccwpck_require__(25093)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isFirstDayOfMonth - * @category Month Helpers - * @summary Is the given date the first day of a month? + * @name lastDayOfISOWeekYear + * @category ISO Week-Numbering Year Helpers + * @summary Return the last day of an ISO week-numbering year for the given date. * * @description - * Is the given date the first day of a month? + * Return the last day of an ISO week-numbering year, + * which always starts 3 days before the year's first Thursday. + * The result will be in the local timezone. * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is the first day of a month + * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date + * + * @param {Date|Number} date - the original date + * @returns {Date} the end of an ISO week-numbering year * @throws {TypeError} 1 argument required * * @example - * // Is 1 September 2014 the first day of a month? - * const result = isFirstDayOfMonth(new Date(2014, 8, 1)) - * //=> true + * // The last day of an ISO week-numbering year for 2 July 2005: + * const result = lastDayOfISOWeekYear(new Date(2005, 6, 2)) + * //=> Sun Jan 01 2006 00:00:00 */ -function isFirstDayOfMonth(dirtyDate) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate).getDate() === 1; +function lastDayOfISOWeekYear(dirtyDate) { + (0, _index3.default)(1, arguments); + var year = (0, _index.default)(dirtyDate); + var fourthOfJanuary = new Date(0); + fourthOfJanuary.setFullYear(year + 1, 0, 4); + fourthOfJanuary.setHours(0, 0, 0, 0); + var date = (0, _index2.default)(fourthOfJanuary); + date.setDate(date.getDate() - 1); + return date; } module.exports = exports.default; /***/ }), -/***/ 81758: +/***/ 62700: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -65917,41 +62103,46 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isFriday; +exports["default"] = lastDayOfMonth; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isFriday - * @category Weekday Helpers - * @summary Is the given date Friday? + * @name lastDayOfMonth + * @category Month Helpers + * @summary Return the last day of a month for the given date. * * @description - * Is the given date Friday? + * Return the last day of a month for the given date. + * The result will be in the local timezone. * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is Friday + * @param {Date|Number} date - the original date + * @returns {Date} the last day of a month * @throws {TypeError} 1 argument required * * @example - * // Is 26 September 2014 Friday? - * const result = isFriday(new Date(2014, 8, 26)) - * //=> true + * // The last day of a month for 2 September 2014 11:55:00: + * const result = lastDayOfMonth(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Tue Sep 30 2014 00:00:00 */ -function isFriday(dirtyDate) { +function lastDayOfMonth(dirtyDate) { (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate).getDay() === 5; + var date = (0, _index.default)(dirtyDate); + var month = date.getMonth(); + date.setFullYear(date.getFullYear(), month + 1, 0); + date.setHours(0, 0, 0, 0); + return date; } module.exports = exports.default; /***/ }), -/***/ 36803: +/***/ 26886: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -65960,45 +62151,50 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isFuture; +exports["default"] = lastDayOfQuarter; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isFuture - * @category Common Helpers - * @summary Is the given date in the future? - * @pure false + * @name lastDayOfQuarter + * @category Quarter Helpers + * @summary Return the last day of a year quarter for the given date. * * @description - * Is the given date in the future? - * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `Date.now()` internally hence impure and can't be safely curried. + * Return the last day of a year quarter for the given date. + * The result will be in the local timezone. * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is in the future + * @param {Date|Number} date - the original date + * @param {Object} [options] - an object with options. + * @param {0|1|2} [options.additionalDigits=2] - passed to `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate} + * @returns {Date} the last day of a quarter * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2 * * @example - * // If today is 6 October 2014, is 31 December 2014 in the future? - * const result = isFuture(new Date(2014, 11, 31)) - * //=> true + * // The last day of a quarter for 2 September 2014 11:55:00: + * const result = lastDayOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Tue Sep 30 2014 00:00:00 */ -function isFuture(dirtyDate) { +function lastDayOfQuarter(dirtyDate) { (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate).getTime() > Date.now(); + var date = (0, _index.default)(dirtyDate); + var currentMonth = date.getMonth(); + var month = currentMonth - currentMonth % 3 + 3; + date.setMonth(month, 0); + date.setHours(0, 0, 0, 0); + return date; } module.exports = exports.default; /***/ }), -/***/ 48506: +/***/ 39013: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -66007,46 +62203,69 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isLastDayOfMonth; +exports["default"] = lastDayOfWeek; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(8569)); +var _index2 = _interopRequireDefault(__nccwpck_require__(35279)); -var _index3 = _interopRequireDefault(__nccwpck_require__(12621)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index4 = __nccwpck_require__(79115); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isLastDayOfMonth - * @category Month Helpers - * @summary Is the given date the last day of a month? + * @name lastDayOfWeek + * @category Week Helpers + * @summary Return the last day of a week for the given date. * * @description - * Is the given date the last day of a month? + * Return the last day of a week for the given date. + * The result will be in the local timezone. * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is the last day of a month + * @param {Date|Number} date - the original date + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @returns {Date} the last day of a week * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 * * @example - * // Is 28 February 2014 the last day of a month? - * const result = isLastDayOfMonth(new Date(2014, 1, 28)) - * //=> true + * // The last day of a week for 2 September 2014 11:55:00: + * const result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Sat Sep 06 2014 00:00:00 + * + * @example + * // If the week starts on Monday, the last day of the week for 2 September 2014 11:55:00: + * const result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 }) + * //=> Sun Sep 07 2014 00:00:00 */ -function isLastDayOfMonth(dirtyDate) { - (0, _index4.default)(1, arguments); +function lastDayOfWeek(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + + (0, _index3.default)(1, arguments); + var defaultOptions = (0, _index4.getDefaultOptions)(); + var weekStartsOn = (0, _index2.default)((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6'); + } + var date = (0, _index.default)(dirtyDate); - return (0, _index2.default)(date).getTime() === (0, _index3.default)(date).getTime(); + var day = date.getDay(); + var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); + date.setHours(0, 0, 0, 0); + date.setDate(date.getDate() + diff); + return date; } module.exports = exports.default; /***/ }), -/***/ 90074: +/***/ 87819: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -66055,43 +62274,46 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isLeapYear; +exports["default"] = lastDayOfYear; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isLeapYear + * @name lastDayOfYear * @category Year Helpers - * @summary Is the given date in the leap year? + * @summary Return the last day of a year for the given date. * * @description - * Is the given date in the leap year? + * Return the last day of a year for the given date. + * The result will be in the local timezone. * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is in the leap year + * @param {Date|Number} date - the original date + * @returns {Date} the last day of a year * @throws {TypeError} 1 argument required * * @example - * // Is 1 September 2012 in the leap year? - * const result = isLeapYear(new Date(2012, 8, 1)) - * //=> true + * // The last day of a year for 2 September 2014 11:55:00: + * const result = lastDayOfYear(new Date(2014, 8, 2, 11, 55, 00)) + * //=> Wed Dec 31 2014 00:00:00 */ -function isLeapYear(dirtyDate) { +function lastDayOfYear(dirtyDate) { (0, _index2.default)(1, arguments); var date = (0, _index.default)(dirtyDate); var year = date.getFullYear(); - return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0; + date.setFullYear(year + 1, 0, 0); + date.setHours(0, 0, 0, 0); + return date; } module.exports = exports.default; /***/ }), -/***/ 90525: +/***/ 28655: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -66100,319 +62322,150 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isMatch; +exports["default"] = lightFormat; + +var _index = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(31634)); -var _index = _interopRequireDefault(__nccwpck_require__(71287)); +var _index3 = _interopRequireDefault(__nccwpck_require__(8316)); -var _index2 = _interopRequireDefault(__nccwpck_require__(59920)); +var _index4 = _interopRequireDefault(__nccwpck_require__(60435)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index5 = _interopRequireDefault(__nccwpck_require__(88874)); + +var _index6 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +// This RegExp consists of three parts separated by `|`: +// - (\w)\1* matches any sequences of the same letter +// - '' matches two quote characters in a row +// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('), +// except a single quote symbol, which ends the sequence. +// Two quote characters do not end the sequence. +// If there is no matching single quote +// then the sequence will continue until the end of the string. +// - . matches any single character unmatched by previous parts of the RegExps +var formattingTokensRegExp = /(\w)\1*|''|'(''|[^'])+('|$)|./g; +var escapedStringRegExp = /^'([^]*?)'?$/; +var doubleQuoteRegExp = /''/g; +var unescapedLatinCharacterRegExp = /[a-zA-Z]/; /** - * @name isMatch + * @name lightFormat * @category Common Helpers - * @summary validates the date string against given formats + * @summary Format the date. * * @description - * Return the true if given date is string correct against the given format else - * will return false. + * Return the formatted date string in the given format. Unlike `format`, + * `lightFormat` doesn't use locales and outputs date using the most popular tokens. * - * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries. + * > ⚠️ Please note that the `lightFormat` tokens differ from Moment.js and other libraries. * > See: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md * - * The characters in the format string wrapped between two single quotes characters (') are escaped. + * The characters wrapped between two single quotes characters (') are escaped. * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. * - * Format of the format string is based on Unicode Technical Standard #35: + * Format of the string is based on Unicode Technical Standard #35: * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table - * with a few additions (see note 5 below the table). - * - * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited - * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception: - * - * ```javascript - * isMatch('23 AM', 'HH a') - * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time - * ``` - * - * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true - * - * Accepted format string patterns: - * | Unit |Prior| Pattern | Result examples | Notes | - * |---------------------------------|-----|---------|-----------------------------------|-------| - * | Era | 140 | G..GGG | AD, BC | | - * | | | GGGG | Anno Domini, Before Christ | 2 | - * | | | GGGGG | A, B | | - * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 | - * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 | - * | | | yy | 44, 01, 00, 17 | 4 | - * | | | yyy | 044, 001, 123, 999 | 4 | - * | | | yyyy | 0044, 0001, 1900, 2017 | 4 | - * | | | yyyyy | ... | 2,4 | - * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 | - * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 | - * | | | YY | 44, 01, 00, 17 | 4,6 | - * | | | YYY | 044, 001, 123, 999 | 4 | - * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 | - * | | | YYYYY | ... | 2,4 | - * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 | - * | | | RR | -43, 01, 00, 17 | 4,5 | - * | | | RRR | -043, 001, 123, 999, -999 | 4,5 | - * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 | - * | | | RRRRR | ... | 2,4,5 | - * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 | - * | | | uu | -43, 01, 99, -99 | 4 | - * | | | uuu | -043, 001, 123, 999, -999 | 4 | - * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 | - * | | | uuuuu | ... | 2,4 | - * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | | - * | | | Qo | 1st, 2nd, 3rd, 4th | 5 | - * | | | QQ | 01, 02, 03, 04 | | - * | | | QQQ | Q1, Q2, Q3, Q4 | | - * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 | - * | | | QQQQQ | 1, 2, 3, 4 | 4 | - * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | | - * | | | qo | 1st, 2nd, 3rd, 4th | 5 | - * | | | qq | 01, 02, 03, 04 | | - * | | | qqq | Q1, Q2, Q3, Q4 | | - * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 | - * | | | qqqqq | 1, 2, 3, 4 | 3 | - * | Month (formatting) | 110 | M | 1, 2, ..., 12 | | - * | | | Mo | 1st, 2nd, ..., 12th | 5 | - * | | | MM | 01, 02, ..., 12 | | - * | | | MMM | Jan, Feb, ..., Dec | | - * | | | MMMM | January, February, ..., December | 2 | - * | | | MMMMM | J, F, ..., D | | - * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | | - * | | | Lo | 1st, 2nd, ..., 12th | 5 | - * | | | LL | 01, 02, ..., 12 | | - * | | | LLL | Jan, Feb, ..., Dec | | - * | | | LLLL | January, February, ..., December | 2 | - * | | | LLLLL | J, F, ..., D | | - * | Local week of year | 100 | w | 1, 2, ..., 53 | | - * | | | wo | 1st, 2nd, ..., 53th | 5 | - * | | | ww | 01, 02, ..., 53 | | - * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 | - * | | | Io | 1st, 2nd, ..., 53th | 5 | - * | | | II | 01, 02, ..., 53 | 5 | - * | Day of month | 90 | d | 1, 2, ..., 31 | | - * | | | do | 1st, 2nd, ..., 31st | 5 | - * | | | dd | 01, 02, ..., 31 | | - * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 | - * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 | - * | | | DD | 01, 02, ..., 365, 366 | 7 | - * | | | DDD | 001, 002, ..., 365, 366 | | - * | | | DDDD | ... | 2 | - * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Su | | - * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 | - * | | | EEEEE | M, T, W, T, F, S, S | | - * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | | - * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 | - * | | | io | 1st, 2nd, ..., 7th | 5 | - * | | | ii | 01, 02, ..., 07 | 5 | - * | | | iii | Mon, Tue, Wed, ..., Su | 5 | - * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 | - * | | | iiiii | M, T, W, T, F, S, S | 5 | - * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 | - * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | | - * | | | eo | 2nd, 3rd, ..., 1st | 5 | - * | | | ee | 02, 03, ..., 01 | | - * | | | eee | Mon, Tue, Wed, ..., Su | | - * | | | eeee | Monday, Tuesday, ..., Sunday | 2 | - * | | | eeeee | M, T, W, T, F, S, S | | - * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | | - * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | | - * | | | co | 2nd, 3rd, ..., 1st | 5 | - * | | | cc | 02, 03, ..., 01 | | - * | | | ccc | Mon, Tue, Wed, ..., Su | | - * | | | cccc | Monday, Tuesday, ..., Sunday | 2 | - * | | | ccccc | M, T, W, T, F, S, S | | - * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | | - * | AM, PM | 80 | a..aaa | AM, PM | | - * | | | aaaa | a.m., p.m. | 2 | - * | | | aaaaa | a, p | | - * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | | - * | | | bbbb | a.m., p.m., noon, midnight | 2 | - * | | | bbbbb | a, p, n, mi | | - * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | | - * | | | BBBB | at night, in the morning, ... | 2 | - * | | | BBBBB | at night, in the morning, ... | | - * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | | - * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 | - * | | | hh | 01, 02, ..., 11, 12 | | - * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | | - * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 | - * | | | HH | 00, 01, 02, ..., 23 | | - * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | | - * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 | - * | | | KK | 01, 02, ..., 11, 00 | | - * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | | - * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 | - * | | | kk | 24, 01, 02, ..., 23 | | - * | Minute | 60 | m | 0, 1, ..., 59 | | - * | | | mo | 0th, 1st, ..., 59th | 5 | - * | | | mm | 00, 01, ..., 59 | | - * | Second | 50 | s | 0, 1, ..., 59 | | - * | | | so | 0th, 1st, ..., 59th | 5 | - * | | | ss | 00, 01, ..., 59 | | - * | Seconds timestamp | 40 | t | 512969520 | | - * | | | tt | ... | 2 | - * | Fraction of second | 30 | S | 0, 1, ..., 9 | | - * | | | SS | 00, 01, ..., 99 | | - * | | | SSS | 000, 001, ..., 999 | | - * | | | SSSS | ... | 2 | - * | Milliseconds timestamp | 20 | T | 512969520900 | | - * | | | TT | ... | 2 | - * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | | - * | | | XX | -0800, +0530, Z | | - * | | | XXX | -08:00, +05:30, Z | | - * | | | XXXX | -0800, +0530, Z, +123456 | 2 | - * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | | - * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | | - * | | | xx | -0800, +0530, +0000 | | - * | | | xxx | -08:00, +05:30, +00:00 | 2 | - * | | | xxxx | -0800, +0530, +0000, +123456 | | - * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | | - * | Long localized date | NA | P | 05/29/1453 | 5,8 | - * | | | PP | May 29, 1453 | | - * | | | PPP | May 29th, 1453 | | - * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 | - * | Long localized time | NA | p | 12:00 AM | 5,8 | - * | | | pp | 12:00:00 AM | | - * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | | - * | | | PPpp | May 29, 1453, 12:00:00 AM | | - * | | | PPPpp | May 29th, 1453 at ... | | - * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 | - * Notes: - * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale - * are the same as "stand-alone" units, but are different in some languages. - * "Formatting" units are declined according to the rules of the language - * in the context of a date. "Stand-alone" units are always nominative singular. - * In `format` function, they will produce different result: - * - * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'` - * - * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'` - * - * `isMatch` will try to match both formatting and stand-alone units interchangably. - * - * 2. Any sequence of the identical letters is a pattern, unless it is escaped by - * the single quote characters (see below). - * If the sequence is longer than listed in table: - * - for numerical units (`yyyyyyyy`) `isMatch` will try to match a number - * as wide as the sequence - * - for text units (`MMMMMMMM`) `isMatch` will try to match the widest variation of the unit. - * These variations are marked with "2" in the last column of the table. - * - * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales. - * These tokens represent the shortest form of the quarter. - * - * 4. The main difference between `y` and `u` patterns are B.C. years: - * - * | Year | `y` | `u` | - * |------|-----|-----| - * | AC 1 | 1 | 1 | - * | BC 1 | 1 | 0 | - * | BC 2 | 2 | -1 | - * - * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`: - * - * `isMatch('50', 'yy') //=> true` - * - * `isMatch('75', 'yy') //=> true` - * - * while `uu` will use the year as is: - * - * `isMatch('50', 'uu') //=> true` - * - * `isMatch('75', 'uu') //=> true` - * - * The same difference is true for local and ISO week-numbering years (`Y` and `R`), - * except local week-numbering years are dependent on `options.weekStartsOn` - * and `options.firstWeekContainsDate` (compare [setISOWeekYear]{@link https://date-fns.org/docs/setISOWeekYear} - * and [setWeekYear]{@link https://date-fns.org/docs/setWeekYear}). - * - * 5. These patterns are not in the Unicode Technical Standard #35: - * - `i`: ISO day of week - * - `I`: ISO week of year - * - `R`: ISO week-numbering year - * - `o`: ordinal number modifier - * - `P`: long localized date - * - `p`: long localized time - * - * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years. - * You should enable `options.useAdditionalWeekYearTokens` to use them. See: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * - * 7. `D` and `DD` tokens represent days of the year but they are ofthen confused with days of the month. - * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * - * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based - * on the given locale. - * - * using `en-US` locale: `P` => `MM/dd/yyyy` - * using `en-US` locale: `p` => `hh:mm a` - * using `pt-BR` locale: `P` => `dd/MM/yyyy` - * using `pt-BR` locale: `p` => `HH:mm` - * - * Values will be checked in the descending order of its unit's priority. - * Units of an equal priority overwrite each other in the order of appearance. - * - * If no values of higher priority are matched (e.g. when matching string 'January 1st' without a year), - * the values will be taken from today's using `new Date()` date which works as a context of parsing. - * - * The result may vary by locale. * - * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned. - * - * - * - * @param {String} dateString - the date string to verify - * @param {String} formatString - the string of tokens - * @param {Object} [options] - an object with options. - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year - * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`; - * see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`; - * see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @returns {Boolean} + * Accepted patterns: + * | Unit | Pattern | Result examples | + * |---------------------------------|---------|-----------------------------------| + * | AM, PM | a..aaa | AM, PM | + * | | aaaa | a.m., p.m. | + * | | aaaaa | a, p | + * | Calendar year | y | 44, 1, 1900, 2017 | + * | | yy | 44, 01, 00, 17 | + * | | yyy | 044, 001, 000, 017 | + * | | yyyy | 0044, 0001, 1900, 2017 | + * | Month (formatting) | M | 1, 2, ..., 12 | + * | | MM | 01, 02, ..., 12 | + * | Day of month | d | 1, 2, ..., 31 | + * | | dd | 01, 02, ..., 31 | + * | Hour [1-12] | h | 1, 2, ..., 11, 12 | + * | | hh | 01, 02, ..., 11, 12 | + * | Hour [0-23] | H | 0, 1, 2, ..., 23 | + * | | HH | 00, 01, 02, ..., 23 | + * | Minute | m | 0, 1, ..., 59 | + * | | mm | 00, 01, ..., 59 | + * | Second | s | 0, 1, ..., 59 | + * | | ss | 00, 01, ..., 59 | + * | Fraction of second | S | 0, 1, ..., 9 | + * | | SS | 00, 01, ..., 99 | + * | | SSS | 000, 001, ..., 999 | + * | | SSSS | ... | + * + * @param {Date|Number} date - the original date + * @param {String} format - the string of tokens + * @returns {String} the formatted date string * @throws {TypeError} 2 arguments required - * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 - * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 - * @throws {RangeError} `options.locale` must contain `match` property - * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years; see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @throws {RangeError} use `yy` instead of `YY` for formatting years; see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @throws {RangeError} use `d` instead of `D` for formatting days of the month; see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month; see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md * @throws {RangeError} format string contains an unescaped latin alphabet character * * @example - * // Match 11 February 2014 from middle-endian format: - * const result = isMatch('02/11/2014', 'MM/dd/yyyy') - * //=> true - * - * @example - * // Match 28th of February in Esperanto locale in the context of 2010 year: - * import eo from 'date-fns/locale/eo' - * const result = isMatch('28-a de februaro', "do 'de' MMMM", { - * locale: eo - * }) - * //=> true + * const result = lightFormat(new Date(2014, 1, 11), 'yyyy-MM-dd') + * //=> '2014-02-11' */ -function isMatch(dateString, formatString, options) { - (0, _index3.default)(2, arguments); - return (0, _index2.default)((0, _index.default)(dateString, formatString, new Date(), options)); + +function lightFormat(dirtyDate, formatStr) { + (0, _index6.default)(2, arguments); + var originalDate = (0, _index.default)(dirtyDate); + + if (!(0, _index4.default)(originalDate)) { + throw new RangeError('Invalid time value'); + } // Convert the date in system timezone to the same date in UTC+00:00 timezone. + // This ensures that when UTC functions will be implemented, locales will be compatible with them. + // See an issue about UTC functions: /~https://github.com/date-fns/date-fns/issues/376 + + + var timezoneOffset = (0, _index3.default)(originalDate); + var utcDate = (0, _index5.default)(originalDate, timezoneOffset); + var tokens = formatStr.match(formattingTokensRegExp); // The only case when formattingTokensRegExp doesn't match the string is when it's empty + + if (!tokens) return ''; + var result = tokens.map(function (substring) { + // Replace two single quote characters with one single quote character + if (substring === "''") { + return "'"; + } + + var firstCharacter = substring[0]; + + if (firstCharacter === "'") { + return cleanEscapedString(substring); + } + + var formatter = _index2.default[firstCharacter]; + + if (formatter) { + return formatter(utcDate, substring); + } + + if (firstCharacter.match(unescapedLatinCharacterRegExp)) { + throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`'); + } + + return substring; + }).join(''); + return result; +} + +function cleanEscapedString(input) { + var matches = input.match(escapedStringRegExp); + + if (!matches) { + return input; + } + + return matches[1].replace(doubleQuoteRegExp, "'"); } module.exports = exports.default; /***/ }), -/***/ 16030: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 18222: +/***/ ((module, exports) => { "use strict"; @@ -66420,42 +62473,24 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isMonday; - -var _index = _interopRequireDefault(__nccwpck_require__(26477)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +exports["default"] = buildFormatLongFn; -/** - * @name isMonday - * @category Weekday Helpers - * @summary Is the given date Monday? - * - * @description - * Is the given date Monday? - * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is Monday - * @throws {TypeError} 1 argument required - * - * @example - * // Is 22 September 2014 Monday? - * const result = isMonday(new Date(2014, 8, 22)) - * //=> true - */ -function isMonday(date) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(date).getDay() === 1; +function buildFormatLongFn(args) { + return function () { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + // TODO: Remove String() + var width = options.width ? String(options.width) : args.defaultWidth; + var format = args.formats[width] || args.formats[args.defaultWidth]; + return format; + }; } module.exports = exports.default; /***/ }), -/***/ 89543: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 86731: +/***/ ((module, exports) => { "use strict"; @@ -66463,46 +62498,37 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isPast; +exports["default"] = buildLocalizeFn; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +function buildLocalizeFn(args) { + return function (dirtyIndex, options) { + var context = options !== null && options !== void 0 && options.context ? String(options.context) : 'standalone'; + var valuesArray; -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + if (context === 'formatting' && args.formattingValues) { + var defaultWidth = args.defaultFormattingWidth || args.defaultWidth; + var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth; + valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth]; + } else { + var _defaultWidth = args.defaultWidth; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth; -/** - * @name isPast - * @category Common Helpers - * @summary Is the given date in the past? - * @pure false - * - * @description - * Is the given date in the past? - * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `Date.now()` internally hence impure and can't be safely curried. - * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is in the past - * @throws {TypeError} 1 argument required - * - * @example - * // If today is 6 October 2014, is 2 July 2014 in the past? - * const result = isPast(new Date(2014, 6, 2)) - * //=> true - */ -function isPast(dirtyDate) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate).getTime() < Date.now(); + valuesArray = args.values[_width] || args.values[_defaultWidth]; + } + + var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex; // @ts-ignore: For some reason TypeScript just don't want to match it, no matter how hard we try. I challenge you to try to remove it! + + return valuesArray[index]; + }; } module.exports = exports.default; /***/ }), -/***/ 52154: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 24355: +/***/ ((module, exports) => { "use strict"; @@ -66510,55 +62536,63 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isSameDay; +exports["default"] = buildMatchFn; -var _index = _interopRequireDefault(__nccwpck_require__(61868)); +function buildMatchFn(args) { + return function (string) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var width = options.width; + var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth]; + var matchResult = string.match(matchPattern); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + if (!matchResult) { + return null; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var matchedString = matchResult[0]; + var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth]; + var key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function (pattern) { + return pattern.test(matchedString); + }) : findKey(parsePatterns, function (pattern) { + return pattern.test(matchedString); + }); + var value; + value = args.valueCallback ? args.valueCallback(key) : key; + value = options.valueCallback ? options.valueCallback(value) : value; + var rest = string.slice(matchedString.length); + return { + value: value, + rest: rest + }; + }; +} -/** - * @name isSameDay - * @category Day Helpers - * @summary Are the given dates in the same day (and year and month)? - * - * @description - * Are the given dates in the same day (and year and month)? - * - * @param {Date|Number} dateLeft - the first date to check - * @param {Date|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same day (and year and month) - * @throws {TypeError} 2 arguments required - * - * @example - * // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day? - * const result = isSameDay(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 18, 0)) - * //=> true - * - * @example - * // Are 4 September and 4 October in the same day? - * const result = isSameDay(new Date(2014, 8, 4), new Date(2014, 9, 4)) - * //=> false - * - * @example - * // Are 4 September, 2014 and 4 September, 2015 in the same day? - * const result = isSameDay(new Date(2014, 8, 4), new Date(2015, 8, 4)) - * //=> false - */ -function isSameDay(dirtyDateLeft, dirtyDateRight) { - (0, _index2.default)(2, arguments); - var dateLeftStartOfDay = (0, _index.default)(dirtyDateLeft); - var dateRightStartOfDay = (0, _index.default)(dirtyDateRight); - return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime(); +function findKey(object, predicate) { + for (var key in object) { + if (object.hasOwnProperty(key) && predicate(object[key])) { + return key; + } + } + + return undefined; +} + +function findIndex(array, predicate) { + for (var key = 0; key < array.length; key++) { + if (predicate(array[key])) { + return key; + } + } + + return undefined; } module.exports = exports.default; /***/ }), -/***/ 42489: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 972: +/***/ ((module, exports) => { "use strict"; @@ -66566,50 +62600,32 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isSameHour; - -var _index = _interopRequireDefault(__nccwpck_require__(46277)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +exports["default"] = buildMatchPatternFn; -/** - * @name isSameHour - * @category Hour Helpers - * @summary Are the given dates in the same hour (and same day)? - * - * @description - * Are the given dates in the same hour (and same day)? - * - * @param {Date|Number} dateLeft - the first date to check - * @param {Date|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same hour (and same day) - * @throws {TypeError} 2 arguments required - * - * @example - * // Are 4 September 2014 06:00:00 and 4 September 06:30:00 in the same hour? - * const result = isSameHour(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 6, 30)) - * //=> true - * - * @example - * // Are 4 September 2014 06:00:00 and 5 September 06:00:00 in the same hour? - * const result = isSameHour(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 5, 6, 0)) - * //=> false - */ -function isSameHour(dirtyDateLeft, dirtyDateRight) { - (0, _index2.default)(2, arguments); - var dateLeftStartOfHour = (0, _index.default)(dirtyDateLeft); - var dateRightStartOfHour = (0, _index.default)(dirtyDateRight); - return dateLeftStartOfHour.getTime() === dateRightStartOfHour.getTime(); +function buildMatchPatternFn(args) { + return function (string) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var matchResult = string.match(args.matchPattern); + if (!matchResult) return null; + var matchedString = matchResult[0]; + var parseResult = string.match(args.parsePattern); + if (!parseResult) return null; + var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0]; + value = options.valueCallback ? options.valueCallback(value) : value; + var rest = string.slice(matchedString.length); + return { + value: value, + rest: rest + }; + }; } module.exports = exports.default; /***/ }), -/***/ 89852: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 44465: +/***/ ((module, exports) => { "use strict"; @@ -66617,51 +62633,101 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isSameISOWeek; +exports["default"] = void 0; +var formatDistanceLocale = { + lessThanXSeconds: { + one: 'less than a second', + other: 'less than {{count}} seconds' + }, + xSeconds: { + one: '1 second', + other: '{{count}} seconds' + }, + halfAMinute: 'half a minute', + lessThanXMinutes: { + one: 'less than a minute', + other: 'less than {{count}} minutes' + }, + xMinutes: { + one: '1 minute', + other: '{{count}} minutes' + }, + aboutXHours: { + one: 'about 1 hour', + other: 'about {{count}} hours' + }, + xHours: { + one: '1 hour', + other: '{{count}} hours' + }, + xDays: { + one: '1 day', + other: '{{count}} days' + }, + aboutXWeeks: { + one: 'about 1 week', + other: 'about {{count}} weeks' + }, + xWeeks: { + one: '1 week', + other: '{{count}} weeks' + }, + aboutXMonths: { + one: 'about 1 month', + other: 'about {{count}} months' + }, + xMonths: { + one: '1 month', + other: '{{count}} months' + }, + aboutXYears: { + one: 'about 1 year', + other: 'about {{count}} years' + }, + xYears: { + one: '1 year', + other: '{{count}} years' + }, + overXYears: { + one: 'over 1 year', + other: 'over {{count}} years' + }, + almostXYears: { + one: 'almost 1 year', + other: 'almost {{count}} years' + } +}; -var _index = _interopRequireDefault(__nccwpck_require__(7013)); +var formatDistance = function (token, count, options) { + var result; + var tokenValue = formatDistanceLocale[token]; -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + if (typeof tokenValue === 'string') { + result = tokenValue; + } else if (count === 1) { + result = tokenValue.one; + } else { + result = tokenValue.other.replace('{{count}}', count.toString()); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (options !== null && options !== void 0 && options.addSuffix) { + if (options.comparison && options.comparison > 0) { + return 'in ' + result; + } else { + return result + ' ago'; + } + } -/** - * @name isSameISOWeek - * @category ISO Week Helpers - * @summary Are the given dates in the same ISO week (and year)? - * - * @description - * Are the given dates in the same ISO week (and year)? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|Number} dateLeft - the first date to check - * @param {Date|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same ISO week (and year) - * @throws {TypeError} 2 arguments required - * - * @example - * // Are 1 September 2014 and 7 September 2014 in the same ISO week? - * const result = isSameISOWeek(new Date(2014, 8, 1), new Date(2014, 8, 7)) - * //=> true - * - * @example - * // Are 1 September 2014 and 1 September 2015 in the same ISO week? - * const result = isSameISOWeek(new Date(2014, 8, 1), new Date(2015, 8, 1)) - * //=> false - */ -function isSameISOWeek(dirtyDateLeft, dirtyDateRight) { - (0, _index2.default)(2, arguments); - return (0, _index.default)(dirtyDateLeft, dirtyDateRight, { - weekStartsOn: 1 - }); -} + return result; +}; +var _default = formatDistance; +exports["default"] = _default; module.exports = exports.default; /***/ }), -/***/ 73944: +/***/ 39652: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -66670,46 +62736,80 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isSameISOWeekYear; - -var _index = _interopRequireDefault(__nccwpck_require__(60776)); +exports["default"] = void 0; -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(18222)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/** - * @name isSameISOWeekYear - * @category ISO Week-Numbering Year Helpers - * @summary Are the given dates in the same ISO week-numbering year? - * - * @description - * Are the given dates in the same ISO week-numbering year? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|Number} dateLeft - the first date to check - * @param {Date|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same ISO week-numbering year - * @throws {TypeError} 2 arguments required - * - * @example - * // Are 29 December 2003 and 2 January 2005 in the same ISO week-numbering year? - * const result = isSameISOWeekYear(new Date(2003, 11, 29), new Date(2005, 0, 2)) - * //=> true - */ -function isSameISOWeekYear(dirtyDateLeft, dirtyDateRight) { - (0, _index2.default)(2, arguments); - var dateLeftStartOfYear = (0, _index.default)(dirtyDateLeft); - var dateRightStartOfYear = (0, _index.default)(dirtyDateRight); - return dateLeftStartOfYear.getTime() === dateRightStartOfYear.getTime(); -} +var dateFormats = { + full: 'EEEE, MMMM do, y', + long: 'MMMM do, y', + medium: 'MMM d, y', + short: 'MM/dd/yyyy' +}; +var timeFormats = { + full: 'h:mm:ss a zzzz', + long: 'h:mm:ss a z', + medium: 'h:mm:ss a', + short: 'h:mm a' +}; +var dateTimeFormats = { + full: "{{date}} 'at' {{time}}", + long: "{{date}} 'at' {{time}}", + medium: '{{date}}, {{time}}', + short: '{{date}}, {{time}}' +}; +var formatLong = { + date: (0, _index.default)({ + formats: dateFormats, + defaultWidth: 'full' + }), + time: (0, _index.default)({ + formats: timeFormats, + defaultWidth: 'full' + }), + dateTime: (0, _index.default)({ + formats: dateTimeFormats, + defaultWidth: 'full' + }) +}; +var _default = formatLong; +exports["default"] = _default; +module.exports = exports.default; + +/***/ }), + +/***/ 91055: +/***/ ((module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var formatRelativeLocale = { + lastWeek: "'last' eeee 'at' p", + yesterday: "'yesterday at' p", + today: "'today at' p", + tomorrow: "'tomorrow at' p", + nextWeek: "eeee 'at' p", + other: 'P' +}; + +var formatRelative = function (token, _date, _baseDate, _options) { + return formatRelativeLocale[token]; +}; +var _default = formatRelative; +exports["default"] = _default; module.exports = exports.default; /***/ }), -/***/ 66: +/***/ 9285: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -66718,106 +62818,163 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isSameMinute; - -var _index = _interopRequireDefault(__nccwpck_require__(48567)); +exports["default"] = void 0; -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(86731)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/** - * @name isSameMinute - * @category Minute Helpers - * @summary Are the given dates in the same minute (and hour and day)? - * - * @description - * Are the given dates in the same minute (and hour and day)? - * - * @param {Date|Number} dateLeft - the first date to check - * @param {Date|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same minute (and hour and day) - * @throws {TypeError} 2 arguments required - * - * @example - * // Are 4 September 2014 06:30:00 and 4 September 2014 06:30:15 in the same minute? - * const result = isSameMinute( - * new Date(2014, 8, 4, 6, 30), - * new Date(2014, 8, 4, 6, 30, 15) - * ) - * //=> true - * - * @example - * // Are 4 September 2014 06:30:00 and 5 September 2014 06:30:00 in the same minute? - * const result = isSameMinute( - * new Date(2014, 8, 4, 6, 30), - * new Date(2014, 8, 5, 6, 30) - * ) - * //=> false - */ -function isSameMinute(dirtyDateLeft, dirtyDateRight) { - (0, _index2.default)(2, arguments); - var dateLeftStartOfMinute = (0, _index.default)(dirtyDateLeft); - var dateRightStartOfMinute = (0, _index.default)(dirtyDateRight); - return dateLeftStartOfMinute.getTime() === dateRightStartOfMinute.getTime(); -} - -module.exports = exports.default; - -/***/ }), - -/***/ 65421: -/***/ ((module, exports, __nccwpck_require__) => { +var eraValues = { + narrow: ['B', 'A'], + abbreviated: ['BC', 'AD'], + wide: ['Before Christ', 'Anno Domini'] +}; +var quarterValues = { + narrow: ['1', '2', '3', '4'], + abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'], + wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter'] +}; // Note: in English, the names of days of the week and months are capitalized. +// If you are making a new locale based on this one, check if the same is true for the language you're working on. +// Generally, formatted dates should look like they are in the middle of a sentence, +// e.g. in Spanish language the weekdays and months should be in the lowercase. -"use strict"; +var monthValues = { + narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], + abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + wide: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] +}; +var dayValues = { + narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'], + short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] +}; +var dayPeriodValues = { + narrow: { + am: 'a', + pm: 'p', + midnight: 'mi', + noon: 'n', + morning: 'morning', + afternoon: 'afternoon', + evening: 'evening', + night: 'night' + }, + abbreviated: { + am: 'AM', + pm: 'PM', + midnight: 'midnight', + noon: 'noon', + morning: 'morning', + afternoon: 'afternoon', + evening: 'evening', + night: 'night' + }, + wide: { + am: 'a.m.', + pm: 'p.m.', + midnight: 'midnight', + noon: 'noon', + morning: 'morning', + afternoon: 'afternoon', + evening: 'evening', + night: 'night' + } +}; +var formattingDayPeriodValues = { + narrow: { + am: 'a', + pm: 'p', + midnight: 'mi', + noon: 'n', + morning: 'in the morning', + afternoon: 'in the afternoon', + evening: 'in the evening', + night: 'at night' + }, + abbreviated: { + am: 'AM', + pm: 'PM', + midnight: 'midnight', + noon: 'noon', + morning: 'in the morning', + afternoon: 'in the afternoon', + evening: 'in the evening', + night: 'at night' + }, + wide: { + am: 'a.m.', + pm: 'p.m.', + midnight: 'midnight', + noon: 'noon', + morning: 'in the morning', + afternoon: 'in the afternoon', + evening: 'in the evening', + night: 'at night' + } +}; +var ordinalNumber = function (dirtyNumber, _options) { + var number = Number(dirtyNumber); // If ordinal numbers depend on context, for example, + // if they are different for different grammatical genders, + // use `options.unit`. + // + // `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear', + // 'day', 'hour', 'minute', 'second'. -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = isSameMonth; + var rem100 = number % 100; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); + if (rem100 > 20 || rem100 < 10) { + switch (rem100 % 10) { + case 1: + return number + 'st'; -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + case 2: + return number + 'nd'; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + case 3: + return number + 'rd'; + } + } -/** - * @name isSameMonth - * @category Month Helpers - * @summary Are the given dates in the same month (and year)? - * - * @description - * Are the given dates in the same month (and year)? - * - * @param {Date|Number} dateLeft - the first date to check - * @param {Date|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same month (and year) - * @throws {TypeError} 2 arguments required - * - * @example - * // Are 2 September 2014 and 25 September 2014 in the same month? - * const result = isSameMonth(new Date(2014, 8, 2), new Date(2014, 8, 25)) - * //=> true - * - * @example - * // Are 2 September 2014 and 25 September 2015 in the same month? - * const result = isSameMonth(new Date(2014, 8, 2), new Date(2015, 8, 25)) - * //=> false - */ -function isSameMonth(dirtyDateLeft, dirtyDateRight) { - (0, _index2.default)(2, arguments); - var dateLeft = (0, _index.default)(dirtyDateLeft); - var dateRight = (0, _index.default)(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear() && dateLeft.getMonth() === dateRight.getMonth(); -} + return number + 'th'; +}; +var localize = { + ordinalNumber: ordinalNumber, + era: (0, _index.default)({ + values: eraValues, + defaultWidth: 'wide' + }), + quarter: (0, _index.default)({ + values: quarterValues, + defaultWidth: 'wide', + argumentCallback: function (quarter) { + return quarter - 1; + } + }), + month: (0, _index.default)({ + values: monthValues, + defaultWidth: 'wide' + }), + day: (0, _index.default)({ + values: dayValues, + defaultWidth: 'wide' + }), + dayPeriod: (0, _index.default)({ + values: dayPeriodValues, + defaultWidth: 'wide', + formattingValues: formattingDayPeriodValues, + defaultFormattingWidth: 'wide' + }) +}; +var _default = localize; +exports["default"] = _default; module.exports = exports.default; /***/ }), -/***/ 40938: +/***/ 62121: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -66826,49 +62983,116 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isSameQuarter; +exports["default"] = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(92932)); +var _index = _interopRequireDefault(__nccwpck_require__(24355)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(972)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/** - * @name isSameQuarter - * @category Quarter Helpers - * @summary Are the given dates in the same quarter (and year)? - * - * @description - * Are the given dates in the same quarter (and year)? - * - * @param {Date|Number} dateLeft - the first date to check - * @param {Date|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same quarter (and year) - * @throws {TypeError} 2 arguments required - * - * @example - * // Are 1 January 2014 and 8 March 2014 in the same quarter? - * const result = isSameQuarter(new Date(2014, 0, 1), new Date(2014, 2, 8)) - * //=> true - * - * @example - * // Are 1 January 2014 and 1 January 2015 in the same quarter? - * const result = isSameQuarter(new Date(2014, 0, 1), new Date(2015, 0, 1)) - * //=> false - */ -function isSameQuarter(dirtyDateLeft, dirtyDateRight) { - (0, _index2.default)(2, arguments); - var dateLeftStartOfQuarter = (0, _index.default)(dirtyDateLeft); - var dateRightStartOfQuarter = (0, _index.default)(dirtyDateRight); - return dateLeftStartOfQuarter.getTime() === dateRightStartOfQuarter.getTime(); -} - +var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i; +var parseOrdinalNumberPattern = /\d+/i; +var matchEraPatterns = { + narrow: /^(b|a)/i, + abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i, + wide: /^(before christ|before common era|anno domini|common era)/i +}; +var parseEraPatterns = { + any: [/^b/i, /^(a|c)/i] +}; +var matchQuarterPatterns = { + narrow: /^[1234]/i, + abbreviated: /^q[1234]/i, + wide: /^[1234](th|st|nd|rd)? quarter/i +}; +var parseQuarterPatterns = { + any: [/1/i, /2/i, /3/i, /4/i] +}; +var matchMonthPatterns = { + narrow: /^[jfmasond]/i, + abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i, + wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i +}; +var parseMonthPatterns = { + narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i], + any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i] +}; +var matchDayPatterns = { + narrow: /^[smtwf]/i, + short: /^(su|mo|tu|we|th|fr|sa)/i, + abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i, + wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i +}; +var parseDayPatterns = { + narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i], + any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i] +}; +var matchDayPeriodPatterns = { + narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i, + any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i +}; +var parseDayPeriodPatterns = { + any: { + am: /^a/i, + pm: /^p/i, + midnight: /^mi/i, + noon: /^no/i, + morning: /morning/i, + afternoon: /afternoon/i, + evening: /evening/i, + night: /night/i + } +}; +var match = { + ordinalNumber: (0, _index2.default)({ + matchPattern: matchOrdinalNumberPattern, + parsePattern: parseOrdinalNumberPattern, + valueCallback: function (value) { + return parseInt(value, 10); + } + }), + era: (0, _index.default)({ + matchPatterns: matchEraPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseEraPatterns, + defaultParseWidth: 'any' + }), + quarter: (0, _index.default)({ + matchPatterns: matchQuarterPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseQuarterPatterns, + defaultParseWidth: 'any', + valueCallback: function (index) { + return index + 1; + } + }), + month: (0, _index.default)({ + matchPatterns: matchMonthPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseMonthPatterns, + defaultParseWidth: 'any' + }), + day: (0, _index.default)({ + matchPatterns: matchDayPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseDayPatterns, + defaultParseWidth: 'any' + }), + dayPeriod: (0, _index.default)({ + matchPatterns: matchDayPeriodPatterns, + defaultMatchWidth: 'any', + parsePatterns: parseDayPeriodPatterns, + defaultParseWidth: 'any' + }) +}; +var _default = match; +exports["default"] = _default; module.exports = exports.default; /***/ }), -/***/ 51988: +/***/ 77553: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -66877,63 +63101,50 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isSameSecond; +exports["default"] = void 0; + +var _index = _interopRequireDefault(__nccwpck_require__(44465)); -var _index = _interopRequireDefault(__nccwpck_require__(86738)); +var _index2 = _interopRequireDefault(__nccwpck_require__(39652)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(91055)); + +var _index4 = _interopRequireDefault(__nccwpck_require__(9285)); + +var _index5 = _interopRequireDefault(__nccwpck_require__(62121)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isSameSecond - * @category Second Helpers - * @summary Are the given dates in the same second (and hour and day)? - * - * @description - * Are the given dates in the same second (and hour and day)? - * - * @param {Date|Number} dateLeft - the first date to check - * @param {Date|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same second (and hour and day) - * @throws {TypeError} 2 arguments required - * - * @example - * // Are 4 September 2014 06:30:15.000 and 4 September 2014 06:30.15.500 in the same second? - * const result = isSameSecond( - * new Date(2014, 8, 4, 6, 30, 15), - * new Date(2014, 8, 4, 6, 30, 15, 500) - * ) - * //=> true - * - * @example - * // Are 4 September 2014 06:00:15.000 and 4 September 2014 06:01.15.000 in the same second? - * const result = isSameSecond( - * new Date(2014, 8, 4, 6, 0, 15), - * new Date(2014, 8, 4, 6, 1, 15) - * ) - * //=> false - * - * @example - * // Are 4 September 2014 06:00:15.000 and 5 September 2014 06:00.15.000 in the same second? - * const result = isSameSecond( - * new Date(2014, 8, 4, 6, 0, 15), - * new Date(2014, 8, 5, 6, 0, 15) - * ) - * //=> false + * @type {Locale} + * @category Locales + * @summary English locale (United States). + * @language English + * @iso-639-2 eng + * @author Sasha Koss [@kossnocorp]{@link /~https://github.com/kossnocorp} + * @author Lesha Koss [@leshakoss]{@link /~https://github.com/leshakoss} */ -function isSameSecond(dirtyDateLeft, dirtyDateRight) { - (0, _index2.default)(2, arguments); - var dateLeftStartOfSecond = (0, _index.default)(dirtyDateLeft); - var dateRightStartOfSecond = (0, _index.default)(dirtyDateRight); - return dateLeftStartOfSecond.getTime() === dateRightStartOfSecond.getTime(); -} - +var locale = { + code: 'en-US', + formatDistance: _index.default, + formatLong: _index2.default, + formatRelative: _index3.default, + localize: _index4.default, + match: _index5.default, + options: { + weekStartsOn: 0 + /* Sunday */ + , + firstWeekContainsDate: 1 + } +}; +var _default = locale; +exports["default"] = _default; module.exports = exports.default; /***/ }), -/***/ 7013: +/***/ 44065: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -66942,61 +63153,65 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isSameWeek; +exports["default"] = max; -var _index = _interopRequireDefault(__nccwpck_require__(29813)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isSameWeek - * @category Week Helpers - * @summary Are the given dates in the same week (and month and year)? + * @name max + * @category Common Helpers + * @summary Return the latest of the given dates. * * @description - * Are the given dates in the same week (and month and year)? - * - * @param {Date|Number} dateLeft - the first date to check - * @param {Date|Number} dateRight - the second date to check - * @param {Object} [options] - an object with options. - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Boolean} the dates are in the same week (and month and year) - * @throws {TypeError} 2 arguments required - * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 - * - * @example - * // Are 31 August 2014 and 4 September 2014 in the same week? - * const result = isSameWeek(new Date(2014, 7, 31), new Date(2014, 8, 4)) - * //=> true + * Return the latest of the given dates. * - * @example - * // If week starts with Monday, - * // are 31 August 2014 and 4 September 2014 in the same week? - * const result = isSameWeek(new Date(2014, 7, 31), new Date(2014, 8, 4), { - * weekStartsOn: 1 - * }) - * //=> false + * @param {Date[]|Number[]} datesArray - the dates to compare + * @returns {Date} the latest of the dates + * @throws {TypeError} 1 argument required * * @example - * // Are 1 January 2014 and 1 January 2015 in the same week? - * const result = isSameWeek(new Date(2014, 0, 1), new Date(2015, 0, 1)) - * //=> false + * // Which of these dates is the latest? + * const result = max([ + * new Date(1989, 6, 10), + * new Date(1987, 1, 11), + * new Date(1995, 6, 2), + * new Date(1990, 0, 1) + * ]) + * //=> Sun Jul 02 1995 00:00:00 */ -function isSameWeek(dirtyDateLeft, dirtyDateRight, options) { - (0, _index2.default)(2, arguments); - var dateLeftStartOfWeek = (0, _index.default)(dirtyDateLeft, options); - var dateRightStartOfWeek = (0, _index.default)(dirtyDateRight, options); - return dateLeftStartOfWeek.getTime() === dateRightStartOfWeek.getTime(); +function max(dirtyDatesArray) { + (0, _index2.default)(1, arguments); + var datesArray; // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method + + if (dirtyDatesArray && typeof dirtyDatesArray.forEach === 'function') { + datesArray = dirtyDatesArray; // If `dirtyDatesArray` is Array-like Object, convert to Array. + } else if (typeof dirtyDatesArray === 'object' && dirtyDatesArray !== null) { + datesArray = Array.prototype.slice.call(dirtyDatesArray); + } else { + // `dirtyDatesArray` is non-iterable, return Invalid Date + return new Date(NaN); + } + + var result; + datesArray.forEach(function (dirtyDate) { + var currentDate = (0, _index.default)(dirtyDate); + + if (result === undefined || result < currentDate || isNaN(Number(currentDate))) { + result = currentDate; + } + }); + return result || new Date(NaN); } module.exports = exports.default; /***/ }), -/***/ 99821: +/***/ 30003: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67005,44 +63220,71 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isSameYear; - -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +exports["default"] = milliseconds; -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +// Leap year occures every 4 years, except for years that are divisable by 100 and not divisable by 400. +// 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days +var daysInYear = 365.2425; /** - * @name isSameYear - * @category Year Helpers - * @summary Are the given dates in the same year? + * @name milliseconds + * @category Millisecond Helpers + * @summary + * Returns the number of milliseconds in the specified, years, months, weeks, days, hours, minutes and seconds. + * + * @description + * Returns the number of milliseconds in the specified, years, months, weeks, days, hours, minutes and seconds. + * + * One years equals 365.2425 days according to the formula: + * + * > Leap year occures every 4 years, except for years that are divisable by 100 and not divisable by 400. + * > 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days * - * @description - * Are the given dates in the same year? + * One month is a year divided by 12. * - * @param {Date|Number} dateLeft - the first date to check - * @param {Date|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same year - * @throws {TypeError} 2 arguments required + * @param {Duration} duration - the object with years, months, weeks, days, hours, minutes and seconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {number} the milliseconds + * @throws {TypeError} 1 argument required * * @example - * // Are 2 September 2014 and 25 September 2014 in the same year? - * const result = isSameYear(new Date(2014, 8, 2), new Date(2014, 8, 25)) - * //=> true + * // 1 year in milliseconds + * milliseconds({ years: 1 }) + * //=> 31556952000 + * + * // 3 months in milliseconds + * milliseconds({ months: 3 }) + * //=> 7889238000 */ -function isSameYear(dirtyDateLeft, dirtyDateRight) { - (0, _index2.default)(2, arguments); - var dateLeft = (0, _index.default)(dirtyDateLeft); - var dateRight = (0, _index.default)(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear(); + +function milliseconds(_ref) { + var years = _ref.years, + months = _ref.months, + weeks = _ref.weeks, + days = _ref.days, + hours = _ref.hours, + minutes = _ref.minutes, + seconds = _ref.seconds; + (0, _index.default)(1, arguments); + var totalDays = 0; + if (years) totalDays += years * daysInYear; + if (months) totalDays += months * (daysInYear / 12); + if (weeks) totalDays += weeks * 7; + if (days) totalDays += days; + var totalSeconds = totalDays * 24 * 60 * 60; + if (hours) totalSeconds += hours * 60 * 60; + if (minutes) totalSeconds += minutes * 60; + if (seconds) totalSeconds += seconds; + return Math.round(totalSeconds * 1000); } module.exports = exports.default; /***/ }), -/***/ 6308: +/***/ 96570: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67051,41 +63293,48 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isSaturday; +exports["default"] = millisecondsToHours; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = __nccwpck_require__(24665); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isSaturday - * @category Weekday Helpers - * @summary Is the given date Saturday? + * @name millisecondsToHours + * @category Conversion Helpers + * @summary Convert milliseconds to hours. * * @description - * Is the given date Saturday? + * Convert a number of milliseconds to a full number of hours. * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is Saturday + * @param {number} milliseconds - number of milliseconds to be converted + * + * @returns {number} the number of milliseconds converted in hours * @throws {TypeError} 1 argument required * * @example - * // Is 27 September 2014 Saturday? - * const result = isSaturday(new Date(2014, 8, 27)) - * //=> true + * // Convert 7200000 milliseconds to hours: + * const result = millisecondsToHours(7200000) + * //=> 2 + * + * @example + * // It uses floor rounding: + * const result = millisecondsToHours(7199999) + * //=> 1 */ -function isSaturday(dirtyDate) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate).getDay() === 6; +function millisecondsToHours(milliseconds) { + (0, _index.default)(1, arguments); + var hours = milliseconds / _index2.millisecondsInHour; + return Math.floor(hours); } module.exports = exports.default; /***/ }), -/***/ 35852: +/***/ 84493: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67094,41 +63343,48 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isSunday; +exports["default"] = millisecondsToMinutes; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = __nccwpck_require__(24665); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isSunday - * @category Weekday Helpers - * @summary Is the given date Sunday? + * @name millisecondsToMinutes + * @category Conversion Helpers + * @summary Convert milliseconds to minutes. * * @description - * Is the given date Sunday? + * Convert a number of milliseconds to a full number of minutes. * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is Sunday + * @param {number} milliseconds - number of milliseconds to be converted. + * + * @returns {number} the number of milliseconds converted in minutes * @throws {TypeError} 1 argument required * * @example - * // Is 21 September 2014 Sunday? - * const result = isSunday(new Date(2014, 8, 21)) - * //=> true + * // Convert 60000 milliseconds to minutes: + * const result = millisecondsToMinutes(60000) + * //=> 1 + * + * @example + * // It uses floor rounding: + * const result = millisecondsToMinutes(119999) + * //=> 1 */ -function isSunday(dirtyDate) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate).getDay() === 0; +function millisecondsToMinutes(milliseconds) { + (0, _index.default)(1, arguments); + var minutes = milliseconds / _index2.millisecondsInMinute; + return Math.floor(minutes); } module.exports = exports.default; /***/ }), -/***/ 84078: +/***/ 21594: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67137,46 +63393,48 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isThisHour; +exports["default"] = millisecondsToSeconds; -var _index = _interopRequireDefault(__nccwpck_require__(42489)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = __nccwpck_require__(24665); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isThisHour - * @category Hour Helpers - * @summary Is the given date in the same hour as the current date? - * @pure false + * @name millisecondsToSeconds + * @category Conversion Helpers + * @summary Convert milliseconds to seconds. * * @description - * Is the given date in the same hour as the current date? + * Convert a number of milliseconds to a full number of seconds. * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `Date.now()` internally hence impure and can't be safely curried. + * @param {number} milliseconds - number of milliseconds to be converted * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is in this hour + * @returns {number} the number of milliseconds converted in seconds * @throws {TypeError} 1 argument required * * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:00:00 in this hour? - * const result = isThisHour(new Date(2014, 8, 25, 18)) - * //=> true + * // Convert 1000 miliseconds to seconds: + * const result = millisecondsToSeconds(1000) + * //=> 1 + * + * @example + * // It uses floor rounding: + * const result = millisecondsToSeconds(1999) + * //=> 1 */ -function isThisHour(dirtyDate) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(Date.now(), dirtyDate); +function millisecondsToSeconds(milliseconds) { + (0, _index.default)(1, arguments); + var seconds = milliseconds / _index2.millisecondsInSecond; + return Math.floor(seconds); } module.exports = exports.default; /***/ }), -/***/ 6065: +/***/ 18163: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67185,47 +63443,65 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isThisISOWeek; +exports["default"] = min; -var _index = _interopRequireDefault(__nccwpck_require__(89852)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isThisISOWeek - * @category ISO Week Helpers - * @summary Is the given date in the same ISO week as the current date? - * @pure false + * @name min + * @category Common Helpers + * @summary Returns the earliest of the given dates. * * @description - * Is the given date in the same ISO week as the current date? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `Date.now()` internally hence impure and can't be safely curried. + * Returns the earliest of the given dates. * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is in this ISO week + * @param {Date[]|Number[]} datesArray - the dates to compare + * @returns {Date} - the earliest of the dates * @throws {TypeError} 1 argument required * * @example - * // If today is 25 September 2014, is 22 September 2014 in this ISO week? - * const result = isThisISOWeek(new Date(2014, 8, 22)) - * //=> true + * // Which of these dates is the earliest? + * const result = min([ + * new Date(1989, 6, 10), + * new Date(1987, 1, 11), + * new Date(1995, 6, 2), + * new Date(1990, 0, 1) + * ]) + * //=> Wed Feb 11 1987 00:00:00 */ -function isThisISOWeek(dirtyDate) { +function min(dirtyDatesArray) { (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate, Date.now()); + var datesArray; // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method + + if (dirtyDatesArray && typeof dirtyDatesArray.forEach === 'function') { + datesArray = dirtyDatesArray; // If `dirtyDatesArray` is Array-like Object, convert to Array. + } else if (typeof dirtyDatesArray === 'object' && dirtyDatesArray !== null) { + datesArray = Array.prototype.slice.call(dirtyDatesArray); + } else { + // `dirtyDatesArray` is non-iterable, return Invalid Date + return new Date(NaN); + } + + var result; + datesArray.forEach(function (dirtyDate) { + var currentDate = (0, _index.default)(dirtyDate); + + if (result === undefined || result > currentDate || isNaN(currentDate.getDate())) { + result = currentDate; + } + }); + return result || new Date(NaN); } module.exports = exports.default; /***/ }), -/***/ 33413: +/***/ 32070: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67234,46 +63510,48 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isThisMinute; +exports["default"] = minutesToHours; -var _index = _interopRequireDefault(__nccwpck_require__(66)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = __nccwpck_require__(24665); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isThisMinute - * @category Minute Helpers - * @summary Is the given date in the same minute as the current date? - * @pure false + * @name minutesToHours + * @category Conversion Helpers + * @summary Convert minutes to hours. * * @description - * Is the given date in the same minute as the current date? + * Convert a number of minutes to a full number of hours. * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `Date.now()` internally hence impure and can't be safely curried. + * @param {number} minutes - number of minutes to be converted * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is in this minute + * @returns {number} the number of minutes converted in hours * @throws {TypeError} 1 argument required * * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:30:00 in this minute? - * const result = isThisMinute(new Date(2014, 8, 25, 18, 30)) - * //=> true + * // Convert 140 minutes to hours: + * const result = minutesToHours(120) + * //=> 2 + * + * @example + * // It uses floor rounding: + * const result = minutesToHours(179) + * //=> 2 */ -function isThisMinute(dirtyDate) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(Date.now(), dirtyDate); +function minutesToHours(minutes) { + (0, _index.default)(1, arguments); + var hours = minutes / _index2.minutesInHour; + return Math.floor(hours); } module.exports = exports.default; /***/ }), -/***/ 51157: +/***/ 12478: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67282,45 +63560,42 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isThisMonth; +exports["default"] = minutesToMilliseconds; -var _index = _interopRequireDefault(__nccwpck_require__(65421)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = __nccwpck_require__(24665); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isThisMonth - * @category Month Helpers - * @summary Is the given date in the same month as the current date? - * @pure false + * @name minutesToMilliseconds + * @category Conversion Helpers + * @summary Convert minutes to milliseconds. * * @description - * Is the given date in the same month as the current date? + * Convert a number of minutes to a full number of milliseconds. * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `Date.now()` internally hence impure and can't be safely curried. + * @param {number} minutes - number of minutes to be converted * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is in this month + * @returns {number} the number of minutes converted in milliseconds * @throws {TypeError} 1 argument required * * @example - * // If today is 25 September 2014, is 15 September 2014 in this month? - * const result = isThisMonth(new Date(2014, 8, 15)) - * //=> true + * // Convert 2 minutes to milliseconds + * const result = minutesToMilliseconds(2) + * //=> 120000 */ -function isThisMonth(dirtyDate) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(Date.now(), dirtyDate); +function minutesToMilliseconds(minutes) { + (0, _index.default)(1, arguments); + return Math.floor(minutes * _index2.millisecondsInMinute); } module.exports = exports.default; /***/ }), -/***/ 25122: +/***/ 45947: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67329,45 +63604,42 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isThisQuarter; +exports["default"] = minutesToSeconds; -var _index = _interopRequireDefault(__nccwpck_require__(40938)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = __nccwpck_require__(24665); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isThisQuarter - * @category Quarter Helpers - * @summary Is the given date in the same quarter as the current date? - * @pure false + * @name minutesToSeconds + * @category Conversion Helpers + * @summary Convert minutes to seconds. * * @description - * Is the given date in the same quarter as the current date? + * Convert a number of minutes to a full number of seconds. * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `Date.now()` internally hence impure and can't be safely curried. + * @param { number } minutes - number of minutes to be converted * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is in this quarter + * @returns {number} the number of minutes converted in seconds * @throws {TypeError} 1 argument required * * @example - * // If today is 25 September 2014, is 2 July 2014 in this quarter? - * const result = isThisQuarter(new Date(2014, 6, 2)) - * //=> true + * // Convert 2 minutes to seconds + * const result = minutesToSeconds(2) + * //=> 120 */ -function isThisQuarter(dirtyDate) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(Date.now(), dirtyDate); +function minutesToSeconds(minutes) { + (0, _index.default)(1, arguments); + return Math.floor(minutes * _index2.secondsInMinute); } module.exports = exports.default; /***/ }), -/***/ 34641: +/***/ 5806: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67376,46 +63648,48 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isThisSecond; +exports["default"] = monthsToQuarters; -var _index = _interopRequireDefault(__nccwpck_require__(51988)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = __nccwpck_require__(24665); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isThisSecond - * @category Second Helpers - * @summary Is the given date in the same second as the current date? - * @pure false + * @name monthsToQuarters + * @category Conversion Helpers + * @summary Convert number of months to quarters. * * @description - * Is the given date in the same second as the current date? + * Convert a number of months to a full number of quarters. * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `Date.now()` internally hence impure and can't be safely curried. + * @param {number} months - number of months to be converted. * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is in this second + * @returns {number} the number of months converted in quarters * @throws {TypeError} 1 argument required * * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:30:15.000 in this second? - * const result = isThisSecond(new Date(2014, 8, 25, 18, 30, 15)) - * //=> true + * // Convert 6 months to quarters: + * const result = monthsToQuarters(6) + * //=> 2 + * + * @example + * // It uses floor rounding: + * const result = monthsToQuarters(7) + * //=> 2 */ -function isThisSecond(dirtyDate) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(Date.now(), dirtyDate); +function monthsToQuarters(months) { + (0, _index.default)(1, arguments); + var quarters = months / _index2.monthsInQuarter; + return Math.floor(quarters); } module.exports = exports.default; /***/ }), -/***/ 32373: +/***/ 76230: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67424,55 +63698,47 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isThisWeek; +exports["default"] = monthsToYears; -var _index = _interopRequireDefault(__nccwpck_require__(7013)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = __nccwpck_require__(24665); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isThisWeek - * @category Week Helpers - * @summary Is the given date in the same week as the current date? - * @pure false + * @name monthsToYears + * @category Conversion Helpers + * @summary Convert number of months to years. * * @description - * Is the given date in the same week as the current date? + * Convert a number of months to a full number of years. * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `Date.now()` internally hence impure and can't be safely curried. + * @param {number} months - number of months to be converted * - * @param {Date|Number} date - the date to check - * @param {Object} [options] - the object with options - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Boolean} the date is in this week + * @returns {number} the number of months converted in years * @throws {TypeError} 1 argument required - * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 * * @example - * // If today is 25 September 2014, is 21 September 2014 in this week? - * const result = isThisWeek(new Date(2014, 8, 21)) - * //=> true + * // Convert 36 months to years: + * const result = monthsToYears(36) + * //=> 3 * - * @example - * // If today is 25 September 2014 and week starts with Monday - * // is 21 September 2014 in this week? - * const result = isThisWeek(new Date(2014, 8, 21), { weekStartsOn: 1 }) - * //=> false + * // It uses floor rounding: + * const result = monthsToYears(40) + * //=> 3 */ -function isThisWeek(dirtyDate, options) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate, Date.now(), options); +function monthsToYears(months) { + (0, _index.default)(1, arguments); + var years = months / _index2.monthsInYear; + return Math.floor(years); } module.exports = exports.default; /***/ }), -/***/ 60856: +/***/ 59894: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67481,45 +63747,51 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isThisYear; +exports["default"] = nextDay; + +var _index = _interopRequireDefault(__nccwpck_require__(53426)); -var _index = _interopRequireDefault(__nccwpck_require__(99821)); +var _index2 = _interopRequireDefault(__nccwpck_require__(99950)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isThisYear - * @category Year Helpers - * @summary Is the given date in the same year as the current date? - * @pure false + * @name nextDay + * @category Weekday Helpers + * @summary When is the next day of the week? * * @description - * Is the given date in the same year as the current date? + * When is the next day of the week? 0-6 the day of the week, 0 represents Sunday. * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `Date.now()` internally hence impure and can't be safely curried. + * @param {Date | number} date - the date to check + * @param {Day} day - day of the week + * @returns {Date} - the date is the next day of week + * @throws {TypeError} - 2 arguments required * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is in this year - * @throws {TypeError} 1 argument required + * @example + * // When is the next Monday after Mar, 20, 2020? + * const result = nextDay(new Date(2020, 2, 20), 1) + * //=> Mon Mar 23 2020 00:00:00 * * @example - * // If today is 25 September 2014, is 2 July 2014 in this year? - * const result = isThisYear(new Date(2014, 6, 2)) - * //=> true + * // When is the next Tuesday after Mar, 21, 2020? + * const result = nextDay(new Date(2020, 2, 21), 2) + * //=> Tue Mar 24 2020 00:00:00 */ -function isThisYear(dirtyDate) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate, Date.now()); +function nextDay(date, day) { + (0, _index3.default)(2, arguments); + var delta = day - (0, _index2.default)(date); + if (delta <= 0) delta += 7; + return (0, _index.default)(date, delta); } module.exports = exports.default; /***/ }), -/***/ 74350: +/***/ 42082: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67528,41 +63800,41 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isThursday; +exports["default"] = nextFriday; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(59894)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isThursday + * @name nextFriday * @category Weekday Helpers - * @summary Is the given date Thursday? + * @summary When is the next Friday? * * @description - * Is the given date Thursday? + * When is the next Friday? * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is Thursday + * @param {Date | number} date - the date to start counting from + * @returns {Date} the next Friday * @throws {TypeError} 1 argument required * * @example - * // Is 25 September 2014 Thursday? - * const result = isThursday(new Date(2014, 8, 25)) - * //=> true + * // When is the next Friday after Mar, 22, 2020? + * const result = nextFriday(new Date(2020, 2, 22)) + * //=> Fri Mar 27 2020 00:00:00 */ -function isThursday(dirtyDate) { +function nextFriday(date) { (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate).getDay() === 4; + return (0, _index.default)(date, 5); } module.exports = exports.default; /***/ }), -/***/ 97185: +/***/ 4311: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67571,45 +63843,41 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isToday; +exports["default"] = nextMonday; -var _index = _interopRequireDefault(__nccwpck_require__(52154)); +var _index = _interopRequireDefault(__nccwpck_require__(59894)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isToday - * @category Day Helpers - * @summary Is the given date today? - * @pure false + * @name nextMonday + * @category Weekday Helpers + * @summary When is the next Monday? * * @description - * Is the given date today? - * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `Date.now()` internally hence impure and can't be safely curried. + * When is the next Monday? * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is today + * @param {Date | number} date - the date to start counting from + * @returns {Date} the next Monday * @throws {TypeError} 1 argument required * * @example - * // If today is 6 October 2014, is 6 October 14:00:00 today? - * const result = isToday(new Date(2014, 9, 6, 14, 0)) - * //=> true + * // When is the next Monday after Mar, 22, 2020? + * const result = nextMonday(new Date(2020, 2, 22)) + * //=> Mon Mar 23 2020 00:00:00 */ -function isToday(dirtyDate) { +function nextMonday(date) { (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate, Date.now()); + return (0, _index.default)(date, 1); } module.exports = exports.default; /***/ }), -/***/ 13014: +/***/ 413: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67618,47 +63886,41 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isTomorrow; - -var _index = _interopRequireDefault(__nccwpck_require__(56227)); +exports["default"] = nextSaturday; -var _index2 = _interopRequireDefault(__nccwpck_require__(52154)); +var _index = _interopRequireDefault(__nccwpck_require__(59894)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isTomorrow - * @category Day Helpers - * @summary Is the given date tomorrow? - * @pure false + * @name nextSaturday + * @category Weekday Helpers + * @summary When is the next Saturday? * * @description - * Is the given date tomorrow? - * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `Date.now()` internally hence impure and can't be safely curried. + * When is the next Saturday? * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is tomorrow + * @param {Date | number} date - the date to start counting from + * @returns {Date} the next Saturday * @throws {TypeError} 1 argument required * * @example - * // If today is 6 October 2014, is 7 October 14:00:00 tomorrow? - * const result = isTomorrow(new Date(2014, 9, 7, 14, 0)) - * //=> true + * // When is the next Saturday after Mar, 22, 2020? + * const result = nextSaturday(new Date(2020, 2, 22)) + * //=> Sat Mar 28 2020 00:00:00 */ -function isTomorrow(dirtyDate) { - (0, _index3.default)(1, arguments); - return (0, _index2.default)(dirtyDate, (0, _index.default)(Date.now(), 1)); +function nextSaturday(date) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(date, 6); } module.exports = exports.default; /***/ }), -/***/ 88235: +/***/ 25033: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67667,41 +63929,41 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isTuesday; +exports["default"] = nextSunday; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(59894)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isTuesday + * @name nextSunday * @category Weekday Helpers - * @summary Is the given date Tuesday? + * @summary When is the next Sunday? * * @description - * Is the given date Tuesday? + * When is the next Sunday? * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is Tuesday + * @param {Date | number} date - the date to start counting from + * @returns {Date} the next Sunday * @throws {TypeError} 1 argument required * * @example - * // Is 23 September 2014 Tuesday? - * const result = isTuesday(new Date(2014, 8, 23)) - * //=> true + * // When is the next Sunday after Mar, 22, 2020? + * const result = nextSunday(new Date(2020, 2, 22)) + * //=> Sun Mar 29 2020 00:00:00 */ -function isTuesday(dirtyDate) { +function nextSunday(date) { (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate).getDay() === 2; + return (0, _index.default)(date, 0); } module.exports = exports.default; /***/ }), -/***/ 59920: +/***/ 49691: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67710,63 +63972,41 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isValid; - -var _index = _interopRequireDefault(__nccwpck_require__(6801)); +exports["default"] = nextThursday; -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(59894)); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isValid - * @category Common Helpers - * @summary Is the given date valid? + * @name nextThursday + * @category Weekday Helpers + * @summary When is the next Thursday? * * @description - * Returns false if argument is Invalid Date and true otherwise. - * Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate} - * Invalid Date is a Date, whose time value is NaN. - * - * Time value of Date: http://es5.github.io/#x15.9.1.1 + * When is the next Thursday? * - * @param {*} date - the date to check - * @returns {Boolean} the date is valid + * @param {Date | number} date - the date to start counting from + * @returns {Date} the next Thursday * @throws {TypeError} 1 argument required * * @example - * // For the valid date: - * const result = isValid(new Date(2014, 1, 31)) - * //=> true - * - * @example - * // For the value, convertable into a date: - * const result = isValid(1393804800000) - * //=> true - * - * @example - * // For the invalid date: - * const result = isValid(new Date('')) - * //=> false + * // When is the next Thursday after Mar, 22, 2020? + * const result = nextThursday(new Date(2020, 2, 22)) + * //=> Thur Mar 26 2020 00:00:00 */ -function isValid(dirtyDate) { - (0, _index3.default)(1, arguments); - - if (!(0, _index.default)(dirtyDate) && typeof dirtyDate !== 'number') { - return false; - } - - var date = (0, _index2.default)(dirtyDate); - return !isNaN(Number(date)); +function nextThursday(date) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(date, 4); } module.exports = exports.default; /***/ }), -/***/ 29218: +/***/ 39621: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67775,41 +64015,41 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isWednesday; +exports["default"] = nextTuesday; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(59894)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isWednesday + * @name nextTuesday * @category Weekday Helpers - * @summary Is the given date Wednesday? + * @summary When is the next Tuesday? * * @description - * Is the given date Wednesday? + * When is the next Tuesday? * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is Wednesday + * @param {Date | number} date - the date to start counting from + * @returns {Date} the next Tuesday * @throws {TypeError} 1 argument required * * @example - * // Is 24 September 2014 Wednesday? - * const result = isWednesday(new Date(2014, 8, 24)) - * //=> true + * // When is the next Tuesday after Mar, 22, 2020? + * const result = nextTuesday(new Date(2020, 2, 22)) + * //=> Tue Mar 24 2020 00:00:00 */ -function isWednesday(dirtyDate) { +function nextTuesday(date) { (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate).getDay() === 3; + return (0, _index.default)(date, 2); } module.exports = exports.default; /***/ }), -/***/ 40403: +/***/ 39608: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -67818,44 +64058,42 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isWeekend; +exports["default"] = nextWednesday; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(59894)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isWeekend + * @name nextWednesday * @category Weekday Helpers - * @summary Does the given date fall on a weekend? + * @summary When is the next Wednesday? * * @description - * Does the given date fall on a weekend? + * When is the next Wednesday? * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date falls on a weekend + * @param {Date | number} date - the date to start counting from + * @returns {Date} the next Wednesday * @throws {TypeError} 1 argument required * * @example - * // Does 5 October 2014 fall on a weekend? - * const result = isWeekend(new Date(2014, 9, 5)) - * //=> true + * // When is the next Wednesday after Mar, 22, 2020? + * const result = nextWednesday(new Date(2020, 2, 22)) + * //=> Wed Mar 25 2020 00:00:00 */ -function isWeekend(dirtyDate) { +function nextWednesday(date) { (0, _index2.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - var day = date.getDay(); - return day === 0 || day === 6; + return (0, _index.default)(date, 3); } module.exports = exports.default; /***/ }), -/***/ 14419: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 80583: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -67863,72 +64101,46 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isWithinInterval; +exports.Parser = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _Setter = __nccwpck_require__(32005); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +class Parser { + constructor() { + _defineProperty(this, "incompatibleTokens", void 0); -/** - * @name isWithinInterval - * @category Interval Helpers - * @summary Is the given date within the interval? - * - * @description - * Is the given date within the interval? (Including start and end.) - * - * @param {Date|Number} date - the date to check - * @param {Interval} interval - the interval to check - * @returns {Boolean} the date is within the interval - * @throws {TypeError} 2 arguments required - * @throws {RangeError} The start of an interval cannot be after its end - * @throws {RangeError} Date in interval cannot be `Invalid Date` - * - * @example - * // For the date within the interval: - * isWithinInterval(new Date(2014, 0, 3), { - * start: new Date(2014, 0, 1), - * end: new Date(2014, 0, 7) - * }) - * //=> true - * - * @example - * // For the date outside of the interval: - * isWithinInterval(new Date(2014, 0, 10), { - * start: new Date(2014, 0, 1), - * end: new Date(2014, 0, 7) - * }) - * //=> false - * - * @example - * // For date equal to interval start: - * isWithinInterval(date, { start, end: date }) // => true - * - * @example - * // For date equal to interval end: - * isWithinInterval(date, { start: date, end }) // => true - */ -function isWithinInterval(dirtyDate, interval) { - (0, _index2.default)(2, arguments); - var time = (0, _index.default)(dirtyDate).getTime(); - var startTime = (0, _index.default)(interval.start).getTime(); - var endTime = (0, _index.default)(interval.end).getTime(); // Throw an exception if start date is after end date or if any date is `Invalid Date` + _defineProperty(this, "priority", void 0); - if (!(startTime <= endTime)) { - throw new RangeError('Invalid interval'); + _defineProperty(this, "subPriority", void 0); + } + + run(dateString, token, match, options) { + var result = this.parse(dateString, token, match, options); + + if (!result) { + return null; + } + + return { + setter: new _Setter.ValueSetter(result.value, this.validate, this.set, this.priority, this.subPriority), + rest: result.rest + }; + } + + validate(_utcDate, _value, _options) { + return true; } - return time >= startTime && time <= endTime; } -module.exports = exports.default; +exports.Parser = Parser; /***/ }), -/***/ 9583: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 32005: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -67936,96 +64148,80 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isYesterday; +exports.DateToSystemTimezoneSetter = exports.ValueSetter = exports.Setter = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(52154)); +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -var _index2 = _interopRequireDefault(__nccwpck_require__(50970)); +var TIMEZONE_UNIT_PRIORITY = 10; -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +class Setter { + constructor() { + _defineProperty(this, "priority", void 0); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + _defineProperty(this, "subPriority", 0); + } + + validate(_utcDate, _options) { + return true; + } -/** - * @name isYesterday - * @category Day Helpers - * @summary Is the given date yesterday? - * @pure false - * - * @description - * Is the given date yesterday? - * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `Date.now()` internally hence impure and can't be safely curried. - * - * @param {Date|Number} date - the date to check - * @returns {Boolean} the date is yesterday - * @throws {TypeError} 1 argument required - * - * @example - * // If today is 6 October 2014, is 5 October 14:00:00 yesterday? - * const result = isYesterday(new Date(2014, 9, 5, 14, 0)) - * //=> true - */ -function isYesterday(dirtyDate) { - (0, _index3.default)(1, arguments); - return (0, _index.default)(dirtyDate, (0, _index2.default)(Date.now(), 1)); } -module.exports = exports.default; +exports.Setter = Setter; -/***/ }), +class ValueSetter extends Setter { + constructor(value, validateValue, setValue, priority, subPriority) { + super(); + this.value = value; + this.validateValue = validateValue; + this.setValue = setValue; + this.priority = priority; -/***/ 94864: -/***/ ((module, exports, __nccwpck_require__) => { + if (subPriority) { + this.subPriority = subPriority; + } + } -"use strict"; + validate(utcDate, options) { + return this.validateValue(utcDate, this.value, options); + } + set(utcDate, flags, options) { + return this.setValue(utcDate, flags, this.value, options); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = lastDayOfDecade; +} -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +exports.ValueSetter = ValueSetter; -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +class DateToSystemTimezoneSetter extends Setter { + constructor() { + super(...arguments); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + _defineProperty(this, "priority", TIMEZONE_UNIT_PRIORITY); + + _defineProperty(this, "subPriority", -1); + } + + set(date, flags) { + if (flags.timestampIsSet) { + return date; + } + + var convertedDate = new Date(0); + convertedDate.setFullYear(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()); + convertedDate.setHours(date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()); + return convertedDate; + } -/** - * @name lastDayOfDecade - * @category Decade Helpers - * @summary Return the last day of a decade for the given date. - * - * @description - * Return the last day of a decade for the given date. - * - * @param {Date|Number} date - the original date - * @returns {Date} the last day of a decade - * @throws {TypeError} 1 argument required - * - * @example - * // The last day of a decade for 21 December 2012 21:12:00: - * const result = lastDayOfDecade(new Date(2012, 11, 21, 21, 12, 00)) - * //=> Wed Dec 31 2019 00:00:00 - */ -function lastDayOfDecade(dirtyDate) { - (0, _index2.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - var year = date.getFullYear(); - var decade = 9 + Math.floor(year / 10) * 10; - date.setFullYear(decade + 1, 0, 0); - date.setHours(0, 0, 0, 0); - return date; } -module.exports = exports.default; +exports.DateToSystemTimezoneSetter = DateToSystemTimezoneSetter; /***/ }), -/***/ 17692: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 88829: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -68033,47 +64229,131 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = lastDayOfISOWeek; +exports.timezonePatterns = exports.numericPatterns = void 0; +var numericPatterns = { + month: /^(1[0-2]|0?\d)/, + // 0 to 12 + date: /^(3[0-1]|[0-2]?\d)/, + // 0 to 31 + dayOfYear: /^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/, + // 0 to 366 + week: /^(5[0-3]|[0-4]?\d)/, + // 0 to 53 + hour23h: /^(2[0-3]|[0-1]?\d)/, + // 0 to 23 + hour24h: /^(2[0-4]|[0-1]?\d)/, + // 0 to 24 + hour11h: /^(1[0-1]|0?\d)/, + // 0 to 11 + hour12h: /^(1[0-2]|0?\d)/, + // 0 to 12 + minute: /^[0-5]?\d/, + // 0 to 59 + second: /^[0-5]?\d/, + // 0 to 59 + singleDigit: /^\d/, + // 0 to 9 + twoDigits: /^\d{1,2}/, + // 0 to 99 + threeDigits: /^\d{1,3}/, + // 0 to 999 + fourDigits: /^\d{1,4}/, + // 0 to 9999 + anyDigitsSigned: /^-?\d+/, + singleDigitSigned: /^-?\d/, + // 0 to 9, -0 to -9 + twoDigitsSigned: /^-?\d{1,2}/, + // 0 to 99, -0 to -99 + threeDigitsSigned: /^-?\d{1,3}/, + // 0 to 999, -0 to -999 + fourDigitsSigned: /^-?\d{1,4}/ // 0 to 9999, -0 to -9999 -var _index = _interopRequireDefault(__nccwpck_require__(20666)); +}; +exports.numericPatterns = numericPatterns; +var timezonePatterns = { + basicOptionalMinutes: /^([+-])(\d{2})(\d{2})?|Z/, + basic: /^([+-])(\d{2})(\d{2})|Z/, + basicOptionalSeconds: /^([+-])(\d{2})(\d{2})((\d{2}))?|Z/, + extended: /^([+-])(\d{2}):(\d{2})|Z/, + extendedOptionalSeconds: /^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/ +}; +exports.timezonePatterns = timezonePatterns; -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +/***/ }), -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/***/ 22240: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.AMPMMidnightParser = void 0; + +var _Parser = __nccwpck_require__(80583); + +var _utils = __nccwpck_require__(21998); + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +class AMPMMidnightParser extends _Parser.Parser { + constructor() { + super(...arguments); + + _defineProperty(this, "priority", 80); + + _defineProperty(this, "incompatibleTokens", ['a', 'B', 'H', 'k', 't', 'T']); + } + + parse(dateString, token, match) { + switch (token) { + case 'b': + case 'bb': + case 'bbb': + return match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); + + case 'bbbbb': + return match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); + + case 'bbbb': + default: + return match.dayPeriod(dateString, { + width: 'wide', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); + } + } + + set(date, _flags, value) { + date.setUTCHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0); + return date; + } -/** - * @name lastDayOfISOWeek - * @category ISO Week Helpers - * @summary Return the last day of an ISO week for the given date. - * - * @description - * Return the last day of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|Number} date - the original date - * @returns {Date} the last day of an ISO week - * @throws {TypeError} 1 argument required - * - * @example - * // The last day of an ISO week for 2 September 2014 11:55:00: - * const result = lastDayOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Sep 07 2014 00:00:00 - */ -function lastDayOfISOWeek(dirtyDate) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate, { - weekStartsOn: 1 - }); } -module.exports = exports.default; +exports.AMPMMidnightParser = AMPMMidnightParser; /***/ }), -/***/ 20217: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 92518: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -68081,54 +64361,70 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = lastDayOfISOWeekYear; +exports.AMPMParser = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(86991)); +var _Parser = __nccwpck_require__(80583); -var _index2 = _interopRequireDefault(__nccwpck_require__(56307)); +var _utils = __nccwpck_require__(21998); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +class AMPMParser extends _Parser.Parser { + constructor() { + super(...arguments); + + _defineProperty(this, "priority", 80); + + _defineProperty(this, "incompatibleTokens", ['b', 'B', 'H', 'k', 't', 'T']); + } + + parse(dateString, token, match) { + switch (token) { + case 'a': + case 'aa': + case 'aaa': + return match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); + + case 'aaaaa': + return match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); + + case 'aaaa': + default: + return match.dayPeriod(dateString, { + width: 'wide', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); + } + } + + set(date, _flags, value) { + date.setUTCHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0); + return date; + } -/** - * @name lastDayOfISOWeekYear - * @category ISO Week-Numbering Year Helpers - * @summary Return the last day of an ISO week-numbering year for the given date. - * - * @description - * Return the last day of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|Number} date - the original date - * @returns {Date} the end of an ISO week-numbering year - * @throws {TypeError} 1 argument required - * - * @example - * // The last day of an ISO week-numbering year for 2 July 2005: - * const result = lastDayOfISOWeekYear(new Date(2005, 6, 2)) - * //=> Sun Jan 01 2006 00:00:00 - */ -function lastDayOfISOWeekYear(dirtyDate) { - (0, _index3.default)(1, arguments); - var year = (0, _index.default)(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year + 1, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = (0, _index2.default)(fourthOfJanuary); - date.setDate(date.getDate() - 1); - return date; } -module.exports = exports.default; +exports.AMPMParser = AMPMParser; /***/ }), -/***/ 43346: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 65790: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -68136,99 +64432,71 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = lastDayOfMonth; +exports.DateParser = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _utils = __nccwpck_require__(21998); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _Parser = __nccwpck_require__(80583); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _constants = __nccwpck_require__(88829); -/** - * @name lastDayOfMonth - * @category Month Helpers - * @summary Return the last day of a month for the given date. - * - * @description - * Return the last day of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|Number} date - the original date - * @returns {Date} the last day of a month - * @throws {TypeError} 1 argument required - * - * @example - * // The last day of a month for 2 September 2014 11:55:00: - * const result = lastDayOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 00:00:00 - */ -function lastDayOfMonth(dirtyDate) { - (0, _index2.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - var month = date.getMonth(); - date.setFullYear(date.getFullYear(), month + 1, 0); - date.setHours(0, 0, 0, 0); - return date; -} +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -module.exports = exports.default; +var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +var DAYS_IN_MONTH_LEAP_YEAR = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; // Day of the month -/***/ }), +class DateParser extends _Parser.Parser { + constructor() { + super(...arguments); -/***/ 98635: -/***/ ((module, exports, __nccwpck_require__) => { + _defineProperty(this, "priority", 90); -"use strict"; + _defineProperty(this, "subPriority", 1); + _defineProperty(this, "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = lastDayOfQuarter; + parse(dateString, token, match) { + switch (token) { + case 'd': + return (0, _utils.parseNumericPattern)(_constants.numericPatterns.date, dateString); -var _index = _interopRequireDefault(__nccwpck_require__(26477)); + case 'do': + return match.ordinalNumber(dateString, { + unit: 'date' + }); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + default: + return (0, _utils.parseNDigits)(token.length, dateString); + } + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + validate(date, value) { + var year = date.getUTCFullYear(); + var isLeapYear = (0, _utils.isLeapYearIndex)(year); + var month = date.getUTCMonth(); + + if (isLeapYear) { + return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month]; + } else { + return value >= 1 && value <= DAYS_IN_MONTH[month]; + } + } + + set(date, _flags, value) { + date.setUTCDate(value); + date.setUTCHours(0, 0, 0, 0); + return date; + } -/** - * @name lastDayOfQuarter - * @category Quarter Helpers - * @summary Return the last day of a year quarter for the given date. - * - * @description - * Return the last day of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|Number} date - the original date - * @param {Object} [options] - an object with options. - * @param {0|1|2} [options.additionalDigits=2] - passed to `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate} - * @returns {Date} the last day of a quarter - * @throws {TypeError} 1 argument required - * @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2 - * - * @example - * // The last day of a quarter for 2 September 2014 11:55:00: - * const result = lastDayOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 00:00:00 - */ -function lastDayOfQuarter(dirtyDate) { - (0, _index2.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3 + 3; - date.setMonth(month, 0); - date.setHours(0, 0, 0, 0); - return date; } -module.exports = exports.default; +exports.DateParser = DateParser; /***/ }), -/***/ 20666: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 31846: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -68236,70 +64504,68 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = lastDayOfWeek; +exports.DayOfYearParser = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _Parser = __nccwpck_require__(80583); -var _index2 = _interopRequireDefault(__nccwpck_require__(1985)); +var _constants = __nccwpck_require__(88829); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _utils = __nccwpck_require__(21998); -var _index4 = __nccwpck_require__(79307); +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +class DayOfYearParser extends _Parser.Parser { + constructor() { + super(...arguments); -/** - * @name lastDayOfWeek - * @category Week Helpers - * @summary Return the last day of a week for the given date. - * - * @description - * Return the last day of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|Number} date - the original date - * @param {Object} [options] - an object with options. - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the last day of a week - * @throws {TypeError} 1 argument required - * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 - * - * @example - * // The last day of a week for 2 September 2014 11:55:00: - * const result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sat Sep 06 2014 00:00:00 - * - * @example - * // If the week starts on Monday, the last day of the week for 2 September 2014 11:55:00: - * const result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 }) - * //=> Sun Sep 07 2014 00:00:00 - */ -function lastDayOfWeek(dirtyDate, options) { - var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + _defineProperty(this, "priority", 90); - (0, _index3.default)(1, arguments); - var defaultOptions = (0, _index4.getDefaultOptions)(); - var weekStartsOn = (0, _index2.default)((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + _defineProperty(this, "subpriority", 1); - if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { - throw new RangeError('weekStartsOn must be between 0 and 6'); + _defineProperty(this, "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'M', 'L', 'w', 'I', 'd', 'E', 'i', 'e', 'c', 't', 'T']); + } + + parse(dateString, token, match) { + switch (token) { + case 'D': + case 'DD': + return (0, _utils.parseNumericPattern)(_constants.numericPatterns.dayOfYear, dateString); + + case 'Do': + return match.ordinalNumber(dateString, { + unit: 'date' + }); + + default: + return (0, _utils.parseNDigits)(token.length, dateString); + } + } + + validate(date, value) { + var year = date.getUTCFullYear(); + var isLeapYear = (0, _utils.isLeapYearIndex)(year); + + if (isLeapYear) { + return value >= 1 && value <= 366; + } else { + return value >= 1 && value <= 365; + } + } + + set(date, _flags, value) { + date.setUTCMonth(0, value); + date.setUTCHours(0, 0, 0, 0); + return date; } - var date = (0, _index.default)(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); - date.setHours(0, 0, 0, 0); - date.setDate(date.getDate() + diff); - return date; } -module.exports = exports.default; +exports.DayOfYearParser = DayOfYearParser; /***/ }), -/***/ 79771: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 63922: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -68307,198 +64573,169 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = lastDayOfYear; +exports.DayParser = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _Parser = __nccwpck_require__(80583); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(98879)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/** - * @name lastDayOfYear - * @category Year Helpers - * @summary Return the last day of a year for the given date. - * - * @description - * Return the last day of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|Number} date - the original date - * @returns {Date} the last day of a year - * @throws {TypeError} 1 argument required - * - * @example - * // The last day of a year for 2 September 2014 11:55:00: - * const result = lastDayOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Dec 31 2014 00:00:00 - */ -function lastDayOfYear(dirtyDate) { - (0, _index2.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - var year = date.getFullYear(); - date.setFullYear(year + 1, 0, 0); - date.setHours(0, 0, 0, 0); - return date; -} - -module.exports = exports.default; +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -/***/ }), +// Day of week +class DayParser extends _Parser.Parser { + constructor() { + super(...arguments); -/***/ 24018: -/***/ ((module, exports, __nccwpck_require__) => { + _defineProperty(this, "priority", 90); -"use strict"; + _defineProperty(this, "incompatibleTokens", ['D', 'i', 'e', 'c', 't', 'T']); + } + parse(dateString, token, match) { + switch (token) { + // Tue + case 'E': + case 'EE': + case 'EEE': + return match.day(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }); + // T -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = lightFormat; + case 'EEEEE': + return match.day(dateString, { + width: 'narrow', + context: 'formatting' + }); + // Tu -var _index = _interopRequireDefault(__nccwpck_require__(26477)); + case 'EEEEEE': + return match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }); + // Tuesday -var _index2 = _interopRequireDefault(__nccwpck_require__(40289)); + case 'EEEE': + default: + return match.day(dateString, { + width: 'wide', + context: 'formatting' + }) || match.day(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }); + } + } -var _index3 = _interopRequireDefault(__nccwpck_require__(97032)); + validate(_date, value) { + return value >= 0 && value <= 6; + } -var _index4 = _interopRequireDefault(__nccwpck_require__(59920)); + set(date, _flags, value, options) { + date = (0, _index.default)(date, value, options); + date.setUTCHours(0, 0, 0, 0); + return date; + } -var _index5 = _interopRequireDefault(__nccwpck_require__(97923)); +} -var _index6 = _interopRequireDefault(__nccwpck_require__(82063)); +exports.DayParser = DayParser; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/***/ }), -// This RegExp consists of three parts separated by `|`: -// - (\w)\1* matches any sequences of the same letter -// - '' matches two quote characters in a row -// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('), -// except a single quote symbol, which ends the sequence. -// Two quote characters do not end the sequence. -// If there is no matching single quote -// then the sequence will continue until the end of the string. -// - . matches any single character unmatched by previous parts of the RegExps -var formattingTokensRegExp = /(\w)\1*|''|'(''|[^'])+('|$)|./g; -var escapedStringRegExp = /^'([^]*?)'?$/; -var doubleQuoteRegExp = /''/g; -var unescapedLatinCharacterRegExp = /[a-zA-Z]/; -/** - * @name lightFormat - * @category Common Helpers - * @summary Format the date. - * - * @description - * Return the formatted date string in the given format. Unlike `format`, - * `lightFormat` doesn't use locales and outputs date using the most popular tokens. - * - * > ⚠️ Please note that the `lightFormat` tokens differ from Moment.js and other libraries. - * > See: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * - * The characters wrapped between two single quotes characters (') are escaped. - * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. - * - * Format of the string is based on Unicode Technical Standard #35: - * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table - * - * Accepted patterns: - * | Unit | Pattern | Result examples | - * |---------------------------------|---------|-----------------------------------| - * | AM, PM | a..aaa | AM, PM | - * | | aaaa | a.m., p.m. | - * | | aaaaa | a, p | - * | Calendar year | y | 44, 1, 1900, 2017 | - * | | yy | 44, 01, 00, 17 | - * | | yyy | 044, 001, 000, 017 | - * | | yyyy | 0044, 0001, 1900, 2017 | - * | Month (formatting) | M | 1, 2, ..., 12 | - * | | MM | 01, 02, ..., 12 | - * | Day of month | d | 1, 2, ..., 31 | - * | | dd | 01, 02, ..., 31 | - * | Hour [1-12] | h | 1, 2, ..., 11, 12 | - * | | hh | 01, 02, ..., 11, 12 | - * | Hour [0-23] | H | 0, 1, 2, ..., 23 | - * | | HH | 00, 01, 02, ..., 23 | - * | Minute | m | 0, 1, ..., 59 | - * | | mm | 00, 01, ..., 59 | - * | Second | s | 0, 1, ..., 59 | - * | | ss | 00, 01, ..., 59 | - * | Fraction of second | S | 0, 1, ..., 9 | - * | | SS | 00, 01, ..., 99 | - * | | SSS | 000, 001, ..., 999 | - * | | SSSS | ... | - * - * @param {Date|Number} date - the original date - * @param {String} format - the string of tokens - * @returns {String} the formatted date string - * @throws {TypeError} 2 arguments required - * @throws {RangeError} format string contains an unescaped latin alphabet character - * - * @example - * const result = lightFormat(new Date(2014, 1, 11), 'yyyy-MM-dd') - * //=> '2014-02-11' - */ +/***/ 40973: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function lightFormat(dirtyDate, formatStr) { - (0, _index6.default)(2, arguments); - var originalDate = (0, _index.default)(dirtyDate); +"use strict"; - if (!(0, _index4.default)(originalDate)) { - throw new RangeError('Invalid time value'); - } // Convert the date in system timezone to the same date in UTC+00:00 timezone. - // This ensures that when UTC functions will be implemented, locales will be compatible with them. - // See an issue about UTC functions: /~https://github.com/date-fns/date-fns/issues/376 +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.DayPeriodParser = void 0; - var timezoneOffset = (0, _index3.default)(originalDate); - var utcDate = (0, _index5.default)(originalDate, timezoneOffset); - var tokens = formatStr.match(formattingTokensRegExp); // The only case when formattingTokensRegExp doesn't match the string is when it's empty +var _Parser = __nccwpck_require__(80583); - if (!tokens) return ''; - var result = tokens.map(function (substring) { - // Replace two single quote characters with one single quote character - if (substring === "''") { - return "'"; - } +var _utils = __nccwpck_require__(21998); - var firstCharacter = substring[0]; +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - if (firstCharacter === "'") { - return cleanEscapedString(substring); - } +// in the morning, in the afternoon, in the evening, at night +class DayPeriodParser extends _Parser.Parser { + constructor() { + super(...arguments); - var formatter = _index2.default[firstCharacter]; + _defineProperty(this, "priority", 80); - if (formatter) { - return formatter(utcDate, substring); - } + _defineProperty(this, "incompatibleTokens", ['a', 'b', 't', 'T']); + } - if (firstCharacter.match(unescapedLatinCharacterRegExp)) { - throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`'); - } + parse(dateString, token, match) { + switch (token) { + case 'B': + case 'BB': + case 'BBB': + return match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); - return substring; - }).join(''); - return result; -} + case 'BBBBB': + return match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); -function cleanEscapedString(input) { - var matches = input.match(escapedStringRegExp); + case 'BBBB': + default: + return match.dayPeriod(dateString, { + width: 'wide', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); + } + } - if (!matches) { - return input; + set(date, _flags, value) { + date.setUTCHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0); + return date; } - return matches[1].replace(doubleQuoteRegExp, "'"); } -module.exports = exports.default; +exports.DayPeriodParser = DayPeriodParser; /***/ }), -/***/ 81244: -/***/ ((module, exports) => { +/***/ 69166: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -68506,24 +64743,67 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = buildFormatLongFn; +exports.EraParser = void 0; + +var _Parser = __nccwpck_require__(80583); + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +class EraParser extends _Parser.Parser { + constructor() { + super(...arguments); + + _defineProperty(this, "priority", 140); + + _defineProperty(this, "incompatibleTokens", ['R', 'u', 't', 'T']); + } + + parse(dateString, token, match) { + switch (token) { + // AD, BC + case 'G': + case 'GG': + case 'GGG': + return match.era(dateString, { + width: 'abbreviated' + }) || match.era(dateString, { + width: 'narrow' + }); + // A, B + + case 'GGGGG': + return match.era(dateString, { + width: 'narrow' + }); + // Anno Domini, Before Christ + + case 'GGGG': + default: + return match.era(dateString, { + width: 'wide' + }) || match.era(dateString, { + width: 'abbreviated' + }) || match.era(dateString, { + width: 'narrow' + }); + } + } + + set(date, flags, value) { + flags.era = value; + date.setUTCFullYear(value, 0, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + } -function buildFormatLongFn(args) { - return function () { - var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - // TODO: Remove String() - var width = options.width ? String(options.width) : args.defaultWidth; - var format = args.formats[width] || args.formats[args.defaultWidth]; - return format; - }; } -module.exports = exports.default; +exports.EraParser = EraParser; /***/ }), -/***/ 13647: -/***/ ((module, exports) => { +/***/ 37503: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -68531,37 +64811,45 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = buildLocalizeFn; +exports.ExtendedYearParser = void 0; -function buildLocalizeFn(args) { - return function (dirtyIndex, options) { - var context = options !== null && options !== void 0 && options.context ? String(options.context) : 'standalone'; - var valuesArray; +var _Parser = __nccwpck_require__(80583); - if (context === 'formatting' && args.formattingValues) { - var defaultWidth = args.defaultFormattingWidth || args.defaultWidth; - var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth; - valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth]; - } else { - var _defaultWidth = args.defaultWidth; +var _utils = __nccwpck_require__(21998); - var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth; +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - valuesArray = args.values[_width] || args.values[_defaultWidth]; +class ExtendedYearParser extends _Parser.Parser { + constructor() { + super(...arguments); + + _defineProperty(this, "priority", 130); + + _defineProperty(this, "incompatibleTokens", ['G', 'y', 'Y', 'R', 'w', 'I', 'i', 'e', 'c', 't', 'T']); + } + + parse(dateString, token) { + if (token === 'u') { + return (0, _utils.parseNDigitsSigned)(4, dateString); } - var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex; // @ts-ignore: For some reason TypeScript just don't want to match it, no matter how hard we try. I challenge you to try to remove it! + return (0, _utils.parseNDigitsSigned)(token.length, dateString); + } + + set(date, _flags, value) { + date.setUTCFullYear(value, 0, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + } - return valuesArray[index]; - }; } -module.exports = exports.default; +exports.ExtendedYearParser = ExtendedYearParser; /***/ }), -/***/ 84029: -/***/ ((module, exports) => { +/***/ 82429: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -68569,63 +64857,44 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = buildMatchFn; +exports.FractionOfSecondParser = void 0; -function buildMatchFn(args) { - return function (string) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var width = options.width; - var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth]; - var matchResult = string.match(matchPattern); +var _Parser = __nccwpck_require__(80583); - if (!matchResult) { - return null; - } +var _utils = __nccwpck_require__(21998); - var matchedString = matchResult[0]; - var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth]; - var key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function (pattern) { - return pattern.test(matchedString); - }) : findKey(parsePatterns, function (pattern) { - return pattern.test(matchedString); - }); - var value; - value = args.valueCallback ? args.valueCallback(key) : key; - value = options.valueCallback ? options.valueCallback(value) : value; - var rest = string.slice(matchedString.length); - return { - value: value, - rest: rest - }; - }; -} +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function findKey(object, predicate) { - for (var key in object) { - if (object.hasOwnProperty(key) && predicate(object[key])) { - return key; - } +class FractionOfSecondParser extends _Parser.Parser { + constructor() { + super(...arguments); + + _defineProperty(this, "priority", 30); + + _defineProperty(this, "incompatibleTokens", ['t', 'T']); } - return undefined; -} + parse(dateString, token) { + var valueCallback = function (value) { + return Math.floor(value * Math.pow(10, -token.length + 3)); + }; -function findIndex(array, predicate) { - for (var key = 0; key < array.length; key++) { - if (predicate(array[key])) { - return key; - } + return (0, _utils.mapValue)((0, _utils.parseNDigits)(token.length, dateString), valueCallback); + } + + set(date, _flags, value) { + date.setUTCMilliseconds(value); + return date; } - return undefined; } -module.exports = exports.default; +exports.FractionOfSecondParser = FractionOfSecondParser; /***/ }), -/***/ 23364: -/***/ ((module, exports) => { +/***/ 97104: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -68633,135 +64902,64 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = buildMatchPatternFn; +exports.Hour0To11Parser = void 0; -function buildMatchPatternFn(args) { - return function (string) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var matchResult = string.match(args.matchPattern); - if (!matchResult) return null; - var matchedString = matchResult[0]; - var parseResult = string.match(args.parsePattern); - if (!parseResult) return null; - var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0]; - value = options.valueCallback ? options.valueCallback(value) : value; - var rest = string.slice(matchedString.length); - return { - value: value, - rest: rest - }; - }; -} +var _Parser = __nccwpck_require__(80583); -module.exports = exports.default; +var _constants = __nccwpck_require__(88829); -/***/ }), +var _utils = __nccwpck_require__(21998); -/***/ 74846: -/***/ ((module, exports) => { +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -"use strict"; +class Hour0To11Parser extends _Parser.Parser { + constructor() { + super(...arguments); + _defineProperty(this, "priority", 70); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var formatDistanceLocale = { - lessThanXSeconds: { - one: 'less than a second', - other: 'less than {{count}} seconds' - }, - xSeconds: { - one: '1 second', - other: '{{count}} seconds' - }, - halfAMinute: 'half a minute', - lessThanXMinutes: { - one: 'less than a minute', - other: 'less than {{count}} minutes' - }, - xMinutes: { - one: '1 minute', - other: '{{count}} minutes' - }, - aboutXHours: { - one: 'about 1 hour', - other: 'about {{count}} hours' - }, - xHours: { - one: '1 hour', - other: '{{count}} hours' - }, - xDays: { - one: '1 day', - other: '{{count}} days' - }, - aboutXWeeks: { - one: 'about 1 week', - other: 'about {{count}} weeks' - }, - xWeeks: { - one: '1 week', - other: '{{count}} weeks' - }, - aboutXMonths: { - one: 'about 1 month', - other: 'about {{count}} months' - }, - xMonths: { - one: '1 month', - other: '{{count}} months' - }, - aboutXYears: { - one: 'about 1 year', - other: 'about {{count}} years' - }, - xYears: { - one: '1 year', - other: '{{count}} years' - }, - overXYears: { - one: 'over 1 year', - other: 'over {{count}} years' - }, - almostXYears: { - one: 'almost 1 year', - other: 'almost {{count}} years' + _defineProperty(this, "incompatibleTokens", ['h', 'H', 'k', 't', 'T']); } -}; -var formatDistance = function (token, count, options) { - var result; - var tokenValue = formatDistanceLocale[token]; + parse(dateString, token, match) { + switch (token) { + case 'K': + return (0, _utils.parseNumericPattern)(_constants.numericPatterns.hour11h, dateString); - if (typeof tokenValue === 'string') { - result = tokenValue; - } else if (count === 1) { - result = tokenValue.one; - } else { - result = tokenValue.other.replace('{{count}}', count.toString()); + case 'Ko': + return match.ordinalNumber(dateString, { + unit: 'hour' + }); + + default: + return (0, _utils.parseNDigits)(token.length, dateString); + } } - if (options !== null && options !== void 0 && options.addSuffix) { - if (options.comparison && options.comparison > 0) { - return 'in ' + result; + validate(_date, value) { + return value >= 0 && value <= 11; + } + + set(date, _flags, value) { + var isPM = date.getUTCHours() >= 12; + + if (isPM && value < 12) { + date.setUTCHours(value + 12, 0, 0, 0); } else { - return result + ' ago'; + date.setUTCHours(value, 0, 0, 0); } + + return date; } - return result; -}; +} -var _default = formatDistance; -exports["default"] = _default; -module.exports = exports.default; +exports.Hour0To11Parser = Hour0To11Parser; /***/ }), -/***/ 20368: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 39360: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -68769,81 +64967,57 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = void 0; +exports.Hour0to23Parser = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(81244)); +var _Parser = __nccwpck_require__(80583); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _constants = __nccwpck_require__(88829); -var dateFormats = { - full: 'EEEE, MMMM do, y', - long: 'MMMM do, y', - medium: 'MMM d, y', - short: 'MM/dd/yyyy' -}; -var timeFormats = { - full: 'h:mm:ss a zzzz', - long: 'h:mm:ss a z', - medium: 'h:mm:ss a', - short: 'h:mm a' -}; -var dateTimeFormats = { - full: "{{date}} 'at' {{time}}", - long: "{{date}} 'at' {{time}}", - medium: '{{date}}, {{time}}', - short: '{{date}}, {{time}}' -}; -var formatLong = { - date: (0, _index.default)({ - formats: dateFormats, - defaultWidth: 'full' - }), - time: (0, _index.default)({ - formats: timeFormats, - defaultWidth: 'full' - }), - dateTime: (0, _index.default)({ - formats: dateTimeFormats, - defaultWidth: 'full' - }) -}; -var _default = formatLong; -exports["default"] = _default; -module.exports = exports.default; +var _utils = __nccwpck_require__(21998); -/***/ }), +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -/***/ 52430: -/***/ ((module, exports) => { +class Hour0to23Parser extends _Parser.Parser { + constructor() { + super(...arguments); -"use strict"; + _defineProperty(this, "priority", 70); + _defineProperty(this, "incompatibleTokens", ['a', 'b', 'h', 'K', 'k', 't', 'T']); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var formatRelativeLocale = { - lastWeek: "'last' eeee 'at' p", - yesterday: "'yesterday at' p", - today: "'today at' p", - tomorrow: "'tomorrow at' p", - nextWeek: "eeee 'at' p", - other: 'P' -}; + parse(dateString, token, match) { + switch (token) { + case 'H': + return (0, _utils.parseNumericPattern)(_constants.numericPatterns.hour23h, dateString); -var formatRelative = function (token, _date, _baseDate, _options) { - return formatRelativeLocale[token]; -}; + case 'Ho': + return match.ordinalNumber(dateString, { + unit: 'hour' + }); -var _default = formatRelative; -exports["default"] = _default; -module.exports = exports.default; + default: + return (0, _utils.parseNDigits)(token.length, dateString); + } + } + + validate(_date, value) { + return value >= 0 && value <= 23; + } + + set(date, _flags, value) { + date.setUTCHours(value, 0, 0, 0); + return date; + } + +} + +exports.Hour0to23Parser = Hour0to23Parser; /***/ }), -/***/ 25474: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 11417: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -68851,164 +65025,58 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = void 0; - -var _index = _interopRequireDefault(__nccwpck_require__(13647)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +exports.Hour1To24Parser = void 0; -var eraValues = { - narrow: ['B', 'A'], - abbreviated: ['BC', 'AD'], - wide: ['Before Christ', 'Anno Domini'] -}; -var quarterValues = { - narrow: ['1', '2', '3', '4'], - abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'], - wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter'] -}; // Note: in English, the names of days of the week and months are capitalized. -// If you are making a new locale based on this one, check if the same is true for the language you're working on. -// Generally, formatted dates should look like they are in the middle of a sentence, -// e.g. in Spanish language the weekdays and months should be in the lowercase. +var _Parser = __nccwpck_require__(80583); -var monthValues = { - narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], - abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], - wide: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] -}; -var dayValues = { - narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'], - short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], - abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], - wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] -}; -var dayPeriodValues = { - narrow: { - am: 'a', - pm: 'p', - midnight: 'mi', - noon: 'n', - morning: 'morning', - afternoon: 'afternoon', - evening: 'evening', - night: 'night' - }, - abbreviated: { - am: 'AM', - pm: 'PM', - midnight: 'midnight', - noon: 'noon', - morning: 'morning', - afternoon: 'afternoon', - evening: 'evening', - night: 'night' - }, - wide: { - am: 'a.m.', - pm: 'p.m.', - midnight: 'midnight', - noon: 'noon', - morning: 'morning', - afternoon: 'afternoon', - evening: 'evening', - night: 'night' - } -}; -var formattingDayPeriodValues = { - narrow: { - am: 'a', - pm: 'p', - midnight: 'mi', - noon: 'n', - morning: 'in the morning', - afternoon: 'in the afternoon', - evening: 'in the evening', - night: 'at night' - }, - abbreviated: { - am: 'AM', - pm: 'PM', - midnight: 'midnight', - noon: 'noon', - morning: 'in the morning', - afternoon: 'in the afternoon', - evening: 'in the evening', - night: 'at night' - }, - wide: { - am: 'a.m.', - pm: 'p.m.', - midnight: 'midnight', - noon: 'noon', - morning: 'in the morning', - afternoon: 'in the afternoon', - evening: 'in the evening', - night: 'at night' - } -}; +var _constants = __nccwpck_require__(88829); -var ordinalNumber = function (dirtyNumber, _options) { - var number = Number(dirtyNumber); // If ordinal numbers depend on context, for example, - // if they are different for different grammatical genders, - // use `options.unit`. - // - // `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear', - // 'day', 'hour', 'minute', 'second'. +var _utils = __nccwpck_require__(21998); - var rem100 = number % 100; +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - if (rem100 > 20 || rem100 < 10) { - switch (rem100 % 10) { - case 1: - return number + 'st'; +class Hour1To24Parser extends _Parser.Parser { + constructor() { + super(...arguments); - case 2: - return number + 'nd'; + _defineProperty(this, "priority", 70); - case 3: - return number + 'rd'; - } + _defineProperty(this, "incompatibleTokens", ['a', 'b', 'h', 'H', 'K', 't', 'T']); } - return number + 'th'; -}; + parse(dateString, token, match) { + switch (token) { + case 'k': + return (0, _utils.parseNumericPattern)(_constants.numericPatterns.hour24h, dateString); -var localize = { - ordinalNumber: ordinalNumber, - era: (0, _index.default)({ - values: eraValues, - defaultWidth: 'wide' - }), - quarter: (0, _index.default)({ - values: quarterValues, - defaultWidth: 'wide', - argumentCallback: function (quarter) { - return quarter - 1; - } - }), - month: (0, _index.default)({ - values: monthValues, - defaultWidth: 'wide' - }), - day: (0, _index.default)({ - values: dayValues, - defaultWidth: 'wide' - }), - dayPeriod: (0, _index.default)({ - values: dayPeriodValues, - defaultWidth: 'wide', - formattingValues: formattingDayPeriodValues, - defaultFormattingWidth: 'wide' - }) -}; -var _default = localize; -exports["default"] = _default; -module.exports = exports.default; + case 'ko': + return match.ordinalNumber(dateString, { + unit: 'hour' + }); + + default: + return (0, _utils.parseNDigits)(token.length, dateString); + } + } + + validate(_date, value) { + return value >= 1 && value <= 24; + } + + set(date, _flags, value) { + var hours = value <= 24 ? value % 24 : value; + date.setUTCHours(hours, 0, 0, 0); + return date; + } + +} + +exports.Hour1To24Parser = Hour1To24Parser; /***/ }), -/***/ 91338: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 54747: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -69016,117 +65084,66 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = void 0; +exports.Hour1to12Parser = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(84029)); +var _Parser = __nccwpck_require__(80583); -var _index2 = _interopRequireDefault(__nccwpck_require__(23364)); +var _constants = __nccwpck_require__(88829); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _utils = __nccwpck_require__(21998); -var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i; -var parseOrdinalNumberPattern = /\d+/i; -var matchEraPatterns = { - narrow: /^(b|a)/i, - abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i, - wide: /^(before christ|before common era|anno domini|common era)/i -}; -var parseEraPatterns = { - any: [/^b/i, /^(a|c)/i] -}; -var matchQuarterPatterns = { - narrow: /^[1234]/i, - abbreviated: /^q[1234]/i, - wide: /^[1234](th|st|nd|rd)? quarter/i -}; -var parseQuarterPatterns = { - any: [/1/i, /2/i, /3/i, /4/i] -}; -var matchMonthPatterns = { - narrow: /^[jfmasond]/i, - abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i, - wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i -}; -var parseMonthPatterns = { - narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i], - any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i] -}; -var matchDayPatterns = { - narrow: /^[smtwf]/i, - short: /^(su|mo|tu|we|th|fr|sa)/i, - abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i, - wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i -}; -var parseDayPatterns = { - narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i], - any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i] -}; -var matchDayPeriodPatterns = { - narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i, - any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i -}; -var parseDayPeriodPatterns = { - any: { - am: /^a/i, - pm: /^p/i, - midnight: /^mi/i, - noon: /^no/i, - morning: /morning/i, - afternoon: /afternoon/i, - evening: /evening/i, - night: /night/i +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +class Hour1to12Parser extends _Parser.Parser { + constructor() { + super(...arguments); + + _defineProperty(this, "priority", 70); + + _defineProperty(this, "incompatibleTokens", ['H', 'K', 'k', 't', 'T']); } -}; -var match = { - ordinalNumber: (0, _index2.default)({ - matchPattern: matchOrdinalNumberPattern, - parsePattern: parseOrdinalNumberPattern, - valueCallback: function (value) { - return parseInt(value, 10); + + parse(dateString, token, match) { + switch (token) { + case 'h': + return (0, _utils.parseNumericPattern)(_constants.numericPatterns.hour12h, dateString); + + case 'ho': + return match.ordinalNumber(dateString, { + unit: 'hour' + }); + + default: + return (0, _utils.parseNDigits)(token.length, dateString); } - }), - era: (0, _index.default)({ - matchPatterns: matchEraPatterns, - defaultMatchWidth: 'wide', - parsePatterns: parseEraPatterns, - defaultParseWidth: 'any' - }), - quarter: (0, _index.default)({ - matchPatterns: matchQuarterPatterns, - defaultMatchWidth: 'wide', - parsePatterns: parseQuarterPatterns, - defaultParseWidth: 'any', - valueCallback: function (index) { - return index + 1; + } + + validate(_date, value) { + return value >= 1 && value <= 12; + } + + set(date, _flags, value) { + var isPM = date.getUTCHours() >= 12; + + if (isPM && value < 12) { + date.setUTCHours(value + 12, 0, 0, 0); + } else if (!isPM && value === 12) { + date.setUTCHours(0, 0, 0, 0); + } else { + date.setUTCHours(value, 0, 0, 0); } - }), - month: (0, _index.default)({ - matchPatterns: matchMonthPatterns, - defaultMatchWidth: 'wide', - parsePatterns: parseMonthPatterns, - defaultParseWidth: 'any' - }), - day: (0, _index.default)({ - matchPatterns: matchDayPatterns, - defaultMatchWidth: 'wide', - parsePatterns: parseDayPatterns, - defaultParseWidth: 'any' - }), - dayPeriod: (0, _index.default)({ - matchPatterns: matchDayPeriodPatterns, - defaultMatchWidth: 'any', - parsePatterns: parseDayPeriodPatterns, - defaultParseWidth: 'any' - }) -}; -var _default = match; -exports["default"] = _default; -module.exports = exports.default; + + return date; + } + +} + +exports.Hour1to12Parser = Hour1to12Parser; /***/ }), -/***/ 31773: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 7081: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -69134,118 +65151,117 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = void 0; +exports.ISODayParser = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(74846)); +var _Parser = __nccwpck_require__(80583); -var _index2 = _interopRequireDefault(__nccwpck_require__(20368)); +var _utils = __nccwpck_require__(21998); -var _index3 = _interopRequireDefault(__nccwpck_require__(52430)); +var _index = _interopRequireDefault(__nccwpck_require__(39729)); -var _index4 = _interopRequireDefault(__nccwpck_require__(25474)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index5 = _interopRequireDefault(__nccwpck_require__(91338)); +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +// ISO day of week +class ISODayParser extends _Parser.Parser { + constructor() { + super(...arguments); -/** - * @type {Locale} - * @category Locales - * @summary English locale (United States). - * @language English - * @iso-639-2 eng - * @author Sasha Koss [@kossnocorp]{@link /~https://github.com/kossnocorp} - * @author Lesha Koss [@leshakoss]{@link /~https://github.com/leshakoss} - */ -var locale = { - code: 'en-US', - formatDistance: _index.default, - formatLong: _index2.default, - formatRelative: _index3.default, - localize: _index4.default, - match: _index5.default, - options: { - weekStartsOn: 0 - /* Sunday */ - , - firstWeekContainsDate: 1 - } -}; -var _default = locale; -exports["default"] = _default; -module.exports = exports.default; + _defineProperty(this, "priority", 90); -/***/ }), + _defineProperty(this, "incompatibleTokens", ['y', 'Y', 'u', 'q', 'Q', 'M', 'L', 'w', 'd', 'D', 'E', 'e', 'c', 't', 'T']); + } -/***/ 35815: -/***/ ((module, exports, __nccwpck_require__) => { + parse(dateString, token, match) { + var valueCallback = function (value) { + if (value === 0) { + return 7; + } -"use strict"; + return value; + }; + switch (token) { + // 2 + case 'i': + case 'ii': + // 02 + return (0, _utils.parseNDigits)(token.length, dateString); + // 2nd -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = max; + case 'io': + return match.ordinalNumber(dateString, { + unit: 'day' + }); + // Tue -var _index = _interopRequireDefault(__nccwpck_require__(26477)); + case 'iii': + return (0, _utils.mapValue)(match.day(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }), valueCallback); + // T -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + case 'iiiii': + return (0, _utils.mapValue)(match.day(dateString, { + width: 'narrow', + context: 'formatting' + }), valueCallback); + // Tu -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + case 'iiiiii': + return (0, _utils.mapValue)(match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }), valueCallback); + // Tuesday -/** - * @name max - * @category Common Helpers - * @summary Return the latest of the given dates. - * - * @description - * Return the latest of the given dates. - * - * @param {Date[]|Number[]} datesArray - the dates to compare - * @returns {Date} the latest of the dates - * @throws {TypeError} 1 argument required - * - * @example - * // Which of these dates is the latest? - * const result = max([ - * new Date(1989, 6, 10), - * new Date(1987, 1, 11), - * new Date(1995, 6, 2), - * new Date(1990, 0, 1) - * ]) - * //=> Sun Jul 02 1995 00:00:00 - */ -function max(dirtyDatesArray) { - (0, _index2.default)(1, arguments); - var datesArray; // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method + case 'iiii': + default: + return (0, _utils.mapValue)(match.day(dateString, { + width: 'wide', + context: 'formatting' + }) || match.day(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }), valueCallback); + } + } - if (dirtyDatesArray && typeof dirtyDatesArray.forEach === 'function') { - datesArray = dirtyDatesArray; // If `dirtyDatesArray` is Array-like Object, convert to Array. - } else if (typeof dirtyDatesArray === 'object' && dirtyDatesArray !== null) { - datesArray = Array.prototype.slice.call(dirtyDatesArray); - } else { - // `dirtyDatesArray` is non-iterable, return Invalid Date - return new Date(NaN); + validate(_date, value) { + return value >= 1 && value <= 7; } - var result; - datesArray.forEach(function (dirtyDate) { - var currentDate = (0, _index.default)(dirtyDate); + set(date, _flags, value) { + date = (0, _index.default)(date, value); + date.setUTCHours(0, 0, 0, 0); + return date; + } - if (result === undefined || result < currentDate || isNaN(Number(currentDate))) { - result = currentDate; - } - }); - return result || new Date(NaN); } -module.exports = exports.default; +exports.ISODayParser = ISODayParser; /***/ }), -/***/ 96133: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 24592: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -69253,122 +65269,62 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = milliseconds; +exports.ISOTimezoneParser = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _Parser = __nccwpck_require__(80583); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _constants = __nccwpck_require__(88829); -// Leap year occures every 4 years, except for years that are divisable by 100 and not divisable by 400. -// 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days -var daysInYear = 365.2425; -/** - * @name milliseconds - * @category Millisecond Helpers - * @summary - * Returns the number of milliseconds in the specified, years, months, weeks, days, hours, minutes and seconds. - * - * @description - * Returns the number of milliseconds in the specified, years, months, weeks, days, hours, minutes and seconds. - * - * One years equals 365.2425 days according to the formula: - * - * > Leap year occures every 4 years, except for years that are divisable by 100 and not divisable by 400. - * > 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days - * - * One month is a year divided by 12. - * - * @param {Duration} duration - the object with years, months, weeks, days, hours, minutes and seconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. - * @returns {number} the milliseconds - * @throws {TypeError} 1 argument required - * - * @example - * // 1 year in milliseconds - * milliseconds({ years: 1 }) - * //=> 31556952000 - * - * // 3 months in milliseconds - * milliseconds({ months: 3 }) - * //=> 7889238000 - */ +var _utils = __nccwpck_require__(21998); -function milliseconds(_ref) { - var years = _ref.years, - months = _ref.months, - weeks = _ref.weeks, - days = _ref.days, - hours = _ref.hours, - minutes = _ref.minutes, - seconds = _ref.seconds; - (0, _index.default)(1, arguments); - var totalDays = 0; - if (years) totalDays += years * daysInYear; - if (months) totalDays += months * (daysInYear / 12); - if (weeks) totalDays += weeks * 7; - if (days) totalDays += days; - var totalSeconds = totalDays * 24 * 60 * 60; - if (hours) totalSeconds += hours * 60 * 60; - if (minutes) totalSeconds += minutes * 60; - if (seconds) totalSeconds += seconds; - return Math.round(totalSeconds * 1000); -} +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -module.exports = exports.default; +// Timezone (ISO-8601) +class ISOTimezoneParser extends _Parser.Parser { + constructor() { + super(...arguments); -/***/ }), + _defineProperty(this, "priority", 10); -/***/ 89571: -/***/ ((module, exports, __nccwpck_require__) => { + _defineProperty(this, "incompatibleTokens", ['t', 'T', 'X']); + } -"use strict"; + parse(dateString, token) { + switch (token) { + case 'x': + return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.basicOptionalMinutes, dateString); + case 'xx': + return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.basic, dateString); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = millisecondsToHours; + case 'xxxx': + return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.basicOptionalSeconds, dateString); -var _index = _interopRequireDefault(__nccwpck_require__(82063)); + case 'xxxxx': + return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.extendedOptionalSeconds, dateString); -var _index2 = __nccwpck_require__(25756); + case 'xxx': + default: + return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.extended, dateString); + } + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + set(date, flags, value) { + if (flags.timestampIsSet) { + return date; + } + + return new Date(date.getTime() - value); + } -/** - * @name millisecondsToHours - * @category Conversion Helpers - * @summary Convert milliseconds to hours. - * - * @description - * Convert a number of milliseconds to a full number of hours. - * - * @param {number} milliseconds - number of milliseconds to be converted - * - * @returns {number} the number of milliseconds converted in hours - * @throws {TypeError} 1 argument required - * - * @example - * // Convert 7200000 milliseconds to hours: - * const result = millisecondsToHours(7200000) - * //=> 2 - * - * @example - * // It uses floor rounding: - * const result = millisecondsToHours(7199999) - * //=> 1 - */ -function millisecondsToHours(milliseconds) { - (0, _index.default)(1, arguments); - var hours = milliseconds / _index2.millisecondsInHour; - return Math.floor(hours); } -module.exports = exports.default; +exports.ISOTimezoneParser = ISOTimezoneParser; /***/ }), -/***/ 5419: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 97010: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -69376,49 +65332,62 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = millisecondsToMinutes; +exports.ISOTimezoneWithZParser = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _Parser = __nccwpck_require__(80583); -var _index2 = __nccwpck_require__(25756); +var _constants = __nccwpck_require__(88829); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _utils = __nccwpck_require__(21998); + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +// Timezone (ISO-8601. +00:00 is `'Z'`) +class ISOTimezoneWithZParser extends _Parser.Parser { + constructor() { + super(...arguments); + + _defineProperty(this, "priority", 10); + + _defineProperty(this, "incompatibleTokens", ['t', 'T', 'x']); + } + + parse(dateString, token) { + switch (token) { + case 'X': + return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.basicOptionalMinutes, dateString); + + case 'XX': + return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.basic, dateString); + + case 'XXXX': + return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.basicOptionalSeconds, dateString); + + case 'XXXXX': + return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.extendedOptionalSeconds, dateString); + + case 'XXX': + default: + return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.extended, dateString); + } + } + + set(date, flags, value) { + if (flags.timestampIsSet) { + return date; + } + + return new Date(date.getTime() - value); + } -/** - * @name millisecondsToMinutes - * @category Conversion Helpers - * @summary Convert milliseconds to minutes. - * - * @description - * Convert a number of milliseconds to a full number of minutes. - * - * @param {number} milliseconds - number of milliseconds to be converted. - * - * @returns {number} the number of milliseconds converted in minutes - * @throws {TypeError} 1 argument required - * - * @example - * // Convert 60000 milliseconds to minutes: - * const result = millisecondsToMinutes(60000) - * //=> 1 - * - * @example - * // It uses floor rounding: - * const result = millisecondsToMinutes(119999) - * //=> 1 - */ -function millisecondsToMinutes(milliseconds) { - (0, _index.default)(1, arguments); - var minutes = milliseconds / _index2.millisecondsInMinute; - return Math.floor(minutes); } -module.exports = exports.default; +exports.ISOTimezoneWithZParser = ISOTimezoneWithZParser; /***/ }), -/***/ 42294: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 13137: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -69426,116 +65395,63 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = millisecondsToSeconds; - -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +exports.ISOWeekParser = void 0; -var _index2 = __nccwpck_require__(25756); +var _Parser = __nccwpck_require__(80583); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _constants = __nccwpck_require__(88829); -/** - * @name millisecondsToSeconds - * @category Conversion Helpers - * @summary Convert milliseconds to seconds. - * - * @description - * Convert a number of milliseconds to a full number of seconds. - * - * @param {number} milliseconds - number of milliseconds to be converted - * - * @returns {number} the number of milliseconds converted in seconds - * @throws {TypeError} 1 argument required - * - * @example - * // Convert 1000 miliseconds to seconds: - * const result = millisecondsToSeconds(1000) - * //=> 1 - * - * @example - * // It uses floor rounding: - * const result = millisecondsToSeconds(1999) - * //=> 1 - */ -function millisecondsToSeconds(milliseconds) { - (0, _index.default)(1, arguments); - var seconds = milliseconds / _index2.millisecondsInSecond; - return Math.floor(seconds); -} +var _utils = __nccwpck_require__(21998); -module.exports = exports.default; +var _index = _interopRequireDefault(__nccwpck_require__(48694)); -/***/ }), +var _index2 = _interopRequireDefault(__nccwpck_require__(6099)); -/***/ 45310: -/***/ ((module, exports, __nccwpck_require__) => { +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -"use strict"; +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +// ISO week of year +class ISOWeekParser extends _Parser.Parser { + constructor() { + super(...arguments); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = min; + _defineProperty(this, "priority", 100); -var _index = _interopRequireDefault(__nccwpck_require__(26477)); + _defineProperty(this, "incompatibleTokens", ['y', 'Y', 'u', 'q', 'Q', 'M', 'L', 'w', 'd', 'D', 'e', 'c', 't', 'T']); + } -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + parse(dateString, token, match) { + switch (token) { + case 'I': + return (0, _utils.parseNumericPattern)(_constants.numericPatterns.week, dateString); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + case 'Io': + return match.ordinalNumber(dateString, { + unit: 'week' + }); -/** - * @name min - * @category Common Helpers - * @summary Returns the earliest of the given dates. - * - * @description - * Returns the earliest of the given dates. - * - * @param {Date[]|Number[]} datesArray - the dates to compare - * @returns {Date} - the earliest of the dates - * @throws {TypeError} 1 argument required - * - * @example - * // Which of these dates is the earliest? - * const result = min([ - * new Date(1989, 6, 10), - * new Date(1987, 1, 11), - * new Date(1995, 6, 2), - * new Date(1990, 0, 1) - * ]) - * //=> Wed Feb 11 1987 00:00:00 - */ -function min(dirtyDatesArray) { - (0, _index2.default)(1, arguments); - var datesArray; // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method + default: + return (0, _utils.parseNDigits)(token.length, dateString); + } + } - if (dirtyDatesArray && typeof dirtyDatesArray.forEach === 'function') { - datesArray = dirtyDatesArray; // If `dirtyDatesArray` is Array-like Object, convert to Array. - } else if (typeof dirtyDatesArray === 'object' && dirtyDatesArray !== null) { - datesArray = Array.prototype.slice.call(dirtyDatesArray); - } else { - // `dirtyDatesArray` is non-iterable, return Invalid Date - return new Date(NaN); + validate(_date, value) { + return value >= 1 && value <= 53; } - var result; - datesArray.forEach(function (dirtyDate) { - var currentDate = (0, _index.default)(dirtyDate); + set(date, _flags, value) { + return (0, _index2.default)((0, _index.default)(date, value)); + } - if (result === undefined || result > currentDate || isNaN(currentDate.getDate())) { - result = currentDate; - } - }); - return result || new Date(NaN); } -module.exports = exports.default; +exports.ISOWeekParser = ISOWeekParser; /***/ }), -/***/ 52516: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 91802: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -69543,49 +65459,51 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = minutesToHours; +exports.ISOWeekYearParser = void 0; + +var _Parser = __nccwpck_require__(80583); -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _utils = __nccwpck_require__(21998); -var _index2 = __nccwpck_require__(25756); +var _index = _interopRequireDefault(__nccwpck_require__(6099)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/** - * @name minutesToHours - * @category Conversion Helpers - * @summary Convert minutes to hours. - * - * @description - * Convert a number of minutes to a full number of hours. - * - * @param {number} minutes - number of minutes to be converted - * - * @returns {number} the number of minutes converted in hours - * @throws {TypeError} 1 argument required - * - * @example - * // Convert 140 minutes to hours: - * const result = minutesToHours(120) - * //=> 2 - * - * @example - * // It uses floor rounding: - * const result = minutesToHours(179) - * //=> 2 - */ -function minutesToHours(minutes) { - (0, _index.default)(1, arguments); - var hours = minutes / _index2.minutesInHour; - return Math.floor(hours); +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +// ISO week-numbering year +class ISOWeekYearParser extends _Parser.Parser { + constructor() { + super(...arguments); + + _defineProperty(this, "priority", 130); + + _defineProperty(this, "incompatibleTokens", ['G', 'y', 'Y', 'u', 'Q', 'q', 'M', 'L', 'w', 'd', 'D', 'e', 'c', 't', 'T']); + } + + parse(dateString, token) { + if (token === 'R') { + return (0, _utils.parseNDigitsSigned)(4, dateString); + } + + return (0, _utils.parseNDigitsSigned)(token.length, dateString); + } + + set(_date, _flags, value) { + var firstWeekOfYear = new Date(0); + firstWeekOfYear.setUTCFullYear(value, 0, 4); + firstWeekOfYear.setUTCHours(0, 0, 0, 0); + return (0, _index.default)(firstWeekOfYear); + } + } -module.exports = exports.default; +exports.ISOWeekYearParser = ISOWeekYearParser; /***/ }), -/***/ 71886: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 11204: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -69593,87 +65511,114 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = minutesToMilliseconds; +exports.LocalDayParser = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _Parser = __nccwpck_require__(80583); -var _index2 = __nccwpck_require__(25756); +var _utils = __nccwpck_require__(21998); + +var _index = _interopRequireDefault(__nccwpck_require__(98879)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/** - * @name minutesToMilliseconds - * @category Conversion Helpers - * @summary Convert minutes to milliseconds. - * - * @description - * Convert a number of minutes to a full number of milliseconds. - * - * @param {number} minutes - number of minutes to be converted - * - * @returns {number} the number of minutes converted in milliseconds - * @throws {TypeError} 1 argument required - * - * @example - * // Convert 2 minutes to milliseconds - * const result = minutesToMilliseconds(2) - * //=> 120000 - */ -function minutesToMilliseconds(minutes) { - (0, _index.default)(1, arguments); - return Math.floor(minutes * _index2.millisecondsInMinute); -} +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -module.exports = exports.default; +// Local day of week +class LocalDayParser extends _Parser.Parser { + constructor() { + super(...arguments); -/***/ }), + _defineProperty(this, "priority", 90); -/***/ 48192: -/***/ ((module, exports, __nccwpck_require__) => { + _defineProperty(this, "incompatibleTokens", ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'E', 'i', 'c', 't', 'T']); + } -"use strict"; + parse(dateString, token, match, options) { + var valueCallback = function (value) { + var wholeWeekDays = Math.floor((value - 1) / 7) * 7; + return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays; + }; + switch (token) { + // 3 + case 'e': + case 'ee': + // 03 + return (0, _utils.mapValue)((0, _utils.parseNDigits)(token.length, dateString), valueCallback); + // 3rd -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = minutesToSeconds; + case 'eo': + return (0, _utils.mapValue)(match.ordinalNumber(dateString, { + unit: 'day' + }), valueCallback); + // Tue + + case 'eee': + return match.day(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }); + // T + + case 'eeeee': + return match.day(dateString, { + width: 'narrow', + context: 'formatting' + }); + // Tu + + case 'eeeeee': + return match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }); + // Tuesday -var _index = _interopRequireDefault(__nccwpck_require__(82063)); + case 'eeee': + default: + return match.day(dateString, { + width: 'wide', + context: 'formatting' + }) || match.day(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }); + } + } -var _index2 = __nccwpck_require__(25756); + validate(_date, value) { + return value >= 0 && value <= 6; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + set(date, _flags, value, options) { + date = (0, _index.default)(date, value, options); + date.setUTCHours(0, 0, 0, 0); + return date; + } -/** - * @name minutesToSeconds - * @category Conversion Helpers - * @summary Convert minutes to seconds. - * - * @description - * Convert a number of minutes to a full number of seconds. - * - * @param { number } minutes - number of minutes to be converted - * - * @returns {number} the number of minutes converted in seconds - * @throws {TypeError} 1 argument required - * - * @example - * // Convert 2 minutes to seconds - * const result = minutesToSeconds(2) - * //=> 120 - */ -function minutesToSeconds(minutes) { - (0, _index.default)(1, arguments); - return Math.floor(minutes * _index2.secondsInMinute); } -module.exports = exports.default; +exports.LocalDayParser = LocalDayParser; /***/ }), -/***/ 91142: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 73194: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -69681,98 +65626,63 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = monthsToQuarters; +exports.LocalWeekParser = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _Parser = __nccwpck_require__(80583); -var _index2 = __nccwpck_require__(25756); +var _constants = __nccwpck_require__(88829); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _utils = __nccwpck_require__(21998); -/** - * @name monthsToQuarters - * @category Conversion Helpers - * @summary Convert number of months to quarters. - * - * @description - * Convert a number of months to a full number of quarters. - * - * @param {number} months - number of months to be converted. - * - * @returns {number} the number of months converted in quarters - * @throws {TypeError} 1 argument required - * - * @example - * // Convert 6 months to quarters: - * const result = monthsToQuarters(6) - * //=> 2 - * - * @example - * // It uses floor rounding: - * const result = monthsToQuarters(7) - * //=> 2 - */ -function monthsToQuarters(months) { - (0, _index.default)(1, arguments); - var quarters = months / _index2.monthsInQuarter; - return Math.floor(quarters); -} +var _index = _interopRequireDefault(__nccwpck_require__(51974)); -module.exports = exports.default; +var _index2 = _interopRequireDefault(__nccwpck_require__(80694)); -/***/ }), +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ 73757: -/***/ ((module, exports, __nccwpck_require__) => { +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -"use strict"; +// Local week of year +class LocalWeekParser extends _Parser.Parser { + constructor() { + super(...arguments); + _defineProperty(this, "priority", 100); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = monthsToYears; + _defineProperty(this, "incompatibleTokens", ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'i', 't', 'T']); + } -var _index = _interopRequireDefault(__nccwpck_require__(82063)); + parse(dateString, token, match) { + switch (token) { + case 'w': + return (0, _utils.parseNumericPattern)(_constants.numericPatterns.week, dateString); -var _index2 = __nccwpck_require__(25756); + case 'wo': + return match.ordinalNumber(dateString, { + unit: 'week' + }); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + default: + return (0, _utils.parseNDigits)(token.length, dateString); + } + } + + validate(_date, value) { + return value >= 1 && value <= 53; + } + + set(date, _flags, value, options) { + return (0, _index2.default)((0, _index.default)(date, value, options), options); + } -/** - * @name monthsToYears - * @category Conversion Helpers - * @summary Convert number of months to years. - * - * @description - * Convert a number of months to a full number of years. - * - * @param {number} months - number of months to be converted - * - * @returns {number} the number of months converted in years - * @throws {TypeError} 1 argument required - * - * @example - * // Convert 36 months to years: - * const result = monthsToYears(36) - * //=> 3 - * - * // It uses floor rounding: - * const result = monthsToYears(40) - * //=> 3 - */ -function monthsToYears(months) { - (0, _index.default)(1, arguments); - var years = months / _index2.monthsInYear; - return Math.floor(years); } -module.exports = exports.default; +exports.LocalWeekParser = LocalWeekParser; /***/ }), -/***/ 46771: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 62161: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -69780,95 +65690,80 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = nextDay; - -var _index = _interopRequireDefault(__nccwpck_require__(56227)); +exports.LocalWeekYearParser = void 0; -var _index2 = _interopRequireDefault(__nccwpck_require__(9361)); +var _Parser = __nccwpck_require__(80583); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +var _utils = __nccwpck_require__(21998); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _index = _interopRequireDefault(__nccwpck_require__(5533)); -/** - * @name nextDay - * @category Weekday Helpers - * @summary When is the next day of the week? - * - * @description - * When is the next day of the week? 0-6 the day of the week, 0 represents Sunday. - * - * @param {Date | number} date - the date to check - * @param {Day} day - day of the week - * @returns {Date} - the date is the next day of week - * @throws {TypeError} - 2 arguments required - * - * @example - * // When is the next Monday after Mar, 20, 2020? - * const result = nextDay(new Date(2020, 2, 20), 1) - * //=> Mon Mar 23 2020 00:00:00 - * - * @example - * // When is the next Tuesday after Mar, 21, 2020? - * const result = nextDay(new Date(2020, 2, 21), 2) - * //=> Tue Mar 24 2020 00:00:00 - */ -function nextDay(date, day) { - (0, _index3.default)(2, arguments); - var delta = day - (0, _index2.default)(date); - if (delta <= 0) delta += 7; - return (0, _index.default)(date, delta); -} +var _index2 = _interopRequireDefault(__nccwpck_require__(80694)); -module.exports = exports.default; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ }), +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -/***/ 61491: -/***/ ((module, exports, __nccwpck_require__) => { +// Local week-numbering year +class LocalWeekYearParser extends _Parser.Parser { + constructor() { + super(...arguments); -"use strict"; + _defineProperty(this, "priority", 130); + _defineProperty(this, "incompatibleTokens", ['y', 'R', 'u', 'Q', 'q', 'M', 'L', 'I', 'd', 'D', 'i', 't', 'T']); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = nextFriday; + parse(dateString, token, match) { + var valueCallback = function (year) { + return { + year: year, + isTwoDigitYear: token === 'YY' + }; + }; -var _index = _interopRequireDefault(__nccwpck_require__(46771)); + switch (token) { + case 'Y': + return (0, _utils.mapValue)((0, _utils.parseNDigits)(4, dateString), valueCallback); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + case 'Yo': + return (0, _utils.mapValue)(match.ordinalNumber(dateString, { + unit: 'year' + }), valueCallback); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + default: + return (0, _utils.mapValue)((0, _utils.parseNDigits)(token.length, dateString), valueCallback); + } + } + + validate(_date, value) { + return value.isTwoDigitYear || value.year > 0; + } + + set(date, flags, value, options) { + var currentYear = (0, _index.default)(date, options); + + if (value.isTwoDigitYear) { + var normalizedTwoDigitYear = (0, _utils.normalizeTwoDigitYear)(value.year, currentYear); + date.setUTCFullYear(normalizedTwoDigitYear, 0, options.firstWeekContainsDate); + date.setUTCHours(0, 0, 0, 0); + return (0, _index2.default)(date, options); + } + + var year = !('era' in flags) || flags.era === 1 ? value.year : 1 - value.year; + date.setUTCFullYear(year, 0, options.firstWeekContainsDate); + date.setUTCHours(0, 0, 0, 0); + return (0, _index2.default)(date, options); + } -/** - * @name nextFriday - * @category Weekday Helpers - * @summary When is the next Friday? - * - * @description - * When is the next Friday? - * - * @param {Date | number} date - the date to start counting from - * @returns {Date} the next Friday - * @throws {TypeError} 1 argument required - * - * @example - * // When is the next Friday after Mar, 22, 2020? - * const result = nextFriday(new Date(2020, 2, 22)) - * //=> Fri Mar 27 2020 00:00:00 - */ -function nextFriday(date) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(date, 5); } -module.exports = exports.default; +exports.LocalWeekYearParser = LocalWeekYearParser; /***/ }), -/***/ 25947: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 41870: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -69876,85 +65771,57 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = nextMonday; - -var _index = _interopRequireDefault(__nccwpck_require__(46771)); +exports.MinuteParser = void 0; -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _Parser = __nccwpck_require__(80583); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _constants = __nccwpck_require__(88829); -/** - * @name nextMonday - * @category Weekday Helpers - * @summary When is the next Monday? - * - * @description - * When is the next Monday? - * - * @param {Date | number} date - the date to start counting from - * @returns {Date} the next Monday - * @throws {TypeError} 1 argument required - * - * @example - * // When is the next Monday after Mar, 22, 2020? - * const result = nextMonday(new Date(2020, 2, 22)) - * //=> Mon Mar 23 2020 00:00:00 - */ -function nextMonday(date) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(date, 1); -} +var _utils = __nccwpck_require__(21998); -module.exports = exports.default; +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -/***/ }), +class MinuteParser extends _Parser.Parser { + constructor() { + super(...arguments); -/***/ 363: -/***/ ((module, exports, __nccwpck_require__) => { + _defineProperty(this, "priority", 60); -"use strict"; + _defineProperty(this, "incompatibleTokens", ['t', 'T']); + } + parse(dateString, token, match) { + switch (token) { + case 'm': + return (0, _utils.parseNumericPattern)(_constants.numericPatterns.minute, dateString); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = nextSaturday; + case 'mo': + return match.ordinalNumber(dateString, { + unit: 'minute' + }); -var _index = _interopRequireDefault(__nccwpck_require__(46771)); + default: + return (0, _utils.parseNDigits)(token.length, dateString); + } + } -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + validate(_date, value) { + return value >= 0 && value <= 59; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + set(date, _flags, value) { + date.setUTCMinutes(value, 0, 0); + return date; + } -/** - * @name nextSaturday - * @category Weekday Helpers - * @summary When is the next Saturday? - * - * @description - * When is the next Saturday? - * - * @param {Date | number} date - the date to start counting from - * @returns {Date} the next Saturday - * @throws {TypeError} 1 argument required - * - * @example - * // When is the next Saturday after Mar, 22, 2020? - * const result = nextSaturday(new Date(2020, 2, 22)) - * //=> Sat Mar 28 2020 00:00:00 - */ -function nextSaturday(date) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(date, 6); } -module.exports = exports.default; +exports.MinuteParser = MinuteParser; /***/ }), -/***/ 17266: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 82711: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -69962,85 +65829,96 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = nextSunday; +exports.MonthParser = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(46771)); +var _utils = __nccwpck_require__(21998); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _Parser = __nccwpck_require__(80583); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _constants = __nccwpck_require__(88829); -/** - * @name nextSunday - * @category Weekday Helpers - * @summary When is the next Sunday? - * - * @description - * When is the next Sunday? - * - * @param {Date | number} date - the date to start counting from - * @returns {Date} the next Sunday - * @throws {TypeError} 1 argument required - * - * @example - * // When is the next Sunday after Mar, 22, 2020? - * const result = nextSunday(new Date(2020, 2, 22)) - * //=> Sun Mar 29 2020 00:00:00 - */ -function nextSunday(date) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(date, 0); -} +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -module.exports = exports.default; +class MonthParser extends _Parser.Parser { + constructor() { + super(...arguments); -/***/ }), + _defineProperty(this, "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'L', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']); -/***/ 9457: -/***/ ((module, exports, __nccwpck_require__) => { + _defineProperty(this, "priority", 110); + } -"use strict"; + parse(dateString, token, match) { + var valueCallback = function (value) { + return value - 1; + }; + switch (token) { + // 1, 2, ..., 12 + case 'M': + return (0, _utils.mapValue)((0, _utils.parseNumericPattern)(_constants.numericPatterns.month, dateString), valueCallback); + // 01, 02, ..., 12 -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = nextThursday; + case 'MM': + return (0, _utils.mapValue)((0, _utils.parseNDigits)(2, dateString), valueCallback); + // 1st, 2nd, ..., 12th -var _index = _interopRequireDefault(__nccwpck_require__(46771)); + case 'Mo': + return (0, _utils.mapValue)(match.ordinalNumber(dateString, { + unit: 'month' + }), valueCallback); + // Jan, Feb, ..., Dec -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + case 'MMM': + return match.month(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.month(dateString, { + width: 'narrow', + context: 'formatting' + }); + // J, F, ..., D -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + case 'MMMMM': + return match.month(dateString, { + width: 'narrow', + context: 'formatting' + }); + // January, February, ..., December + + case 'MMMM': + default: + return match.month(dateString, { + width: 'wide', + context: 'formatting' + }) || match.month(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.month(dateString, { + width: 'narrow', + context: 'formatting' + }); + } + } + + validate(_date, value) { + return value >= 0 && value <= 11; + } + + set(date, _flags, value) { + date.setUTCMonth(value, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + } -/** - * @name nextThursday - * @category Weekday Helpers - * @summary When is the next Thursday? - * - * @description - * When is the next Thursday? - * - * @param {Date | number} date - the date to start counting from - * @returns {Date} the next Thursday - * @throws {TypeError} 1 argument required - * - * @example - * // When is the next Thursday after Mar, 22, 2020? - * const result = nextThursday(new Date(2020, 2, 22)) - * //=> Thur Mar 26 2020 00:00:00 - */ -function nextThursday(date) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(date, 4); } -module.exports = exports.default; +exports.MonthParser = MonthParser; /***/ }), -/***/ 7894: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 55846: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -70048,84 +65926,87 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = nextTuesday; +exports.QuarterParser = void 0; -var _index = _interopRequireDefault(__nccwpck_require__(46771)); +var _Parser = __nccwpck_require__(80583); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _utils = __nccwpck_require__(21998); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -/** - * @name nextTuesday - * @category Weekday Helpers - * @summary When is the next Tuesday? - * - * @description - * When is the next Tuesday? - * - * @param {Date | number} date - the date to start counting from - * @returns {Date} the next Tuesday - * @throws {TypeError} 1 argument required - * - * @example - * // When is the next Tuesday after Mar, 22, 2020? - * const result = nextTuesday(new Date(2020, 2, 22)) - * //=> Tue Mar 24 2020 00:00:00 - */ -function nextTuesday(date) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(date, 2); -} +class QuarterParser extends _Parser.Parser { + constructor() { + super(...arguments); -module.exports = exports.default; + _defineProperty(this, "priority", 120); -/***/ }), + _defineProperty(this, "incompatibleTokens", ['Y', 'R', 'q', 'M', 'L', 'w', 'I', 'd', 'D', 'i', 'e', 'c', 't', 'T']); + } -/***/ 70029: -/***/ ((module, exports, __nccwpck_require__) => { + parse(dateString, token, match) { + switch (token) { + // 1, 2, 3, 4 + case 'Q': + case 'QQ': + // 01, 02, 03, 04 + return (0, _utils.parseNDigits)(token.length, dateString); + // 1st, 2nd, 3rd, 4th -"use strict"; + case 'Qo': + return match.ordinalNumber(dateString, { + unit: 'quarter' + }); + // Q1, Q2, Q3, Q4 + case 'QQQ': + return match.quarter(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.quarter(dateString, { + width: 'narrow', + context: 'formatting' + }); + // 1, 2, 3, 4 (narrow quarter; could be not numerical) -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = nextWednesday; + case 'QQQQQ': + return match.quarter(dateString, { + width: 'narrow', + context: 'formatting' + }); + // 1st quarter, 2nd quarter, ... -var _index = _interopRequireDefault(__nccwpck_require__(46771)); + case 'QQQQ': + default: + return match.quarter(dateString, { + width: 'wide', + context: 'formatting' + }) || match.quarter(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.quarter(dateString, { + width: 'narrow', + context: 'formatting' + }); + } + } -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + validate(_date, value) { + return value >= 1 && value <= 4; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + set(date, _flags, value) { + date.setUTCMonth((value - 1) * 3, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + } -/** - * @name nextWednesday - * @category Weekday Helpers - * @summary When is the next Wednesday? - * - * @description - * When is the next Wednesday? - * - * @param {Date | number} date - the date to start counting from - * @returns {Date} the next Wednesday - * @throws {TypeError} 1 argument required - * - * @example - * // When is the next Wednesday after Mar, 22, 2020? - * const result = nextWednesday(new Date(2020, 2, 22)) - * //=> Wed Mar 25 2020 00:00:00 - */ -function nextWednesday(date) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(date, 3); } -module.exports = exports.default; +exports.QuarterParser = QuarterParser; /***/ }), -/***/ 5619: +/***/ 4060: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -70134,46 +66015,57 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Parser = void 0; +exports.SecondParser = void 0; + +var _Parser = __nccwpck_require__(80583); -var _Setter = __nccwpck_require__(75665); +var _constants = __nccwpck_require__(88829); + +var _utils = __nccwpck_require__(21998); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -class Parser { +class SecondParser extends _Parser.Parser { constructor() { - _defineProperty(this, "incompatibleTokens", void 0); + super(...arguments); - _defineProperty(this, "priority", void 0); + _defineProperty(this, "priority", 50); - _defineProperty(this, "subPriority", void 0); + _defineProperty(this, "incompatibleTokens", ['t', 'T']); } - run(dateString, token, match, options) { - var result = this.parse(dateString, token, match, options); + parse(dateString, token, match) { + switch (token) { + case 's': + return (0, _utils.parseNumericPattern)(_constants.numericPatterns.second, dateString); - if (!result) { - return null; + case 'so': + return match.ordinalNumber(dateString, { + unit: 'second' + }); + + default: + return (0, _utils.parseNDigits)(token.length, dateString); } + } - return { - setter: new _Setter.ValueSetter(result.value, this.validate, this.set, this.priority, this.subPriority), - rest: result.rest - }; + validate(_date, value) { + return value >= 0 && value <= 59; } - validate(_utcDate, _value, _options) { - return true; + set(date, _flags, value) { + date.setUTCSeconds(value, 0); + return date; } } -exports.Parser = Parser; +exports.SecondParser = SecondParser; /***/ }), -/***/ 75665: -/***/ ((__unused_webpack_module, exports) => { +/***/ 76716: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -70181,140 +66073,113 @@ exports.Parser = Parser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DateToSystemTimezoneSetter = exports.ValueSetter = exports.Setter = void 0; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var TIMEZONE_UNIT_PRIORITY = 10; +exports.StandAloneLocalDayParser = void 0; -class Setter { - constructor() { - _defineProperty(this, "priority", void 0); +var _Parser = __nccwpck_require__(80583); - _defineProperty(this, "subPriority", 0); - } +var _utils = __nccwpck_require__(21998); - validate(_utcDate, _options) { - return true; - } +var _index = _interopRequireDefault(__nccwpck_require__(98879)); -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -exports.Setter = Setter; +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -class ValueSetter extends Setter { - constructor(value, validateValue, setValue, priority, subPriority) { - super(); - this.value = value; - this.validateValue = validateValue; - this.setValue = setValue; - this.priority = priority; +// Stand-alone local day of week +class StandAloneLocalDayParser extends _Parser.Parser { + constructor() { + super(...arguments); - if (subPriority) { - this.subPriority = subPriority; - } - } + _defineProperty(this, "priority", 90); - validate(utcDate, options) { - return this.validateValue(utcDate, this.value, options); + _defineProperty(this, "incompatibleTokens", ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'E', 'i', 'e', 't', 'T']); } - set(utcDate, flags, options) { - return this.setValue(utcDate, flags, this.value, options); - } + parse(dateString, token, match, options) { + var valueCallback = function (value) { + var wholeWeekDays = Math.floor((value - 1) / 7) * 7; + return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays; + }; -} + switch (token) { + // 3 + case 'c': + case 'cc': + // 03 + return (0, _utils.mapValue)((0, _utils.parseNDigits)(token.length, dateString), valueCallback); + // 3rd -exports.ValueSetter = ValueSetter; + case 'co': + return (0, _utils.mapValue)(match.ordinalNumber(dateString, { + unit: 'day' + }), valueCallback); + // Tue -class DateToSystemTimezoneSetter extends Setter { - constructor() { - super(...arguments); + case 'ccc': + return match.day(dateString, { + width: 'abbreviated', + context: 'standalone' + }) || match.day(dateString, { + width: 'short', + context: 'standalone' + }) || match.day(dateString, { + width: 'narrow', + context: 'standalone' + }); + // T - _defineProperty(this, "priority", TIMEZONE_UNIT_PRIORITY); + case 'ccccc': + return match.day(dateString, { + width: 'narrow', + context: 'standalone' + }); + // Tu - _defineProperty(this, "subPriority", -1); - } + case 'cccccc': + return match.day(dateString, { + width: 'short', + context: 'standalone' + }) || match.day(dateString, { + width: 'narrow', + context: 'standalone' + }); + // Tuesday - set(date, flags) { - if (flags.timestampIsSet) { - return date; + case 'cccc': + default: + return match.day(dateString, { + width: 'wide', + context: 'standalone' + }) || match.day(dateString, { + width: 'abbreviated', + context: 'standalone' + }) || match.day(dateString, { + width: 'short', + context: 'standalone' + }) || match.day(dateString, { + width: 'narrow', + context: 'standalone' + }); } - - var convertedDate = new Date(0); - convertedDate.setFullYear(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()); - convertedDate.setHours(date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()); - return convertedDate; } -} - -exports.DateToSystemTimezoneSetter = DateToSystemTimezoneSetter; - -/***/ }), - -/***/ 30463: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; + validate(_date, value) { + return value >= 0 && value <= 6; + } + set(date, _flags, value, options) { + date = (0, _index.default)(date, value, options); + date.setUTCHours(0, 0, 0, 0); + return date; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.timezonePatterns = exports.numericPatterns = void 0; -var numericPatterns = { - month: /^(1[0-2]|0?\d)/, - // 0 to 12 - date: /^(3[0-1]|[0-2]?\d)/, - // 0 to 31 - dayOfYear: /^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/, - // 0 to 366 - week: /^(5[0-3]|[0-4]?\d)/, - // 0 to 53 - hour23h: /^(2[0-3]|[0-1]?\d)/, - // 0 to 23 - hour24h: /^(2[0-4]|[0-1]?\d)/, - // 0 to 24 - hour11h: /^(1[0-1]|0?\d)/, - // 0 to 11 - hour12h: /^(1[0-2]|0?\d)/, - // 0 to 12 - minute: /^[0-5]?\d/, - // 0 to 59 - second: /^[0-5]?\d/, - // 0 to 59 - singleDigit: /^\d/, - // 0 to 9 - twoDigits: /^\d{1,2}/, - // 0 to 99 - threeDigits: /^\d{1,3}/, - // 0 to 999 - fourDigits: /^\d{1,4}/, - // 0 to 9999 - anyDigitsSigned: /^-?\d+/, - singleDigitSigned: /^-?\d/, - // 0 to 9, -0 to -9 - twoDigitsSigned: /^-?\d{1,2}/, - // 0 to 99, -0 to -99 - threeDigitsSigned: /^-?\d{1,3}/, - // 0 to 999, -0 to -999 - fourDigitsSigned: /^-?\d{1,4}/ // 0 to 9999, -0 to -9999 +} -}; -exports.numericPatterns = numericPatterns; -var timezonePatterns = { - basicOptionalMinutes: /^([+-])(\d{2})(\d{2})?|Z/, - basic: /^([+-])(\d{2})(\d{2})|Z/, - basicOptionalSeconds: /^([+-])(\d{2})(\d{2})((\d{2}))?|Z/, - extended: /^([+-])(\d{2}):(\d{2})|Z/, - extendedOptionalSeconds: /^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/ -}; -exports.timezonePatterns = timezonePatterns; +exports.StandAloneLocalDayParser = StandAloneLocalDayParser; /***/ }), -/***/ 19187: +/***/ 11853: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -70323,69 +66188,95 @@ exports.timezonePatterns = timezonePatterns; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AMPMMidnightParser = void 0; +exports.StandAloneMonthParser = void 0; + +var _Parser = __nccwpck_require__(80583); -var _Parser = __nccwpck_require__(5619); +var _constants = __nccwpck_require__(88829); -var _utils = __nccwpck_require__(59042); +var _utils = __nccwpck_require__(21998); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -class AMPMMidnightParser extends _Parser.Parser { +class StandAloneMonthParser extends _Parser.Parser { constructor() { super(...arguments); - _defineProperty(this, "priority", 80); + _defineProperty(this, "priority", 110); - _defineProperty(this, "incompatibleTokens", ['a', 'B', 'H', 'k', 't', 'T']); + _defineProperty(this, "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'M', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']); } parse(dateString, token, match) { + var valueCallback = function (value) { + return value - 1; + }; + switch (token) { - case 'b': - case 'bb': - case 'bbb': - return match.dayPeriod(dateString, { + // 1, 2, ..., 12 + case 'L': + return (0, _utils.mapValue)((0, _utils.parseNumericPattern)(_constants.numericPatterns.month, dateString), valueCallback); + // 01, 02, ..., 12 + + case 'LL': + return (0, _utils.mapValue)((0, _utils.parseNDigits)(2, dateString), valueCallback); + // 1st, 2nd, ..., 12th + + case 'Lo': + return (0, _utils.mapValue)(match.ordinalNumber(dateString, { + unit: 'month' + }), valueCallback); + // Jan, Feb, ..., Dec + + case 'LLL': + return match.month(dateString, { width: 'abbreviated', - context: 'formatting' - }) || match.dayPeriod(dateString, { + context: 'standalone' + }) || match.month(dateString, { width: 'narrow', - context: 'formatting' + context: 'standalone' }); + // J, F, ..., D - case 'bbbbb': - return match.dayPeriod(dateString, { + case 'LLLLL': + return match.month(dateString, { width: 'narrow', - context: 'formatting' + context: 'standalone' }); + // January, February, ..., December - case 'bbbb': + case 'LLLL': default: - return match.dayPeriod(dateString, { + return match.month(dateString, { width: 'wide', - context: 'formatting' - }) || match.dayPeriod(dateString, { + context: 'standalone' + }) || match.month(dateString, { width: 'abbreviated', - context: 'formatting' - }) || match.dayPeriod(dateString, { + context: 'standalone' + }) || match.month(dateString, { width: 'narrow', - context: 'formatting' + context: 'standalone' }); } } + validate(_date, value) { + return value >= 0 && value <= 11; + } + set(date, _flags, value) { - date.setUTCHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0); + date.setUTCMonth(value, 1); + date.setUTCHours(0, 0, 0, 0); return date; } } -exports.AMPMMidnightParser = AMPMMidnightParser; +exports.StandAloneMonthParser = StandAloneMonthParser; /***/ }), -/***/ 38678: +/***/ 75864: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -70394,69 +66285,87 @@ exports.AMPMMidnightParser = AMPMMidnightParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AMPMParser = void 0; +exports.StandAloneQuarterParser = void 0; -var _Parser = __nccwpck_require__(5619); +var _Parser = __nccwpck_require__(80583); -var _utils = __nccwpck_require__(59042); +var _utils = __nccwpck_require__(21998); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -class AMPMParser extends _Parser.Parser { +class StandAloneQuarterParser extends _Parser.Parser { constructor() { super(...arguments); - _defineProperty(this, "priority", 80); + _defineProperty(this, "priority", 120); - _defineProperty(this, "incompatibleTokens", ['b', 'B', 'H', 'k', 't', 'T']); + _defineProperty(this, "incompatibleTokens", ['Y', 'R', 'Q', 'M', 'L', 'w', 'I', 'd', 'D', 'i', 'e', 'c', 't', 'T']); } parse(dateString, token, match) { switch (token) { - case 'a': - case 'aa': - case 'aaa': - return match.dayPeriod(dateString, { + // 1, 2, 3, 4 + case 'q': + case 'qq': + // 01, 02, 03, 04 + return (0, _utils.parseNDigits)(token.length, dateString); + // 1st, 2nd, 3rd, 4th + + case 'qo': + return match.ordinalNumber(dateString, { + unit: 'quarter' + }); + // Q1, Q2, Q3, Q4 + + case 'qqq': + return match.quarter(dateString, { width: 'abbreviated', - context: 'formatting' - }) || match.dayPeriod(dateString, { + context: 'standalone' + }) || match.quarter(dateString, { width: 'narrow', - context: 'formatting' + context: 'standalone' }); + // 1, 2, 3, 4 (narrow quarter; could be not numerical) - case 'aaaaa': - return match.dayPeriod(dateString, { + case 'qqqqq': + return match.quarter(dateString, { width: 'narrow', - context: 'formatting' + context: 'standalone' }); + // 1st quarter, 2nd quarter, ... - case 'aaaa': + case 'qqqq': default: - return match.dayPeriod(dateString, { + return match.quarter(dateString, { width: 'wide', - context: 'formatting' - }) || match.dayPeriod(dateString, { + context: 'standalone' + }) || match.quarter(dateString, { width: 'abbreviated', - context: 'formatting' - }) || match.dayPeriod(dateString, { + context: 'standalone' + }) || match.quarter(dateString, { width: 'narrow', - context: 'formatting' + context: 'standalone' }); } } + validate(_date, value) { + return value >= 1 && value <= 4; + } + set(date, _flags, value) { - date.setUTCHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0); + date.setUTCMonth((value - 1) * 3, 1); + date.setUTCHours(0, 0, 0, 0); return date; } } -exports.AMPMParser = AMPMParser; +exports.StandAloneQuarterParser = StandAloneQuarterParser; /***/ }), -/***/ 64757: +/***/ 94574: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -70465,70 +66374,82 @@ exports.AMPMParser = AMPMParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DateParser = void 0; - -var _utils = __nccwpck_require__(59042); +exports.TimestampMillisecondsParser = void 0; -var _Parser = __nccwpck_require__(5619); +var _Parser = __nccwpck_require__(80583); -var _constants = __nccwpck_require__(30463); +var _utils = __nccwpck_require__(21998); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -var DAYS_IN_MONTH_LEAP_YEAR = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; // Day of the month - -class DateParser extends _Parser.Parser { +class TimestampMillisecondsParser extends _Parser.Parser { constructor() { super(...arguments); - _defineProperty(this, "priority", 90); + _defineProperty(this, "priority", 20); - _defineProperty(this, "subPriority", 1); + _defineProperty(this, "incompatibleTokens", '*'); + } - _defineProperty(this, "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']); + parse(dateString) { + return (0, _utils.parseAnyDigitsSigned)(dateString); } - parse(dateString, token, match) { - switch (token) { - case 'd': - return (0, _utils.parseNumericPattern)(_constants.numericPatterns.date, dateString); + set(_date, _flags, value) { + return [new Date(value), { + timestampIsSet: true + }]; + } - case 'do': - return match.ordinalNumber(dateString, { - unit: 'date' - }); +} - default: - return (0, _utils.parseNDigits)(token.length, dateString); - } - } +exports.TimestampMillisecondsParser = TimestampMillisecondsParser; - validate(date, value) { - var year = date.getUTCFullYear(); - var isLeapYear = (0, _utils.isLeapYearIndex)(year); - var month = date.getUTCMonth(); +/***/ }), - if (isLeapYear) { - return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month]; - } else { - return value >= 1 && value <= DAYS_IN_MONTH[month]; - } +/***/ 47301: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.TimestampSecondsParser = void 0; + +var _Parser = __nccwpck_require__(80583); + +var _utils = __nccwpck_require__(21998); + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +class TimestampSecondsParser extends _Parser.Parser { + constructor() { + super(...arguments); + + _defineProperty(this, "priority", 40); + + _defineProperty(this, "incompatibleTokens", '*'); } - set(date, _flags, value) { - date.setUTCDate(value); - date.setUTCHours(0, 0, 0, 0); - return date; + parse(dateString) { + return (0, _utils.parseAnyDigitsSigned)(dateString); + } + + set(_date, _flags, value) { + return [new Date(value * 1000), { + timestampIsSet: true + }]; } } -exports.DateParser = DateParser; +exports.TimestampSecondsParser = TimestampSecondsParser; /***/ }), -/***/ 17001: +/***/ 1994: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -70537,166 +66458,396 @@ exports.DateParser = DateParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DayOfYearParser = void 0; - -var _Parser = __nccwpck_require__(5619); +exports.YearParser = void 0; -var _constants = __nccwpck_require__(30463); +var _Parser = __nccwpck_require__(80583); -var _utils = __nccwpck_require__(59042); +var _utils = __nccwpck_require__(21998); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -class DayOfYearParser extends _Parser.Parser { +// From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns +// | Year | y | yy | yyy | yyyy | yyyyy | +// |----------|-------|----|-------|-------|-------| +// | AD 1 | 1 | 01 | 001 | 0001 | 00001 | +// | AD 12 | 12 | 12 | 012 | 0012 | 00012 | +// | AD 123 | 123 | 23 | 123 | 0123 | 00123 | +// | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 | +// | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 | +class YearParser extends _Parser.Parser { constructor() { super(...arguments); - _defineProperty(this, "priority", 90); - - _defineProperty(this, "subpriority", 1); + _defineProperty(this, "priority", 130); - _defineProperty(this, "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'M', 'L', 'w', 'I', 'd', 'E', 'i', 'e', 'c', 't', 'T']); + _defineProperty(this, "incompatibleTokens", ['Y', 'R', 'u', 'w', 'I', 'i', 'e', 'c', 't', 'T']); } parse(dateString, token, match) { + var valueCallback = function (year) { + return { + year: year, + isTwoDigitYear: token === 'yy' + }; + }; + switch (token) { - case 'D': - case 'DD': - return (0, _utils.parseNumericPattern)(_constants.numericPatterns.dayOfYear, dateString); + case 'y': + return (0, _utils.mapValue)((0, _utils.parseNDigits)(4, dateString), valueCallback); - case 'Do': - return match.ordinalNumber(dateString, { - unit: 'date' - }); + case 'yo': + return (0, _utils.mapValue)(match.ordinalNumber(dateString, { + unit: 'year' + }), valueCallback); default: - return (0, _utils.parseNDigits)(token.length, dateString); + return (0, _utils.mapValue)((0, _utils.parseNDigits)(token.length, dateString), valueCallback); } } - validate(date, value) { - var year = date.getUTCFullYear(); - var isLeapYear = (0, _utils.isLeapYearIndex)(year); + validate(_date, value) { + return value.isTwoDigitYear || value.year > 0; + } - if (isLeapYear) { - return value >= 1 && value <= 366; - } else { - return value >= 1 && value <= 365; + set(date, flags, value) { + var currentYear = date.getUTCFullYear(); + + if (value.isTwoDigitYear) { + var normalizedTwoDigitYear = (0, _utils.normalizeTwoDigitYear)(value.year, currentYear); + date.setUTCFullYear(normalizedTwoDigitYear, 0, 1); + date.setUTCHours(0, 0, 0, 0); + return date; } - } - set(date, _flags, value) { - date.setUTCMonth(0, value); + var year = !('era' in flags) || flags.era === 1 ? value.year : 1 - value.year; + date.setUTCFullYear(year, 0, 1); date.setUTCHours(0, 0, 0, 0); return date; } -} +} + +exports.YearParser = YearParser; + +/***/ }), + +/***/ 54077: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.parsers = void 0; + +var _EraParser = __nccwpck_require__(69166); + +var _YearParser = __nccwpck_require__(1994); + +var _LocalWeekYearParser = __nccwpck_require__(62161); + +var _ISOWeekYearParser = __nccwpck_require__(91802); + +var _ExtendedYearParser = __nccwpck_require__(37503); + +var _QuarterParser = __nccwpck_require__(55846); + +var _StandAloneQuarterParser = __nccwpck_require__(75864); + +var _MonthParser = __nccwpck_require__(82711); + +var _StandAloneMonthParser = __nccwpck_require__(11853); + +var _LocalWeekParser = __nccwpck_require__(73194); + +var _ISOWeekParser = __nccwpck_require__(13137); + +var _DateParser = __nccwpck_require__(65790); + +var _DayOfYearParser = __nccwpck_require__(31846); + +var _DayParser = __nccwpck_require__(63922); + +var _LocalDayParser = __nccwpck_require__(11204); + +var _StandAloneLocalDayParser = __nccwpck_require__(76716); + +var _ISODayParser = __nccwpck_require__(7081); + +var _AMPMParser = __nccwpck_require__(92518); + +var _AMPMMidnightParser = __nccwpck_require__(22240); + +var _DayPeriodParser = __nccwpck_require__(40973); + +var _Hour1to12Parser = __nccwpck_require__(54747); + +var _Hour0to23Parser = __nccwpck_require__(39360); + +var _Hour0To11Parser = __nccwpck_require__(97104); + +var _Hour1To24Parser = __nccwpck_require__(11417); + +var _MinuteParser = __nccwpck_require__(41870); + +var _SecondParser = __nccwpck_require__(4060); + +var _FractionOfSecondParser = __nccwpck_require__(82429); + +var _ISOTimezoneWithZParser = __nccwpck_require__(97010); + +var _ISOTimezoneParser = __nccwpck_require__(24592); + +var _TimestampSecondsParser = __nccwpck_require__(47301); + +var _TimestampMillisecondsParser = __nccwpck_require__(94574); + +/* + * | | Unit | | Unit | + * |-----|--------------------------------|-----|--------------------------------| + * | a | AM, PM | A* | Milliseconds in day | + * | b | AM, PM, noon, midnight | B | Flexible day period | + * | c | Stand-alone local day of week | C* | Localized hour w/ day period | + * | d | Day of month | D | Day of year | + * | e | Local day of week | E | Day of week | + * | f | | F* | Day of week in month | + * | g* | Modified Julian day | G | Era | + * | h | Hour [1-12] | H | Hour [0-23] | + * | i! | ISO day of week | I! | ISO week of year | + * | j* | Localized hour w/ day period | J* | Localized hour w/o day period | + * | k | Hour [1-24] | K | Hour [0-11] | + * | l* | (deprecated) | L | Stand-alone month | + * | m | Minute | M | Month | + * | n | | N | | + * | o! | Ordinal number modifier | O* | Timezone (GMT) | + * | p | | P | | + * | q | Stand-alone quarter | Q | Quarter | + * | r* | Related Gregorian year | R! | ISO week-numbering year | + * | s | Second | S | Fraction of second | + * | t! | Seconds timestamp | T! | Milliseconds timestamp | + * | u | Extended year | U* | Cyclic year | + * | v* | Timezone (generic non-locat.) | V* | Timezone (location) | + * | w | Local week of year | W* | Week of month | + * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) | + * | y | Year (abs) | Y | Local week-numbering year | + * | z* | Timezone (specific non-locat.) | Z* | Timezone (aliases) | + * + * Letters marked by * are not implemented but reserved by Unicode standard. + * + * Letters marked by ! are non-standard, but implemented by date-fns: + * - `o` modifies the previous token to turn it into an ordinal (see `parse` docs) + * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days, + * i.e. 7 for Sunday, 1 for Monday, etc. + * - `I` is ISO week of year, as opposed to `w` which is local week of year. + * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year. + * `R` is supposed to be used in conjunction with `I` and `i` + * for universal ISO week-numbering date, whereas + * `Y` is supposed to be used in conjunction with `w` and `e` + * for week-numbering date specific to the locale. + */ +var parsers = { + G: new _EraParser.EraParser(), + y: new _YearParser.YearParser(), + Y: new _LocalWeekYearParser.LocalWeekYearParser(), + R: new _ISOWeekYearParser.ISOWeekYearParser(), + u: new _ExtendedYearParser.ExtendedYearParser(), + Q: new _QuarterParser.QuarterParser(), + q: new _StandAloneQuarterParser.StandAloneQuarterParser(), + M: new _MonthParser.MonthParser(), + L: new _StandAloneMonthParser.StandAloneMonthParser(), + w: new _LocalWeekParser.LocalWeekParser(), + I: new _ISOWeekParser.ISOWeekParser(), + d: new _DateParser.DateParser(), + D: new _DayOfYearParser.DayOfYearParser(), + E: new _DayParser.DayParser(), + e: new _LocalDayParser.LocalDayParser(), + c: new _StandAloneLocalDayParser.StandAloneLocalDayParser(), + i: new _ISODayParser.ISODayParser(), + a: new _AMPMParser.AMPMParser(), + b: new _AMPMMidnightParser.AMPMMidnightParser(), + B: new _DayPeriodParser.DayPeriodParser(), + h: new _Hour1to12Parser.Hour1to12Parser(), + H: new _Hour0to23Parser.Hour0to23Parser(), + K: new _Hour0To11Parser.Hour0To11Parser(), + k: new _Hour1To24Parser.Hour1To24Parser(), + m: new _MinuteParser.MinuteParser(), + s: new _SecondParser.SecondParser(), + S: new _FractionOfSecondParser.FractionOfSecondParser(), + X: new _ISOTimezoneWithZParser.ISOTimezoneWithZParser(), + x: new _ISOTimezoneParser.ISOTimezoneParser(), + t: new _TimestampSecondsParser.TimestampSecondsParser(), + T: new _TimestampMillisecondsParser.TimestampMillisecondsParser() +}; +exports.parsers = parsers; + +/***/ }), + +/***/ 21998: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.mapValue = mapValue; +exports.parseNumericPattern = parseNumericPattern; +exports.parseTimezonePattern = parseTimezonePattern; +exports.parseAnyDigitsSigned = parseAnyDigitsSigned; +exports.parseNDigits = parseNDigits; +exports.parseNDigitsSigned = parseNDigitsSigned; +exports.dayPeriodEnumToHours = dayPeriodEnumToHours; +exports.normalizeTwoDigitYear = normalizeTwoDigitYear; +exports.isLeapYearIndex = isLeapYearIndex; + +var _index = __nccwpck_require__(24665); + +var _constants = __nccwpck_require__(88829); + +function mapValue(parseFnResult, mapFn) { + if (!parseFnResult) { + return parseFnResult; + } + + return { + value: mapFn(parseFnResult.value), + rest: parseFnResult.rest + }; +} + +function parseNumericPattern(pattern, dateString) { + var matchResult = dateString.match(pattern); + + if (!matchResult) { + return null; + } + + return { + value: parseInt(matchResult[0], 10), + rest: dateString.slice(matchResult[0].length) + }; +} + +function parseTimezonePattern(pattern, dateString) { + var matchResult = dateString.match(pattern); + + if (!matchResult) { + return null; + } // Input is 'Z' + -exports.DayOfYearParser = DayOfYearParser; + if (matchResult[0] === 'Z') { + return { + value: 0, + rest: dateString.slice(1) + }; + } -/***/ }), + var sign = matchResult[1] === '+' ? 1 : -1; + var hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0; + var minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0; + var seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0; + return { + value: sign * (hours * _index.millisecondsInHour + minutes * _index.millisecondsInMinute + seconds * _index.millisecondsInSecond), + rest: dateString.slice(matchResult[0].length) + }; +} -/***/ 72280: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function parseAnyDigitsSigned(dateString) { + return parseNumericPattern(_constants.numericPatterns.anyDigitsSigned, dateString); +} -"use strict"; +function parseNDigits(n, dateString) { + switch (n) { + case 1: + return parseNumericPattern(_constants.numericPatterns.singleDigit, dateString); + case 2: + return parseNumericPattern(_constants.numericPatterns.twoDigits, dateString); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.DayParser = void 0; + case 3: + return parseNumericPattern(_constants.numericPatterns.threeDigits, dateString); -var _Parser = __nccwpck_require__(5619); + case 4: + return parseNumericPattern(_constants.numericPatterns.fourDigits, dateString); -var _index = _interopRequireDefault(__nccwpck_require__(82694)); + default: + return parseNumericPattern(new RegExp('^\\d{1,' + n + '}'), dateString); + } +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function parseNDigitsSigned(n, dateString) { + switch (n) { + case 1: + return parseNumericPattern(_constants.numericPatterns.singleDigitSigned, dateString); -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + case 2: + return parseNumericPattern(_constants.numericPatterns.twoDigitsSigned, dateString); -// Day of week -class DayParser extends _Parser.Parser { - constructor() { - super(...arguments); + case 3: + return parseNumericPattern(_constants.numericPatterns.threeDigitsSigned, dateString); - _defineProperty(this, "priority", 90); + case 4: + return parseNumericPattern(_constants.numericPatterns.fourDigitsSigned, dateString); - _defineProperty(this, "incompatibleTokens", ['D', 'i', 'e', 'c', 't', 'T']); + default: + return parseNumericPattern(new RegExp('^-?\\d{1,' + n + '}'), dateString); } +} - parse(dateString, token, match) { - switch (token) { - // Tue - case 'E': - case 'EE': - case 'EEE': - return match.day(dateString, { - width: 'abbreviated', - context: 'formatting' - }) || match.day(dateString, { - width: 'short', - context: 'formatting' - }) || match.day(dateString, { - width: 'narrow', - context: 'formatting' - }); - // T +function dayPeriodEnumToHours(dayPeriod) { + switch (dayPeriod) { + case 'morning': + return 4; - case 'EEEEE': - return match.day(dateString, { - width: 'narrow', - context: 'formatting' - }); - // Tu + case 'evening': + return 17; - case 'EEEEEE': - return match.day(dateString, { - width: 'short', - context: 'formatting' - }) || match.day(dateString, { - width: 'narrow', - context: 'formatting' - }); - // Tuesday + case 'pm': + case 'noon': + case 'afternoon': + return 12; - case 'EEEE': - default: - return match.day(dateString, { - width: 'wide', - context: 'formatting' - }) || match.day(dateString, { - width: 'abbreviated', - context: 'formatting' - }) || match.day(dateString, { - width: 'short', - context: 'formatting' - }) || match.day(dateString, { - width: 'narrow', - context: 'formatting' - }); - } + case 'am': + case 'midnight': + case 'night': + default: + return 0; } +} - validate(_date, value) { - return value >= 0 && value <= 6; - } +function normalizeTwoDigitYear(twoDigitYear, currentYear) { + var isCommonEra = currentYear > 0; // Absolute number of the current year: + // 1 -> 1 AC + // 0 -> 1 BC + // -1 -> 2 BC - set(date, _flags, value, options) { - date = (0, _index.default)(date, value, options); - date.setUTCHours(0, 0, 0, 0); - return date; + var absCurrentYear = isCommonEra ? currentYear : 1 - currentYear; + var result; + + if (absCurrentYear <= 50) { + result = twoDigitYear || 100; + } else { + var rangeEnd = absCurrentYear + 50; + var rangeEndCentury = Math.floor(rangeEnd / 100) * 100; + var isPreviousCentury = twoDigitYear >= rangeEnd % 100; + result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0); } + return isCommonEra ? result : 1 - result; } -exports.DayParser = DayParser; +function isLeapYearIndex(year) { + return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0; +} /***/ }), -/***/ 29273: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 10435: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -70704,295 +66855,539 @@ exports.DayParser = DayParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DayPeriodParser = void 0; - -var _Parser = __nccwpck_require__(5619); - -var _utils = __nccwpck_require__(59042); - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -// in the morning, in the afternoon, in the evening, at night -class DayPeriodParser extends _Parser.Parser { - constructor() { - super(...arguments); +exports["default"] = parse; - _defineProperty(this, "priority", 80); +var _index = _interopRequireDefault(__nccwpck_require__(57143)); - _defineProperty(this, "incompatibleTokens", ['a', 'b', 't', 'T']); - } +var _index2 = _interopRequireDefault(__nccwpck_require__(88874)); - parse(dateString, token, match) { - switch (token) { - case 'B': - case 'BB': - case 'BBB': - return match.dayPeriod(dateString, { - width: 'abbreviated', - context: 'formatting' - }) || match.dayPeriod(dateString, { - width: 'narrow', - context: 'formatting' - }); +var _index3 = _interopRequireDefault(__nccwpck_require__(80603)); - case 'BBBBB': - return match.dayPeriod(dateString, { - width: 'narrow', - context: 'formatting' - }); +var _index4 = _interopRequireDefault(__nccwpck_require__(49829)); - case 'BBBB': - default: - return match.dayPeriod(dateString, { - width: 'wide', - context: 'formatting' - }) || match.dayPeriod(dateString, { - width: 'abbreviated', - context: 'formatting' - }) || match.dayPeriod(dateString, { - width: 'narrow', - context: 'formatting' - }); - } - } +var _index5 = _interopRequireDefault(__nccwpck_require__(58676)); - set(date, _flags, value) { - date.setUTCHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0); - return date; - } +var _index6 = _interopRequireDefault(__nccwpck_require__(8316)); -} +var _index7 = __nccwpck_require__(29030); -exports.DayPeriodParser = DayPeriodParser; +var _index8 = _interopRequireDefault(__nccwpck_require__(35279)); -/***/ }), +var _index9 = _interopRequireDefault(__nccwpck_require__(76822)); -/***/ 36309: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var _Setter = __nccwpck_require__(32005); -"use strict"; +var _index10 = __nccwpck_require__(54077); +var _index11 = __nccwpck_require__(79115); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.EraParser = void 0; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _Parser = __nccwpck_require__(5619); +// This RegExp consists of three parts separated by `|`: +// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token +// (one of the certain letters followed by `o`) +// - (\w)\1* matches any sequences of the same letter +// - '' matches two quote characters in a row +// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('), +// except a single quote symbol, which ends the sequence. +// Two quote characters do not end the sequence. +// If there is no matching single quote +// then the sequence will continue until the end of the string. +// - . matches any single character unmatched by previous parts of the RegExps +var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; // This RegExp catches symbols escaped by quotes, and also +// sequences of symbols P, p, and the combinations like `PPPPPPPppppp` -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g; +var escapedStringRegExp = /^'([^]*?)'?$/; +var doubleQuoteRegExp = /''/g; +var notWhitespaceRegExp = /\S/; +var unescapedLatinCharacterRegExp = /[a-zA-Z]/; +/** + * @name parse + * @category Common Helpers + * @summary Parse the date. + * + * @description + * Return the date parsed from string using the given format string. + * + * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries. + * > See: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * The characters in the format string wrapped between two single quotes characters (') are escaped. + * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. + * + * Format of the format string is based on Unicode Technical Standard #35: + * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table + * with a few additions (see note 5 below the table). + * + * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited + * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception: + * + * ```javascript + * parse('23 AM', 'HH a', new Date()) + * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time + * ``` + * + * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true + * + * Accepted format string patterns: + * | Unit |Prior| Pattern | Result examples | Notes | + * |---------------------------------|-----|---------|-----------------------------------|-------| + * | Era | 140 | G..GGG | AD, BC | | + * | | | GGGG | Anno Domini, Before Christ | 2 | + * | | | GGGGG | A, B | | + * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 | + * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 | + * | | | yy | 44, 01, 00, 17 | 4 | + * | | | yyy | 044, 001, 123, 999 | 4 | + * | | | yyyy | 0044, 0001, 1900, 2017 | 4 | + * | | | yyyyy | ... | 2,4 | + * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 | + * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 | + * | | | YY | 44, 01, 00, 17 | 4,6 | + * | | | YYY | 044, 001, 123, 999 | 4 | + * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 | + * | | | YYYYY | ... | 2,4 | + * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 | + * | | | RR | -43, 01, 00, 17 | 4,5 | + * | | | RRR | -043, 001, 123, 999, -999 | 4,5 | + * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 | + * | | | RRRRR | ... | 2,4,5 | + * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 | + * | | | uu | -43, 01, 99, -99 | 4 | + * | | | uuu | -043, 001, 123, 999, -999 | 4 | + * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 | + * | | | uuuuu | ... | 2,4 | + * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | | + * | | | Qo | 1st, 2nd, 3rd, 4th | 5 | + * | | | QQ | 01, 02, 03, 04 | | + * | | | QQQ | Q1, Q2, Q3, Q4 | | + * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 | + * | | | QQQQQ | 1, 2, 3, 4 | 4 | + * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | | + * | | | qo | 1st, 2nd, 3rd, 4th | 5 | + * | | | qq | 01, 02, 03, 04 | | + * | | | qqq | Q1, Q2, Q3, Q4 | | + * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 | + * | | | qqqqq | 1, 2, 3, 4 | 3 | + * | Month (formatting) | 110 | M | 1, 2, ..., 12 | | + * | | | Mo | 1st, 2nd, ..., 12th | 5 | + * | | | MM | 01, 02, ..., 12 | | + * | | | MMM | Jan, Feb, ..., Dec | | + * | | | MMMM | January, February, ..., December | 2 | + * | | | MMMMM | J, F, ..., D | | + * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | | + * | | | Lo | 1st, 2nd, ..., 12th | 5 | + * | | | LL | 01, 02, ..., 12 | | + * | | | LLL | Jan, Feb, ..., Dec | | + * | | | LLLL | January, February, ..., December | 2 | + * | | | LLLLL | J, F, ..., D | | + * | Local week of year | 100 | w | 1, 2, ..., 53 | | + * | | | wo | 1st, 2nd, ..., 53th | 5 | + * | | | ww | 01, 02, ..., 53 | | + * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 | + * | | | Io | 1st, 2nd, ..., 53th | 5 | + * | | | II | 01, 02, ..., 53 | 5 | + * | Day of month | 90 | d | 1, 2, ..., 31 | | + * | | | do | 1st, 2nd, ..., 31st | 5 | + * | | | dd | 01, 02, ..., 31 | | + * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 | + * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 | + * | | | DD | 01, 02, ..., 365, 366 | 7 | + * | | | DDD | 001, 002, ..., 365, 366 | | + * | | | DDDD | ... | 2 | + * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Sun | | + * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 | + * | | | EEEEE | M, T, W, T, F, S, S | | + * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | | + * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 | + * | | | io | 1st, 2nd, ..., 7th | 5 | + * | | | ii | 01, 02, ..., 07 | 5 | + * | | | iii | Mon, Tue, Wed, ..., Sun | 5 | + * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 | + * | | | iiiii | M, T, W, T, F, S, S | 5 | + * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 | + * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | | + * | | | eo | 2nd, 3rd, ..., 1st | 5 | + * | | | ee | 02, 03, ..., 01 | | + * | | | eee | Mon, Tue, Wed, ..., Sun | | + * | | | eeee | Monday, Tuesday, ..., Sunday | 2 | + * | | | eeeee | M, T, W, T, F, S, S | | + * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | | + * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | | + * | | | co | 2nd, 3rd, ..., 1st | 5 | + * | | | cc | 02, 03, ..., 01 | | + * | | | ccc | Mon, Tue, Wed, ..., Sun | | + * | | | cccc | Monday, Tuesday, ..., Sunday | 2 | + * | | | ccccc | M, T, W, T, F, S, S | | + * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | | + * | AM, PM | 80 | a..aaa | AM, PM | | + * | | | aaaa | a.m., p.m. | 2 | + * | | | aaaaa | a, p | | + * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | | + * | | | bbbb | a.m., p.m., noon, midnight | 2 | + * | | | bbbbb | a, p, n, mi | | + * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | | + * | | | BBBB | at night, in the morning, ... | 2 | + * | | | BBBBB | at night, in the morning, ... | | + * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | | + * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 | + * | | | hh | 01, 02, ..., 11, 12 | | + * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | | + * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 | + * | | | HH | 00, 01, 02, ..., 23 | | + * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | | + * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 | + * | | | KK | 01, 02, ..., 11, 00 | | + * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | | + * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 | + * | | | kk | 24, 01, 02, ..., 23 | | + * | Minute | 60 | m | 0, 1, ..., 59 | | + * | | | mo | 0th, 1st, ..., 59th | 5 | + * | | | mm | 00, 01, ..., 59 | | + * | Second | 50 | s | 0, 1, ..., 59 | | + * | | | so | 0th, 1st, ..., 59th | 5 | + * | | | ss | 00, 01, ..., 59 | | + * | Seconds timestamp | 40 | t | 512969520 | | + * | | | tt | ... | 2 | + * | Fraction of second | 30 | S | 0, 1, ..., 9 | | + * | | | SS | 00, 01, ..., 99 | | + * | | | SSS | 000, 001, ..., 999 | | + * | | | SSSS | ... | 2 | + * | Milliseconds timestamp | 20 | T | 512969520900 | | + * | | | TT | ... | 2 | + * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | | + * | | | XX | -0800, +0530, Z | | + * | | | XXX | -08:00, +05:30, Z | | + * | | | XXXX | -0800, +0530, Z, +123456 | 2 | + * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | | + * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | | + * | | | xx | -0800, +0530, +0000 | | + * | | | xxx | -08:00, +05:30, +00:00 | 2 | + * | | | xxxx | -0800, +0530, +0000, +123456 | | + * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | | + * | Long localized date | NA | P | 05/29/1453 | 5,8 | + * | | | PP | May 29, 1453 | | + * | | | PPP | May 29th, 1453 | | + * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 | + * | Long localized time | NA | p | 12:00 AM | 5,8 | + * | | | pp | 12:00:00 AM | | + * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | | + * | | | PPpp | May 29, 1453, 12:00:00 AM | | + * | | | PPPpp | May 29th, 1453 at ... | | + * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 | + * Notes: + * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale + * are the same as "stand-alone" units, but are different in some languages. + * "Formatting" units are declined according to the rules of the language + * in the context of a date. "Stand-alone" units are always nominative singular. + * In `format` function, they will produce different result: + * + * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'` + * + * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'` + * + * `parse` will try to match both formatting and stand-alone units interchangably. + * + * 2. Any sequence of the identical letters is a pattern, unless it is escaped by + * the single quote characters (see below). + * If the sequence is longer than listed in table: + * - for numerical units (`yyyyyyyy`) `parse` will try to match a number + * as wide as the sequence + * - for text units (`MMMMMMMM`) `parse` will try to match the widest variation of the unit. + * These variations are marked with "2" in the last column of the table. + * + * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales. + * These tokens represent the shortest form of the quarter. + * + * 4. The main difference between `y` and `u` patterns are B.C. years: + * + * | Year | `y` | `u` | + * |------|-----|-----| + * | AC 1 | 1 | 1 | + * | BC 1 | 1 | 0 | + * | BC 2 | 2 | -1 | + * + * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`: + * + * `parse('50', 'yy', new Date(2018, 0, 1)) //=> Sat Jan 01 2050 00:00:00` + * + * `parse('75', 'yy', new Date(2018, 0, 1)) //=> Wed Jan 01 1975 00:00:00` + * + * while `uu` will just assign the year as is: + * + * `parse('50', 'uu', new Date(2018, 0, 1)) //=> Sat Jan 01 0050 00:00:00` + * + * `parse('75', 'uu', new Date(2018, 0, 1)) //=> Tue Jan 01 0075 00:00:00` + * + * The same difference is true for local and ISO week-numbering years (`Y` and `R`), + * except local week-numbering years are dependent on `options.weekStartsOn` + * and `options.firstWeekContainsDate` (compare [setISOWeekYear]{@link https://date-fns.org/docs/setISOWeekYear} + * and [setWeekYear]{@link https://date-fns.org/docs/setWeekYear}). + * + * 5. These patterns are not in the Unicode Technical Standard #35: + * - `i`: ISO day of week + * - `I`: ISO week of year + * - `R`: ISO week-numbering year + * - `o`: ordinal number modifier + * - `P`: long localized date + * - `p`: long localized time + * + * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years. + * You should enable `options.useAdditionalWeekYearTokens` to use them. See: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * 7. `D` and `DD` tokens represent days of the year but they are ofthen confused with days of the month. + * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based + * on the given locale. + * + * using `en-US` locale: `P` => `MM/dd/yyyy` + * using `en-US` locale: `p` => `hh:mm a` + * using `pt-BR` locale: `P` => `dd/MM/yyyy` + * using `pt-BR` locale: `p` => `HH:mm` + * + * Values will be assigned to the date in the descending order of its unit's priority. + * Units of an equal priority overwrite each other in the order of appearance. + * + * If no values of higher priority are parsed (e.g. when parsing string 'January 1st' without a year), + * the values will be taken from 3rd argument `referenceDate` which works as a context of parsing. + * + * `referenceDate` must be passed for correct work of the function. + * If you're not sure which `referenceDate` to supply, create a new instance of Date: + * `parse('02/11/2014', 'MM/dd/yyyy', new Date())` + * In this case parsing will be done in the context of the current date. + * If `referenceDate` is `Invalid Date` or a value not convertible to valid `Date`, + * then `Invalid Date` will be returned. + * + * The result may vary by locale. + * + * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned. + * + * If parsing failed, `Invalid Date` will be returned. + * Invalid Date is a Date, whose time value is NaN. + * Time value of Date: http://es5.github.io/#x15.9.1.1 + * + * @param {String} dateString - the string to parse + * @param {String} formatString - the string of tokens + * @param {Date|Number} referenceDate - defines values missing from the parsed dateString + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year + * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`; + * see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`; + * see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @returns {Date} the parsed date + * @throws {TypeError} 3 arguments required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 + * @throws {RangeError} `options.locale` must contain `match` property + * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} format string contains an unescaped latin alphabet character + * + * @example + * // Parse 11 February 2014 from middle-endian format: + * var result = parse('02/11/2014', 'MM/dd/yyyy', new Date()) + * //=> Tue Feb 11 2014 00:00:00 + * + * @example + * // Parse 28th of February in Esperanto locale in the context of 2010 year: + * import eo from 'date-fns/locale/eo' + * var result = parse('28-a de februaro', "do 'de' MMMM", new Date(2010, 0, 1), { + * locale: eo + * }) + * //=> Sun Feb 28 2010 00:00:00 + */ -class EraParser extends _Parser.Parser { - constructor() { - super(...arguments); +function parse(dirtyDateString, dirtyFormatString, dirtyReferenceDate, options) { + var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4; - _defineProperty(this, "priority", 140); + (0, _index9.default)(3, arguments); + var dateString = String(dirtyDateString); + var formatString = String(dirtyFormatString); + var defaultOptions = (0, _index11.getDefaultOptions)(); + var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : _index.default; - _defineProperty(this, "incompatibleTokens", ['R', 'u', 't', 'T']); + if (!locale.match) { + throw new RangeError('locale must contain match property'); } - parse(dateString, token, match) { - switch (token) { - // AD, BC - case 'G': - case 'GG': - case 'GGG': - return match.era(dateString, { - width: 'abbreviated' - }) || match.era(dateString, { - width: 'narrow' - }); - // A, B - - case 'GGGGG': - return match.era(dateString, { - width: 'narrow' - }); - // Anno Domini, Before Christ - - case 'GGGG': - default: - return match.era(dateString, { - width: 'wide' - }) || match.era(dateString, { - width: 'abbreviated' - }) || match.era(dateString, { - width: 'narrow' - }); - } - } + var firstWeekContainsDate = (0, _index8.default)((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN - set(date, flags, value) { - flags.era = value; - date.setUTCFullYear(value, 0, 1); - date.setUTCHours(0, 0, 0, 0); - return date; + if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { + throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively'); } -} - -exports.EraParser = EraParser; - -/***/ }), - -/***/ 14754: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ExtendedYearParser = void 0; - -var _Parser = __nccwpck_require__(5619); - -var _utils = __nccwpck_require__(59042); - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -class ExtendedYearParser extends _Parser.Parser { - constructor() { - super(...arguments); - - _defineProperty(this, "priority", 130); + var weekStartsOn = (0, _index8.default)((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN - _defineProperty(this, "incompatibleTokens", ['G', 'y', 'Y', 'R', 'w', 'I', 'i', 'e', 'c', 't', 'T']); + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); } - parse(dateString, token) { - if (token === 'u') { - return (0, _utils.parseNDigitsSigned)(4, dateString); + if (formatString === '') { + if (dateString === '') { + return (0, _index3.default)(dirtyReferenceDate); + } else { + return new Date(NaN); } - - return (0, _utils.parseNDigitsSigned)(token.length, dateString); - } - - set(date, _flags, value) { - date.setUTCFullYear(value, 0, 1); - date.setUTCHours(0, 0, 0, 0); - return date; } -} - -exports.ExtendedYearParser = ExtendedYearParser; - -/***/ }), - -/***/ 75194: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.FractionOfSecondParser = void 0; + var subFnOptions = { + firstWeekContainsDate: firstWeekContainsDate, + weekStartsOn: weekStartsOn, + locale: locale + }; // If timezone isn't specified, it will be set to the system timezone -var _Parser = __nccwpck_require__(5619); + var setters = [new _Setter.DateToSystemTimezoneSetter()]; + var tokens = formatString.match(longFormattingTokensRegExp).map(function (substring) { + var firstCharacter = substring[0]; -var _utils = __nccwpck_require__(59042); + if (firstCharacter in _index5.default) { + var longFormatter = _index5.default[firstCharacter]; + return longFormatter(substring, locale.formatLong); + } -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + return substring; + }).join('').match(formattingTokensRegExp); + var usedTokens = []; -class FractionOfSecondParser extends _Parser.Parser { - constructor() { - super(...arguments); + var _loop = function (_token) { + if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && (0, _index7.isProtectedWeekYearToken)(_token)) { + (0, _index7.throwProtectedError)(_token, formatString, dirtyDateString); + } - _defineProperty(this, "priority", 30); + if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && (0, _index7.isProtectedDayOfYearToken)(_token)) { + (0, _index7.throwProtectedError)(_token, formatString, dirtyDateString); + } - _defineProperty(this, "incompatibleTokens", ['t', 'T']); - } + var firstCharacter = _token[0]; + var parser = _index10.parsers[firstCharacter]; - parse(dateString, token) { - var valueCallback = function (value) { - return Math.floor(value * Math.pow(10, -token.length + 3)); - }; + if (parser) { + var incompatibleTokens = parser.incompatibleTokens; - return (0, _utils.mapValue)((0, _utils.parseNDigits)(token.length, dateString), valueCallback); - } + if (Array.isArray(incompatibleTokens)) { + var incompatibleToken = usedTokens.find(function (usedToken) { + return incompatibleTokens.includes(usedToken.token) || usedToken.token === firstCharacter; + }); - set(date, _flags, value) { - date.setUTCMilliseconds(value); - return date; - } + if (incompatibleToken) { + throw new RangeError("The format string mustn't contain `".concat(incompatibleToken.fullToken, "` and `").concat(_token, "` at the same time")); + } + } else if (parser.incompatibleTokens === '*' && usedTokens.length > 0) { + throw new RangeError("The format string mustn't contain `".concat(_token, "` and any other token at the same time")); + } -} + usedTokens.push({ + token: firstCharacter, + fullToken: _token + }); + var parseResult = parser.run(dateString, _token, locale.match, subFnOptions); -exports.FractionOfSecondParser = FractionOfSecondParser; + if (!parseResult) { + token = _token; + return { + v: new Date(NaN) + }; + } -/***/ }), + setters.push(parseResult.setter); + dateString = parseResult.rest; + } else { + if (firstCharacter.match(unescapedLatinCharacterRegExp)) { + throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`'); + } // Replace two single quote characters with one single quote character -/***/ 323: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; + if (_token === "''") { + _token = "'"; + } else if (firstCharacter === "'") { + _token = cleanEscapedString(_token); + } // Cut token from string, or, if string doesn't match the token, return Invalid Date -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.Hour0To11Parser = void 0; + if (dateString.indexOf(_token) === 0) { + dateString = dateString.slice(_token.length); + } else { + token = _token; + return { + v: new Date(NaN) + }; + } + } -var _Parser = __nccwpck_require__(5619); + token = _token; + }; -var _constants = __nccwpck_require__(30463); + for (var token of tokens) { + var _ret = _loop(token); -var _utils = __nccwpck_require__(59042); + if (typeof _ret === "object") return _ret.v; + } // Check if the remaining input contains something other than whitespace -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -class Hour0To11Parser extends _Parser.Parser { - constructor() { - super(...arguments); + if (dateString.length > 0 && notWhitespaceRegExp.test(dateString)) { + return new Date(NaN); + } - _defineProperty(this, "priority", 70); + var uniquePrioritySetters = setters.map(function (setter) { + return setter.priority; + }).sort(function (a, b) { + return b - a; + }).filter(function (priority, index, array) { + return array.indexOf(priority) === index; + }).map(function (priority) { + return setters.filter(function (setter) { + return setter.priority === priority; + }).sort(function (a, b) { + return b.subPriority - a.subPriority; + }); + }).map(function (setterArray) { + return setterArray[0]; + }); + var date = (0, _index3.default)(dirtyReferenceDate); - _defineProperty(this, "incompatibleTokens", ['h', 'H', 'k', 't', 'T']); - } + if (isNaN(date.getTime())) { + return new Date(NaN); + } // Convert the date in system timezone to the same date in UTC+00:00 timezone. - parse(dateString, token, match) { - switch (token) { - case 'K': - return (0, _utils.parseNumericPattern)(_constants.numericPatterns.hour11h, dateString); - case 'Ko': - return match.ordinalNumber(dateString, { - unit: 'hour' - }); + var utcDate = (0, _index2.default)(date, (0, _index6.default)(date)); + var flags = {}; - default: - return (0, _utils.parseNDigits)(token.length, dateString); + for (var setter of uniquePrioritySetters) { + if (!setter.validate(utcDate, subFnOptions)) { + return new Date(NaN); } - } - validate(_date, value) { - return value >= 0 && value <= 11; - } - - set(date, _flags, value) { - var isPM = date.getUTCHours() >= 12; + var result = setter.set(utcDate, flags, subFnOptions); // Result is tuple (date, flags) - if (isPM && value < 12) { - date.setUTCHours(value + 12, 0, 0, 0); + if (Array.isArray(result)) { + utcDate = result[0]; + (0, _index4.default)(flags, result[1]); // Result is date } else { - date.setUTCHours(value, 0, 0, 0); + utcDate = result; } - - return date; } + return utcDate; } -exports.Hour0To11Parser = Hour0To11Parser; +function cleanEscapedString(input) { + return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'"); +} + +module.exports = exports.default; /***/ }), -/***/ 82610: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 78081: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -71000,301 +67395,286 @@ exports.Hour0To11Parser = Hour0To11Parser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Hour0to23Parser = void 0; +exports["default"] = parseISO; -var _Parser = __nccwpck_require__(5619); +var _index = __nccwpck_require__(24665); -var _constants = __nccwpck_require__(30463); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _utils = __nccwpck_require__(59042); +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -class Hour0to23Parser extends _Parser.Parser { - constructor() { - super(...arguments); +/** + * @name parseISO + * @category Common Helpers + * @summary Parse ISO string + * + * @description + * Parse the given string in ISO 8601 format and return an instance of Date. + * + * Function accepts complete ISO 8601 formats as well as partial implementations. + * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601 + * + * If the argument isn't a string, the function cannot parse the string or + * the values are invalid, it returns Invalid Date. + * + * @param {String} argument - the value to convert + * @param {Object} [options] - an object with options. + * @param {0|1|2} [options.additionalDigits=2] - the additional number of digits in the extended year format + * @returns {Date} the parsed date in the local time zone + * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2 + * + * @example + * // Convert string '2014-02-11T11:30:30' to date: + * const result = parseISO('2014-02-11T11:30:30') + * //=> Tue Feb 11 2014 11:30:30 + * + * @example + * // Convert string '+02014101' to date, + * // if the additional number of digits in the extended year format is 1: + * const result = parseISO('+02014101', { additionalDigits: 1 }) + * //=> Fri Apr 11 2014 00:00:00 + */ +function parseISO(argument, options) { + var _options$additionalDi; - _defineProperty(this, "priority", 70); + (0, _index2.default)(1, arguments); + var additionalDigits = (0, _index3.default)((_options$additionalDi = options === null || options === void 0 ? void 0 : options.additionalDigits) !== null && _options$additionalDi !== void 0 ? _options$additionalDi : 2); - _defineProperty(this, "incompatibleTokens", ['a', 'b', 'h', 'K', 'k', 't', 'T']); + if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) { + throw new RangeError('additionalDigits must be 0, 1 or 2'); } - parse(dateString, token, match) { - switch (token) { - case 'H': - return (0, _utils.parseNumericPattern)(_constants.numericPatterns.hour23h, dateString); - - case 'Ho': - return match.ordinalNumber(dateString, { - unit: 'hour' - }); - - default: - return (0, _utils.parseNDigits)(token.length, dateString); - } + if (!(typeof argument === 'string' || Object.prototype.toString.call(argument) === '[object String]')) { + return new Date(NaN); } - validate(_date, value) { - return value >= 0 && value <= 23; - } + var dateStrings = splitDateString(argument); + var date; - set(date, _flags, value) { - date.setUTCHours(value, 0, 0, 0); - return date; + if (dateStrings.date) { + var parseYearResult = parseYear(dateStrings.date, additionalDigits); + date = parseDate(parseYearResult.restDateString, parseYearResult.year); } -} - -exports.Hour0to23Parser = Hour0to23Parser; - -/***/ }), - -/***/ 25980: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.Hour1To24Parser = void 0; - -var _Parser = __nccwpck_require__(5619); - -var _constants = __nccwpck_require__(30463); - -var _utils = __nccwpck_require__(59042); - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -class Hour1To24Parser extends _Parser.Parser { - constructor() { - super(...arguments); - - _defineProperty(this, "priority", 70); - - _defineProperty(this, "incompatibleTokens", ['a', 'b', 'h', 'H', 'K', 't', 'T']); + if (!date || isNaN(date.getTime())) { + return new Date(NaN); } - parse(dateString, token, match) { - switch (token) { - case 'k': - return (0, _utils.parseNumericPattern)(_constants.numericPatterns.hour24h, dateString); + var timestamp = date.getTime(); + var time = 0; + var offset; - case 'ko': - return match.ordinalNumber(dateString, { - unit: 'hour' - }); + if (dateStrings.time) { + time = parseTime(dateStrings.time); - default: - return (0, _utils.parseNDigits)(token.length, dateString); + if (isNaN(time)) { + return new Date(NaN); } } - validate(_date, value) { - return value >= 1 && value <= 24; - } + if (dateStrings.timezone) { + offset = parseTimezone(dateStrings.timezone); - set(date, _flags, value) { - var hours = value <= 24 ? value % 24 : value; - date.setUTCHours(hours, 0, 0, 0); - return date; + if (isNaN(offset)) { + return new Date(NaN); + } + } else { + var dirtyDate = new Date(timestamp + time); // js parsed string assuming it's in UTC timezone + // but we need it to be parsed in our timezone + // so we use utc values to build date in our timezone. + // Year values from 0 to 99 map to the years 1900 to 1999 + // so set year explicitly with setFullYear. + + var result = new Date(0); + result.setFullYear(dirtyDate.getUTCFullYear(), dirtyDate.getUTCMonth(), dirtyDate.getUTCDate()); + result.setHours(dirtyDate.getUTCHours(), dirtyDate.getUTCMinutes(), dirtyDate.getUTCSeconds(), dirtyDate.getUTCMilliseconds()); + return result; } + return new Date(timestamp + time + offset); } -exports.Hour1To24Parser = Hour1To24Parser; - -/***/ }), - -/***/ 27929: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.Hour1to12Parser = void 0; - -var _Parser = __nccwpck_require__(5619); - -var _constants = __nccwpck_require__(30463); - -var _utils = __nccwpck_require__(59042); +var patterns = { + dateTimeDelimiter: /[T ]/, + timeZoneDelimiter: /[Z ]/i, + timezone: /([Z+-].*)$/ +}; +var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/; +var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/; +var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/; -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function splitDateString(dateString) { + var dateStrings = {}; + var array = dateString.split(patterns.dateTimeDelimiter); + var timeString; // The regex match should only return at maximum two array elements. + // [date], [time], or [date, time]. -class Hour1to12Parser extends _Parser.Parser { - constructor() { - super(...arguments); + if (array.length > 2) { + return dateStrings; + } - _defineProperty(this, "priority", 70); + if (/:/.test(array[0])) { + timeString = array[0]; + } else { + dateStrings.date = array[0]; + timeString = array[1]; - _defineProperty(this, "incompatibleTokens", ['H', 'K', 'k', 't', 'T']); + if (patterns.timeZoneDelimiter.test(dateStrings.date)) { + dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0]; + timeString = dateString.substr(dateStrings.date.length, dateString.length); + } } - parse(dateString, token, match) { - switch (token) { - case 'h': - return (0, _utils.parseNumericPattern)(_constants.numericPatterns.hour12h, dateString); - - case 'ho': - return match.ordinalNumber(dateString, { - unit: 'hour' - }); + if (timeString) { + var token = patterns.timezone.exec(timeString); - default: - return (0, _utils.parseNDigits)(token.length, dateString); + if (token) { + dateStrings.time = timeString.replace(token[1], ''); + dateStrings.timezone = token[1]; + } else { + dateStrings.time = timeString; } } - validate(_date, value) { - return value >= 1 && value <= 12; - } - - set(date, _flags, value) { - var isPM = date.getUTCHours() >= 12; + return dateStrings; +} - if (isPM && value < 12) { - date.setUTCHours(value + 12, 0, 0, 0); - } else if (!isPM && value === 12) { - date.setUTCHours(0, 0, 0, 0); - } else { - date.setUTCHours(value, 0, 0, 0); - } +function parseYear(dateString, additionalDigits) { + var regex = new RegExp('^(?:(\\d{4}|[+-]\\d{' + (4 + additionalDigits) + '})|(\\d{2}|[+-]\\d{' + (2 + additionalDigits) + '})$)'); + var captures = dateString.match(regex); // Invalid ISO-formatted year - return date; - } + if (!captures) return { + year: NaN, + restDateString: '' + }; + var year = captures[1] ? parseInt(captures[1]) : null; + var century = captures[2] ? parseInt(captures[2]) : null; // either year or century is null, not both + return { + year: century === null ? year : century * 100, + restDateString: dateString.slice((captures[1] || captures[2]).length) + }; } -exports.Hour1to12Parser = Hour1to12Parser; +function parseDate(dateString, year) { + // Invalid ISO-formatted year + if (year === null) return new Date(NaN); + var captures = dateString.match(dateRegex); // Invalid ISO-formatted string -/***/ }), + if (!captures) return new Date(NaN); + var isWeekDate = !!captures[4]; + var dayOfYear = parseDateUnit(captures[1]); + var month = parseDateUnit(captures[2]) - 1; + var day = parseDateUnit(captures[3]); + var week = parseDateUnit(captures[4]); + var dayOfWeek = parseDateUnit(captures[5]) - 1; -/***/ 96376: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (isWeekDate) { + if (!validateWeekDate(year, week, dayOfWeek)) { + return new Date(NaN); + } -"use strict"; + return dayOfISOWeekYear(year, week, dayOfWeek); + } else { + var date = new Date(0); + if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) { + return new Date(NaN); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ISODayParser = void 0; + date.setUTCFullYear(year, month, Math.max(dayOfYear, day)); + return date; + } +} -var _Parser = __nccwpck_require__(5619); +function parseDateUnit(value) { + return value ? parseInt(value) : 1; +} -var _utils = __nccwpck_require__(59042); +function parseTime(timeString) { + var captures = timeString.match(timeRegex); + if (!captures) return NaN; // Invalid ISO-formatted time -var _index = _interopRequireDefault(__nccwpck_require__(97985)); + var hours = parseTimeUnit(captures[1]); + var minutes = parseTimeUnit(captures[2]); + var seconds = parseTimeUnit(captures[3]); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (!validateTime(hours, minutes, seconds)) { + return NaN; + } -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + return hours * _index.millisecondsInHour + minutes * _index.millisecondsInMinute + seconds * 1000; +} -// ISO day of week -class ISODayParser extends _Parser.Parser { - constructor() { - super(...arguments); +function parseTimeUnit(value) { + return value && parseFloat(value.replace(',', '.')) || 0; +} - _defineProperty(this, "priority", 90); +function parseTimezone(timezoneString) { + if (timezoneString === 'Z') return 0; + var captures = timezoneString.match(timezoneRegex); + if (!captures) return 0; + var sign = captures[1] === '+' ? -1 : 1; + var hours = parseInt(captures[2]); + var minutes = captures[3] && parseInt(captures[3]) || 0; - _defineProperty(this, "incompatibleTokens", ['y', 'Y', 'u', 'q', 'Q', 'M', 'L', 'w', 'd', 'D', 'E', 'e', 'c', 't', 'T']); + if (!validateTimezone(hours, minutes)) { + return NaN; } - parse(dateString, token, match) { - var valueCallback = function (value) { - if (value === 0) { - return 7; - } + return sign * (hours * _index.millisecondsInHour + minutes * _index.millisecondsInMinute); +} - return value; - }; +function dayOfISOWeekYear(isoWeekYear, week, day) { + var date = new Date(0); + date.setUTCFullYear(isoWeekYear, 0, 4); + var fourthOfJanuaryDay = date.getUTCDay() || 7; + var diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay; + date.setUTCDate(date.getUTCDate() + diff); + return date; +} // Validation functions +// February is null to handle the leap year (using ||) - switch (token) { - // 2 - case 'i': - case 'ii': - // 02 - return (0, _utils.parseNDigits)(token.length, dateString); - // 2nd - case 'io': - return match.ordinalNumber(dateString, { - unit: 'day' - }); - // Tue +var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - case 'iii': - return (0, _utils.mapValue)(match.day(dateString, { - width: 'abbreviated', - context: 'formatting' - }) || match.day(dateString, { - width: 'short', - context: 'formatting' - }) || match.day(dateString, { - width: 'narrow', - context: 'formatting' - }), valueCallback); - // T +function isLeapYearIndex(year) { + return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0; +} - case 'iiiii': - return (0, _utils.mapValue)(match.day(dateString, { - width: 'narrow', - context: 'formatting' - }), valueCallback); - // Tu +function validateDate(year, month, date) { + return month >= 0 && month <= 11 && date >= 1 && date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28)); +} - case 'iiiiii': - return (0, _utils.mapValue)(match.day(dateString, { - width: 'short', - context: 'formatting' - }) || match.day(dateString, { - width: 'narrow', - context: 'formatting' - }), valueCallback); - // Tuesday +function validateDayOfYearDate(year, dayOfYear) { + return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365); +} - case 'iiii': - default: - return (0, _utils.mapValue)(match.day(dateString, { - width: 'wide', - context: 'formatting' - }) || match.day(dateString, { - width: 'abbreviated', - context: 'formatting' - }) || match.day(dateString, { - width: 'short', - context: 'formatting' - }) || match.day(dateString, { - width: 'narrow', - context: 'formatting' - }), valueCallback); - } - } +function validateWeekDate(_year, week, day) { + return week >= 1 && week <= 53 && day >= 0 && day <= 6; +} - validate(_date, value) { - return value >= 1 && value <= 7; +function validateTime(hours, minutes, seconds) { + if (hours === 24) { + return minutes === 0 && seconds === 0; } - set(date, _flags, value) { - date = (0, _index.default)(date, value); - date.setUTCHours(0, 0, 0, 0); - return date; - } + return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25; +} +function validateTimezone(_hours, minutes) { + return minutes >= 0 && minutes <= 59; } -exports.ISODayParser = ISODayParser; +module.exports = exports.default; /***/ }), -/***/ 69874: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 45183: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -71302,62 +67682,71 @@ exports.ISODayParser = ISODayParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ISOTimezoneParser = void 0; - -var _Parser = __nccwpck_require__(5619); - -var _constants = __nccwpck_require__(30463); - -var _utils = __nccwpck_require__(59042); - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -// Timezone (ISO-8601) -class ISOTimezoneParser extends _Parser.Parser { - constructor() { - super(...arguments); - - _defineProperty(this, "priority", 10); - - _defineProperty(this, "incompatibleTokens", ['t', 'T', 'X']); - } +exports["default"] = parseJSON; - parse(dateString, token) { - switch (token) { - case 'x': - return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.basicOptionalMinutes, dateString); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); - case 'xx': - return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.basic, dateString); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); - case 'xxxx': - return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.basicOptionalSeconds, dateString); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - case 'xxxxx': - return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.extendedOptionalSeconds, dateString); +/** + * @name parseJSON + * @category Common Helpers + * @summary Parse a JSON date string + * + * @description + * Converts a complete ISO date string in UTC time, the typical format for transmitting + * a date in JSON, to a JavaScript `Date` instance. + * + * This is a minimal implementation for converting dates retrieved from a JSON API to + * a `Date` instance which can be used with other functions in the `date-fns` library. + * The following formats are supported: + * + * - `2000-03-15T05:20:10.123Z`: The output of `.toISOString()` and `JSON.stringify(new Date())` + * - `2000-03-15T05:20:10Z`: Without milliseconds + * - `2000-03-15T05:20:10+00:00`: With a zero offset, the default JSON encoded format in some other languages + * - `2000-03-15T05:20:10+05:45`: With a positive or negative offset, the default JSON encoded format in some other languages + * - `2000-03-15T05:20:10+0000`: With a zero offset without a colon + * - `2000-03-15T05:20:10`: Without a trailing 'Z' symbol + * - `2000-03-15T05:20:10.1234567`: Up to 7 digits in milliseconds field. Only first 3 are taken into account since JS does not allow fractional milliseconds + * - `2000-03-15 05:20:10`: With a space instead of a 'T' separator for APIs returning a SQL date without reformatting + * + * For convenience and ease of use these other input types are also supported + * via [toDate]{@link https://date-fns.org/docs/toDate}: + * + * - A `Date` instance will be cloned + * - A `number` will be treated as a timestamp + * + * Any other input type or invalid date strings will return an `Invalid Date`. + * + * @param {String|Number|Date} argument A fully formed ISO8601 date string to convert + * @returns {Date} the parsed date in the local time zone + * @throws {TypeError} 1 argument required + */ +function parseJSON(argument) { + (0, _index2.default)(1, arguments); - case 'xxx': - default: - return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.extended, dateString); - } - } + if (typeof argument === 'string') { + var parts = argument.match(/(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{0,7}))?(?:Z|(.)(\d{2}):?(\d{2})?)?/); - set(date, flags, value) { - if (flags.timestampIsSet) { - return date; + if (parts) { + // Group 8 matches the sign + return new Date(Date.UTC(+parts[1], +parts[2] - 1, +parts[3], +parts[4] - (+parts[9] || 0) * (parts[8] == '-' ? -1 : 1), +parts[5] - (+parts[10] || 0) * (parts[8] == '-' ? -1 : 1), +parts[6], +((parts[7] || '0') + '00').substring(0, 3))); } - return new Date(date.getTime() - value); + return new Date(NaN); } + return (0, _index.default)(argument); } -exports.ISOTimezoneParser = ISOTimezoneParser; +module.exports = exports.default; /***/ }), -/***/ 9822: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 95896: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -71365,62 +67754,95 @@ exports.ISOTimezoneParser = ISOTimezoneParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ISOTimezoneWithZParser = void 0; +exports["default"] = previousDay; -var _Parser = __nccwpck_require__(5619); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _constants = __nccwpck_require__(30463); +var _index2 = _interopRequireDefault(__nccwpck_require__(99950)); -var _utils = __nccwpck_require__(59042); +var _index3 = _interopRequireDefault(__nccwpck_require__(80289)); -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -// Timezone (ISO-8601. +00:00 is `'Z'`) -class ISOTimezoneWithZParser extends _Parser.Parser { - constructor() { - super(...arguments); +/** + * @name previousDay + * @category Weekday Helpers + * @summary When is the previous day of the week? + * + * @description + * When is the previous day of the week? 0-6 the day of the week, 0 represents Sunday. + * + * @param {Date | number} date - the date to check + * @param {number} day - day of the week + * @returns {Date} - the date is the previous day of week + * @throws {TypeError} - 2 arguments required + * + * @example + * // When is the previous Monday before Mar, 20, 2020? + * const result = previousDay(new Date(2020, 2, 20), 1) + * //=> Mon Mar 16 2020 00:00:00 + * + * @example + * // When is the previous Tuesday before Mar, 21, 2020? + * const result = previousDay(new Date(2020, 2, 21), 2) + * //=> Tue Mar 17 2020 00:00:00 + */ +function previousDay(date, day) { + (0, _index.default)(2, arguments); + var delta = (0, _index2.default)(date) - day; + if (delta <= 0) delta += 7; + return (0, _index3.default)(date, delta); +} - _defineProperty(this, "priority", 10); +module.exports = exports.default; - _defineProperty(this, "incompatibleTokens", ['t', 'T', 'x']); - } +/***/ }), - parse(dateString, token) { - switch (token) { - case 'X': - return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.basicOptionalMinutes, dateString); +/***/ 58048: +/***/ ((module, exports, __nccwpck_require__) => { - case 'XX': - return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.basic, dateString); +"use strict"; - case 'XXXX': - return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.basicOptionalSeconds, dateString); - case 'XXXXX': - return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.extendedOptionalSeconds, dateString); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = previousFriday; - case 'XXX': - default: - return (0, _utils.parseTimezonePattern)(_constants.timezonePatterns.extended, dateString); - } - } +var _index = _interopRequireDefault(__nccwpck_require__(76822)); - set(date, flags, value) { - if (flags.timestampIsSet) { - return date; - } +var _index2 = _interopRequireDefault(__nccwpck_require__(95896)); - return new Date(date.getTime() - value); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/** + * @name previousFriday + * @category Weekday Helpers + * @summary When is the previous Friday? + * + * @description + * When is the previous Friday? + * + * @param {Date | number} date - the date to start counting from + * @returns {Date} the previous Friday + * @throws {TypeError} 1 argument required + * + * @example + * // When is the previous Friday before Jun, 19, 2021? + * const result = previousFriday(new Date(2021, 5, 19)) + * //=> Fri June 18 2021 00:00:00 + */ +function previousFriday(date) { + (0, _index.default)(1, arguments); + return (0, _index2.default)(date, 5); } -exports.ISOTimezoneWithZParser = ISOTimezoneWithZParser; +module.exports = exports.default; /***/ }), -/***/ 92127: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 57101: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -71428,63 +67850,85 @@ exports.ISOTimezoneWithZParser = ISOTimezoneWithZParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ISOWeekParser = void 0; - -var _Parser = __nccwpck_require__(5619); - -var _constants = __nccwpck_require__(30463); - -var _utils = __nccwpck_require__(59042); +exports["default"] = previousMonday; -var _index = _interopRequireDefault(__nccwpck_require__(88921)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = _interopRequireDefault(__nccwpck_require__(13061)); +var _index2 = _interopRequireDefault(__nccwpck_require__(95896)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +/** + * @name previousMonday + * @category Weekday Helpers + * @summary When is the previous Monday? + * + * @description + * When is the previous Monday? + * + * @param {Date | number} date - the date to start counting from + * @returns {Date} the previous Monday + * @throws {TypeError} 1 argument required + * + * @example + * // When is the previous Monday before Jun, 18, 2021? + * const result = previousMonday(new Date(2021, 5, 18)) + * //=> Mon June 14 2021 00:00:00 + */ +function previousMonday(date) { + (0, _index.default)(1, arguments); + return (0, _index2.default)(date, 1); +} -// ISO week of year -class ISOWeekParser extends _Parser.Parser { - constructor() { - super(...arguments); +module.exports = exports.default; - _defineProperty(this, "priority", 100); +/***/ }), - _defineProperty(this, "incompatibleTokens", ['y', 'Y', 'u', 'q', 'Q', 'M', 'L', 'w', 'd', 'D', 'e', 'c', 't', 'T']); - } +/***/ 50572: +/***/ ((module, exports, __nccwpck_require__) => { - parse(dateString, token, match) { - switch (token) { - case 'I': - return (0, _utils.parseNumericPattern)(_constants.numericPatterns.week, dateString); +"use strict"; - case 'Io': - return match.ordinalNumber(dateString, { - unit: 'week' - }); - default: - return (0, _utils.parseNDigits)(token.length, dateString); - } - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = previousSaturday; - validate(_date, value) { - return value >= 1 && value <= 53; - } +var _index = _interopRequireDefault(__nccwpck_require__(76822)); - set(date, _flags, value) { - return (0, _index2.default)((0, _index.default)(date, value)); - } +var _index2 = _interopRequireDefault(__nccwpck_require__(95896)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/** + * @name previousSaturday + * @category Weekday Helpers + * @summary When is the previous Saturday? + * + * @description + * When is the previous Saturday? + * + * @param {Date | number} date - the date to start counting from + * @returns {Date} the previous Saturday + * @throws {TypeError} 1 argument required + * + * @example + * // When is the previous Saturday before Jun, 20, 2021? + * const result = previousSaturday(new Date(2021, 5, 20)) + * //=> Sat June 19 2021 00:00:00 + */ +function previousSaturday(date) { + (0, _index.default)(1, arguments); + return (0, _index2.default)(date, 6); } -exports.ISOWeekParser = ISOWeekParser; +module.exports = exports.default; /***/ }), -/***/ 40519: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 71757: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -71492,51 +67936,42 @@ exports.ISOWeekParser = ISOWeekParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ISOWeekYearParser = void 0; - -var _Parser = __nccwpck_require__(5619); +exports["default"] = previousSunday; -var _utils = __nccwpck_require__(59042); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index = _interopRequireDefault(__nccwpck_require__(13061)); +var _index2 = _interopRequireDefault(__nccwpck_require__(95896)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -// ISO week-numbering year -class ISOWeekYearParser extends _Parser.Parser { - constructor() { - super(...arguments); - - _defineProperty(this, "priority", 130); - - _defineProperty(this, "incompatibleTokens", ['G', 'y', 'Y', 'u', 'Q', 'q', 'M', 'L', 'w', 'd', 'D', 'e', 'c', 't', 'T']); - } - - parse(dateString, token) { - if (token === 'R') { - return (0, _utils.parseNDigitsSigned)(4, dateString); - } - - return (0, _utils.parseNDigitsSigned)(token.length, dateString); - } - - set(_date, _flags, value) { - var firstWeekOfYear = new Date(0); - firstWeekOfYear.setUTCFullYear(value, 0, 4); - firstWeekOfYear.setUTCHours(0, 0, 0, 0); - return (0, _index.default)(firstWeekOfYear); - } - +/** + * @name previousSunday + * @category Weekday Helpers + * @summary When is the previous Sunday? + * + * @description + * When is the previous Sunday? + * + * @param {Date | number} date - the date to start counting from + * @returns {Date} the previous Sunday + * @throws {TypeError} 1 argument required + * + * @example + * // When is the previous Sunday before Jun, 21, 2021? + * const result = previousSunday(new Date(2021, 5, 21)) + * //=> Sun June 20 2021 00:00:00 + */ +function previousSunday(date) { + (0, _index.default)(1, arguments); + return (0, _index2.default)(date, 0); } -exports.ISOWeekYearParser = ISOWeekYearParser; +module.exports = exports.default; /***/ }), -/***/ 31190: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 89817: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -71544,114 +67979,85 @@ exports.ISOWeekYearParser = ISOWeekYearParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LocalDayParser = void 0; - -var _Parser = __nccwpck_require__(5619); +exports["default"] = previousThursday; -var _utils = __nccwpck_require__(59042); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index = _interopRequireDefault(__nccwpck_require__(82694)); +var _index2 = _interopRequireDefault(__nccwpck_require__(95896)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -// Local day of week -class LocalDayParser extends _Parser.Parser { - constructor() { - super(...arguments); - - _defineProperty(this, "priority", 90); - - _defineProperty(this, "incompatibleTokens", ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'E', 'i', 'c', 't', 'T']); - } +/** + * @name previousThursday + * @category Weekday Helpers + * @summary When is the previous Thursday? + * + * @description + * When is the previous Thursday? + * + * @param {Date | number} date - the date to start counting from + * @returns {Date} the previous Thursday + * @throws {TypeError} 1 argument required + * + * @example + * // When is the previous Thursday before Jun, 18, 2021? + * const result = previousThursday(new Date(2021, 5, 18)) + * //=> Thu June 17 2021 00:00:00 + */ +function previousThursday(date) { + (0, _index.default)(1, arguments); + return (0, _index2.default)(date, 4); +} - parse(dateString, token, match, options) { - var valueCallback = function (value) { - var wholeWeekDays = Math.floor((value - 1) / 7) * 7; - return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays; - }; +module.exports = exports.default; - switch (token) { - // 3 - case 'e': - case 'ee': - // 03 - return (0, _utils.mapValue)((0, _utils.parseNDigits)(token.length, dateString), valueCallback); - // 3rd +/***/ }), - case 'eo': - return (0, _utils.mapValue)(match.ordinalNumber(dateString, { - unit: 'day' - }), valueCallback); - // Tue +/***/ 7721: +/***/ ((module, exports, __nccwpck_require__) => { - case 'eee': - return match.day(dateString, { - width: 'abbreviated', - context: 'formatting' - }) || match.day(dateString, { - width: 'short', - context: 'formatting' - }) || match.day(dateString, { - width: 'narrow', - context: 'formatting' - }); - // T +"use strict"; - case 'eeeee': - return match.day(dateString, { - width: 'narrow', - context: 'formatting' - }); - // Tu - case 'eeeeee': - return match.day(dateString, { - width: 'short', - context: 'formatting' - }) || match.day(dateString, { - width: 'narrow', - context: 'formatting' - }); - // Tuesday +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = previousTuesday; - case 'eeee': - default: - return match.day(dateString, { - width: 'wide', - context: 'formatting' - }) || match.day(dateString, { - width: 'abbreviated', - context: 'formatting' - }) || match.day(dateString, { - width: 'short', - context: 'formatting' - }) || match.day(dateString, { - width: 'narrow', - context: 'formatting' - }); - } - } +var _index = _interopRequireDefault(__nccwpck_require__(76822)); - validate(_date, value) { - return value >= 0 && value <= 6; - } +var _index2 = _interopRequireDefault(__nccwpck_require__(95896)); - set(date, _flags, value, options) { - date = (0, _index.default)(date, value, options); - date.setUTCHours(0, 0, 0, 0); - return date; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/** + * @name previousTuesday + * @category Weekday Helpers + * @summary When is the previous Tuesday? + * + * @description + * When is the previous Tuesday? + * + * @param {Date | number} date - the date to start counting from + * @returns {Date} the previous Tuesday + * @throws {TypeError} 1 argument required + * + * @example + * // When is the previous Tuesday before Jun, 18, 2021? + * const result = previousTuesday(new Date(2021, 5, 18)) + * //=> Tue June 15 2021 00:00:00 + */ +function previousTuesday(date) { + (0, _index.default)(1, arguments); + return (0, _index2.default)(date, 2); } -exports.LocalDayParser = LocalDayParser; +module.exports = exports.default; /***/ }), -/***/ 76125: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 90754: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -71659,63 +68065,42 @@ exports.LocalDayParser = LocalDayParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LocalWeekParser = void 0; - -var _Parser = __nccwpck_require__(5619); - -var _constants = __nccwpck_require__(30463); - -var _utils = __nccwpck_require__(59042); +exports["default"] = previousWednesday; -var _index = _interopRequireDefault(__nccwpck_require__(53285)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82258)); +var _index2 = _interopRequireDefault(__nccwpck_require__(95896)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -// Local week of year -class LocalWeekParser extends _Parser.Parser { - constructor() { - super(...arguments); - - _defineProperty(this, "priority", 100); - - _defineProperty(this, "incompatibleTokens", ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'i', 't', 'T']); - } - - parse(dateString, token, match) { - switch (token) { - case 'w': - return (0, _utils.parseNumericPattern)(_constants.numericPatterns.week, dateString); - - case 'wo': - return match.ordinalNumber(dateString, { - unit: 'week' - }); - - default: - return (0, _utils.parseNDigits)(token.length, dateString); - } - } - - validate(_date, value) { - return value >= 1 && value <= 53; - } - - set(date, _flags, value, options) { - return (0, _index2.default)((0, _index.default)(date, value, options), options); - } - +/** + * @name previousWednesday + * @category Weekday Helpers + * @summary When is the previous Wednesday? + * + * @description + * When is the previous Wednesday? + * + * @param {Date | number} date - the date to start counting from + * @returns {Date} the previous Wednesday + * @throws {TypeError} 1 argument required + * + * @example + * // When is the previous Wednesday before Jun, 18, 2021? + * const result = previousWednesday(new Date(2021, 5, 18)) + * //=> Wed June 16 2021 00:00:00 + */ +function previousWednesday(date) { + (0, _index.default)(1, arguments); + return (0, _index2.default)(date, 3); } -exports.LocalWeekParser = LocalWeekParser; +module.exports = exports.default; /***/ }), -/***/ 90085: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 62381: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -71723,80 +68108,93 @@ exports.LocalWeekParser = LocalWeekParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LocalWeekYearParser = void 0; - -var _Parser = __nccwpck_require__(5619); - -var _utils = __nccwpck_require__(59042); +exports["default"] = quartersToMonths; -var _index = _interopRequireDefault(__nccwpck_require__(78050)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82258)); +var _index2 = __nccwpck_require__(24665); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -// Local week-numbering year -class LocalWeekYearParser extends _Parser.Parser { - constructor() { - super(...arguments); - - _defineProperty(this, "priority", 130); +/** + * @name quartersToMonths + * @category Conversion Helpers + * @summary Convert number of quarters to months. + * + * @description + * Convert a number of quarters to a full number of months. + * + * @param {number} quarters - number of quarters to be converted + * + * @returns {number} the number of quarters converted in months + * @throws {TypeError} 1 argument required + * + * @example + * // Convert 2 quarters to months + * const result = quartersToMonths(2) + * //=> 6 + */ +function quartersToMonths(quarters) { + (0, _index.default)(1, arguments); + return Math.floor(quarters * _index2.monthsInQuarter); +} - _defineProperty(this, "incompatibleTokens", ['y', 'R', 'u', 'Q', 'q', 'M', 'L', 'I', 'd', 'D', 'i', 't', 'T']); - } +module.exports = exports.default; - parse(dateString, token, match) { - var valueCallback = function (year) { - return { - year: year, - isTwoDigitYear: token === 'YY' - }; - }; +/***/ }), - switch (token) { - case 'Y': - return (0, _utils.mapValue)((0, _utils.parseNDigits)(4, dateString), valueCallback); +/***/ 97483: +/***/ ((module, exports, __nccwpck_require__) => { - case 'Yo': - return (0, _utils.mapValue)(match.ordinalNumber(dateString, { - unit: 'year' - }), valueCallback); +"use strict"; - default: - return (0, _utils.mapValue)((0, _utils.parseNDigits)(token.length, dateString), valueCallback); - } - } - validate(_date, value) { - return value.isTwoDigitYear || value.year > 0; - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = quartersToYears; - set(date, flags, value, options) { - var currentYear = (0, _index.default)(date, options); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); - if (value.isTwoDigitYear) { - var normalizedTwoDigitYear = (0, _utils.normalizeTwoDigitYear)(value.year, currentYear); - date.setUTCFullYear(normalizedTwoDigitYear, 0, options.firstWeekContainsDate); - date.setUTCHours(0, 0, 0, 0); - return (0, _index2.default)(date, options); - } +var _index2 = __nccwpck_require__(24665); - var year = !('era' in flags) || flags.era === 1 ? value.year : 1 - value.year; - date.setUTCFullYear(year, 0, options.firstWeekContainsDate); - date.setUTCHours(0, 0, 0, 0); - return (0, _index2.default)(date, options); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/** + * @name quartersToYears + * @category Conversion Helpers + * @summary Convert number of quarters to years. + * + * @description + * Convert a number of quarters to a full number of years. + * + * @param {number} quarters - number of quarters to be converted + * + * @returns {number} the number of quarters converted in years + * @throws {TypeError} 1 argument required + * + * @example + * // Convert 8 quarters to years + * const result = quartersToYears(8) + * //=> 2 + * + * @example + * // It uses floor rounding: + * const result = quartersToYears(11) + * //=> 2 + */ +function quartersToYears(quarters) { + (0, _index.default)(1, arguments); + var years = quarters / _index2.quartersInYear; + return Math.floor(years); } -exports.LocalWeekYearParser = LocalWeekYearParser; +module.exports = exports.default; /***/ }), -/***/ 84254: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 13854: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -71804,57 +68202,74 @@ exports.LocalWeekYearParser = LocalWeekYearParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MinuteParser = void 0; - -var _Parser = __nccwpck_require__(5619); +exports["default"] = roundToNearestMinutes; -var _constants = __nccwpck_require__(30463); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _utils = __nccwpck_require__(59042); +var _index2 = __nccwpck_require__(38860); -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); -class MinuteParser extends _Parser.Parser { - constructor() { - super(...arguments); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - _defineProperty(this, "priority", 60); +/** + * @name roundToNearestMinutes + * @category Minute Helpers + * @summary Rounds the given date to the nearest minute + * + * @description + * Rounds the given date to the nearest minute (or number of minutes). + * Rounds up when the given date is exactly between the nearest round minutes. + * + * @param {Date|Number} date - the date to round + * @param {Object} [options] - an object with options. + * @param {Number} [options.nearestTo=1] - nearest number of minutes to round to. E.g. `15` to round to quarter hours. + * @param {String} [options.roundingMethod='trunc'] - a rounding method (`ceil`, `floor`, `round` or `trunc`) + * @returns {Date} the new date rounded to the closest minute + * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.nearestTo` must be between 1 and 30 + * + * @example + * // Round 10 July 2014 12:12:34 to nearest minute: + * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34)) + * //=> Thu Jul 10 2014 12:13:00 + * + * @example + * // Round 10 July 2014 12:07:30 to nearest quarter hour: + * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { nearestTo: 15 }) + * // rounds up because given date is exactly between 12:00:00 and 12:15:00 + * //=> Thu Jul 10 2014 12:15:00 + */ +function roundToNearestMinutes(dirtyDate, options) { + var _options$nearestTo; - _defineProperty(this, "incompatibleTokens", ['t', 'T']); + if (arguments.length < 1) { + throw new TypeError('1 argument required, but only none provided present'); } - parse(dateString, token, match) { - switch (token) { - case 'm': - return (0, _utils.parseNumericPattern)(_constants.numericPatterns.minute, dateString); - - case 'mo': - return match.ordinalNumber(dateString, { - unit: 'minute' - }); - - default: - return (0, _utils.parseNDigits)(token.length, dateString); - } - } + var nearestTo = (0, _index3.default)((_options$nearestTo = options === null || options === void 0 ? void 0 : options.nearestTo) !== null && _options$nearestTo !== void 0 ? _options$nearestTo : 1); - validate(_date, value) { - return value >= 0 && value <= 59; + if (nearestTo < 1 || nearestTo > 30) { + throw new RangeError('`options.nearestTo` must be between 1 and 30'); } - set(date, _flags, value) { - date.setUTCMinutes(value, 0, 0); - return date; - } + var date = (0, _index.default)(dirtyDate); + var seconds = date.getSeconds(); // relevant if nearestTo is 1, which is the default case + var minutes = date.getMinutes() + seconds / 60; + var roundingMethod = (0, _index2.getRoundingMethod)(options === null || options === void 0 ? void 0 : options.roundingMethod); + var roundedMinutes = roundingMethod(minutes / nearestTo) * nearestTo; + var remainderMinutes = minutes % nearestTo; + var addedMinutes = Math.round(remainderMinutes / nearestTo) * nearestTo; + return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), roundedMinutes + addedMinutes); } -exports.MinuteParser = MinuteParser; +module.exports = exports.default; /***/ }), -/***/ 9581: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 79595: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -71862,96 +68277,93 @@ exports.MinuteParser = MinuteParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MonthParser = void 0; - -var _utils = __nccwpck_require__(59042); - -var _Parser = __nccwpck_require__(5619); - -var _constants = __nccwpck_require__(30463); +exports["default"] = secondsToHours; -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -class MonthParser extends _Parser.Parser { - constructor() { - super(...arguments); +var _index2 = __nccwpck_require__(24665); - _defineProperty(this, "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'L', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - _defineProperty(this, "priority", 110); - } +/** + * @name secondsToHours + * @category Conversion Helpers + * @summary Convert seconds to hours. + * + * @description + * Convert a number of seconds to a full number of hours. + * + * @param {number} seconds - number of seconds to be converted + * + * @returns {number} the number of seconds converted in hours + * @throws {TypeError} 1 argument required + * + * @example + * // Convert 7200 seconds into hours + * const result = secondsToHours(7200) + * //=> 2 + * + * @example + * // It uses floor rounding: + * const result = secondsToHours(7199) + * //=> 1 + */ +function secondsToHours(seconds) { + (0, _index.default)(1, arguments); + var hours = seconds / _index2.secondsInHour; + return Math.floor(hours); +} - parse(dateString, token, match) { - var valueCallback = function (value) { - return value - 1; - }; +module.exports = exports.default; - switch (token) { - // 1, 2, ..., 12 - case 'M': - return (0, _utils.mapValue)((0, _utils.parseNumericPattern)(_constants.numericPatterns.month, dateString), valueCallback); - // 01, 02, ..., 12 +/***/ }), - case 'MM': - return (0, _utils.mapValue)((0, _utils.parseNDigits)(2, dateString), valueCallback); - // 1st, 2nd, ..., 12th +/***/ 11499: +/***/ ((module, exports, __nccwpck_require__) => { - case 'Mo': - return (0, _utils.mapValue)(match.ordinalNumber(dateString, { - unit: 'month' - }), valueCallback); - // Jan, Feb, ..., Dec +"use strict"; - case 'MMM': - return match.month(dateString, { - width: 'abbreviated', - context: 'formatting' - }) || match.month(dateString, { - width: 'narrow', - context: 'formatting' - }); - // J, F, ..., D - case 'MMMMM': - return match.month(dateString, { - width: 'narrow', - context: 'formatting' - }); - // January, February, ..., December +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = secondsToMilliseconds; - case 'MMMM': - default: - return match.month(dateString, { - width: 'wide', - context: 'formatting' - }) || match.month(dateString, { - width: 'abbreviated', - context: 'formatting' - }) || match.month(dateString, { - width: 'narrow', - context: 'formatting' - }); - } - } +var _index = _interopRequireDefault(__nccwpck_require__(76822)); - validate(_date, value) { - return value >= 0 && value <= 11; - } +var _index2 = __nccwpck_require__(24665); - set(date, _flags, value) { - date.setUTCMonth(value, 1); - date.setUTCHours(0, 0, 0, 0); - return date; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/** + * @name secondsToMilliseconds + * @category Conversion Helpers + * @summary Convert seconds to milliseconds. + * + * @description + * Convert a number of seconds to a full number of milliseconds. + * + * @param {number} seconds - number of seconds to be converted + * + * @returns {number} the number of seconds converted in milliseconds + * @throws {TypeError} 1 argument required + * + * @example + * // Convert 2 seconds into milliseconds + * const result = secondsToMilliseconds(2) + * //=> 2000 + */ +function secondsToMilliseconds(seconds) { + (0, _index.default)(1, arguments); + return seconds * _index2.millisecondsInSecond; } -exports.MonthParser = MonthParser; +module.exports = exports.default; /***/ }), -/***/ 65667: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 15559: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -71959,88 +68371,49 @@ exports.MonthParser = MonthParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.QuarterParser = void 0; - -var _Parser = __nccwpck_require__(5619); - -var _utils = __nccwpck_require__(59042); - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -class QuarterParser extends _Parser.Parser { - constructor() { - super(...arguments); - - _defineProperty(this, "priority", 120); - - _defineProperty(this, "incompatibleTokens", ['Y', 'R', 'q', 'M', 'L', 'w', 'I', 'd', 'D', 'i', 'e', 'c', 't', 'T']); - } - - parse(dateString, token, match) { - switch (token) { - // 1, 2, 3, 4 - case 'Q': - case 'QQ': - // 01, 02, 03, 04 - return (0, _utils.parseNDigits)(token.length, dateString); - // 1st, 2nd, 3rd, 4th - - case 'Qo': - return match.ordinalNumber(dateString, { - unit: 'quarter' - }); - // Q1, Q2, Q3, Q4 - - case 'QQQ': - return match.quarter(dateString, { - width: 'abbreviated', - context: 'formatting' - }) || match.quarter(dateString, { - width: 'narrow', - context: 'formatting' - }); - // 1, 2, 3, 4 (narrow quarter; could be not numerical) - - case 'QQQQQ': - return match.quarter(dateString, { - width: 'narrow', - context: 'formatting' - }); - // 1st quarter, 2nd quarter, ... +exports["default"] = secondsToMinutes; - case 'QQQQ': - default: - return match.quarter(dateString, { - width: 'wide', - context: 'formatting' - }) || match.quarter(dateString, { - width: 'abbreviated', - context: 'formatting' - }) || match.quarter(dateString, { - width: 'narrow', - context: 'formatting' - }); - } - } +var _index = _interopRequireDefault(__nccwpck_require__(76822)); - validate(_date, value) { - return value >= 1 && value <= 4; - } +var _index2 = __nccwpck_require__(24665); - set(date, _flags, value) { - date.setUTCMonth((value - 1) * 3, 1); - date.setUTCHours(0, 0, 0, 0); - return date; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/** + * @name secondsToMinutes + * @category Conversion Helpers + * @summary Convert seconds to minutes. + * + * @description + * Convert a number of seconds to a full number of minutes. + * + * @param {number} seconds - number of seconds to be converted + * + * @returns {number} the number of seconds converted in minutes + * @throws {TypeError} 1 argument required + * + * @example + * // Convert 120 seconds into minutes + * const result = secondsToMinutes(120) + * //=> 2 + * + * @example + * // It uses floor rounding: + * const result = secondsToMinutes(119) + * //=> 1 + */ +function secondsToMinutes(seconds) { + (0, _index.default)(1, arguments); + var minutes = seconds / _index2.secondsInMinute; + return Math.floor(minutes); } -exports.QuarterParser = QuarterParser; +module.exports = exports.default; /***/ }), -/***/ 63478: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 67142: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -72048,57 +68421,106 @@ exports.QuarterParser = QuarterParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SecondParser = void 0; +exports["default"] = set; -var _Parser = __nccwpck_require__(5619); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _constants = __nccwpck_require__(30463); +var _index2 = _interopRequireDefault(__nccwpck_require__(70029)); -var _utils = __nccwpck_require__(59042); +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); -class SecondParser extends _Parser.Parser { - constructor() { - super(...arguments); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - _defineProperty(this, "priority", 50); +/** + * @name set + * @category Common Helpers + * @summary Set date values to a given date. + * + * @description + * Set date values to a given date. + * + * Sets time values to date from object `values`. + * A value is not set if it is undefined or null or doesn't exist in `values`. + * + * Note about bundle size: `set` does not internally use `setX` functions from date-fns but instead opts + * to use native `Date#setX` methods. If you use this function, you may not want to include the + * other `setX` functions that date-fns provides if you are concerned about the bundle size. + * + * @param {Date|Number} date - the date to be changed + * @param {Object} values - an object with options + * @param {Number} [values.year] - the number of years to be set + * @param {Number} [values.month] - the number of months to be set + * @param {Number} [values.date] - the number of days to be set + * @param {Number} [values.hours] - the number of hours to be set + * @param {Number} [values.minutes] - the number of minutes to be set + * @param {Number} [values.seconds] - the number of seconds to be set + * @param {Number} [values.milliseconds] - the number of milliseconds to be set + * @returns {Date} the new date with options set + * @throws {TypeError} 2 arguments required + * @throws {RangeError} `values` must be an object + * + * @example + * // Transform 1 September 2014 into 20 October 2015 in a single line: + * const result = set(new Date(2014, 8, 20), { year: 2015, month: 9, date: 20 }) + * //=> Tue Oct 20 2015 00:00:00 + * + * @example + * // Set 12 PM to 1 September 2014 01:23:45 to 1 September 2014 12:00:00: + * const result = set(new Date(2014, 8, 1, 1, 23, 45), { hours: 12 }) + * //=> Mon Sep 01 2014 12:23:45 + */ +function set(dirtyDate, values) { + (0, _index4.default)(2, arguments); - _defineProperty(this, "incompatibleTokens", ['t', 'T']); + if (typeof values !== 'object' || values === null) { + throw new RangeError('values parameter must be an object'); } - parse(dateString, token, match) { - switch (token) { - case 's': - return (0, _utils.parseNumericPattern)(_constants.numericPatterns.second, dateString); + var date = (0, _index.default)(dirtyDate); // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date - case 'so': - return match.ordinalNumber(dateString, { - unit: 'second' - }); + if (isNaN(date.getTime())) { + return new Date(NaN); + } - default: - return (0, _utils.parseNDigits)(token.length, dateString); - } + if (values.year != null) { + date.setFullYear(values.year); } - validate(_date, value) { - return value >= 0 && value <= 59; + if (values.month != null) { + date = (0, _index2.default)(date, values.month); } - set(date, _flags, value) { - date.setUTCSeconds(value, 0); - return date; + if (values.date != null) { + date.setDate((0, _index3.default)(values.date)); + } + + if (values.hours != null) { + date.setHours((0, _index3.default)(values.hours)); + } + + if (values.minutes != null) { + date.setMinutes((0, _index3.default)(values.minutes)); + } + + if (values.seconds != null) { + date.setSeconds((0, _index3.default)(values.seconds)); + } + + if (values.milliseconds != null) { + date.setMilliseconds((0, _index3.default)(values.milliseconds)); } + return date; } -exports.SecondParser = SecondParser; +module.exports = exports.default; /***/ }), -/***/ 51556: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 760: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -72106,114 +68528,123 @@ exports.SecondParser = SecondParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StandAloneLocalDayParser = void 0; +exports["default"] = setDate; -var _Parser = __nccwpck_require__(5619); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _utils = __nccwpck_require__(59042); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _index = _interopRequireDefault(__nccwpck_require__(82694)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +/** + * @name setDate + * @category Day Helpers + * @summary Set the day of the month to the given date. + * + * @description + * Set the day of the month to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} dayOfMonth - the day of the month of the new date + * @returns {Date} the new date with the day of the month set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set the 30th day of the month to 1 September 2014: + * const result = setDate(new Date(2014, 8, 1), 30) + * //=> Tue Sep 30 2014 00:00:00 + */ +function setDate(dirtyDate, dirtyDayOfMonth) { + (0, _index3.default)(2, arguments); + var date = (0, _index2.default)(dirtyDate); + var dayOfMonth = (0, _index.default)(dirtyDayOfMonth); + date.setDate(dayOfMonth); + return date; +} -// Stand-alone local day of week -class StandAloneLocalDayParser extends _Parser.Parser { - constructor() { - super(...arguments); +module.exports = exports.default; - _defineProperty(this, "priority", 90); +/***/ }), - _defineProperty(this, "incompatibleTokens", ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'E', 'i', 'e', 't', 'T']); - } +/***/ 25247: +/***/ ((module, exports, __nccwpck_require__) => { - parse(dateString, token, match, options) { - var valueCallback = function (value) { - var wholeWeekDays = Math.floor((value - 1) / 7) * 7; - return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays; - }; +"use strict"; - switch (token) { - // 3 - case 'c': - case 'cc': - // 03 - return (0, _utils.mapValue)((0, _utils.parseNDigits)(token.length, dateString), valueCallback); - // 3rd - case 'co': - return (0, _utils.mapValue)(match.ordinalNumber(dateString, { - unit: 'day' - }), valueCallback); - // Tue +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = setDay; - case 'ccc': - return match.day(dateString, { - width: 'abbreviated', - context: 'standalone' - }) || match.day(dateString, { - width: 'short', - context: 'standalone' - }) || match.day(dateString, { - width: 'narrow', - context: 'standalone' - }); - // T +var _index = _interopRequireDefault(__nccwpck_require__(53426)); - case 'ccccc': - return match.day(dateString, { - width: 'narrow', - context: 'standalone' - }); - // Tu +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); - case 'cccccc': - return match.day(dateString, { - width: 'short', - context: 'standalone' - }) || match.day(dateString, { - width: 'narrow', - context: 'standalone' - }); - // Tuesday +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); - case 'cccc': - default: - return match.day(dateString, { - width: 'wide', - context: 'standalone' - }) || match.day(dateString, { - width: 'abbreviated', - context: 'standalone' - }) || match.day(dateString, { - width: 'short', - context: 'standalone' - }) || match.day(dateString, { - width: 'narrow', - context: 'standalone' - }); - } - } +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); - validate(_date, value) { - return value >= 0 && value <= 6; - } +var _index5 = __nccwpck_require__(79115); - set(date, _flags, value, options) { - date = (0, _index.default)(date, value, options); - date.setUTCHours(0, 0, 0, 0); - return date; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name setDay + * @category Weekday Helpers + * @summary Set the day of the week to the given date. + * + * @description + * Set the day of the week to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} day - the day of the week of the new date + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @returns {Date} the new date with the day of the week set + * @throws {TypeError} 2 arguments required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * + * @example + * // Set week day to Sunday, with the default weekStartsOn of Sunday: + * const result = setDay(new Date(2014, 8, 1), 0) + * //=> Sun Aug 31 2014 00:00:00 + * + * @example + * // Set week day to Sunday, with a weekStartsOn of Monday: + * const result = setDay(new Date(2014, 8, 1), 0, { weekStartsOn: 1 }) + * //=> Sun Sep 07 2014 00:00:00 + */ +function setDay(dirtyDate, dirtyDay, options) { + var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + + (0, _index4.default)(2, arguments); + var defaultOptions = (0, _index5.getDefaultOptions)(); + var weekStartsOn = (0, _index3.default)((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); } + var date = (0, _index2.default)(dirtyDate); + var day = (0, _index3.default)(dirtyDay); + var currentDay = date.getDay(); + var remainder = day % 7; + var dayIndex = (remainder + 7) % 7; + var delta = 7 - weekStartsOn; + var diff = day < 0 || day > 6 ? day - (currentDay + delta) % 7 : (dayIndex + delta) % 7 - (currentDay + delta) % 7; + return (0, _index.default)(date, diff); } -exports.StandAloneLocalDayParser = StandAloneLocalDayParser; +module.exports = exports.default; /***/ }), -/***/ 69915: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 31003: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -72221,96 +68652,145 @@ exports.StandAloneLocalDayParser = StandAloneLocalDayParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StandAloneMonthParser = void 0; +exports["default"] = setDayOfYear; -var _Parser = __nccwpck_require__(5619); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _constants = __nccwpck_require__(30463); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _utils = __nccwpck_require__(59042); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -class StandAloneMonthParser extends _Parser.Parser { - constructor() { - super(...arguments); +/** + * @name setDayOfYear + * @category Day Helpers + * @summary Set the day of the year to the given date. + * + * @description + * Set the day of the year to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} dayOfYear - the day of the year of the new date + * @returns {Date} the new date with the day of the year set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set the 2nd day of the year to 2 July 2014: + * const result = setDayOfYear(new Date(2014, 6, 2), 2) + * //=> Thu Jan 02 2014 00:00:00 + */ +function setDayOfYear(dirtyDate, dirtyDayOfYear) { + (0, _index3.default)(2, arguments); + var date = (0, _index2.default)(dirtyDate); + var dayOfYear = (0, _index.default)(dirtyDayOfYear); + date.setMonth(0); + date.setDate(dayOfYear); + return date; +} - _defineProperty(this, "priority", 110); +module.exports = exports.default; - _defineProperty(this, "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'M', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']); - } +/***/ }), - parse(dateString, token, match) { - var valueCallback = function (value) { - return value - 1; - }; +/***/ 44604: +/***/ ((module, exports, __nccwpck_require__) => { - switch (token) { - // 1, 2, ..., 12 - case 'L': - return (0, _utils.mapValue)((0, _utils.parseNumericPattern)(_constants.numericPatterns.month, dateString), valueCallback); - // 01, 02, ..., 12 +"use strict"; - case 'LL': - return (0, _utils.mapValue)((0, _utils.parseNDigits)(2, dateString), valueCallback); - // 1st, 2nd, ..., 12th - case 'Lo': - return (0, _utils.mapValue)(match.ordinalNumber(dateString, { - unit: 'month' - }), valueCallback); - // Jan, Feb, ..., Dec +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = setDefaultOptions; - case 'LLL': - return match.month(dateString, { - width: 'abbreviated', - context: 'standalone' - }) || match.month(dateString, { - width: 'narrow', - context: 'standalone' - }); - // J, F, ..., D +var _index = __nccwpck_require__(79115); - case 'LLLLL': - return match.month(dateString, { - width: 'narrow', - context: 'standalone' - }); - // January, February, ..., December +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); - case 'LLLL': - default: - return match.month(dateString, { - width: 'wide', - context: 'standalone' - }) || match.month(dateString, { - width: 'abbreviated', - context: 'standalone' - }) || match.month(dateString, { - width: 'narrow', - context: 'standalone' - }); - } - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name setDefaultOptions + * @category Common Helpers + * @summary Set default options including locale. + * @pure false + * + * @description + * Sets the defaults for + * `options.locale`, `options.weekStartsOn` and `options.firstWeekContainsDate` + * arguments for all functions. + * + * @param {Object} newOptions - an object with options. + * @param {Locale} [newOptions.locale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [newOptions.weekStartsOn] - the index of the first day of the week (0 - Sunday) + * @param {1|2|3|4|5|6|7} [newOptions.firstWeekContainsDate] - the day of January, which is always in the first week of the year + * @throws {TypeError} 1 argument required + * + * @example + * // Set global locale: + * import { es } from 'date-fns/locale' + * setDefaultOptions({ locale: es }) + * const result = format(new Date(2014, 8, 2), 'PPPP') + * //=> 'martes, 2 de septiembre de 2014' + * + * @example + * // Start of the week for 2 September 2014: + * const result = startOfWeek(new Date(2014, 8, 2)) + * //=> Sun Aug 31 2014 00:00:00 + * + * @example + * // Start of the week for 2 September 2014, + * // when we set that week starts on Monday by default: + * setDefaultOptions({ weekStartsOn: 1 }) + * const result = startOfWeek(new Date(2014, 8, 2)) + * //=> Mon Sep 01 2014 00:00:00 + * + * @example + * // Manually set options take priority over default options: + * setDefaultOptions({ weekStartsOn: 1 }) + * const result = startOfWeek(new Date(2014, 8, 2), { weekStartsOn: 0 }) + * //=> Sun Aug 31 2014 00:00:00 + * + * @example + * // Remove the option by setting it to `undefined`: + * setDefaultOptions({ weekStartsOn: 1 }) + * setDefaultOptions({ weekStartsOn: undefined }) + * const result = startOfWeek(new Date(2014, 8, 2)) + * //=> Sun Aug 31 2014 00:00:00 + */ +function setDefaultOptions(newOptions) { + (0, _index2.default)(1, arguments); + var result = {}; + var defaultOptions = (0, _index.getDefaultOptions)(); - validate(_date, value) { - return value >= 0 && value <= 11; + for (var property in defaultOptions) { + if (Object.prototype.hasOwnProperty.call(defaultOptions, property)) { + ; + result[property] = defaultOptions[property]; + } } - set(date, _flags, value) { - date.setUTCMonth(value, 1); - date.setUTCHours(0, 0, 0, 0); - return date; + for (var _property in newOptions) { + if (Object.prototype.hasOwnProperty.call(newOptions, _property)) { + if (newOptions[_property] === undefined) { + delete result[_property]; + } else { + ; + result[_property] = newOptions[_property]; + } + } } + (0, _index.setDefaultOptions)(result); } -exports.StandAloneMonthParser = StandAloneMonthParser; +module.exports = exports.default; /***/ }), -/***/ 22898: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 42664: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -72318,88 +68798,48 @@ exports.StandAloneMonthParser = StandAloneMonthParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StandAloneQuarterParser = void 0; - -var _Parser = __nccwpck_require__(5619); - -var _utils = __nccwpck_require__(59042); - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -class StandAloneQuarterParser extends _Parser.Parser { - constructor() { - super(...arguments); - - _defineProperty(this, "priority", 120); - - _defineProperty(this, "incompatibleTokens", ['Y', 'R', 'Q', 'M', 'L', 'w', 'I', 'd', 'D', 'i', 'e', 'c', 't', 'T']); - } - - parse(dateString, token, match) { - switch (token) { - // 1, 2, 3, 4 - case 'q': - case 'qq': - // 01, 02, 03, 04 - return (0, _utils.parseNDigits)(token.length, dateString); - // 1st, 2nd, 3rd, 4th - - case 'qo': - return match.ordinalNumber(dateString, { - unit: 'quarter' - }); - // Q1, Q2, Q3, Q4 - - case 'qqq': - return match.quarter(dateString, { - width: 'abbreviated', - context: 'standalone' - }) || match.quarter(dateString, { - width: 'narrow', - context: 'standalone' - }); - // 1, 2, 3, 4 (narrow quarter; could be not numerical) +exports["default"] = setHours; - case 'qqqqq': - return match.quarter(dateString, { - width: 'narrow', - context: 'standalone' - }); - // 1st quarter, 2nd quarter, ... +var _index = _interopRequireDefault(__nccwpck_require__(35279)); - case 'qqqq': - default: - return match.quarter(dateString, { - width: 'wide', - context: 'standalone' - }) || match.quarter(dateString, { - width: 'abbreviated', - context: 'standalone' - }) || match.quarter(dateString, { - width: 'narrow', - context: 'standalone' - }); - } - } +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); - validate(_date, value) { - return value >= 1 && value <= 4; - } +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); - set(date, _flags, value) { - date.setUTCMonth((value - 1) * 3, 1); - date.setUTCHours(0, 0, 0, 0); - return date; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/** + * @name setHours + * @category Hour Helpers + * @summary Set the hours to the given date. + * + * @description + * Set the hours to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} hours - the hours of the new date + * @returns {Date} the new date with the hours set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set 4 hours to 1 September 2014 11:30:00: + * const result = setHours(new Date(2014, 8, 1, 11, 30), 4) + * //=> Mon Sep 01 2014 04:30:00 + */ +function setHours(dirtyDate, dirtyHours) { + (0, _index3.default)(2, arguments); + var date = (0, _index2.default)(dirtyDate); + var hours = (0, _index.default)(dirtyHours); + date.setHours(hours); + return date; } -exports.StandAloneQuarterParser = StandAloneQuarterParser; +module.exports = exports.default; /***/ }), -/***/ 63726: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 50193: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -72407,41 +68847,55 @@ exports.StandAloneQuarterParser = StandAloneQuarterParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TimestampMillisecondsParser = void 0; - -var _Parser = __nccwpck_require__(5619); - -var _utils = __nccwpck_require__(59042); +exports["default"] = setISODay; -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -class TimestampMillisecondsParser extends _Parser.Parser { - constructor() { - super(...arguments); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); - _defineProperty(this, "priority", 20); +var _index3 = _interopRequireDefault(__nccwpck_require__(53426)); - _defineProperty(this, "incompatibleTokens", '*'); - } +var _index4 = _interopRequireDefault(__nccwpck_require__(40321)); - parse(dateString) { - return (0, _utils.parseAnyDigitsSigned)(dateString); - } +var _index5 = _interopRequireDefault(__nccwpck_require__(76822)); - set(_date, _flags, value) { - return [new Date(value), { - timestampIsSet: true - }]; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/** + * @name setISODay + * @category Weekday Helpers + * @summary Set the day of the ISO week to the given date. + * + * @description + * Set the day of the ISO week to the given date. + * ISO week starts with Monday. + * 7 is the index of Sunday, 1 is the index of Monday etc. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} day - the day of the ISO week of the new date + * @returns {Date} the new date with the day of the ISO week set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set Sunday to 1 September 2014: + * const result = setISODay(new Date(2014, 8, 1), 7) + * //=> Sun Sep 07 2014 00:00:00 + */ +function setISODay(dirtyDate, dirtyDay) { + (0, _index5.default)(2, arguments); + var date = (0, _index2.default)(dirtyDate); + var day = (0, _index.default)(dirtyDay); + var currentDay = (0, _index4.default)(date); + var diff = day - currentDay; + return (0, _index3.default)(date, diff); } -exports.TimestampMillisecondsParser = TimestampMillisecondsParser; +module.exports = exports.default; /***/ }), -/***/ 90771: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 41744: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -72449,41 +68903,53 @@ exports.TimestampMillisecondsParser = TimestampMillisecondsParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TimestampSecondsParser = void 0; - -var _Parser = __nccwpck_require__(5619); - -var _utils = __nccwpck_require__(59042); - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +exports["default"] = setISOWeek; -class TimestampSecondsParser extends _Parser.Parser { - constructor() { - super(...arguments); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); - _defineProperty(this, "priority", 40); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); - _defineProperty(this, "incompatibleTokens", '*'); - } +var _index3 = _interopRequireDefault(__nccwpck_require__(67374)); - parse(dateString) { - return (0, _utils.parseAnyDigitsSigned)(dateString); - } +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); - set(_date, _flags, value) { - return [new Date(value * 1000), { - timestampIsSet: true - }]; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/** + * @name setISOWeek + * @category ISO Week Helpers + * @summary Set the ISO week to the given date. + * + * @description + * Set the ISO week to the given date, saving the weekday number. + * + * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date + * + * @param {Date|Number} date - the date to be changed + * @param {Number} isoWeek - the ISO week of the new date + * @returns {Date} the new date with the ISO week set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set the 53rd ISO week to 7 August 2004: + * const result = setISOWeek(new Date(2004, 7, 7), 53) + * //=> Sat Jan 01 2005 00:00:00 + */ +function setISOWeek(dirtyDate, dirtyISOWeek) { + (0, _index4.default)(2, arguments); + var date = (0, _index2.default)(dirtyDate); + var isoWeek = (0, _index.default)(dirtyISOWeek); + var diff = (0, _index3.default)(date) - isoWeek; + date.setDate(date.getDate() - diff * 7); + return date; } -exports.TimestampSecondsParser = TimestampSecondsParser; +module.exports = exports.default; /***/ }), -/***/ 12493: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 72593: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -72491,81 +68957,60 @@ exports.TimestampSecondsParser = TimestampSecondsParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.YearParser = void 0; - -var _Parser = __nccwpck_require__(5619); - -var _utils = __nccwpck_require__(59042); - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -// From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns -// | Year | y | yy | yyy | yyyy | yyyyy | -// |----------|-------|----|-------|-------|-------| -// | AD 1 | 1 | 01 | 001 | 0001 | 00001 | -// | AD 12 | 12 | 12 | 012 | 0012 | 00012 | -// | AD 123 | 123 | 23 | 123 | 0123 | 00123 | -// | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 | -// | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 | -class YearParser extends _Parser.Parser { - constructor() { - super(...arguments); - - _defineProperty(this, "priority", 130); - - _defineProperty(this, "incompatibleTokens", ['Y', 'R', 'u', 'w', 'I', 'i', 'e', 'c', 't', 'T']); - } - - parse(dateString, token, match) { - var valueCallback = function (year) { - return { - year: year, - isTwoDigitYear: token === 'yy' - }; - }; - - switch (token) { - case 'y': - return (0, _utils.mapValue)((0, _utils.parseNDigits)(4, dateString), valueCallback); +exports["default"] = setISOWeekYear; - case 'yo': - return (0, _utils.mapValue)(match.ordinalNumber(dateString, { - unit: 'year' - }), valueCallback); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); - default: - return (0, _utils.mapValue)((0, _utils.parseNDigits)(token.length, dateString), valueCallback); - } - } +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); - validate(_date, value) { - return value.isTwoDigitYear || value.year > 0; - } +var _index3 = _interopRequireDefault(__nccwpck_require__(34855)); - set(date, flags, value) { - var currentYear = date.getUTCFullYear(); +var _index4 = _interopRequireDefault(__nccwpck_require__(68607)); - if (value.isTwoDigitYear) { - var normalizedTwoDigitYear = (0, _utils.normalizeTwoDigitYear)(value.year, currentYear); - date.setUTCFullYear(normalizedTwoDigitYear, 0, 1); - date.setUTCHours(0, 0, 0, 0); - return date; - } +var _index5 = _interopRequireDefault(__nccwpck_require__(76822)); - var year = !('era' in flags) || flags.era === 1 ? value.year : 1 - value.year; - date.setUTCFullYear(year, 0, 1); - date.setUTCHours(0, 0, 0, 0); - return date; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/** + * @name setISOWeekYear + * @category ISO Week-Numbering Year Helpers + * @summary Set the ISO week-numbering year to the given date. + * + * @description + * Set the ISO week-numbering year to the given date, + * saving the week number and the weekday number. + * + * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date + * + * @param {Date|Number} date - the date to be changed + * @param {Number} isoWeekYear - the ISO week-numbering year of the new date + * @returns {Date} the new date with the ISO week-numbering year set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set ISO week-numbering year 2007 to 29 December 2008: + * const result = setISOWeekYear(new Date(2008, 11, 29), 2007) + * //=> Mon Jan 01 2007 00:00:00 + */ +function setISOWeekYear(dirtyDate, dirtyISOWeekYear) { + (0, _index5.default)(2, arguments); + var date = (0, _index2.default)(dirtyDate); + var isoWeekYear = (0, _index.default)(dirtyISOWeekYear); + var diff = (0, _index4.default)(date, (0, _index3.default)(date)); + var fourthOfJanuary = new Date(0); + fourthOfJanuary.setFullYear(isoWeekYear, 0, 4); + fourthOfJanuary.setHours(0, 0, 0, 0); + date = (0, _index3.default)(fourthOfJanuary); + date.setDate(date.getDate() + diff); + return date; } -exports.YearParser = YearParser; +module.exports = exports.default; /***/ }), -/***/ 15193: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 29973: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -72573,152 +69018,156 @@ exports.YearParser = YearParser; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parsers = void 0; - -var _EraParser = __nccwpck_require__(36309); - -var _YearParser = __nccwpck_require__(12493); - -var _LocalWeekYearParser = __nccwpck_require__(90085); - -var _ISOWeekYearParser = __nccwpck_require__(40519); +exports["default"] = setMilliseconds; -var _ExtendedYearParser = __nccwpck_require__(14754); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _QuarterParser = __nccwpck_require__(65667); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _StandAloneQuarterParser = __nccwpck_require__(22898); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); -var _MonthParser = __nccwpck_require__(9581); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _StandAloneMonthParser = __nccwpck_require__(69915); +/** + * @name setMilliseconds + * @category Millisecond Helpers + * @summary Set the milliseconds to the given date. + * + * @description + * Set the milliseconds to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} milliseconds - the milliseconds of the new date + * @returns {Date} the new date with the milliseconds set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set 300 milliseconds to 1 September 2014 11:30:40.500: + * const result = setMilliseconds(new Date(2014, 8, 1, 11, 30, 40, 500), 300) + * //=> Mon Sep 01 2014 11:30:40.300 + */ +function setMilliseconds(dirtyDate, dirtyMilliseconds) { + (0, _index3.default)(2, arguments); + var date = (0, _index2.default)(dirtyDate); + var milliseconds = (0, _index.default)(dirtyMilliseconds); + date.setMilliseconds(milliseconds); + return date; +} -var _LocalWeekParser = __nccwpck_require__(76125); +module.exports = exports.default; -var _ISOWeekParser = __nccwpck_require__(92127); +/***/ }), -var _DateParser = __nccwpck_require__(64757); +/***/ 88434: +/***/ ((module, exports, __nccwpck_require__) => { -var _DayOfYearParser = __nccwpck_require__(17001); +"use strict"; -var _DayParser = __nccwpck_require__(72280); -var _LocalDayParser = __nccwpck_require__(31190); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = setMinutes; -var _StandAloneLocalDayParser = __nccwpck_require__(51556); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _ISODayParser = __nccwpck_require__(96376); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _AMPMParser = __nccwpck_require__(38678); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); -var _AMPMMidnightParser = __nccwpck_require__(19187); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _DayPeriodParser = __nccwpck_require__(29273); +/** + * @name setMinutes + * @category Minute Helpers + * @summary Set the minutes to the given date. + * + * @description + * Set the minutes to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} minutes - the minutes of the new date + * @returns {Date} the new date with the minutes set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set 45 minutes to 1 September 2014 11:30:40: + * const result = setMinutes(new Date(2014, 8, 1, 11, 30, 40), 45) + * //=> Mon Sep 01 2014 11:45:40 + */ +function setMinutes(dirtyDate, dirtyMinutes) { + (0, _index3.default)(2, arguments); + var date = (0, _index2.default)(dirtyDate); + var minutes = (0, _index.default)(dirtyMinutes); + date.setMinutes(minutes); + return date; +} -var _Hour1to12Parser = __nccwpck_require__(27929); +module.exports = exports.default; -var _Hour0to23Parser = __nccwpck_require__(82610); +/***/ }), -var _Hour0To11Parser = __nccwpck_require__(323); +/***/ 70029: +/***/ ((module, exports, __nccwpck_require__) => { -var _Hour1To24Parser = __nccwpck_require__(25980); +"use strict"; -var _MinuteParser = __nccwpck_require__(84254); -var _SecondParser = __nccwpck_require__(63478); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = setMonth; -var _FractionOfSecondParser = __nccwpck_require__(75194); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _ISOTimezoneWithZParser = __nccwpck_require__(9822); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -var _ISOTimezoneParser = __nccwpck_require__(69874); +var _index3 = _interopRequireDefault(__nccwpck_require__(19768)); -var _TimestampSecondsParser = __nccwpck_require__(90771); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); -var _TimestampMillisecondsParser = __nccwpck_require__(63726); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/* - * | | Unit | | Unit | - * |-----|--------------------------------|-----|--------------------------------| - * | a | AM, PM | A* | Milliseconds in day | - * | b | AM, PM, noon, midnight | B | Flexible day period | - * | c | Stand-alone local day of week | C* | Localized hour w/ day period | - * | d | Day of month | D | Day of year | - * | e | Local day of week | E | Day of week | - * | f | | F* | Day of week in month | - * | g* | Modified Julian day | G | Era | - * | h | Hour [1-12] | H | Hour [0-23] | - * | i! | ISO day of week | I! | ISO week of year | - * | j* | Localized hour w/ day period | J* | Localized hour w/o day period | - * | k | Hour [1-24] | K | Hour [0-11] | - * | l* | (deprecated) | L | Stand-alone month | - * | m | Minute | M | Month | - * | n | | N | | - * | o! | Ordinal number modifier | O* | Timezone (GMT) | - * | p | | P | | - * | q | Stand-alone quarter | Q | Quarter | - * | r* | Related Gregorian year | R! | ISO week-numbering year | - * | s | Second | S | Fraction of second | - * | t! | Seconds timestamp | T! | Milliseconds timestamp | - * | u | Extended year | U* | Cyclic year | - * | v* | Timezone (generic non-locat.) | V* | Timezone (location) | - * | w | Local week of year | W* | Week of month | - * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) | - * | y | Year (abs) | Y | Local week-numbering year | - * | z* | Timezone (specific non-locat.) | Z* | Timezone (aliases) | +/** + * @name setMonth + * @category Month Helpers + * @summary Set the month to the given date. * - * Letters marked by * are not implemented but reserved by Unicode standard. + * @description + * Set the month to the given date. * - * Letters marked by ! are non-standard, but implemented by date-fns: - * - `o` modifies the previous token to turn it into an ordinal (see `parse` docs) - * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days, - * i.e. 7 for Sunday, 1 for Monday, etc. - * - `I` is ISO week of year, as opposed to `w` which is local week of year. - * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year. - * `R` is supposed to be used in conjunction with `I` and `i` - * for universal ISO week-numbering date, whereas - * `Y` is supposed to be used in conjunction with `w` and `e` - * for week-numbering date specific to the locale. + * @param {Date|Number} date - the date to be changed + * @param {Number} month - the month of the new date + * @returns {Date} the new date with the month set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set February to 1 September 2014: + * const result = setMonth(new Date(2014, 8, 1), 1) + * //=> Sat Feb 01 2014 00:00:00 */ -var parsers = { - G: new _EraParser.EraParser(), - y: new _YearParser.YearParser(), - Y: new _LocalWeekYearParser.LocalWeekYearParser(), - R: new _ISOWeekYearParser.ISOWeekYearParser(), - u: new _ExtendedYearParser.ExtendedYearParser(), - Q: new _QuarterParser.QuarterParser(), - q: new _StandAloneQuarterParser.StandAloneQuarterParser(), - M: new _MonthParser.MonthParser(), - L: new _StandAloneMonthParser.StandAloneMonthParser(), - w: new _LocalWeekParser.LocalWeekParser(), - I: new _ISOWeekParser.ISOWeekParser(), - d: new _DateParser.DateParser(), - D: new _DayOfYearParser.DayOfYearParser(), - E: new _DayParser.DayParser(), - e: new _LocalDayParser.LocalDayParser(), - c: new _StandAloneLocalDayParser.StandAloneLocalDayParser(), - i: new _ISODayParser.ISODayParser(), - a: new _AMPMParser.AMPMParser(), - b: new _AMPMMidnightParser.AMPMMidnightParser(), - B: new _DayPeriodParser.DayPeriodParser(), - h: new _Hour1to12Parser.Hour1to12Parser(), - H: new _Hour0to23Parser.Hour0to23Parser(), - K: new _Hour0To11Parser.Hour0To11Parser(), - k: new _Hour1To24Parser.Hour1To24Parser(), - m: new _MinuteParser.MinuteParser(), - s: new _SecondParser.SecondParser(), - S: new _FractionOfSecondParser.FractionOfSecondParser(), - X: new _ISOTimezoneWithZParser.ISOTimezoneWithZParser(), - x: new _ISOTimezoneParser.ISOTimezoneParser(), - t: new _TimestampSecondsParser.TimestampSecondsParser(), - T: new _TimestampMillisecondsParser.TimestampMillisecondsParser() -}; -exports.parsers = parsers; +function setMonth(dirtyDate, dirtyMonth) { + (0, _index4.default)(2, arguments); + var date = (0, _index2.default)(dirtyDate); + var month = (0, _index.default)(dirtyMonth); + var year = date.getFullYear(); + var day = date.getDate(); + var dateWithDesiredMonth = new Date(0); + dateWithDesiredMonth.setFullYear(year, month, 15); + dateWithDesiredMonth.setHours(0, 0, 0, 0); + var daysInMonth = (0, _index3.default)(dateWithDesiredMonth); // Set the last day of the new month + // if the original date was the last day of the longer month + + date.setMonth(month, Math.min(day, daysInMonth)); + return date; +} + +module.exports = exports.default; /***/ }), -/***/ 59042: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 12973: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -72726,160 +69175,173 @@ exports.parsers = parsers; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.mapValue = mapValue; -exports.parseNumericPattern = parseNumericPattern; -exports.parseTimezonePattern = parseTimezonePattern; -exports.parseAnyDigitsSigned = parseAnyDigitsSigned; -exports.parseNDigits = parseNDigits; -exports.parseNDigitsSigned = parseNDigitsSigned; -exports.dayPeriodEnumToHours = dayPeriodEnumToHours; -exports.normalizeTwoDigitYear = normalizeTwoDigitYear; -exports.isLeapYearIndex = isLeapYearIndex; - -var _index = __nccwpck_require__(25756); +exports["default"] = setQuarter; -var _constants = __nccwpck_require__(30463); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -function mapValue(parseFnResult, mapFn) { - if (!parseFnResult) { - return parseFnResult; - } +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); - return { - value: mapFn(parseFnResult.value), - rest: parseFnResult.rest - }; -} +var _index3 = _interopRequireDefault(__nccwpck_require__(70029)); -function parseNumericPattern(pattern, dateString) { - var matchResult = dateString.match(pattern); +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); - if (!matchResult) { - return null; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return { - value: parseInt(matchResult[0], 10), - rest: dateString.slice(matchResult[0].length) - }; +/** + * @name setQuarter + * @category Quarter Helpers + * @summary Set the year quarter to the given date. + * + * @description + * Set the year quarter to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} quarter - the quarter of the new date + * @returns {Date} the new date with the quarter set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set the 2nd quarter to 2 July 2014: + * const result = setQuarter(new Date(2014, 6, 2), 2) + * //=> Wed Apr 02 2014 00:00:00 + */ +function setQuarter(dirtyDate, dirtyQuarter) { + (0, _index4.default)(2, arguments); + var date = (0, _index2.default)(dirtyDate); + var quarter = (0, _index.default)(dirtyQuarter); + var oldQuarter = Math.floor(date.getMonth() / 3) + 1; + var diff = quarter - oldQuarter; + return (0, _index3.default)(date, date.getMonth() + diff * 3); } -function parseTimezonePattern(pattern, dateString) { - var matchResult = dateString.match(pattern); +module.exports = exports.default; - if (!matchResult) { - return null; - } // Input is 'Z' +/***/ }), +/***/ 74275: +/***/ ((module, exports, __nccwpck_require__) => { - if (matchResult[0] === 'Z') { - return { - value: 0, - rest: dateString.slice(1) - }; - } +"use strict"; - var sign = matchResult[1] === '+' ? 1 : -1; - var hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0; - var minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0; - var seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0; - return { - value: sign * (hours * _index.millisecondsInHour + minutes * _index.millisecondsInMinute + seconds * _index.millisecondsInSecond), - rest: dateString.slice(matchResult[0].length) - }; -} -function parseAnyDigitsSigned(dateString) { - return parseNumericPattern(_constants.numericPatterns.anyDigitsSigned, dateString); -} +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = setSeconds; -function parseNDigits(n, dateString) { - switch (n) { - case 1: - return parseNumericPattern(_constants.numericPatterns.singleDigit, dateString); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); - case 2: - return parseNumericPattern(_constants.numericPatterns.twoDigits, dateString); +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); - case 3: - return parseNumericPattern(_constants.numericPatterns.threeDigits, dateString); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); - case 4: - return parseNumericPattern(_constants.numericPatterns.fourDigits, dateString); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - default: - return parseNumericPattern(new RegExp('^\\d{1,' + n + '}'), dateString); - } +/** + * @name setSeconds + * @category Second Helpers + * @summary Set the seconds to the given date. + * + * @description + * Set the seconds to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} seconds - the seconds of the new date + * @returns {Date} the new date with the seconds set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set 45 seconds to 1 September 2014 11:30:40: + * const result = setSeconds(new Date(2014, 8, 1, 11, 30, 40), 45) + * //=> Mon Sep 01 2014 11:30:45 + */ +function setSeconds(dirtyDate, dirtySeconds) { + (0, _index3.default)(2, arguments); + var date = (0, _index2.default)(dirtyDate); + var seconds = (0, _index.default)(dirtySeconds); + date.setSeconds(seconds); + return date; } -function parseNDigitsSigned(n, dateString) { - switch (n) { - case 1: - return parseNumericPattern(_constants.numericPatterns.singleDigitSigned, dateString); - - case 2: - return parseNumericPattern(_constants.numericPatterns.twoDigitsSigned, dateString); +module.exports = exports.default; - case 3: - return parseNumericPattern(_constants.numericPatterns.threeDigitsSigned, dateString); +/***/ }), - case 4: - return parseNumericPattern(_constants.numericPatterns.fourDigitsSigned, dateString); +/***/ 19966: +/***/ ((module, exports, __nccwpck_require__) => { - default: - return parseNumericPattern(new RegExp('^-?\\d{1,' + n + '}'), dateString); - } -} +"use strict"; -function dayPeriodEnumToHours(dayPeriod) { - switch (dayPeriod) { - case 'morning': - return 4; - case 'evening': - return 17; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = setWeek; - case 'pm': - case 'noon': - case 'afternoon': - return 12; +var _index = _interopRequireDefault(__nccwpck_require__(21090)); - case 'am': - case 'midnight': - case 'night': - default: - return 0; - } -} +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); -function normalizeTwoDigitYear(twoDigitYear, currentYear) { - var isCommonEra = currentYear > 0; // Absolute number of the current year: - // 1 -> 1 AC - // 0 -> 1 BC - // -1 -> 2 BC +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); - var absCurrentYear = isCommonEra ? currentYear : 1 - currentYear; - var result; +var _index4 = _interopRequireDefault(__nccwpck_require__(35279)); - if (absCurrentYear <= 50) { - result = twoDigitYear || 100; - } else { - var rangeEnd = absCurrentYear + 50; - var rangeEndCentury = Math.floor(rangeEnd / 100) * 100; - var isPreviousCentury = twoDigitYear >= rangeEnd % 100; - result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return isCommonEra ? result : 1 - result; +/** + * @name setWeek + * @category Week Helpers + * @summary Set the local week to the given date. + * + * @description + * Set the local week to the given date, saving the weekday number. + * The exact calculation depends on the values of + * `options.weekStartsOn` (which is the index of the first day of the week) + * and `options.firstWeekContainsDate` (which is the day of January, which is always in + * the first week of the week-numbering year) + * + * Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering + * + * @param {Date|Number} date - the date to be changed + * @param {Number} week - the week of the new date + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year + * @returns {Date} the new date with the local week set + * @throws {TypeError} 2 arguments required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 + * + * @example + * // Set the 1st week to 2 January 2005 with default options: + * const result = setWeek(new Date(2005, 0, 2), 1) + * //=> Sun Dec 26 2004 00:00:00 + * + * @example + * // Set the 1st week to 2 January 2005, + * // if Monday is the first day of the week, + * // and the first week of the year always contains 4 January: + * const result = setWeek(new Date(2005, 0, 2), 1, { + * weekStartsOn: 1, + * firstWeekContainsDate: 4 + * }) + * //=> Sun Jan 4 2004 00:00:00 + */ +function setWeek(dirtyDate, dirtyWeek, options) { + (0, _index3.default)(2, arguments); + var date = (0, _index2.default)(dirtyDate); + var week = (0, _index4.default)(dirtyWeek); + var diff = (0, _index.default)(date, options) - week; + date.setDate(date.getDate() - diff * 7); + return date; } -function isLeapYearIndex(year) { - return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0; -} +module.exports = exports.default; /***/ }), -/***/ 71287: +/***/ 43844: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -72888,538 +69350,523 @@ function isLeapYearIndex(year) { Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = parse; - -var _index = _interopRequireDefault(__nccwpck_require__(618)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(97923)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(26477)); - -var _index4 = _interopRequireDefault(__nccwpck_require__(22631)); - -var _index5 = _interopRequireDefault(__nccwpck_require__(78387)); - -var _index6 = _interopRequireDefault(__nccwpck_require__(97032)); +exports["default"] = setWeekYear; -var _index7 = __nccwpck_require__(22509); +var _index = _interopRequireDefault(__nccwpck_require__(68607)); -var _index8 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index2 = _interopRequireDefault(__nccwpck_require__(53392)); -var _index9 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(80603)); -var _Setter = __nccwpck_require__(75665); +var _index4 = _interopRequireDefault(__nccwpck_require__(35279)); -var _index10 = __nccwpck_require__(15193); +var _index5 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index11 = __nccwpck_require__(79307); +var _index6 = __nccwpck_require__(79115); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -// This RegExp consists of three parts separated by `|`: -// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token -// (one of the certain letters followed by `o`) -// - (\w)\1* matches any sequences of the same letter -// - '' matches two quote characters in a row -// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('), -// except a single quote symbol, which ends the sequence. -// Two quote characters do not end the sequence. -// If there is no matching single quote -// then the sequence will continue until the end of the string. -// - . matches any single character unmatched by previous parts of the RegExps -var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; // This RegExp catches symbols escaped by quotes, and also -// sequences of symbols P, p, and the combinations like `PPPPPPPppppp` - -var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g; -var escapedStringRegExp = /^'([^]*?)'?$/; -var doubleQuoteRegExp = /''/g; -var notWhitespaceRegExp = /\S/; -var unescapedLatinCharacterRegExp = /[a-zA-Z]/; /** - * @name parse - * @category Common Helpers - * @summary Parse the date. + * @name setWeekYear + * @category Week-Numbering Year Helpers + * @summary Set the local week-numbering year to the given date. * * @description - * Return the date parsed from string using the given format string. - * - * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries. - * > See: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * - * The characters in the format string wrapped between two single quotes characters (') are escaped. - * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. - * - * Format of the format string is based on Unicode Technical Standard #35: - * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table - * with a few additions (see note 5 below the table). - * - * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited - * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception: - * - * ```javascript - * parse('23 AM', 'HH a', new Date()) - * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time - * ``` - * - * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true - * - * Accepted format string patterns: - * | Unit |Prior| Pattern | Result examples | Notes | - * |---------------------------------|-----|---------|-----------------------------------|-------| - * | Era | 140 | G..GGG | AD, BC | | - * | | | GGGG | Anno Domini, Before Christ | 2 | - * | | | GGGGG | A, B | | - * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 | - * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 | - * | | | yy | 44, 01, 00, 17 | 4 | - * | | | yyy | 044, 001, 123, 999 | 4 | - * | | | yyyy | 0044, 0001, 1900, 2017 | 4 | - * | | | yyyyy | ... | 2,4 | - * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 | - * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 | - * | | | YY | 44, 01, 00, 17 | 4,6 | - * | | | YYY | 044, 001, 123, 999 | 4 | - * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 | - * | | | YYYYY | ... | 2,4 | - * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 | - * | | | RR | -43, 01, 00, 17 | 4,5 | - * | | | RRR | -043, 001, 123, 999, -999 | 4,5 | - * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 | - * | | | RRRRR | ... | 2,4,5 | - * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 | - * | | | uu | -43, 01, 99, -99 | 4 | - * | | | uuu | -043, 001, 123, 999, -999 | 4 | - * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 | - * | | | uuuuu | ... | 2,4 | - * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | | - * | | | Qo | 1st, 2nd, 3rd, 4th | 5 | - * | | | QQ | 01, 02, 03, 04 | | - * | | | QQQ | Q1, Q2, Q3, Q4 | | - * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 | - * | | | QQQQQ | 1, 2, 3, 4 | 4 | - * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | | - * | | | qo | 1st, 2nd, 3rd, 4th | 5 | - * | | | qq | 01, 02, 03, 04 | | - * | | | qqq | Q1, Q2, Q3, Q4 | | - * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 | - * | | | qqqqq | 1, 2, 3, 4 | 3 | - * | Month (formatting) | 110 | M | 1, 2, ..., 12 | | - * | | | Mo | 1st, 2nd, ..., 12th | 5 | - * | | | MM | 01, 02, ..., 12 | | - * | | | MMM | Jan, Feb, ..., Dec | | - * | | | MMMM | January, February, ..., December | 2 | - * | | | MMMMM | J, F, ..., D | | - * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | | - * | | | Lo | 1st, 2nd, ..., 12th | 5 | - * | | | LL | 01, 02, ..., 12 | | - * | | | LLL | Jan, Feb, ..., Dec | | - * | | | LLLL | January, February, ..., December | 2 | - * | | | LLLLL | J, F, ..., D | | - * | Local week of year | 100 | w | 1, 2, ..., 53 | | - * | | | wo | 1st, 2nd, ..., 53th | 5 | - * | | | ww | 01, 02, ..., 53 | | - * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 | - * | | | Io | 1st, 2nd, ..., 53th | 5 | - * | | | II | 01, 02, ..., 53 | 5 | - * | Day of month | 90 | d | 1, 2, ..., 31 | | - * | | | do | 1st, 2nd, ..., 31st | 5 | - * | | | dd | 01, 02, ..., 31 | | - * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 | - * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 | - * | | | DD | 01, 02, ..., 365, 366 | 7 | - * | | | DDD | 001, 002, ..., 365, 366 | | - * | | | DDDD | ... | 2 | - * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Sun | | - * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 | - * | | | EEEEE | M, T, W, T, F, S, S | | - * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | | - * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 | - * | | | io | 1st, 2nd, ..., 7th | 5 | - * | | | ii | 01, 02, ..., 07 | 5 | - * | | | iii | Mon, Tue, Wed, ..., Sun | 5 | - * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 | - * | | | iiiii | M, T, W, T, F, S, S | 5 | - * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 | - * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | | - * | | | eo | 2nd, 3rd, ..., 1st | 5 | - * | | | ee | 02, 03, ..., 01 | | - * | | | eee | Mon, Tue, Wed, ..., Sun | | - * | | | eeee | Monday, Tuesday, ..., Sunday | 2 | - * | | | eeeee | M, T, W, T, F, S, S | | - * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | | - * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | | - * | | | co | 2nd, 3rd, ..., 1st | 5 | - * | | | cc | 02, 03, ..., 01 | | - * | | | ccc | Mon, Tue, Wed, ..., Sun | | - * | | | cccc | Monday, Tuesday, ..., Sunday | 2 | - * | | | ccccc | M, T, W, T, F, S, S | | - * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | | - * | AM, PM | 80 | a..aaa | AM, PM | | - * | | | aaaa | a.m., p.m. | 2 | - * | | | aaaaa | a, p | | - * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | | - * | | | bbbb | a.m., p.m., noon, midnight | 2 | - * | | | bbbbb | a, p, n, mi | | - * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | | - * | | | BBBB | at night, in the morning, ... | 2 | - * | | | BBBBB | at night, in the morning, ... | | - * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | | - * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 | - * | | | hh | 01, 02, ..., 11, 12 | | - * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | | - * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 | - * | | | HH | 00, 01, 02, ..., 23 | | - * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | | - * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 | - * | | | KK | 01, 02, ..., 11, 00 | | - * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | | - * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 | - * | | | kk | 24, 01, 02, ..., 23 | | - * | Minute | 60 | m | 0, 1, ..., 59 | | - * | | | mo | 0th, 1st, ..., 59th | 5 | - * | | | mm | 00, 01, ..., 59 | | - * | Second | 50 | s | 0, 1, ..., 59 | | - * | | | so | 0th, 1st, ..., 59th | 5 | - * | | | ss | 00, 01, ..., 59 | | - * | Seconds timestamp | 40 | t | 512969520 | | - * | | | tt | ... | 2 | - * | Fraction of second | 30 | S | 0, 1, ..., 9 | | - * | | | SS | 00, 01, ..., 99 | | - * | | | SSS | 000, 001, ..., 999 | | - * | | | SSSS | ... | 2 | - * | Milliseconds timestamp | 20 | T | 512969520900 | | - * | | | TT | ... | 2 | - * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | | - * | | | XX | -0800, +0530, Z | | - * | | | XXX | -08:00, +05:30, Z | | - * | | | XXXX | -0800, +0530, Z, +123456 | 2 | - * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | | - * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | | - * | | | xx | -0800, +0530, +0000 | | - * | | | xxx | -08:00, +05:30, +00:00 | 2 | - * | | | xxxx | -0800, +0530, +0000, +123456 | | - * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | | - * | Long localized date | NA | P | 05/29/1453 | 5,8 | - * | | | PP | May 29, 1453 | | - * | | | PPP | May 29th, 1453 | | - * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 | - * | Long localized time | NA | p | 12:00 AM | 5,8 | - * | | | pp | 12:00:00 AM | | - * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | | - * | | | PPpp | May 29, 1453, 12:00:00 AM | | - * | | | PPPpp | May 29th, 1453 at ... | | - * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 | - * Notes: - * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale - * are the same as "stand-alone" units, but are different in some languages. - * "Formatting" units are declined according to the rules of the language - * in the context of a date. "Stand-alone" units are always nominative singular. - * In `format` function, they will produce different result: - * - * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'` - * - * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'` - * - * `parse` will try to match both formatting and stand-alone units interchangably. - * - * 2. Any sequence of the identical letters is a pattern, unless it is escaped by - * the single quote characters (see below). - * If the sequence is longer than listed in table: - * - for numerical units (`yyyyyyyy`) `parse` will try to match a number - * as wide as the sequence - * - for text units (`MMMMMMMM`) `parse` will try to match the widest variation of the unit. - * These variations are marked with "2" in the last column of the table. - * - * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales. - * These tokens represent the shortest form of the quarter. - * - * 4. The main difference between `y` and `u` patterns are B.C. years: - * - * | Year | `y` | `u` | - * |------|-----|-----| - * | AC 1 | 1 | 1 | - * | BC 1 | 1 | 0 | - * | BC 2 | 2 | -1 | - * - * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`: + * Set the local week-numbering year to the given date, + * saving the week number and the weekday number. + * The exact calculation depends on the values of + * `options.weekStartsOn` (which is the index of the first day of the week) + * and `options.firstWeekContainsDate` (which is the day of January, which is always in + * the first week of the week-numbering year) * - * `parse('50', 'yy', new Date(2018, 0, 1)) //=> Sat Jan 01 2050 00:00:00` + * Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering * - * `parse('75', 'yy', new Date(2018, 0, 1)) //=> Wed Jan 01 1975 00:00:00` + * @param {Date|Number} date - the date to be changed + * @param {Number} weekYear - the local week-numbering year of the new date + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year + * @returns {Date} the new date with the local week-numbering year set + * @throws {TypeError} 2 arguments required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 * - * while `uu` will just assign the year as is: + * @example + * // Set the local week-numbering year 2004 to 2 January 2010 with default options: + * const result = setWeekYear(new Date(2010, 0, 2), 2004) + * //=> Sat Jan 03 2004 00:00:00 * - * `parse('50', 'uu', new Date(2018, 0, 1)) //=> Sat Jan 01 0050 00:00:00` + * @example + * // Set the local week-numbering year 2004 to 2 January 2010, + * // if Monday is the first day of week + * // and 4 January is always in the first week of the year: + * const result = setWeekYear(new Date(2010, 0, 2), 2004, { + * weekStartsOn: 1, + * firstWeekContainsDate: 4 + * }) + * //=> Sat Jan 01 2005 00:00:00 + */ +function setWeekYear(dirtyDate, dirtyWeekYear, options) { + var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + + (0, _index5.default)(2, arguments); + var defaultOptions = (0, _index6.getDefaultOptions)(); + var firstWeekContainsDate = (0, _index4.default)((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); + var date = (0, _index3.default)(dirtyDate); + var weekYear = (0, _index4.default)(dirtyWeekYear); + var diff = (0, _index.default)(date, (0, _index2.default)(date, options)); + var firstWeek = new Date(0); + firstWeek.setFullYear(weekYear, 0, firstWeekContainsDate); + firstWeek.setHours(0, 0, 0, 0); + date = (0, _index2.default)(firstWeek, options); + date.setDate(date.getDate() + diff); + return date; +} + +module.exports = exports.default; + +/***/ }), + +/***/ 16313: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = setYear; + +var _index = _interopRequireDefault(__nccwpck_require__(35279)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name setYear + * @category Year Helpers + * @summary Set the year to the given date. * - * `parse('75', 'uu', new Date(2018, 0, 1)) //=> Tue Jan 01 0075 00:00:00` + * @description + * Set the year to the given date. * - * The same difference is true for local and ISO week-numbering years (`Y` and `R`), - * except local week-numbering years are dependent on `options.weekStartsOn` - * and `options.firstWeekContainsDate` (compare [setISOWeekYear]{@link https://date-fns.org/docs/setISOWeekYear} - * and [setWeekYear]{@link https://date-fns.org/docs/setWeekYear}). + * @param {Date|Number} date - the date to be changed + * @param {Number} year - the year of the new date + * @returns {Date} the new date with the year set + * @throws {TypeError} 2 arguments required * - * 5. These patterns are not in the Unicode Technical Standard #35: - * - `i`: ISO day of week - * - `I`: ISO week of year - * - `R`: ISO week-numbering year - * - `o`: ordinal number modifier - * - `P`: long localized date - * - `p`: long localized time + * @example + * // Set year 2013 to 1 September 2014: + * const result = setYear(new Date(2014, 8, 1), 2013) + * //=> Sun Sep 01 2013 00:00:00 + */ +function setYear(dirtyDate, dirtyYear) { + (0, _index3.default)(2, arguments); + var date = (0, _index2.default)(dirtyDate); + var year = (0, _index.default)(dirtyYear); // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date + + if (isNaN(date.getTime())) { + return new Date(NaN); + } + + date.setFullYear(year); + return date; +} + +module.exports = exports.default; + +/***/ }), + +/***/ 72287: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = startOfDay; + +var _index = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name startOfDay + * @category Day Helpers + * @summary Return the start of a day for the given date. * - * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years. - * You should enable `options.useAdditionalWeekYearTokens` to use them. See: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @description + * Return the start of a day for the given date. + * The result will be in the local timezone. * - * 7. `D` and `DD` tokens represent days of the year but they are ofthen confused with days of the month. - * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @param {Date|Number} date - the original date + * @returns {Date} the start of a day + * @throws {TypeError} 1 argument required * - * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based - * on the given locale. + * @example + * // The start of a day for 2 September 2014 11:55:00: + * const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Tue Sep 02 2014 00:00:00 + */ +function startOfDay(dirtyDate) { + (0, _index2.default)(1, arguments); + var date = (0, _index.default)(dirtyDate); + date.setHours(0, 0, 0, 0); + return date; +} + +module.exports = exports.default; + +/***/ }), + +/***/ 20343: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = startOfDecade; + +var _index = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name startOfDecade + * @category Decade Helpers + * @summary Return the start of a decade for the given date. * - * using `en-US` locale: `P` => `MM/dd/yyyy` - * using `en-US` locale: `p` => `hh:mm a` - * using `pt-BR` locale: `P` => `dd/MM/yyyy` - * using `pt-BR` locale: `p` => `HH:mm` + * @description + * Return the start of a decade for the given date. * - * Values will be assigned to the date in the descending order of its unit's priority. - * Units of an equal priority overwrite each other in the order of appearance. + * @param {Date|Number} date - the original date + * @returns {Date} the start of a decade + * @throws {TypeError} 1 argument required * - * If no values of higher priority are parsed (e.g. when parsing string 'January 1st' without a year), - * the values will be taken from 3rd argument `referenceDate` which works as a context of parsing. + * @example + * // The start of a decade for 21 October 2015 00:00:00: + * const result = startOfDecade(new Date(2015, 9, 21, 00, 00, 00)) + * //=> Jan 01 2010 00:00:00 + */ +function startOfDecade(dirtyDate) { + (0, _index2.default)(1, arguments); + var date = (0, _index.default)(dirtyDate); + var year = date.getFullYear(); + var decade = Math.floor(year / 10) * 10; + date.setFullYear(decade, 0, 1); + date.setHours(0, 0, 0, 0); + return date; +} + +module.exports = exports.default; + +/***/ }), + +/***/ 46561: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = startOfHour; + +var _index = _interopRequireDefault(__nccwpck_require__(80603)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name startOfHour + * @category Hour Helpers + * @summary Return the start of an hour for the given date. * - * `referenceDate` must be passed for correct work of the function. - * If you're not sure which `referenceDate` to supply, create a new instance of Date: - * `parse('02/11/2014', 'MM/dd/yyyy', new Date())` - * In this case parsing will be done in the context of the current date. - * If `referenceDate` is `Invalid Date` or a value not convertible to valid `Date`, - * then `Invalid Date` will be returned. + * @description + * Return the start of an hour for the given date. + * The result will be in the local timezone. * - * The result may vary by locale. + * @param {Date|Number} date - the original date + * @returns {Date} the start of an hour + * @throws {TypeError} 1 argument required * - * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned. + * @example + * // The start of an hour for 2 September 2014 11:55:00: + * const result = startOfHour(new Date(2014, 8, 2, 11, 55)) + * //=> Tue Sep 02 2014 11:00:00 + */ +function startOfHour(dirtyDate) { + (0, _index2.default)(1, arguments); + var date = (0, _index.default)(dirtyDate); + date.setMinutes(0, 0, 0); + return date; +} + +module.exports = exports.default; + +/***/ }), + +/***/ 25093: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = startOfISOWeek; + +var _index = _interopRequireDefault(__nccwpck_require__(38599)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name startOfISOWeek + * @category ISO Week Helpers + * @summary Return the start of an ISO week for the given date. * - * If parsing failed, `Invalid Date` will be returned. - * Invalid Date is a Date, whose time value is NaN. - * Time value of Date: http://es5.github.io/#x15.9.1.1 + * @description + * Return the start of an ISO week for the given date. + * The result will be in the local timezone. * - * @param {String} dateString - the string to parse - * @param {String} formatString - the string of tokens - * @param {Date|Number} referenceDate - defines values missing from the parsed dateString - * @param {Object} [options] - an object with options. - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year - * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`; - * see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`; - * see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @returns {Date} the parsed date - * @throws {TypeError} 3 arguments required - * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 - * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 - * @throws {RangeError} `options.locale` must contain `match` property - * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: /~https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @throws {RangeError} format string contains an unescaped latin alphabet character + * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date * - * @example - * // Parse 11 February 2014 from middle-endian format: - * var result = parse('02/11/2014', 'MM/dd/yyyy', new Date()) - * //=> Tue Feb 11 2014 00:00:00 + * @param {Date|Number} date - the original date + * @returns {Date} the start of an ISO week + * @throws {TypeError} 1 argument required * * @example - * // Parse 28th of February in Esperanto locale in the context of 2010 year: - * import eo from 'date-fns/locale/eo' - * var result = parse('28-a de februaro', "do 'de' MMMM", new Date(2010, 0, 1), { - * locale: eo - * }) - * //=> Sun Feb 28 2010 00:00:00 + * // The start of an ISO week for 2 September 2014 11:55:00: + * const result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Mon Sep 01 2014 00:00:00 */ +function startOfISOWeek(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate, { + weekStartsOn: 1 + }); +} -function parse(dirtyDateString, dirtyFormatString, dirtyReferenceDate, options) { - var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4; +module.exports = exports.default; - (0, _index9.default)(3, arguments); - var dateString = String(dirtyDateString); - var formatString = String(dirtyFormatString); - var defaultOptions = (0, _index11.getDefaultOptions)(); - var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : _index.default; +/***/ }), - if (!locale.match) { - throw new RangeError('locale must contain match property'); - } +/***/ 34855: +/***/ ((module, exports, __nccwpck_require__) => { - var firstWeekContainsDate = (0, _index8.default)((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN +"use strict"; - if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { - throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively'); - } - var weekStartsOn = (0, _index8.default)((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = startOfISOWeekYear; - if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { - throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); - } +var _index = _interopRequireDefault(__nccwpck_require__(57869)); - if (formatString === '') { - if (dateString === '') { - return (0, _index3.default)(dirtyReferenceDate); - } else { - return new Date(NaN); - } - } +var _index2 = _interopRequireDefault(__nccwpck_require__(25093)); - var subFnOptions = { - firstWeekContainsDate: firstWeekContainsDate, - weekStartsOn: weekStartsOn, - locale: locale - }; // If timezone isn't specified, it will be set to the system timezone +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); - var setters = [new _Setter.DateToSystemTimezoneSetter()]; - var tokens = formatString.match(longFormattingTokensRegExp).map(function (substring) { - var firstCharacter = substring[0]; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (firstCharacter in _index5.default) { - var longFormatter = _index5.default[firstCharacter]; - return longFormatter(substring, locale.formatLong); - } +/** + * @name startOfISOWeekYear + * @category ISO Week-Numbering Year Helpers + * @summary Return the start of an ISO week-numbering year for the given date. + * + * @description + * Return the start of an ISO week-numbering year, + * which always starts 3 days before the year's first Thursday. + * The result will be in the local timezone. + * + * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of an ISO week-numbering year + * @throws {TypeError} 1 argument required + * + * @example + * // The start of an ISO week-numbering year for 2 July 2005: + * const result = startOfISOWeekYear(new Date(2005, 6, 2)) + * //=> Mon Jan 03 2005 00:00:00 + */ +function startOfISOWeekYear(dirtyDate) { + (0, _index3.default)(1, arguments); + var year = (0, _index.default)(dirtyDate); + var fourthOfJanuary = new Date(0); + fourthOfJanuary.setFullYear(year, 0, 4); + fourthOfJanuary.setHours(0, 0, 0, 0); + var date = (0, _index2.default)(fourthOfJanuary); + return date; +} - return substring; - }).join('').match(formattingTokensRegExp); - var usedTokens = []; +module.exports = exports.default; - var _loop = function (_token) { - if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && (0, _index7.isProtectedWeekYearToken)(_token)) { - (0, _index7.throwProtectedError)(_token, formatString, dirtyDateString); - } +/***/ }), - if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && (0, _index7.isProtectedDayOfYearToken)(_token)) { - (0, _index7.throwProtectedError)(_token, formatString, dirtyDateString); - } +/***/ 10749: +/***/ ((module, exports, __nccwpck_require__) => { - var firstCharacter = _token[0]; - var parser = _index10.parsers[firstCharacter]; +"use strict"; - if (parser) { - var incompatibleTokens = parser.incompatibleTokens; - if (Array.isArray(incompatibleTokens)) { - var incompatibleToken = usedTokens.find(function (usedToken) { - return incompatibleTokens.includes(usedToken.token) || usedToken.token === firstCharacter; - }); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = startOfMinute; - if (incompatibleToken) { - throw new RangeError("The format string mustn't contain `".concat(incompatibleToken.fullToken, "` and `").concat(_token, "` at the same time")); - } - } else if (parser.incompatibleTokens === '*' && usedTokens.length > 0) { - throw new RangeError("The format string mustn't contain `".concat(_token, "` and any other token at the same time")); - } +var _index = _interopRequireDefault(__nccwpck_require__(80603)); - usedTokens.push({ - token: firstCharacter, - fullToken: _token - }); - var parseResult = parser.run(dateString, _token, locale.match, subFnOptions); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); - if (!parseResult) { - token = _token; - return { - v: new Date(NaN) - }; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - setters.push(parseResult.setter); - dateString = parseResult.rest; - } else { - if (firstCharacter.match(unescapedLatinCharacterRegExp)) { - throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`'); - } // Replace two single quote characters with one single quote character +/** + * @name startOfMinute + * @category Minute Helpers + * @summary Return the start of a minute for the given date. + * + * @description + * Return the start of a minute for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of a minute + * @throws {TypeError} 1 argument required + * + * @example + * // The start of a minute for 1 December 2014 22:15:45.400: + * const result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) + * //=> Mon Dec 01 2014 22:15:00 + */ +function startOfMinute(dirtyDate) { + (0, _index2.default)(1, arguments); + var date = (0, _index.default)(dirtyDate); + date.setSeconds(0, 0); + return date; +} +module.exports = exports.default; - if (_token === "''") { - _token = "'"; - } else if (firstCharacter === "'") { - _token = cleanEscapedString(_token); - } // Cut token from string, or, if string doesn't match the token, return Invalid Date +/***/ }), +/***/ 12081: +/***/ ((module, exports, __nccwpck_require__) => { - if (dateString.indexOf(_token) === 0) { - dateString = dateString.slice(_token.length); - } else { - token = _token; - return { - v: new Date(NaN) - }; - } - } +"use strict"; - token = _token; - }; - for (var token of tokens) { - var _ret = _loop(token); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = startOfMonth; - if (typeof _ret === "object") return _ret.v; - } // Check if the remaining input contains something other than whitespace +var _index = _interopRequireDefault(__nccwpck_require__(80603)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); - if (dateString.length > 0 && notWhitespaceRegExp.test(dateString)) { - return new Date(NaN); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var uniquePrioritySetters = setters.map(function (setter) { - return setter.priority; - }).sort(function (a, b) { - return b - a; - }).filter(function (priority, index, array) { - return array.indexOf(priority) === index; - }).map(function (priority) { - return setters.filter(function (setter) { - return setter.priority === priority; - }).sort(function (a, b) { - return b.subPriority - a.subPriority; - }); - }).map(function (setterArray) { - return setterArray[0]; - }); - var date = (0, _index3.default)(dirtyReferenceDate); +/** + * @name startOfMonth + * @category Month Helpers + * @summary Return the start of a month for the given date. + * + * @description + * Return the start of a month for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of a month + * @throws {TypeError} 1 argument required + * + * @example + * // The start of a month for 2 September 2014 11:55:00: + * const result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Mon Sep 01 2014 00:00:00 + */ +function startOfMonth(dirtyDate) { + (0, _index2.default)(1, arguments); + var date = (0, _index.default)(dirtyDate); + date.setDate(1); + date.setHours(0, 0, 0, 0); + return date; +} - if (isNaN(date.getTime())) { - return new Date(NaN); - } // Convert the date in system timezone to the same date in UTC+00:00 timezone. +module.exports = exports.default; + +/***/ }), + +/***/ 44860: +/***/ ((module, exports, __nccwpck_require__) => { +"use strict"; - var utcDate = (0, _index2.default)(date, (0, _index6.default)(date)); - var flags = {}; - for (var setter of uniquePrioritySetters) { - if (!setter.validate(utcDate, subFnOptions)) { - return new Date(NaN); - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = startOfQuarter; - var result = setter.set(utcDate, flags, subFnOptions); // Result is tuple (date, flags) +var _index = _interopRequireDefault(__nccwpck_require__(80603)); - if (Array.isArray(result)) { - utcDate = result[0]; - (0, _index4.default)(flags, result[1]); // Result is date - } else { - utcDate = result; - } - } +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); - return utcDate; -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function cleanEscapedString(input) { - return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'"); +/** + * @name startOfQuarter + * @category Quarter Helpers + * @summary Return the start of a year quarter for the given date. + * + * @description + * Return the start of a year quarter for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of a quarter + * @throws {TypeError} 1 argument required + * + * @example + * // The start of a quarter for 2 September 2014 11:55:00: + * const result = startOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Tue Jul 01 2014 00:00:00 + */ +function startOfQuarter(dirtyDate) { + (0, _index2.default)(1, arguments); + var date = (0, _index.default)(dirtyDate); + var currentMonth = date.getMonth(); + var month = currentMonth - currentMonth % 3; + date.setMonth(month, 1); + date.setHours(0, 0, 0, 0); + return date; } module.exports = exports.default; /***/ }), -/***/ 33390: +/***/ 20740: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -73428,285 +69875,375 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = parseISO; - -var _index = __nccwpck_require__(25756); +exports["default"] = startOfSecond; -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name parseISO - * @category Common Helpers - * @summary Parse ISO string + * @name startOfSecond + * @category Second Helpers + * @summary Return the start of a second for the given date. * * @description - * Parse the given string in ISO 8601 format and return an instance of Date. - * - * Function accepts complete ISO 8601 formats as well as partial implementations. - * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601 - * - * If the argument isn't a string, the function cannot parse the string or - * the values are invalid, it returns Invalid Date. + * Return the start of a second for the given date. + * The result will be in the local timezone. * - * @param {String} argument - the value to convert - * @param {Object} [options] - an object with options. - * @param {0|1|2} [options.additionalDigits=2] - the additional number of digits in the extended year format - * @returns {Date} the parsed date in the local time zone + * @param {Date|Number} date - the original date + * @returns {Date} the start of a second * @throws {TypeError} 1 argument required - * @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2 * * @example - * // Convert string '2014-02-11T11:30:30' to date: - * const result = parseISO('2014-02-11T11:30:30') - * //=> Tue Feb 11 2014 11:30:30 + * // The start of a second for 1 December 2014 22:15:45.400: + * const result = startOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) + * //=> Mon Dec 01 2014 22:15:45.000 + */ +function startOfSecond(dirtyDate) { + (0, _index2.default)(1, arguments); + var date = (0, _index.default)(dirtyDate); + date.setMilliseconds(0); + return date; +} + +module.exports = exports.default; + +/***/ }), + +/***/ 89912: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = startOfToday; + +var _index = _interopRequireDefault(__nccwpck_require__(72287)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name startOfToday + * @category Day Helpers + * @summary Return the start of today. + * @pure false + * + * @description + * Return the start of today. + * + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `Date.now()` internally hence impure and can't be safely curried. + * + * @returns {Date} the start of today * * @example - * // Convert string '+02014101' to date, - * // if the additional number of digits in the extended year format is 1: - * const result = parseISO('+02014101', { additionalDigits: 1 }) - * //=> Fri Apr 11 2014 00:00:00 + * // If today is 6 October 2014: + * const result = startOfToday() + * //=> Mon Oct 6 2014 00:00:00 */ -function parseISO(argument, options) { - var _options$additionalDi; +function startOfToday() { + return (0, _index.default)(Date.now()); +} - (0, _index2.default)(1, arguments); - var additionalDigits = (0, _index3.default)((_options$additionalDi = options === null || options === void 0 ? void 0 : options.additionalDigits) !== null && _options$additionalDi !== void 0 ? _options$additionalDi : 2); +module.exports = exports.default; - if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) { - throw new RangeError('additionalDigits must be 0, 1 or 2'); - } +/***/ }), - if (!(typeof argument === 'string' || Object.prototype.toString.call(argument) === '[object String]')) { - return new Date(NaN); - } +/***/ 25713: +/***/ ((module, exports) => { - var dateStrings = splitDateString(argument); - var date; +"use strict"; - if (dateStrings.date) { - var parseYearResult = parseYear(dateStrings.date, additionalDigits); - date = parseDate(parseYearResult.restDateString, parseYearResult.year); - } - if (!date || isNaN(date.getTime())) { - return new Date(NaN); - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = startOfTomorrow; - var timestamp = date.getTime(); - var time = 0; - var offset; +/** + * @name startOfTomorrow + * @category Day Helpers + * @summary Return the start of tomorrow. + * @pure false + * + * @description + * Return the start of tomorrow. + * + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `new Date()` internally hence impure and can't be safely curried. + * + * @returns {Date} the start of tomorrow + * + * @example + * // If today is 6 October 2014: + * const result = startOfTomorrow() + * //=> Tue Oct 7 2014 00:00:00 + */ +function startOfTomorrow() { + var now = new Date(); + var year = now.getFullYear(); + var month = now.getMonth(); + var day = now.getDate(); + var date = new Date(0); + date.setFullYear(year, month, day + 1); + date.setHours(0, 0, 0, 0); + return date; +} - if (dateStrings.time) { - time = parseTime(dateStrings.time); +module.exports = exports.default; - if (isNaN(time)) { - return new Date(NaN); - } - } +/***/ }), - if (dateStrings.timezone) { - offset = parseTimezone(dateStrings.timezone); +/***/ 38599: +/***/ ((module, exports, __nccwpck_require__) => { - if (isNaN(offset)) { - return new Date(NaN); - } - } else { - var dirtyDate = new Date(timestamp + time); // js parsed string assuming it's in UTC timezone - // but we need it to be parsed in our timezone - // so we use utc values to build date in our timezone. - // Year values from 0 to 99 map to the years 1900 to 1999 - // so set year explicitly with setFullYear. +"use strict"; - var result = new Date(0); - result.setFullYear(dirtyDate.getUTCFullYear(), dirtyDate.getUTCMonth(), dirtyDate.getUTCDate()); - result.setHours(dirtyDate.getUTCHours(), dirtyDate.getUTCMinutes(), dirtyDate.getUTCSeconds(), dirtyDate.getUTCMilliseconds()); - return result; - } - return new Date(timestamp + time + offset); -} +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = startOfWeek; -var patterns = { - dateTimeDelimiter: /[T ]/, - timeZoneDelimiter: /[Z ]/i, - timezone: /([Z+-].*)$/ -}; -var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/; -var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/; -var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/; +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -function splitDateString(dateString) { - var dateStrings = {}; - var array = dateString.split(patterns.dateTimeDelimiter); - var timeString; // The regex match should only return at maximum two array elements. - // [date], [time], or [date, time]. +var _index2 = _interopRequireDefault(__nccwpck_require__(35279)); - if (array.length > 2) { - return dateStrings; - } +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); - if (/:/.test(array[0])) { - timeString = array[0]; - } else { - dateStrings.date = array[0]; - timeString = array[1]; +var _index4 = __nccwpck_require__(79115); - if (patterns.timeZoneDelimiter.test(dateStrings.date)) { - dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0]; - timeString = dateString.substr(dateStrings.date.length, dateString.length); - } - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (timeString) { - var token = patterns.timezone.exec(timeString); +/** + * @name startOfWeek + * @category Week Helpers + * @summary Return the start of a week for the given date. + * + * @description + * Return the start of a week for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @returns {Date} the start of a week + * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * + * @example + * // The start of a week for 2 September 2014 11:55:00: + * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Sun Aug 31 2014 00:00:00 + * + * @example + * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00: + * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 }) + * //=> Mon Sep 01 2014 00:00:00 + */ +function startOfWeek(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; - if (token) { - dateStrings.time = timeString.replace(token[1], ''); - dateStrings.timezone = token[1]; - } else { - dateStrings.time = timeString; - } + (0, _index3.default)(1, arguments); + var defaultOptions = (0, _index4.getDefaultOptions)(); + var weekStartsOn = (0, _index2.default)((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); } - return dateStrings; + var date = (0, _index.default)(dirtyDate); + var day = date.getDay(); + var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; + date.setDate(date.getDate() - diff); + date.setHours(0, 0, 0, 0); + return date; } -function parseYear(dateString, additionalDigits) { - var regex = new RegExp('^(?:(\\d{4}|[+-]\\d{' + (4 + additionalDigits) + '})|(\\d{2}|[+-]\\d{' + (2 + additionalDigits) + '})$)'); - var captures = dateString.match(regex); // Invalid ISO-formatted year +module.exports = exports.default; - if (!captures) return { - year: NaN, - restDateString: '' - }; - var year = captures[1] ? parseInt(captures[1]) : null; - var century = captures[2] ? parseInt(captures[2]) : null; // either year or century is null, not both +/***/ }), - return { - year: century === null ? year : century * 100, - restDateString: dateString.slice((captures[1] || captures[2]).length) - }; -} +/***/ 53392: +/***/ ((module, exports, __nccwpck_require__) => { -function parseDate(dateString, year) { - // Invalid ISO-formatted year - if (year === null) return new Date(NaN); - var captures = dateString.match(dateRegex); // Invalid ISO-formatted string +"use strict"; - if (!captures) return new Date(NaN); - var isWeekDate = !!captures[4]; - var dayOfYear = parseDateUnit(captures[1]); - var month = parseDateUnit(captures[2]) - 1; - var day = parseDateUnit(captures[3]); - var week = parseDateUnit(captures[4]); - var dayOfWeek = parseDateUnit(captures[5]) - 1; - if (isWeekDate) { - if (!validateWeekDate(year, week, dayOfWeek)) { - return new Date(NaN); - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = startOfWeekYear; - return dayOfISOWeekYear(year, week, dayOfWeek); - } else { - var date = new Date(0); +var _index = _interopRequireDefault(__nccwpck_require__(51354)); - if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) { - return new Date(NaN); - } +var _index2 = _interopRequireDefault(__nccwpck_require__(38599)); - date.setUTCFullYear(year, month, Math.max(dayOfYear, day)); - return date; - } -} +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); -function parseDateUnit(value) { - return value ? parseInt(value) : 1; -} +var _index4 = _interopRequireDefault(__nccwpck_require__(76822)); -function parseTime(timeString) { - var captures = timeString.match(timeRegex); - if (!captures) return NaN; // Invalid ISO-formatted time +var _index5 = __nccwpck_require__(79115); - var hours = parseTimeUnit(captures[1]); - var minutes = parseTimeUnit(captures[2]); - var seconds = parseTimeUnit(captures[3]); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (!validateTime(hours, minutes, seconds)) { - return NaN; - } +/** + * @name startOfWeekYear + * @category Week-Numbering Year Helpers + * @summary Return the start of a local week-numbering year for the given date. + * + * @description + * Return the start of a local week-numbering year. + * The exact calculation depends on the values of + * `options.weekStartsOn` (which is the index of the first day of the week) + * and `options.firstWeekContainsDate` (which is the day of January, which is always in + * the first week of the week-numbering year) + * + * Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering + * + * @param {Date|Number} date - the original date + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year + * @returns {Date} the start of a week-numbering year + * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 + * + * @example + * // The start of an a week-numbering year for 2 July 2005 with default settings: + * const result = startOfWeekYear(new Date(2005, 6, 2)) + * //=> Sun Dec 26 2004 00:00:00 + * + * @example + * // The start of a week-numbering year for 2 July 2005 + * // if Monday is the first day of week + * // and 4 January is always in the first week of the year: + * const result = startOfWeekYear(new Date(2005, 6, 2), { + * weekStartsOn: 1, + * firstWeekContainsDate: 4 + * }) + * //=> Mon Jan 03 2005 00:00:00 + */ +function startOfWeekYear(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; - return hours * _index.millisecondsInHour + minutes * _index.millisecondsInMinute + seconds * 1000; + (0, _index4.default)(1, arguments); + var defaultOptions = (0, _index5.getDefaultOptions)(); + var firstWeekContainsDate = (0, _index3.default)((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); + var year = (0, _index.default)(dirtyDate, options); + var firstWeek = new Date(0); + firstWeek.setFullYear(year, 0, firstWeekContainsDate); + firstWeek.setHours(0, 0, 0, 0); + var date = (0, _index2.default)(firstWeek, options); + return date; } -function parseTimeUnit(value) { - return value && parseFloat(value.replace(',', '.')) || 0; -} +module.exports = exports.default; -function parseTimezone(timezoneString) { - if (timezoneString === 'Z') return 0; - var captures = timezoneString.match(timezoneRegex); - if (!captures) return 0; - var sign = captures[1] === '+' ? -1 : 1; - var hours = parseInt(captures[2]); - var minutes = captures[3] && parseInt(captures[3]) || 0; +/***/ }), - if (!validateTimezone(hours, minutes)) { - return NaN; - } +/***/ 71986: +/***/ ((module, exports, __nccwpck_require__) => { - return sign * (hours * _index.millisecondsInHour + minutes * _index.millisecondsInMinute); -} +"use strict"; -function dayOfISOWeekYear(isoWeekYear, week, day) { - var date = new Date(0); - date.setUTCFullYear(isoWeekYear, 0, 4); - var fourthOfJanuaryDay = date.getUTCDay() || 7; - var diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay; - date.setUTCDate(date.getUTCDate() + diff); - return date; -} // Validation functions -// February is null to handle the leap year (using ||) +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = startOfYear; -var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +var _index = _interopRequireDefault(__nccwpck_require__(80603)); -function isLeapYearIndex(year) { - return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0; -} +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -function validateDate(year, month, date) { - return month >= 0 && month <= 11 && date >= 1 && date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28)); -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function validateDayOfYearDate(year, dayOfYear) { - return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365); +/** + * @name startOfYear + * @category Year Helpers + * @summary Return the start of a year for the given date. + * + * @description + * Return the start of a year for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of a year + * @throws {TypeError} 1 argument required + * + * @example + * // The start of a year for 2 September 2014 11:55:00: + * const result = startOfYear(new Date(2014, 8, 2, 11, 55, 00)) + * //=> Wed Jan 01 2014 00:00:00 + */ +function startOfYear(dirtyDate) { + (0, _index2.default)(1, arguments); + var cleanDate = (0, _index.default)(dirtyDate); + var date = new Date(0); + date.setFullYear(cleanDate.getFullYear(), 0, 1); + date.setHours(0, 0, 0, 0); + return date; } -function validateWeekDate(_year, week, day) { - return week >= 1 && week <= 53 && day >= 0 && day <= 6; -} +module.exports = exports.default; -function validateTime(hours, minutes, seconds) { - if (hours === 24) { - return minutes === 0 && seconds === 0; - } +/***/ }), - return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25; -} +/***/ 3610: +/***/ ((module, exports) => { -function validateTimezone(_hours, minutes) { - return minutes >= 0 && minutes <= 59; +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = startOfYesterday; + +/** + * @name startOfYesterday + * @category Day Helpers + * @summary Return the start of yesterday. + * @pure false + * + * @description + * Return the start of yesterday. + * + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `new Date()` internally hence impure and can't be safely curried. + * + * @returns {Date} the start of yesterday + * + * @example + * // If today is 6 October 2014: + * const result = startOfYesterday() + * //=> Sun Oct 5 2014 00:00:00 + */ +function startOfYesterday() { + var now = new Date(); + var year = now.getFullYear(); + var month = now.getMonth(); + var day = now.getDate(); + var date = new Date(0); + date.setFullYear(year, month, day - 1); + date.setHours(0, 0, 0, 0); + return date; } module.exports = exports.default; /***/ }), -/***/ 28159: +/***/ 79395: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -73715,70 +70252,84 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = parseJSON; +exports["default"] = sub; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(80289)); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(54591)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); + +var _index4 = _interopRequireDefault(__nccwpck_require__(35279)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name parseJSON + * @name sub * @category Common Helpers - * @summary Parse a JSON date string + * @summary Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date. * * @description - * Converts a complete ISO date string in UTC time, the typical format for transmitting - * a date in JSON, to a JavaScript `Date` instance. - * - * This is a minimal implementation for converting dates retrieved from a JSON API to - * a `Date` instance which can be used with other functions in the `date-fns` library. - * The following formats are supported: + * Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date. * - * - `2000-03-15T05:20:10.123Z`: The output of `.toISOString()` and `JSON.stringify(new Date())` - * - `2000-03-15T05:20:10Z`: Without milliseconds - * - `2000-03-15T05:20:10+00:00`: With a zero offset, the default JSON encoded format in some other languages - * - `2000-03-15T05:20:10+05:45`: With a positive or negative offset, the default JSON encoded format in some other languages - * - `2000-03-15T05:20:10+0000`: With a zero offset without a colon - * - `2000-03-15T05:20:10`: Without a trailing 'Z' symbol - * - `2000-03-15T05:20:10.1234567`: Up to 7 digits in milliseconds field. Only first 3 are taken into account since JS does not allow fractional milliseconds - * - `2000-03-15 05:20:10`: With a space instead of a 'T' separator for APIs returning a SQL date without reformatting + * @param {Date|Number} date - the date to be changed + * @param {Duration} duration - the object with years, months, weeks, days, hours, minutes and seconds to be subtracted * - * For convenience and ease of use these other input types are also supported - * via [toDate]{@link https://date-fns.org/docs/toDate}: + * | Key | Description | + * |---------|------------------------------------| + * | years | Amount of years to be subtracted | + * | months | Amount of months to be subtracted | + * | weeks | Amount of weeks to be subtracted | + * | days | Amount of days to be subtracted | + * | hours | Amount of hours to be subtracted | + * | minutes | Amount of minutes to be subtracted | + * | seconds | Amount of seconds to be subtracted | * - * - A `Date` instance will be cloned - * - A `number` will be treated as a timestamp + * All values default to 0 * - * Any other input type or invalid date strings will return an `Invalid Date`. + * @returns {Date} the new date with the seconds subtracted + * @throws {TypeError} 2 arguments required * - * @param {String|Number|Date} argument A fully formed ISO8601 date string to convert - * @returns {Date} the parsed date in the local time zone - * @throws {TypeError} 1 argument required + * @example + * // Subtract the following duration from 15 June 2017 15:29:20 + * const result = sub(new Date(2017, 5, 15, 15, 29, 20), { + * years: 2, + * months: 9, + * weeks: 1, + * days: 7, + * hours: 5, + * minutes: 9, + * seconds: 30 + * }) + * //=> Mon Sep 1 2014 10:19:50 */ -function parseJSON(argument) { - (0, _index2.default)(1, arguments); - - if (typeof argument === 'string') { - var parts = argument.match(/(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{0,7}))?(?:Z|(.)(\d{2}):?(\d{2})?)?/); +function sub(date, duration) { + (0, _index3.default)(2, arguments); + if (!duration || typeof duration !== 'object') return new Date(NaN); + var years = duration.years ? (0, _index4.default)(duration.years) : 0; + var months = duration.months ? (0, _index4.default)(duration.months) : 0; + var weeks = duration.weeks ? (0, _index4.default)(duration.weeks) : 0; + var days = duration.days ? (0, _index4.default)(duration.days) : 0; + var hours = duration.hours ? (0, _index4.default)(duration.hours) : 0; + var minutes = duration.minutes ? (0, _index4.default)(duration.minutes) : 0; + var seconds = duration.seconds ? (0, _index4.default)(duration.seconds) : 0; // Subtract years and months - if (parts) { - // Group 8 matches the sign - return new Date(Date.UTC(+parts[1], +parts[2] - 1, +parts[3], +parts[4] - (+parts[9] || 0) * (parts[8] == '-' ? -1 : 1), +parts[5] - (+parts[10] || 0) * (parts[8] == '-' ? -1 : 1), +parts[6], +((parts[7] || '0') + '00').substring(0, 3))); - } + var dateWithoutMonths = (0, _index2.default)(date, months + years * 12); // Subtract weeks and days - return new Date(NaN); - } + var dateWithoutDays = (0, _index.default)(dateWithoutMonths, days + weeks * 7); // Subtract hours, minutes and seconds - return (0, _index.default)(argument); + var minutestoSub = minutes + hours * 60; + var secondstoSub = seconds + minutestoSub * 60; + var mstoSub = secondstoSub * 1000; + var finalDate = new Date(dateWithoutDays.getTime() - mstoSub); + return finalDate; } module.exports = exports.default; /***/ }), -/***/ 68756: +/***/ 569: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -73787,51 +70338,45 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = previousDay; +exports["default"] = subBusinessDays; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(96547)); -var _index2 = _interopRequireDefault(__nccwpck_require__(9361)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index3 = _interopRequireDefault(__nccwpck_require__(50970)); +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name previousDay - * @category Weekday Helpers - * @summary When is the previous day of the week? + * @name subBusinessDays + * @category Day Helpers + * @summary Substract the specified number of business days (mon - fri) to the given date. * * @description - * When is the previous day of the week? 0-6 the day of the week, 0 represents Sunday. - * - * @param {Date | number} date - the date to check - * @param {number} day - day of the week - * @returns {Date} - the date is the previous day of week - * @throws {TypeError} - 2 arguments required + * Substract the specified number of business days (mon - fri) to the given date, ignoring weekends. * - * @example - * // When is the previous Monday before Mar, 20, 2020? - * const result = previousDay(new Date(2020, 2, 20), 1) - * //=> Mon Mar 16 2020 00:00:00 + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of business days to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the business days subtracted + * @throws {TypeError} 2 arguments required * * @example - * // When is the previous Tuesday before Mar, 21, 2020? - * const result = previousDay(new Date(2020, 2, 21), 2) - * //=> Tue Mar 17 2020 00:00:00 + * // Substract 10 business days from 1 September 2014: + * const result = subBusinessDays(new Date(2014, 8, 1), 10) + * //=> Mon Aug 18 2014 00:00:00 (skipped weekend days) */ -function previousDay(date, day) { - (0, _index.default)(2, arguments); - var delta = (0, _index2.default)(date) - day; - if (delta <= 0) delta += 7; - return (0, _index3.default)(date, delta); +function subBusinessDays(dirtyDate, dirtyAmount) { + (0, _index2.default)(2, arguments); + var amount = (0, _index3.default)(dirtyAmount); + return (0, _index.default)(dirtyDate, -amount); } module.exports = exports.default; /***/ }), -/***/ 9558: +/***/ 80289: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -73840,41 +70385,45 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = previousFriday; +exports["default"] = subDays; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(53426)); -var _index2 = _interopRequireDefault(__nccwpck_require__(68756)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name previousFriday - * @category Weekday Helpers - * @summary When is the previous Friday? + * @name subDays + * @category Day Helpers + * @summary Subtract the specified number of days from the given date. * * @description - * When is the previous Friday? + * Subtract the specified number of days from the given date. * - * @param {Date | number} date - the date to start counting from - * @returns {Date} the previous Friday - * @throws {TypeError} 1 argument required + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of days to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the days subtracted + * @throws {TypeError} 2 arguments required * * @example - * // When is the previous Friday before Jun, 19, 2021? - * const result = previousFriday(new Date(2021, 5, 19)) - * //=> Fri June 18 2021 00:00:00 + * // Subtract 10 days from 1 September 2014: + * const result = subDays(new Date(2014, 8, 1), 10) + * //=> Fri Aug 22 2014 00:00:00 */ -function previousFriday(date) { - (0, _index.default)(1, arguments); - return (0, _index2.default)(date, 5); +function subDays(dirtyDate, dirtyAmount) { + (0, _index2.default)(2, arguments); + var amount = (0, _index3.default)(dirtyAmount); + return (0, _index.default)(dirtyDate, -amount); } module.exports = exports.default; /***/ }), -/***/ 48386: +/***/ 51423: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -73883,41 +70432,45 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = previousMonday; +exports["default"] = subHours; + +var _index = _interopRequireDefault(__nccwpck_require__(15856)); -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = _interopRequireDefault(__nccwpck_require__(68756)); +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name previousMonday - * @category Weekday Helpers - * @summary When is the previous Monday? + * @name subHours + * @category Hour Helpers + * @summary Subtract the specified number of hours from the given date. * * @description - * When is the previous Monday? + * Subtract the specified number of hours from the given date. * - * @param {Date | number} date - the date to start counting from - * @returns {Date} the previous Monday - * @throws {TypeError} 1 argument required + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of hours to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the hours subtracted + * @throws {TypeError} 2 arguments required * * @example - * // When is the previous Monday before Jun, 18, 2021? - * const result = previousMonday(new Date(2021, 5, 18)) - * //=> Mon June 14 2021 00:00:00 + * // Subtract 2 hours from 11 July 2014 01:00:00: + * const result = subHours(new Date(2014, 6, 11, 1, 0), 2) + * //=> Thu Jul 10 2014 23:00:00 */ -function previousMonday(date) { - (0, _index.default)(1, arguments); - return (0, _index2.default)(date, 1); +function subHours(dirtyDate, dirtyAmount) { + (0, _index2.default)(2, arguments); + var amount = (0, _index3.default)(dirtyAmount); + return (0, _index.default)(dirtyDate, -amount); } module.exports = exports.default; /***/ }), -/***/ 94834: +/***/ 34148: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -73926,41 +70479,47 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = previousSaturday; +exports["default"] = subISOWeekYears; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(18809)); -var _index2 = _interopRequireDefault(__nccwpck_require__(68756)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name previousSaturday - * @category Weekday Helpers - * @summary When is the previous Saturday? + * @name subISOWeekYears + * @category ISO Week-Numbering Year Helpers + * @summary Subtract the specified number of ISO week-numbering years from the given date. * * @description - * When is the previous Saturday? + * Subtract the specified number of ISO week-numbering years from the given date. * - * @param {Date | number} date - the date to start counting from - * @returns {Date} the previous Saturday - * @throws {TypeError} 1 argument required + * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of ISO week-numbering years to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the ISO week-numbering years subtracted + * @throws {TypeError} 2 arguments required * * @example - * // When is the previous Saturday before Jun, 20, 2021? - * const result = previousSaturday(new Date(2021, 5, 20)) - * //=> Sat June 19 2021 00:00:00 + * // Subtract 5 ISO week-numbering years from 1 September 2014: + * const result = subISOWeekYears(new Date(2014, 8, 1), 5) + * //=> Mon Aug 31 2009 00:00:00 */ -function previousSaturday(date) { - (0, _index.default)(1, arguments); - return (0, _index2.default)(date, 6); +function subISOWeekYears(dirtyDate, dirtyAmount) { + (0, _index2.default)(2, arguments); + var amount = (0, _index3.default)(dirtyAmount); + return (0, _index.default)(dirtyDate, -amount); } module.exports = exports.default; /***/ }), -/***/ 60264: +/***/ 88874: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -73969,41 +70528,45 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = previousSunday; +exports["default"] = subMilliseconds; + +var _index = _interopRequireDefault(__nccwpck_require__(23734)); -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = _interopRequireDefault(__nccwpck_require__(68756)); +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name previousSunday - * @category Weekday Helpers - * @summary When is the previous Sunday? + * @name subMilliseconds + * @category Millisecond Helpers + * @summary Subtract the specified number of milliseconds from the given date. * * @description - * When is the previous Sunday? + * Subtract the specified number of milliseconds from the given date. * - * @param {Date | number} date - the date to start counting from - * @returns {Date} the previous Sunday - * @throws {TypeError} 1 argument required + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of milliseconds to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the milliseconds subtracted + * @throws {TypeError} 2 arguments required * * @example - * // When is the previous Sunday before Jun, 21, 2021? - * const result = previousSunday(new Date(2021, 5, 21)) - * //=> Sun June 20 2021 00:00:00 + * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000: + * const result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) + * //=> Thu Jul 10 2014 12:45:29.250 */ -function previousSunday(date) { - (0, _index.default)(1, arguments); - return (0, _index2.default)(date, 0); +function subMilliseconds(dirtyDate, dirtyAmount) { + (0, _index2.default)(2, arguments); + var amount = (0, _index3.default)(dirtyAmount); + return (0, _index.default)(dirtyDate, -amount); } module.exports = exports.default; /***/ }), -/***/ 70019: +/***/ 27350: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -74012,41 +70575,45 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = previousThursday; +exports["default"] = subMinutes; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(23232)); -var _index2 = _interopRequireDefault(__nccwpck_require__(68756)); +var _index2 = _interopRequireDefault(__nccwpck_require__(76822)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(35279)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name previousThursday - * @category Weekday Helpers - * @summary When is the previous Thursday? + * @name subMinutes + * @category Minute Helpers + * @summary Subtract the specified number of minutes from the given date. * * @description - * When is the previous Thursday? + * Subtract the specified number of minutes from the given date. * - * @param {Date | number} date - the date to start counting from - * @returns {Date} the previous Thursday - * @throws {TypeError} 1 argument required + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of minutes to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the minutes subtracted + * @throws {TypeError} 2 arguments required * * @example - * // When is the previous Thursday before Jun, 18, 2021? - * const result = previousThursday(new Date(2021, 5, 18)) - * //=> Thu June 17 2021 00:00:00 + * // Subtract 30 minutes from 10 July 2014 12:00:00: + * const result = subMinutes(new Date(2014, 6, 10, 12, 0), 30) + * //=> Thu Jul 10 2014 11:30:00 */ -function previousThursday(date) { - (0, _index.default)(1, arguments); - return (0, _index2.default)(date, 4); +function subMinutes(dirtyDate, dirtyAmount) { + (0, _index2.default)(2, arguments); + var amount = (0, _index3.default)(dirtyAmount); + return (0, _index.default)(dirtyDate, -amount); } module.exports = exports.default; /***/ }), -/***/ 3294: +/***/ 54591: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -74055,41 +70622,45 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = previousTuesday; +exports["default"] = subMonths; + +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(71158)); -var _index2 = _interopRequireDefault(__nccwpck_require__(68756)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name previousTuesday - * @category Weekday Helpers - * @summary When is the previous Tuesday? + * @name subMonths + * @category Month Helpers + * @summary Subtract the specified number of months from the given date. * * @description - * When is the previous Tuesday? + * Subtract the specified number of months from the given date. * - * @param {Date | number} date - the date to start counting from - * @returns {Date} the previous Tuesday - * @throws {TypeError} 1 argument required + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of months to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the months subtracted + * @throws {TypeError} 2 arguments required * * @example - * // When is the previous Tuesday before Jun, 18, 2021? - * const result = previousTuesday(new Date(2021, 5, 18)) - * //=> Tue June 15 2021 00:00:00 + * // Subtract 5 months from 1 February 2015: + * const result = subMonths(new Date(2015, 1, 1), 5) + * //=> Mon Sep 01 2014 00:00:00 */ -function previousTuesday(date) { - (0, _index.default)(1, arguments); - return (0, _index2.default)(date, 2); +function subMonths(dirtyDate, dirtyAmount) { + (0, _index3.default)(2, arguments); + var amount = (0, _index.default)(dirtyAmount); + return (0, _index2.default)(dirtyDate, -amount); } module.exports = exports.default; /***/ }), -/***/ 48630: +/***/ 98728: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -74098,41 +70669,45 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = previousWednesday; +exports["default"] = subQuarters; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index2 = _interopRequireDefault(__nccwpck_require__(68756)); +var _index2 = _interopRequireDefault(__nccwpck_require__(5341)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name previousWednesday - * @category Weekday Helpers - * @summary When is the previous Wednesday? + * @name subQuarters + * @category Quarter Helpers + * @summary Subtract the specified number of year quarters from the given date. * * @description - * When is the previous Wednesday? + * Subtract the specified number of year quarters from the given date. * - * @param {Date | number} date - the date to start counting from - * @returns {Date} the previous Wednesday - * @throws {TypeError} 1 argument required + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of quarters to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the quarters subtracted + * @throws {TypeError} 2 arguments required * * @example - * // When is the previous Wednesday before Jun, 18, 2021? - * const result = previousWednesday(new Date(2021, 5, 18)) - * //=> Wed June 16 2021 00:00:00 + * // Subtract 3 quarters from 1 September 2014: + * const result = subQuarters(new Date(2014, 8, 1), 3) + * //=> Sun Dec 01 2013 00:00:00 */ -function previousWednesday(date) { - (0, _index.default)(1, arguments); - return (0, _index2.default)(date, 3); +function subQuarters(dirtyDate, dirtyAmount) { + (0, _index3.default)(2, arguments); + var amount = (0, _index.default)(dirtyAmount); + return (0, _index2.default)(dirtyDate, -amount); } module.exports = exports.default; /***/ }), -/***/ 78995: +/***/ 29133: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -74141,42 +70716,45 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = quartersToMonths; +exports["default"] = subSeconds; + +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(97927)); -var _index2 = __nccwpck_require__(25756); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name quartersToMonths - * @category Conversion Helpers - * @summary Convert number of quarters to months. + * @name subSeconds + * @category Second Helpers + * @summary Subtract the specified number of seconds from the given date. * * @description - * Convert a number of quarters to a full number of months. - * - * @param {number} quarters - number of quarters to be converted + * Subtract the specified number of seconds from the given date. * - * @returns {number} the number of quarters converted in months - * @throws {TypeError} 1 argument required + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of seconds to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the seconds subtracted + * @throws {TypeError} 2 arguments required * * @example - * // Convert 2 quarters to months - * const result = quartersToMonths(2) - * //=> 6 + * // Subtract 30 seconds from 10 July 2014 12:45:00: + * const result = subSeconds(new Date(2014, 6, 10, 12, 45, 0), 30) + * //=> Thu Jul 10 2014 12:44:30 */ -function quartersToMonths(quarters) { - (0, _index.default)(1, arguments); - return Math.floor(quarters * _index2.monthsInQuarter); +function subSeconds(dirtyDate, dirtyAmount) { + (0, _index3.default)(2, arguments); + var amount = (0, _index.default)(dirtyAmount); + return (0, _index2.default)(dirtyDate, -amount); } module.exports = exports.default; /***/ }), -/***/ 40883: +/***/ 47076: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -74185,48 +70763,45 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = quartersToYears; +exports["default"] = subWeeks; + +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(75214)); -var _index2 = __nccwpck_require__(25756); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name quartersToYears - * @category Conversion Helpers - * @summary Convert number of quarters to years. + * @name subWeeks + * @category Week Helpers + * @summary Subtract the specified number of weeks from the given date. * * @description - * Convert a number of quarters to a full number of years. - * - * @param {number} quarters - number of quarters to be converted - * - * @returns {number} the number of quarters converted in years - * @throws {TypeError} 1 argument required + * Subtract the specified number of weeks from the given date. * - * @example - * // Convert 8 quarters to years - * const result = quartersToYears(8) - * //=> 2 + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of weeks to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the weeks subtracted + * @throws {TypeError} 2 arguments required * * @example - * // It uses floor rounding: - * const result = quartersToYears(11) - * //=> 2 + * // Subtract 4 weeks from 1 September 2014: + * const result = subWeeks(new Date(2014, 8, 1), 4) + * //=> Mon Aug 04 2014 00:00:00 */ -function quartersToYears(quarters) { - (0, _index.default)(1, arguments); - var years = quarters / _index2.quartersInYear; - return Math.floor(years); +function subWeeks(dirtyDate, dirtyAmount) { + (0, _index3.default)(2, arguments); + var amount = (0, _index.default)(dirtyAmount); + return (0, _index2.default)(dirtyDate, -amount); } module.exports = exports.default; /***/ }), -/***/ 75515: +/***/ 61751: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -74235,73 +70810,115 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = roundToNearestMinutes; +exports["default"] = subYears; -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +var _index = _interopRequireDefault(__nccwpck_require__(35279)); -var _index2 = __nccwpck_require__(58016); +var _index2 = _interopRequireDefault(__nccwpck_require__(91590)); -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index3 = _interopRequireDefault(__nccwpck_require__(76822)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name roundToNearestMinutes - * @category Minute Helpers - * @summary Rounds the given date to the nearest minute + * @name subYears + * @category Year Helpers + * @summary Subtract the specified number of years from the given date. * * @description - * Rounds the given date to the nearest minute (or number of minutes). - * Rounds up when the given date is exactly between the nearest round minutes. + * Subtract the specified number of years from the given date. * - * @param {Date|Number} date - the date to round - * @param {Object} [options] - an object with options. - * @param {Number} [options.nearestTo=1] - nearest number of minutes to round to. E.g. `15` to round to quarter hours. - * @param {String} [options.roundingMethod='trunc'] - a rounding method (`ceil`, `floor`, `round` or `trunc`) - * @returns {Date} the new date rounded to the closest minute + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of years to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the years subtracted + * @throws {TypeError} 2 arguments required + * + * @example + * // Subtract 5 years from 1 September 2014: + * const result = subYears(new Date(2014, 8, 1), 5) + * //=> Tue Sep 01 2009 00:00:00 + */ +function subYears(dirtyDate, dirtyAmount) { + (0, _index3.default)(2, arguments); + var amount = (0, _index.default)(dirtyAmount); + return (0, _index2.default)(dirtyDate, -amount); +} + +module.exports = exports.default; + +/***/ }), + +/***/ 80603: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = toDate; + +var _index = _interopRequireDefault(__nccwpck_require__(76822)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name toDate + * @category Common Helpers + * @summary Convert the given argument to an instance of Date. + * + * @description + * Convert the given argument to an instance of Date. + * + * If the argument is an instance of Date, the function returns its clone. + * + * If the argument is a number, it is treated as a timestamp. + * + * If the argument is none of the above, the function returns Invalid Date. + * + * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`. + * + * @param {Date|Number} argument - the value to convert + * @returns {Date} the parsed date in the local time zone * @throws {TypeError} 1 argument required - * @throws {RangeError} `options.nearestTo` must be between 1 and 30 * * @example - * // Round 10 July 2014 12:12:34 to nearest minute: - * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34)) - * //=> Thu Jul 10 2014 12:13:00 + * // Clone the date: + * const result = toDate(new Date(2014, 1, 11, 11, 30, 30)) + * //=> Tue Feb 11 2014 11:30:30 * * @example - * // Round 10 July 2014 12:07:30 to nearest quarter hour: - * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { nearestTo: 15 }) - * // rounds up because given date is exactly between 12:00:00 and 12:15:00 - * //=> Thu Jul 10 2014 12:15:00 + * // Convert the timestamp to date: + * const result = toDate(1392098430000) + * //=> Tue Feb 11 2014 11:30:30 */ -function roundToNearestMinutes(dirtyDate, options) { - var _options$nearestTo; +function toDate(argument) { + (0, _index.default)(1, arguments); + var argStr = Object.prototype.toString.call(argument); // Clone the date - if (arguments.length < 1) { - throw new TypeError('1 argument required, but only none provided present'); - } + if (argument instanceof Date || typeof argument === 'object' && argStr === '[object Date]') { + // Prevent the date to lose the milliseconds when passed to new Date() in IE10 + return new Date(argument.getTime()); + } else if (typeof argument === 'number' || argStr === '[object Number]') { + return new Date(argument); + } else { + if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') { + // eslint-disable-next-line no-console + console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: /~https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"); // eslint-disable-next-line no-console - var nearestTo = (0, _index3.default)((_options$nearestTo = options === null || options === void 0 ? void 0 : options.nearestTo) !== null && _options$nearestTo !== void 0 ? _options$nearestTo : 1); + console.warn(new Error().stack); + } - if (nearestTo < 1 || nearestTo > 30) { - throw new RangeError('`options.nearestTo` must be between 1 and 30'); + return new Date(NaN); } - - var date = (0, _index.default)(dirtyDate); - var seconds = date.getSeconds(); // relevant if nearestTo is 1, which is the default case - - var minutes = date.getMinutes() + seconds / 60; - var roundingMethod = (0, _index2.getRoundingMethod)(options === null || options === void 0 ? void 0 : options.roundingMethod); - var roundedMinutes = roundingMethod(minutes / nearestTo) * nearestTo; - var remainderMinutes = minutes % nearestTo; - var addedMinutes = Math.round(remainderMinutes / nearestTo) * nearestTo; - return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), roundedMinutes + addedMinutes); } module.exports = exports.default; /***/ }), -/***/ 60594: +/***/ 61287: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -74310,48 +70927,42 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = secondsToHours; +exports["default"] = weeksToDays; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = __nccwpck_require__(25756); +var _index2 = __nccwpck_require__(24665); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name secondsToHours + * @name weeksToDays * @category Conversion Helpers - * @summary Convert seconds to hours. + * @summary Convert weeks to days. * * @description - * Convert a number of seconds to a full number of hours. + * Convert a number of weeks to a full number of days. * - * @param {number} seconds - number of seconds to be converted + * @param {number} weeks - number of weeks to be converted * - * @returns {number} the number of seconds converted in hours + * @returns {number} the number of weeks converted in days * @throws {TypeError} 1 argument required * * @example - * // Convert 7200 seconds into hours - * const result = secondsToHours(7200) - * //=> 2 - * - * @example - * // It uses floor rounding: - * const result = secondsToHours(7199) - * //=> 1 + * // Convert 2 weeks into days + * const result = weeksToDays(2) + * //=> 14 */ -function secondsToHours(seconds) { +function weeksToDays(weeks) { (0, _index.default)(1, arguments); - var hours = seconds / _index2.secondsInHour; - return Math.floor(hours); + return Math.floor(weeks * _index2.daysInWeek); } module.exports = exports.default; /***/ }), -/***/ 26779: +/***/ 28436: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -74360,42 +70971,42 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = secondsToMilliseconds; +exports["default"] = yearsToMonths; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = __nccwpck_require__(25756); +var _index2 = __nccwpck_require__(24665); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name secondsToMilliseconds + * @name yearsToMonths * @category Conversion Helpers - * @summary Convert seconds to milliseconds. + * @summary Convert years to months. * * @description - * Convert a number of seconds to a full number of milliseconds. + * Convert a number of years to a full number of months. * - * @param {number} seconds - number of seconds to be converted + * @param {number} years - number of years to be converted * - * @returns {number} the number of seconds converted in milliseconds + * @returns {number} the number of years converted in months * @throws {TypeError} 1 argument required * * @example - * // Convert 2 seconds into milliseconds - * const result = secondsToMilliseconds(2) - * //=> 2000 + * // Convert 2 years into months + * const result = yearsToMonths(2) + * //=> 24 */ -function secondsToMilliseconds(seconds) { +function yearsToMonths(years) { (0, _index.default)(1, arguments); - return seconds * _index2.millisecondsInSecond; + return Math.floor(years * _index2.monthsInYear); } module.exports = exports.default; /***/ }), -/***/ 78438: +/***/ 55738: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -74404,10927 +71015,12891 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = secondsToMinutes; +exports["default"] = yearsToQuarters; -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +var _index = _interopRequireDefault(__nccwpck_require__(76822)); -var _index2 = __nccwpck_require__(25756); +var _index2 = __nccwpck_require__(24665); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name secondsToMinutes + * @name yearsToQuarters * @category Conversion Helpers - * @summary Convert seconds to minutes. + * @summary Convert years to quarters. * * @description - * Convert a number of seconds to a full number of minutes. + * Convert a number of years to a full number of quarters. * - * @param {number} seconds - number of seconds to be converted + * @param {number} years - number of years to be converted * - * @returns {number} the number of seconds converted in minutes + * @returns {number} the number of years converted in quarters * @throws {TypeError} 1 argument required * * @example - * // Convert 120 seconds into minutes - * const result = secondsToMinutes(120) - * //=> 2 - * - * @example - * // It uses floor rounding: - * const result = secondsToMinutes(119) - * //=> 1 + * // Convert 2 years to quarters + * const result = yearsToQuarters(2) + * //=> 8 */ -function secondsToMinutes(seconds) { +function yearsToQuarters(years) { (0, _index.default)(1, arguments); - var minutes = seconds / _index2.secondsInMinute; - return Math.floor(minutes); + return Math.floor(years * _index2.quartersInYear); } module.exports = exports.default; /***/ }), -/***/ 32031: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 40249: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Stream = (__nccwpck_require__(12781).Stream); +var util = __nccwpck_require__(73837); + +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)); +}; + + +/***/ }), + +/***/ 38455: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = set; +Object.defineProperty(exports, "__esModule", ({ value: true })); + +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) -var _index = _interopRequireDefault(__nccwpck_require__(26477)); + /* istanbul ignore next */ -var _index2 = _interopRequireDefault(__nccwpck_require__(80847)); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); + this.name = 'Deprecation'; + } -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +exports.Deprecation = Deprecation; + + +/***/ }), + +/***/ 89834: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var CombinedStream = __nccwpck_require__(59987); +var util = __nccwpck_require__(73837); +var path = __nccwpck_require__(71017); +var http = __nccwpck_require__(13685); +var https = __nccwpck_require__(95687); +var parseUrl = (__nccwpck_require__(57310).parse); +var fs = __nccwpck_require__(57147); +var Stream = (__nccwpck_require__(12781).Stream); +var mime = __nccwpck_require__(92075); +var asynckit = __nccwpck_require__(74324); +var populate = __nccwpck_require__(21513); + +// Public API +module.exports = FormData; + +// make it a Stream +util.inherits(FormData, CombinedStream); /** - * @name set - * @category Common Helpers - * @summary Set date values to a given date. - * - * @description - * Set date values to a given date. - * - * Sets time values to date from object `values`. - * A value is not set if it is undefined or null or doesn't exist in `values`. - * - * Note about bundle size: `set` does not internally use `setX` functions from date-fns but instead opts - * to use native `Date#setX` methods. If you use this function, you may not want to include the - * other `setX` functions that date-fns provides if you are concerned about the bundle size. - * - * @param {Date|Number} date - the date to be changed - * @param {Object} values - an object with options - * @param {Number} [values.year] - the number of years to be set - * @param {Number} [values.month] - the number of months to be set - * @param {Number} [values.date] - the number of days to be set - * @param {Number} [values.hours] - the number of hours to be set - * @param {Number} [values.minutes] - the number of minutes to be set - * @param {Number} [values.seconds] - the number of seconds to be set - * @param {Number} [values.milliseconds] - the number of milliseconds to be set - * @returns {Date} the new date with options set - * @throws {TypeError} 2 arguments required - * @throws {RangeError} `values` must be an object - * - * @example - * // Transform 1 September 2014 into 20 October 2015 in a single line: - * const result = set(new Date(2014, 8, 20), { year: 2015, month: 9, date: 20 }) - * //=> Tue Oct 20 2015 00:00:00 + * Create readable "multipart/form-data" streams. + * Can be used to submit forms + * and file uploads to other web applications. * - * @example - * // Set 12 PM to 1 September 2014 01:23:45 to 1 September 2014 12:00:00: - * const result = set(new Date(2014, 8, 1, 1, 23, 45), { hours: 12 }) - * //=> Mon Sep 01 2014 12:23:45 + * @constructor + * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream */ -function set(dirtyDate, values) { - (0, _index4.default)(2, arguments); +function FormData(options) { + if (!(this instanceof FormData)) { + return new FormData(options); + } - if (typeof values !== 'object' || values === null) { - throw new RangeError('values parameter must be an object'); + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; + + CombinedStream.call(this); + + options = options || {}; + for (var option in options) { + this[option] = options[option]; + } +} + +FormData.LINE_BREAK = '\r\n'; +FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; + +FormData.prototype.append = function(field, value, options) { + + options = options || {}; + + // allow filename as single option + if (typeof options == 'string') { + options = {filename: options}; + } + + var append = CombinedStream.prototype.append.bind(this); + + // all that streamy business can't handle numbers + if (typeof value == 'number') { + value = '' + value; + } + + // /~https://github.com/felixge/node-form-data/issues/38 + if (util.isArray(value)) { + // Please convert your array into string + // the way web server expects it + this._error(new Error('Arrays are not supported.')); + return; + } + + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); + + append(header); + append(value); + append(footer); + + // pass along options.knownLength + this._trackLength(header, value, options); +}; + +FormData.prototype._trackLength = function(header, value, options) { + var valueLength = 0; + + // used w/ getLengthSync(), when length is known. + // e.g. for streaming directly from a remote server, + // w/ a known file a size, and not wanting to wait for + // incoming file to finish to get its size. + if (options.knownLength != null) { + valueLength += +options.knownLength; + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); + } + + this._valueLength += valueLength; + + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += + Buffer.byteLength(header) + + FormData.LINE_BREAK.length; + + // empty or either doesn't have path or not an http response or not a stream + if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { + return; + } + + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } +}; + +FormData.prototype._lengthRetriever = function(value, callback) { + + if (value.hasOwnProperty('fd')) { + + // take read range into a account + // `end` = Infinity –> read file till the end + // + // TODO: Looks like there is bug in Node fs.createReadStream + // it doesn't respect `end` options without `start` options + // Fix it when node fixes it. + // /~https://github.com/joyent/node/issues/7819 + if (value.end != undefined && value.end != Infinity && value.start != undefined) { + + // when end specified + // no need to calculate range + // inclusive, starts with 0 + callback(null, value.end + 1 - (value.start ? value.start : 0)); + + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function(err, stat) { + + var fileSize; + + if (err) { + callback(err); + return; + } + + // update final size based on the range options + fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } + + // or http response + } else if (value.hasOwnProperty('httpVersion')) { + callback(null, +value.headers['content-length']); + + // or request stream http://github.com/mikeal/request + } else if (value.hasOwnProperty('httpModule')) { + // wait till response come back + value.on('response', function(response) { + value.pause(); + callback(null, +response.headers['content-length']); + }); + value.resume(); + + // something else + } else { + callback('Unknown stream'); + } +}; + +FormData.prototype._multiPartHeader = function(field, value, options) { + // custom header specified (as string)? + // it becomes responsible for boundary + // (e.g. to handle extra CRLFs on .NET servers) + if (typeof options.header == 'string') { + return options.header; + } + + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); + + var contents = ''; + var headers = { + // add custom disposition as third element or keep it two elements if not + 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + 'Content-Type': [].concat(contentType || []) + }; + + // allow custom headers. + if (typeof options.header == 'object') { + populate(headers, options.header); + } + + var header; + for (var prop in headers) { + if (!headers.hasOwnProperty(prop)) continue; + header = headers[prop]; + + // skip nullish headers. + if (header == null) { + continue; + } + + // convert all headers to arrays. + if (!Array.isArray(header)) { + header = [header]; + } + + // add non-empty headers. + if (header.length) { + contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; + } + } + + return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; +}; + +FormData.prototype._getContentDisposition = function(value, options) { + + var filename + , contentDisposition + ; + + if (typeof options.filepath === 'string') { + // custom filepath for relative paths + filename = path.normalize(options.filepath).replace(/\\/g, '/'); + } else if (options.filename || value.name || value.path) { + // custom filename take precedence + // formidable and the browser add a name property + // fs- and request- streams have path property + filename = path.basename(options.filename || value.name || value.path); + } else if (value.readable && value.hasOwnProperty('httpVersion')) { + // or try http response + filename = path.basename(value.client._httpMessage.path || ''); + } + + if (filename) { + contentDisposition = 'filename="' + filename + '"'; } - var date = (0, _index.default)(dirtyDate); // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date + return contentDisposition; +}; - if (isNaN(date.getTime())) { - return new Date(NaN); - } +FormData.prototype._getContentType = function(value, options) { - if (values.year != null) { - date.setFullYear(values.year); - } + // use custom content-type above all + var contentType = options.contentType; - if (values.month != null) { - date = (0, _index2.default)(date, values.month); + // or try `name` from formidable, browser + if (!contentType && value.name) { + contentType = mime.lookup(value.name); } - if (values.date != null) { - date.setDate((0, _index3.default)(values.date)); + // or try `path` from fs-, request- streams + if (!contentType && value.path) { + contentType = mime.lookup(value.path); } - if (values.hours != null) { - date.setHours((0, _index3.default)(values.hours)); + // or if it's http-reponse + if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { + contentType = value.headers['content-type']; } - if (values.minutes != null) { - date.setMinutes((0, _index3.default)(values.minutes)); + // or guess it from the filepath or filename + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); } - if (values.seconds != null) { - date.setSeconds((0, _index3.default)(values.seconds)); + // fallback to the default content type if `value` is not simple value + if (!contentType && typeof value == 'object') { + contentType = FormData.DEFAULT_CONTENT_TYPE; } - if (values.milliseconds != null) { - date.setMilliseconds((0, _index3.default)(values.milliseconds)); - } + return contentType; +}; - return date; -} +FormData.prototype._multiPartFooter = function() { + return function(next) { + var footer = FormData.LINE_BREAK; -module.exports = exports.default; + var lastPart = (this._streams.length === 0); + if (lastPart) { + footer += this._lastBoundary(); + } -/***/ }), + next(footer); + }.bind(this); +}; -/***/ 68760: -/***/ ((module, exports, __nccwpck_require__) => { +FormData.prototype._lastBoundary = function() { + return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +}; -"use strict"; +FormData.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() + }; + for (header in userHeaders) { + if (userHeaders.hasOwnProperty(header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; + } + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setDate; + return formHeaders; +}; -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +FormData.prototype.setBoundary = function(boundary) { + this._boundary = boundary; +}; -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); +FormData.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); + } -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); + return this._boundary; +}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +FormData.prototype.getBuffer = function() { + var dataBuffer = new Buffer.alloc( 0 ); + var boundary = this.getBoundary(); -/** - * @name setDate - * @category Day Helpers - * @summary Set the day of the month to the given date. - * - * @description - * Set the day of the month to the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} dayOfMonth - the day of the month of the new date - * @returns {Date} the new date with the day of the month set - * @throws {TypeError} 2 arguments required - * - * @example - * // Set the 30th day of the month to 1 September 2014: - * const result = setDate(new Date(2014, 8, 1), 30) - * //=> Tue Sep 30 2014 00:00:00 - */ -function setDate(dirtyDate, dirtyDayOfMonth) { - (0, _index3.default)(2, arguments); - var date = (0, _index2.default)(dirtyDate); - var dayOfMonth = (0, _index.default)(dirtyDayOfMonth); - date.setDate(dayOfMonth); - return date; -} + // Create the form content. Add Line breaks to the end of data. + for (var i = 0, len = this._streams.length; i < len; i++) { + if (typeof this._streams[i] !== 'function') { -module.exports = exports.default; + // Add content to the buffer. + if(Buffer.isBuffer(this._streams[i])) { + dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); + }else { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); + } -/***/ }), + // Add break after content. + if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); + } + } + } -/***/ 89540: -/***/ ((module, exports, __nccwpck_require__) => { + // Add the footer and return the Buffer object. + return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); +}; -"use strict"; +FormData.prototype._generateBoundary = function() { + // This generates a 50 character boundary similar to those used by Firefox. + // They are optimized for boyer-moore parsing. + var boundary = '--------------------------'; + for (var i = 0; i < 24; i++) { + boundary += Math.floor(Math.random() * 10).toString(16); + } + this._boundary = boundary; +}; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setDay; +// Note: getLengthSync DOESN'T calculate streams length +// As workaround one can calculate file size manually +// and add it as knownLength option +FormData.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; -var _index = _interopRequireDefault(__nccwpck_require__(56227)); + // Don't get confused, there are 3 "internal" streams for each keyval pair + // so it basically checks if there is any value added to the form + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); + // /~https://github.com/form-data/form-data/issues/40 + if (!this.hasKnownLength()) { + // Some async length retrievers are present + // therefore synchronous length calculation is false. + // Please use getLength(callback) to get proper length + this._error(new Error('Cannot calculate proper length in synchronous way.')); + } -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); + return knownLength; +}; -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +// Public API to check if length of added values is known +// /~https://github.com/form-data/form-data/issues/196 +// /~https://github.com/form-data/form-data/issues/262 +FormData.prototype.hasKnownLength = function() { + var hasKnownLength = true; -var _index5 = __nccwpck_require__(79307); + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return hasKnownLength; +}; -/** - * @name setDay - * @category Weekday Helpers - * @summary Set the day of the week to the given date. - * - * @description - * Set the day of the week to the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} day - the day of the week of the new date - * @param {Object} [options] - an object with options. - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the new date with the day of the week set - * @throws {TypeError} 2 arguments required - * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 - * - * @example - * // Set week day to Sunday, with the default weekStartsOn of Sunday: - * const result = setDay(new Date(2014, 8, 1), 0) - * //=> Sun Aug 31 2014 00:00:00 - * - * @example - * // Set week day to Sunday, with a weekStartsOn of Monday: - * const result = setDay(new Date(2014, 8, 1), 0, { weekStartsOn: 1 }) - * //=> Sun Sep 07 2014 00:00:00 - */ -function setDay(dirtyDate, dirtyDay, options) { - var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; +FormData.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; - (0, _index4.default)(2, arguments); - var defaultOptions = (0, _index5.getDefaultOptions)(); - var weekStartsOn = (0, _index3.default)((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } - if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { - throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; } - var date = (0, _index2.default)(dirtyDate); - var day = (0, _index3.default)(dirtyDay); - var currentDay = date.getDay(); - var remainder = day % 7; - var dayIndex = (remainder + 7) % 7; - var delta = 7 - weekStartsOn; - var diff = day < 0 || day > 6 ? day - (currentDay + delta) % 7 : (dayIndex + delta) % 7 - (currentDay + delta) % 7; - return (0, _index.default)(date, diff); -} + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; + } -module.exports = exports.default; + values.forEach(function(length) { + knownLength += length; + }); -/***/ }), + cb(null, knownLength); + }); +}; -/***/ 34002: -/***/ ((module, exports, __nccwpck_require__) => { +FormData.prototype.submit = function(params, cb) { + var request + , options + , defaults = {method: 'post'} + ; -"use strict"; + // parse provided url if it's string + // or treat it as options object + if (typeof params == 'string') { + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setDayOfYear; + // use custom params + } else { -var _index = _interopRequireDefault(__nccwpck_require__(1985)); + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol == 'https:' ? 443 : 80; + } + } -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); + // https if specified, fallback to http in any other case + if (options.protocol == 'https:') { + request = https.request(options); + } else { + request = http.request(options); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // get content length and fire away + this.getLength(function(err, length) { + if (err && err !== 'Unknown stream') { + this._error(err); + return; + } -/** - * @name setDayOfYear - * @category Day Helpers - * @summary Set the day of the year to the given date. - * - * @description - * Set the day of the year to the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} dayOfYear - the day of the year of the new date - * @returns {Date} the new date with the day of the year set - * @throws {TypeError} 2 arguments required - * - * @example - * // Set the 2nd day of the year to 2 July 2014: - * const result = setDayOfYear(new Date(2014, 6, 2), 2) - * //=> Thu Jan 02 2014 00:00:00 - */ -function setDayOfYear(dirtyDate, dirtyDayOfYear) { - (0, _index3.default)(2, arguments); - var date = (0, _index2.default)(dirtyDate); - var dayOfYear = (0, _index.default)(dirtyDayOfYear); - date.setMonth(0); - date.setDate(dayOfYear); - return date; -} + // add content length + if (length) { + request.setHeader('Content-Length', length); + } -module.exports = exports.default; + this.pipe(request); + if (cb) { + var onResponse; -/***/ }), + var callback = function (error, responce) { + request.removeListener('error', callback); + request.removeListener('response', onResponse); -/***/ 30054: -/***/ ((module, exports, __nccwpck_require__) => { + return cb.call(this, error, responce); + }; -"use strict"; + onResponse = callback.bind(this, null); + request.on('error', callback); + request.on('response', onResponse); + } + }.bind(this)); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setDefaultOptions; + return request; +}; -var _index = __nccwpck_require__(79307); +FormData.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit('error', err); + } +}; -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +FormData.prototype.toString = function () { + return '[object FormData]'; +}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/** - * @name setDefaultOptions - * @category Common Helpers - * @summary Set default options including locale. - * @pure false - * - * @description - * Sets the defaults for - * `options.locale`, `options.weekStartsOn` and `options.firstWeekContainsDate` - * arguments for all functions. - * - * @param {Object} newOptions - an object with options. - * @param {Locale} [newOptions.locale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @param {0|1|2|3|4|5|6} [newOptions.weekStartsOn] - the index of the first day of the week (0 - Sunday) - * @param {1|2|3|4|5|6|7} [newOptions.firstWeekContainsDate] - the day of January, which is always in the first week of the year - * @throws {TypeError} 1 argument required - * - * @example - * // Set global locale: - * import { es } from 'date-fns/locale' - * setDefaultOptions({ locale: es }) - * const result = format(new Date(2014, 8, 2), 'PPPP') - * //=> 'martes, 2 de septiembre de 2014' - * - * @example - * // Start of the week for 2 September 2014: - * const result = startOfWeek(new Date(2014, 8, 2)) - * //=> Sun Aug 31 2014 00:00:00 - * - * @example - * // Start of the week for 2 September 2014, - * // when we set that week starts on Monday by default: - * setDefaultOptions({ weekStartsOn: 1 }) - * const result = startOfWeek(new Date(2014, 8, 2)) - * //=> Mon Sep 01 2014 00:00:00 - * - * @example - * // Manually set options take priority over default options: - * setDefaultOptions({ weekStartsOn: 1 }) - * const result = startOfWeek(new Date(2014, 8, 2), { weekStartsOn: 0 }) - * //=> Sun Aug 31 2014 00:00:00 - * - * @example - * // Remove the option by setting it to `undefined`: - * setDefaultOptions({ weekStartsOn: 1 }) - * setDefaultOptions({ weekStartsOn: undefined }) - * const result = startOfWeek(new Date(2014, 8, 2)) - * //=> Sun Aug 31 2014 00:00:00 - */ -function setDefaultOptions(newOptions) { - (0, _index2.default)(1, arguments); - var result = {}; - var defaultOptions = (0, _index.getDefaultOptions)(); +/***/ }), - for (var property in defaultOptions) { - if (Object.prototype.hasOwnProperty.call(defaultOptions, property)) { - ; - result[property] = defaultOptions[property]; - } - } +/***/ 21513: +/***/ ((module) => { - for (var _property in newOptions) { - if (Object.prototype.hasOwnProperty.call(newOptions, _property)) { - if (newOptions[_property] === undefined) { - delete result[_property]; - } else { - ; - result[_property] = newOptions[_property]; - } - } - } +// populates missing values +module.exports = function(dst, src) { - (0, _index.setDefaultOptions)(result); -} + Object.keys(src).forEach(function(prop) + { + dst[prop] = dst[prop] || src[prop]; + }); + + return dst; +}; -module.exports = exports.default; /***/ }), -/***/ 96355: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 34014: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setHours; +Object.defineProperty(exports, "__esModule", ({ value: true })); + +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +function isObject(o) { + return Object.prototype.toString.call(o) === '[object Object]'; +} -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); +function isPlainObject(o) { + var ctor,prot; -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); + if (isObject(o) === false) return false; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // If has modified constructor + ctor = o.constructor; + if (ctor === undefined) return true; -/** - * @name setHours - * @category Hour Helpers - * @summary Set the hours to the given date. - * - * @description - * Set the hours to the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} hours - the hours of the new date - * @returns {Date} the new date with the hours set - * @throws {TypeError} 2 arguments required - * - * @example - * // Set 4 hours to 1 September 2014 11:30:00: - * const result = setHours(new Date(2014, 8, 1, 11, 30), 4) - * //=> Mon Sep 01 2014 04:30:00 - */ -function setHours(dirtyDate, dirtyHours) { - (0, _index3.default)(2, arguments); - var date = (0, _index2.default)(dirtyDate); - var hours = (0, _index.default)(dirtyHours); - date.setHours(hours); - return date; + // If has modified prototype + prot = ctor.prototype; + if (isObject(prot) === false) return false; + + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; + } + + // Most likely a plain Object + return true; } -module.exports = exports.default; +exports.isPlainObject = isPlainObject; + /***/ }), -/***/ 23705: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 4467: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setISODay; +// A linked list to keep track of recently-used-ness +const Yallist = __nccwpck_require__(44851) + +const MAX = Symbol('max') +const LENGTH = Symbol('length') +const LENGTH_CALCULATOR = Symbol('lengthCalculator') +const ALLOW_STALE = Symbol('allowStale') +const MAX_AGE = Symbol('maxAge') +const DISPOSE = Symbol('dispose') +const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') +const LRU_LIST = Symbol('lruList') +const CACHE = Symbol('cache') +const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') + +const naiveLength = () => 1 -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +// lruList is a yallist where the head is the youngest +// item, and the tail is the oldest. the list contains the Hit +// objects as the entries. +// Each Hit object has a reference to its Yallist.Node. This +// never changes. +// +// cache is a Map (or PseudoMap) that matches the keys to +// the Yallist.Node object. +class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options } -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); + if (!options) + options = {} -var _index3 = _interopRequireDefault(__nccwpck_require__(56227)); + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + const max = this[MAX] = options.max || Infinity -var _index4 = _interopRequireDefault(__nccwpck_require__(98313)); + const lc = options.length || naiveLength + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc + this[ALLOW_STALE] = options.stale || false + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0 + this[DISPOSE] = options.dispose + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false + this.reset() + } -var _index5 = _interopRequireDefault(__nccwpck_require__(82063)); + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + this[MAX] = mL || Infinity + trim(this) + } + get max () { + return this[MAX] + } -/** - * @name setISODay - * @category Weekday Helpers - * @summary Set the day of the ISO week to the given date. - * - * @description - * Set the day of the ISO week to the given date. - * ISO week starts with Monday. - * 7 is the index of Sunday, 1 is the index of Monday etc. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} day - the day of the ISO week of the new date - * @returns {Date} the new date with the day of the ISO week set - * @throws {TypeError} 2 arguments required - * - * @example - * // Set Sunday to 1 September 2014: - * const result = setISODay(new Date(2014, 8, 1), 7) - * //=> Sun Sep 07 2014 00:00:00 - */ -function setISODay(dirtyDate, dirtyDay) { - (0, _index5.default)(2, arguments); - var date = (0, _index2.default)(dirtyDate); - var day = (0, _index.default)(dirtyDay); - var currentDay = (0, _index4.default)(date); - var diff = day - currentDay; - return (0, _index3.default)(date, diff); -} + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale + } + get allowStale () { + return this[ALLOW_STALE] + } -module.exports = exports.default; + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') -/***/ }), + this[MAX_AGE] = mA + trim(this) + } + get maxAge () { + return this[MAX_AGE] + } -/***/ 33035: -/***/ ((module, exports, __nccwpck_require__) => { + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength -"use strict"; + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC + this[LENGTH] = 0 + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) + this[LENGTH] += hit.length + }) + } + trim(this) + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setISOWeek; + rforEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev + forEachStep(this, fn, walker, thisp) + walker = prev + } + } -var _index = _interopRequireDefault(__nccwpck_require__(1985)); + forEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next + forEachStep(this, fn, walker, thisp) + walker = next + } + } -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } -var _index3 = _interopRequireDefault(__nccwpck_require__(19894)); + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + this[CACHE] = new Map() // hash of items by key + this[LRU_LIST] = new Yallist() // list of items in order of use recency + this[LENGTH] = 0 // length of items in the list + } -/** - * @name setISOWeek - * @category ISO Week Helpers - * @summary Set the ISO week to the given date. - * - * @description - * Set the ISO week to the given date, saving the weekday number. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|Number} date - the date to be changed - * @param {Number} isoWeek - the ISO week of the new date - * @returns {Date} the new date with the ISO week set - * @throws {TypeError} 2 arguments required - * - * @example - * // Set the 53rd ISO week to 7 August 2004: - * const result = setISOWeek(new Date(2004, 7, 7), 53) - * //=> Sat Jan 01 2005 00:00:00 - */ -function setISOWeek(dirtyDate, dirtyISOWeek) { - (0, _index4.default)(2, arguments); - var date = (0, _index2.default)(dirtyDate); - var isoWeek = (0, _index.default)(dirtyISOWeek); - var diff = (0, _index3.default)(date) - isoWeek; - date.setDate(date.getDate() - diff * 7); - return date; -} + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } -module.exports = exports.default; + dumpLru () { + return this[LRU_LIST] + } -/***/ }), + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE] -/***/ 50822: -/***/ ((module, exports, __nccwpck_require__) => { + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') -"use strict"; + const now = maxAge ? Date.now() : 0 + const len = this[LENGTH_CALCULATOR](value, key) + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)) + return false + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setISOWeekYear; + const node = this[CACHE].get(key) + const item = node.value -var _index = _interopRequireDefault(__nccwpck_require__(1985)); + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value) + } -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); + item.now = now + item.maxAge = maxAge + item.value = value + this[LENGTH] += len - item.length + item.length = len + this.get(key) + trim(this) + return true + } -var _index3 = _interopRequireDefault(__nccwpck_require__(60776)); + const hit = new Entry(key, value, len, now, maxAge) -var _index4 = _interopRequireDefault(__nccwpck_require__(3086)); + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value) -var _index5 = _interopRequireDefault(__nccwpck_require__(82063)); + return false + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + this[LENGTH] += hit.length + this[LRU_LIST].unshift(hit) + this[CACHE].set(key, this[LRU_LIST].head) + trim(this) + return true + } -/** - * @name setISOWeekYear - * @category ISO Week-Numbering Year Helpers - * @summary Set the ISO week-numbering year to the given date. - * - * @description - * Set the ISO week-numbering year to the given date, - * saving the week number and the weekday number. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|Number} date - the date to be changed - * @param {Number} isoWeekYear - the ISO week-numbering year of the new date - * @returns {Date} the new date with the ISO week-numbering year set - * @throws {TypeError} 2 arguments required - * - * @example - * // Set ISO week-numbering year 2007 to 29 December 2008: - * const result = setISOWeekYear(new Date(2008, 11, 29), 2007) - * //=> Mon Jan 01 2007 00:00:00 - */ -function setISOWeekYear(dirtyDate, dirtyISOWeekYear) { - (0, _index5.default)(2, arguments); - var date = (0, _index2.default)(dirtyDate); - var isoWeekYear = (0, _index.default)(dirtyISOWeekYear); - var diff = (0, _index4.default)(date, (0, _index3.default)(date)); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(isoWeekYear, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - date = (0, _index3.default)(fourthOfJanuary); - date.setDate(date.getDate() + diff); - return date; -} + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value + return !isStale(this, hit) + } -module.exports = exports.default; + get (key) { + return get(this, key, true) + } -/***/ }), + peek (key) { + return get(this, key, false) + } -/***/ 59105: -/***/ ((module, exports, __nccwpck_require__) => { + pop () { + const node = this[LRU_LIST].tail + if (!node) + return null -"use strict"; + del(this, node) + return node.value + } + del (key) { + del(this, this[CACHE].get(key)) + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setMilliseconds; + load (arr) { + // reset the cache + this.reset() -var _index = _interopRequireDefault(__nccwpck_require__(1985)); + const now = Date.now() + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l] + const expiresAt = hit.e || 0 + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v) + else { + const maxAge = expiresAt - now + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge) + } + } + } + } -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); + prune () { + this[CACHE].forEach((value, key) => get(this, key, false)) + } +} -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +const get = (self, key, doUse) => { + const node = self[CACHE].get(key) + if (node) { + const hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now() + self[LRU_LIST].unshiftNode(node) + } + } + return hit.value + } +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false -/** - * @name setMilliseconds - * @category Millisecond Helpers - * @summary Set the milliseconds to the given date. - * - * @description - * Set the milliseconds to the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} milliseconds - the milliseconds of the new date - * @returns {Date} the new date with the milliseconds set - * @throws {TypeError} 2 arguments required - * - * @example - * // Set 300 milliseconds to 1 September 2014 11:30:40.500: - * const result = setMilliseconds(new Date(2014, 8, 1, 11, 30, 40, 500), 300) - * //=> Mon Sep 01 2014 11:30:40.300 - */ -function setMilliseconds(dirtyDate, dirtyMilliseconds) { - (0, _index3.default)(2, arguments); - var date = (0, _index2.default)(dirtyDate); - var milliseconds = (0, _index.default)(dirtyMilliseconds); - date.setMilliseconds(milliseconds); - return date; + const diff = Date.now() - hit.now + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) } -module.exports = exports.default; +const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev + del(self, walker) + walker = prev + } + } +} -/***/ }), +const del = (self, node) => { + if (node) { + const hit = node.value + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value) -/***/ 49207: -/***/ ((module, exports, __nccwpck_require__) => { + self[LENGTH] -= hit.length + self[CACHE].delete(hit.key) + self[LRU_LIST].removeNode(node) + } +} -"use strict"; +class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key + this.value = value + this.length = length + this.now = now + this.maxAge = maxAge || 0 + } +} +const forEachStep = (self, fn, node, thisp) => { + let hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + hit = undefined + } + if (hit) + fn.call(thisp, hit.value, hit.key, self) +} -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setMinutes; +module.exports = LRUCache -var _index = _interopRequireDefault(__nccwpck_require__(1985)); -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); +/***/ }), -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +/***/ 67165: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ /** - * @name setMinutes - * @category Minute Helpers - * @summary Set the minutes to the given date. - * - * @description - * Set the minutes to the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} minutes - the minutes of the new date - * @returns {Date} the new date with the minutes set - * @throws {TypeError} 2 arguments required - * - * @example - * // Set 45 minutes to 1 September 2014 11:30:40: - * const result = setMinutes(new Date(2014, 8, 1, 11, 30, 40), 45) - * //=> Mon Sep 01 2014 11:45:40 + * Module exports. */ -function setMinutes(dirtyDate, dirtyMinutes) { - (0, _index3.default)(2, arguments); - var date = (0, _index2.default)(dirtyDate); - var minutes = (0, _index.default)(dirtyMinutes); - date.setMinutes(minutes); - return date; -} -module.exports = exports.default; +module.exports = __nccwpck_require__(54558) + /***/ }), -/***/ 80847: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 92075: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setMonth; - -var _index = _interopRequireDefault(__nccwpck_require__(1985)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(97573)); - -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name setMonth - * @category Month Helpers - * @summary Set the month to the given date. - * - * @description - * Set the month to the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} month - the month of the new date - * @returns {Date} the new date with the month set - * @throws {TypeError} 2 arguments required - * - * @example - * // Set February to 1 September 2014: - * const result = setMonth(new Date(2014, 8, 1), 1) - * //=> Sat Feb 01 2014 00:00:00 + * Module dependencies. + * @private */ -function setMonth(dirtyDate, dirtyMonth) { - (0, _index4.default)(2, arguments); - var date = (0, _index2.default)(dirtyDate); - var month = (0, _index.default)(dirtyMonth); - var year = date.getFullYear(); - var day = date.getDate(); - var dateWithDesiredMonth = new Date(0); - dateWithDesiredMonth.setFullYear(year, month, 15); - dateWithDesiredMonth.setHours(0, 0, 0, 0); - var daysInMonth = (0, _index3.default)(dateWithDesiredMonth); // Set the last day of the new month - // if the original date was the last day of the longer month - date.setMonth(month, Math.min(day, daysInMonth)); - return date; -} +var db = __nccwpck_require__(67165) +var extname = (__nccwpck_require__(71017).extname) -module.exports = exports.default; +/** + * Module variables. + * @private + */ -/***/ }), +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i -/***/ 10621: -/***/ ((module, exports, __nccwpck_require__) => { +/** + * Module exports. + * @public + */ -"use strict"; +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setQuarter; +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] -var _index3 = _interopRequireDefault(__nccwpck_require__(80847)); + if (mime && mime.charset) { + return mime.charset + } -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return false +} /** - * @name setQuarter - * @category Quarter Helpers - * @summary Set the year quarter to the given date. - * - * @description - * Set the year quarter to the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} quarter - the quarter of the new date - * @returns {Date} the new date with the quarter set - * @throws {TypeError} 2 arguments required + * Create a full Content-Type header given a MIME type or extension. * - * @example - * // Set the 2nd quarter to 2 July 2014: - * const result = setQuarter(new Date(2014, 6, 2), 2) - * //=> Wed Apr 02 2014 00:00:00 + * @param {string} str + * @return {boolean|string} */ -function setQuarter(dirtyDate, dirtyQuarter) { - (0, _index4.default)(2, arguments); - var date = (0, _index2.default)(dirtyDate); - var quarter = (0, _index.default)(dirtyQuarter); - var oldQuarter = Math.floor(date.getMonth() / 3) + 1; - var diff = quarter - oldQuarter; - return (0, _index3.default)(date, date.getMonth() + diff * 3); -} -module.exports = exports.default; +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } -/***/ }), + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str -/***/ 61346: -/***/ ((module, exports, __nccwpck_require__) => { + if (!mime) { + return false + } -"use strict"; + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + return mime +} -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setSeconds; +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } -var _index = _interopRequireDefault(__nccwpck_require__(1985)); + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); + if (!exts || !exts.length) { + return false + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return exts[0] +} /** - * @name setSeconds - * @category Second Helpers - * @summary Set the seconds to the given date. - * - * @description - * Set the seconds to the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} seconds - the seconds of the new date - * @returns {Date} the new date with the seconds set - * @throws {TypeError} 2 arguments required + * Lookup the MIME type for a file path/extension. * - * @example - * // Set 45 seconds to 1 September 2014 11:30:40: - * const result = setSeconds(new Date(2014, 8, 1, 11, 30, 40), 45) - * //=> Mon Sep 01 2014 11:30:45 + * @param {string} path + * @return {boolean|string} */ -function setSeconds(dirtyDate, dirtySeconds) { - (0, _index3.default)(2, arguments); - var date = (0, _index2.default)(dirtyDate); - var seconds = (0, _index.default)(dirtySeconds); - date.setSeconds(seconds); - return date; -} -module.exports = exports.default; +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } -/***/ }), + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) -/***/ 22664: -/***/ ((module, exports, __nccwpck_require__) => { + if (!extension) { + return false + } -"use strict"; + return exports.types[extension] || false +} +/** + * Populate the extensions and types maps. + * @private + */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setWeek; +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] -var _index = _interopRequireDefault(__nccwpck_require__(81)); + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); + if (!exts || !exts.length) { + return + } -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); + // mime -> extensions + extensions[type] = exts -var _index4 = _interopRequireDefault(__nccwpck_require__(1985)); + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) -/** - * @name setWeek - * @category Week Helpers - * @summary Set the local week to the given date. - * - * @description - * Set the local week to the given date, saving the weekday number. - * The exact calculation depends on the values of - * `options.weekStartsOn` (which is the index of the first day of the week) - * and `options.firstWeekContainsDate` (which is the day of January, which is always in - * the first week of the week-numbering year) - * - * Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering - * - * @param {Date|Number} date - the date to be changed - * @param {Number} week - the week of the new date - * @param {Object} [options] - an object with options. - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year - * @returns {Date} the new date with the local week set - * @throws {TypeError} 2 arguments required - * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 - * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 - * - * @example - * // Set the 1st week to 2 January 2005 with default options: - * const result = setWeek(new Date(2005, 0, 2), 1) - * //=> Sun Dec 26 2004 00:00:00 - * - * @example - * // Set the 1st week to 2 January 2005, - * // if Monday is the first day of the week, - * // and the first week of the year always contains 4 January: - * const result = setWeek(new Date(2005, 0, 2), 1, { - * weekStartsOn: 1, - * firstWeekContainsDate: 4 - * }) - * //=> Sun Jan 4 2004 00:00:00 - */ -function setWeek(dirtyDate, dirtyWeek, options) { - (0, _index3.default)(2, arguments); - var date = (0, _index2.default)(dirtyDate); - var week = (0, _index4.default)(dirtyWeek); - var diff = (0, _index.default)(date, options) - week; - date.setDate(date.getDate() - diff * 7); - return date; + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) } -module.exports = exports.default; /***/ }), -/***/ 43438: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 67586: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +module.exports = minimatch +minimatch.Minimatch = Minimatch + +var path = (function () { try { return __nccwpck_require__(71017) } catch (e) {}}()) || { + sep: '/' +} +minimatch.sep = path.sep +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = __nccwpck_require__(60909) -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setWeekYear; +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} -var _index = _interopRequireDefault(__nccwpck_require__(3086)); +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' -var _index2 = _interopRequireDefault(__nccwpck_require__(18014)); +// * => any number of characters +var star = qmark + '*?' -var _index3 = _interopRequireDefault(__nccwpck_require__(26477)); +// ** 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})($|\\\/)).)*?' -var _index4 = _interopRequireDefault(__nccwpck_require__(1985)); +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' -var _index5 = _interopRequireDefault(__nccwpck_require__(82063)); +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') -var _index6 = __nccwpck_require__(79307); +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +// normalizes slashes. +var slashSplit = /\/+/ -/** - * @name setWeekYear - * @category Week-Numbering Year Helpers - * @summary Set the local week-numbering year to the given date. - * - * @description - * Set the local week-numbering year to the given date, - * saving the week number and the weekday number. - * The exact calculation depends on the values of - * `options.weekStartsOn` (which is the index of the first day of the week) - * and `options.firstWeekContainsDate` (which is the day of January, which is always in - * the first week of the week-numbering year) - * - * Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering - * - * @param {Date|Number} date - the date to be changed - * @param {Number} weekYear - the local week-numbering year of the new date - * @param {Object} [options] - an object with options. - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year - * @returns {Date} the new date with the local week-numbering year set - * @throws {TypeError} 2 arguments required - * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 - * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 - * - * @example - * // Set the local week-numbering year 2004 to 2 January 2010 with default options: - * const result = setWeekYear(new Date(2010, 0, 2), 2004) - * //=> Sat Jan 03 2004 00:00:00 - * - * @example - * // Set the local week-numbering year 2004 to 2 January 2010, - * // if Monday is the first day of week - * // and 4 January is always in the first week of the year: - * const result = setWeekYear(new Date(2010, 0, 2), 2004, { - * weekStartsOn: 1, - * firstWeekContainsDate: 4 - * }) - * //=> Sat Jan 01 2005 00:00:00 - */ -function setWeekYear(dirtyDate, dirtyWeekYear, options) { - var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} - (0, _index5.default)(2, arguments); - var defaultOptions = (0, _index6.getDefaultOptions)(); - var firstWeekContainsDate = (0, _index4.default)((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); - var date = (0, _index3.default)(dirtyDate); - var weekYear = (0, _index4.default)(dirtyWeekYear); - var diff = (0, _index.default)(date, (0, _index2.default)(date, options)); - var firstWeek = new Date(0); - firstWeek.setFullYear(weekYear, 0, firstWeekContainsDate); - firstWeek.setHours(0, 0, 0, 0); - date = (0, _index2.default)(firstWeek, options); - date.setDate(date.getDate() + diff); - return date; +function ext (a, b) { + b = b || {} + var t = {} + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + return t } -module.exports = exports.default; +minimatch.defaults = function (def) { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch + } -/***/ }), + var orig = minimatch -/***/ 6212: -/***/ ((module, exports, __nccwpck_require__) => { + var m = function minimatch (p, pattern, options) { + return orig(p, pattern, ext(def, options)) + } -"use strict"; + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + m.Minimatch.defaults = function defaults (options) { + return orig.defaults(ext(def, options)).Minimatch + } + + m.filter = function filter (pattern, options) { + return orig.filter(pattern, ext(def, options)) + } + m.defaults = function defaults (options) { + return orig.defaults(ext(def, options)) + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setYear; + m.makeRe = function makeRe (pattern, options) { + return orig.makeRe(pattern, ext(def, options)) + } -var _index = _interopRequireDefault(__nccwpck_require__(1985)); + m.braceExpand = function braceExpand (pattern, options) { + return orig.braceExpand(pattern, ext(def, options)) + } -var _index2 = _interopRequireDefault(__nccwpck_require__(26477)); + m.match = function (list, pattern, options) { + return orig.match(list, pattern, ext(def, options)) + } -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); + return m +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +Minimatch.defaults = function (def) { + return minimatch.defaults(def).Minimatch +} -/** - * @name setYear - * @category Year Helpers - * @summary Set the year to the given date. - * - * @description - * Set the year to the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} year - the year of the new date - * @returns {Date} the new date with the year set - * @throws {TypeError} 2 arguments required - * - * @example - * // Set year 2013 to 1 September 2014: - * const result = setYear(new Date(2014, 8, 1), 2013) - * //=> Sun Sep 01 2013 00:00:00 - */ -function setYear(dirtyDate, dirtyYear) { - (0, _index3.default)(2, arguments); - var date = (0, _index2.default)(dirtyDate); - var year = (0, _index.default)(dirtyYear); // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date +function minimatch (p, pattern, options) { + assertValidPattern(pattern) - if (isNaN(date.getTime())) { - return new Date(NaN); + if (!options) options = {} + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false } - date.setFullYear(year); - return date; + return new Minimatch(pattern, options).match(p) } -module.exports = exports.default; +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } -/***/ }), + assertValidPattern(pattern) -/***/ 61868: -/***/ ((module, exports, __nccwpck_require__) => { + if (!options) options = {} -"use strict"; + pattern = pattern.trim() + // windows support: need to use /, not \ + if (!options.allowWindowsEscape && path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfDay; + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + this.partial = !!options.partial -var _index = _interopRequireDefault(__nccwpck_require__(26477)); + // make the set of regexps etc. + this.make() +} -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +Minimatch.prototype.debug = function () {} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +Minimatch.prototype.make = make +function make () { + var pattern = this.pattern + var options = this.options -/** - * @name startOfDay - * @category Day Helpers - * @summary Return the start of a day for the given date. - * - * @description - * Return the start of a day for the given date. - * The result will be in the local timezone. - * - * @param {Date|Number} date - the original date - * @returns {Date} the start of a day - * @throws {TypeError} 1 argument required - * - * @example - * // The start of a day for 2 September 2014 11:55:00: - * const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 02 2014 00:00:00 - */ -function startOfDay(dirtyDate) { - (0, _index2.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - date.setHours(0, 0, 0, 0); - return date; -} + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } -module.exports = exports.default; + // step 1: figure out negation, etc. + this.parseNegate() -/***/ }), + // step 2: expand braces + var set = this.globSet = this.braceExpand() -/***/ 52025: -/***/ ((module, exports, __nccwpck_require__) => { + if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } -"use strict"; + this.debug(this.pattern, set) + // 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) + }) -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfDecade; + this.debug(this.pattern, set) -var _index = _interopRequireDefault(__nccwpck_require__(26477)); + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + this.debug(this.pattern, set) -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) -/** - * @name startOfDecade - * @category Decade Helpers - * @summary Return the start of a decade for the given date. - * - * @description - * Return the start of a decade for the given date. - * - * @param {Date|Number} date - the original date - * @returns {Date} the start of a decade - * @throws {TypeError} 1 argument required - * - * @example - * // The start of a decade for 21 October 2015 00:00:00: - * const result = startOfDecade(new Date(2015, 9, 21, 00, 00, 00)) - * //=> Jan 01 2010 00:00:00 - */ -function startOfDecade(dirtyDate) { - (0, _index2.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - var year = date.getFullYear(); - var decade = Math.floor(year / 10) * 10; - date.setFullYear(decade, 0, 1); - date.setHours(0, 0, 0, 0); - return date; + this.debug(this.pattern, set) + + this.set = set } -module.exports = exports.default; +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 -/***/ }), + if (options.nonegate) return -/***/ 46277: -/***/ ((module, exports, __nccwpck_require__) => { + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } -"use strict"; + 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) +} -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfHour; +Minimatch.prototype.braceExpand = braceExpand -var _index = _interopRequireDefault(__nccwpck_require__(26477)); +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + assertValidPattern(pattern) -/** - * @name startOfHour - * @category Hour Helpers - * @summary Return the start of an hour for the given date. - * - * @description - * Return the start of an hour for the given date. - * The result will be in the local timezone. - * - * @param {Date|Number} date - the original date - * @returns {Date} the start of an hour - * @throws {TypeError} 1 argument required - * - * @example - * // The start of an hour for 2 September 2014 11:55:00: - * const result = startOfHour(new Date(2014, 8, 2, 11, 55)) - * //=> Tue Sep 02 2014 11:00:00 - */ -function startOfHour(dirtyDate) { - (0, _index2.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - date.setMinutes(0, 0, 0); - return date; -} + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern] + } -module.exports = exports.default; + return expand(pattern) +} -/***/ }), +var MAX_PATTERN_LENGTH = 1024 * 64 +var assertValidPattern = function (pattern) { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern') + } -/***/ 56307: -/***/ ((module, exports, __nccwpck_require__) => { + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') + } +} -"use strict"; +// 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) { + assertValidPattern(pattern) + var options = this.options -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfISOWeek; + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR + else + pattern = '*' + } + if (pattern === '') return '' -var _index = _interopRequireDefault(__nccwpck_require__(29813)); + 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 -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + 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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + 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) -/** - * @name startOfISOWeek - * @category ISO Week Helpers - * @summary Return the start of an ISO week for the given date. - * - * @description - * Return the start of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|Number} date - the original date - * @returns {Date} the start of an ISO week - * @throws {TypeError} 1 argument required - * - * @example - * // The start of an ISO week for 2 September 2014 11:55:00: - * const result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Mon Sep 01 2014 00:00:00 - */ -function startOfISOWeek(dirtyDate) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate, { - weekStartsOn: 1 - }); -} + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } -module.exports = exports.default; + switch (c) { + /* istanbul ignore next */ + case '/': { + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + } -/***/ }), + case '\\': + clearStateChar() + escaping = true + continue -/***/ 60776: -/***/ ((module, exports, __nccwpck_require__) => { + // 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) -"use strict"; + // 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 + } + // 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 -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfISOWeekYear; + case '(': + if (inClass) { + re += '(' + continue + } -var _index = _interopRequireDefault(__nccwpck_require__(86991)); + if (!stateChar) { + re += '\\(' + continue + } -var _index2 = _interopRequireDefault(__nccwpck_require__(56307)); + 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 -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + 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 -/** - * @name startOfISOWeekYear - * @category ISO Week-Numbering Year Helpers - * @summary Return the start of an ISO week-numbering year for the given date. - * - * @description - * Return the start of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|Number} date - the original date - * @returns {Date} the start of an ISO week-numbering year - * @throws {TypeError} 1 argument required - * - * @example - * // The start of an ISO week-numbering year for 2 July 2005: - * const result = startOfISOWeekYear(new Date(2005, 6, 2)) - * //=> Mon Jan 03 2005 00:00:00 - */ -function startOfISOWeekYear(dirtyDate) { - (0, _index3.default)(1, arguments); - var year = (0, _index.default)(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = (0, _index2.default)(fourthOfJanuary); - return date; -} + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } -module.exports = exports.default; + clearStateChar() + re += '|' + continue -/***/ }), + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() -/***/ 48567: -/***/ ((module, exports, __nccwpck_require__) => { + if (inClass) { + re += '\\' + c + continue + } -"use strict"; + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + 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 + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfMinute; + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + // 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 + } -var _index = _interopRequireDefault(__nccwpck_require__(26477)); + // finish up the class. + hasMagic = true + inClass = false + re += c + continue -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + default: + // swallow any state char that wasn't consumed + clearStateChar() -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } -/** - * @name startOfMinute - * @category Minute Helpers - * @summary Return the start of a minute for the given date. - * - * @description - * Return the start of a minute for the given date. - * The result will be in the local timezone. - * - * @param {Date|Number} date - the original date - * @returns {Date} the start of a minute - * @throws {TypeError} 1 argument required - * - * @example - * // The start of a minute for 1 December 2014 22:15:45.400: - * const result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:00 - */ -function startOfMinute(dirtyDate) { - (0, _index2.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - date.setSeconds(0, 0); - return date; -} + re += c -module.exports = exports.default; + } // switch + } // for -/***/ }), + // 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] + } -/***/ 97182: -/***/ ((module, exports, __nccwpck_require__) => { + // 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 = '\\' + } -"use strict"; + // 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 + '|' + }) + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfMonth; + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } -var _index = _interopRequireDefault(__nccwpck_require__(26477)); + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + // 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 + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // 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] -/** - * @name startOfMonth - * @category Month Helpers - * @summary Return the start of a month for the given date. - * - * @description - * Return the start of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|Number} date - the original date - * @returns {Date} the start of a month - * @throws {TypeError} 1 argument required - * - * @example - * // The start of a month for 2 September 2014 11:55:00: - * const result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Mon Sep 01 2014 00:00:00 - */ -function startOfMonth(dirtyDate) { - (0, _index2.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - date.setDate(1); - date.setHours(0, 0, 0, 0); - return date; -} + 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) -module.exports = exports.default; + 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 -/***/ 92932: -/***/ ((module, exports, __nccwpck_require__) => { + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe + } -"use strict"; + // 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 + } + if (addPatternStart) { + re = patternStart + re + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfQuarter; + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } -var _index = _interopRequireDefault(__nccwpck_require__(26477)); + // 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) + } -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) /* istanbul ignore next - should be impossible */ { + // 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('$.') + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + regExp._glob = pattern + regExp._src = re -/** - * @name startOfQuarter - * @category Quarter Helpers - * @summary Return the start of a year quarter for the given date. - * - * @description - * Return the start of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|Number} date - the original date - * @returns {Date} the start of a quarter - * @throws {TypeError} 1 argument required - * - * @example - * // The start of a quarter for 2 September 2014 11:55:00: - * const result = startOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Jul 01 2014 00:00:00 - */ -function startOfQuarter(dirtyDate) { - (0, _index2.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3; - date.setMonth(month, 1); - date.setHours(0, 0, 0, 0); - return date; + return regExp } -module.exports = exports.default; - -/***/ }), +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} -/***/ 86738: -/***/ ((module, exports, __nccwpck_require__) => { +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp -"use strict"; + // 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 -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfSecond; + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' -var _index = _interopRequireDefault(__nccwpck_require__(26477)); + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' -/** - * @name startOfSecond - * @category Second Helpers - * @summary Return the start of a second for the given date. - * - * @description - * Return the start of a second for the given date. - * The result will be in the local timezone. - * - * @param {Date|Number} date - the original date - * @returns {Date} the start of a second - * @throws {TypeError} 1 argument required - * - * @example - * // The start of a second for 1 December 2014 22:15:45.400: - * const result = startOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:45.000 - */ -function startOfSecond(dirtyDate) { - (0, _index2.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - date.setMilliseconds(0); - return date; + try { + this.regexp = new RegExp(re, flags) + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false + } + return this.regexp } -module.exports = exports.default; +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} -/***/ }), +Minimatch.prototype.match = function match (f, partial) { + if (typeof partial === 'undefined') partial = this.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 === '' -/***/ 35516: -/***/ ((module, exports, __nccwpck_require__) => { + if (f === '/' && partial) return true -"use strict"; + var options = this.options + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfToday; + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) -var _index = _interopRequireDefault(__nccwpck_require__(61868)); + // 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. -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var set = this.set + this.debug(this.pattern, 'set', set) -/** - * @name startOfToday - * @category Day Helpers - * @summary Return the start of today. - * @pure false - * - * @description - * Return the start of today. - * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `Date.now()` internally hence impure and can't be safely curried. - * - * @returns {Date} the start of today - * - * @example - * // If today is 6 October 2014: - * const result = startOfToday() - * //=> Mon Oct 6 2014 00:00:00 - */ -function startOfToday() { - return (0, _index.default)(Date.now()); -} + // 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 + } -module.exports = exports.default; + 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 + } + } -/***/ }), + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} -/***/ 12442: -/***/ ((module, exports) => { +// 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 -"use strict"; + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + this.debug('matchOne', file.length, pattern.length) -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfTomorrow; + 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] -/** - * @name startOfTomorrow - * @category Day Helpers - * @summary Return the start of tomorrow. - * @pure false - * - * @description - * Return the start of tomorrow. - * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `new Date()` internally hence impure and can't be safely curried. - * - * @returns {Date} the start of tomorrow - * - * @example - * // If today is 6 October 2014: - * const result = startOfTomorrow() - * //=> Tue Oct 7 2014 00:00:00 - */ -function startOfTomorrow() { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - var date = new Date(0); - date.setFullYear(year, month, day + 1); - date.setHours(0, 0, 0, 0); - return date; -} + this.debug(pattern, p, f) -module.exports = exports.default; + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false) return false -/***/ }), + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) -/***/ 29813: -/***/ ((module, exports, __nccwpck_require__) => { + // "**" + // 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 + } -"use strict"; + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfWeek; + // 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 + } -var _index = _interopRequireDefault(__nccwpck_require__(26477)); + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } -var _index2 = _interopRequireDefault(__nccwpck_require__(1985)); + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + /* istanbul ignore if */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); + // 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') { + hit = f === p + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } -var _index4 = __nccwpck_require__(79307); + if (!hit) return false + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // 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/* -/** - * @name startOfWeek - * @category Week Helpers - * @summary Return the start of a week for the given date. - * - * @description - * Return the start of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|Number} date - the original date - * @param {Object} [options] - an object with options. - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the start of a week - * @throws {TypeError} 1 argument required - * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 - * - * @example - * // The start of a week for 2 September 2014 11:55:00: - * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Aug 31 2014 00:00:00 - * - * @example - * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00: - * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 }) - * //=> Mon Sep 01 2014 00:00:00 - */ -function startOfWeek(dirtyDate, options) { - var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + // 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 /* istanbul ignore 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/ + return (fi === fl - 1) && (file[fi] === '') + } - (0, _index3.default)(1, arguments); - var defaultOptions = (0, _index4.getDefaultOptions)(); - var weekStartsOn = (0, _index2.default)((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') +} - if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { - throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); - } +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} - var date = (0, _index.default)(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; - date.setDate(date.getDate() - diff); - date.setHours(0, 0, 0, 0); - return date; +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') } -module.exports = exports.default; /***/ }), -/***/ 18014: +/***/ 69608: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfWeekYear; - -var _index = _interopRequireDefault(__nccwpck_require__(33494)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(29813)); +Object.defineProperty(exports, "__esModule", ({ value: true })); -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var _index4 = _interopRequireDefault(__nccwpck_require__(82063)); +var Stream = _interopDefault(__nccwpck_require__(12781)); +var http = _interopDefault(__nccwpck_require__(13685)); +var Url = _interopDefault(__nccwpck_require__(57310)); +var whatwgUrl = _interopDefault(__nccwpck_require__(51241)); +var https = _interopDefault(__nccwpck_require__(95687)); +var zlib = _interopDefault(__nccwpck_require__(59796)); -var _index5 = __nccwpck_require__(79307); +// Based on /~https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; -/** - * @name startOfWeekYear - * @category Week-Numbering Year Helpers - * @summary Return the start of a local week-numbering year for the given date. - * - * @description - * Return the start of a local week-numbering year. - * The exact calculation depends on the values of - * `options.weekStartsOn` (which is the index of the first day of the week) - * and `options.firstWeekContainsDate` (which is the day of January, which is always in - * the first week of the week-numbering year) - * - * Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering - * - * @param {Date|Number} date - the original date - * @param {Object} [options] - an object with options. - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year - * @returns {Date} the start of a week-numbering year - * @throws {TypeError} 1 argument required - * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 - * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 - * - * @example - * // The start of an a week-numbering year for 2 July 2005 with default settings: - * const result = startOfWeekYear(new Date(2005, 6, 2)) - * //=> Sun Dec 26 2004 00:00:00 - * - * @example - * // The start of a week-numbering year for 2 July 2005 - * // if Monday is the first day of week - * // and 4 January is always in the first week of the year: - * const result = startOfWeekYear(new Date(2005, 6, 2), { - * weekStartsOn: 1, - * firstWeekContainsDate: 4 - * }) - * //=> Mon Jan 03 2005 00:00:00 - */ -function startOfWeekYear(dirtyDate, options) { - var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); - (0, _index4.default)(1, arguments); - var defaultOptions = (0, _index5.getDefaultOptions)(); - var firstWeekContainsDate = (0, _index3.default)((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); - var year = (0, _index.default)(dirtyDate, options); - var firstWeek = new Date(0); - firstWeek.setFullYear(year, 0, firstWeekContainsDate); - firstWeek.setHours(0, 0, 0, 0); - var date = (0, _index2.default)(firstWeek, options); - return date; -} +class Blob { + constructor() { + this[TYPE] = ''; -module.exports = exports.default; + const blobParts = arguments[0]; + const options = arguments[1]; -/***/ }), + const buffers = []; + let size = 0; -/***/ 88225: -/***/ ((module, exports, __nccwpck_require__) => { + 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); + } + } -"use strict"; + 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; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfYear; + 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); -var _index = _interopRequireDefault(__nccwpck_require__(26477)); + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); /** - * @name startOfYear - * @category Year Helpers - * @summary Return the start of a year for the given date. - * - * @description - * Return the start of a year for the given date. - * The result will be in the local timezone. + * fetch-error.js * - * @param {Date|Number} date - the original date - * @returns {Date} the start of a year - * @throws {TypeError} 1 argument required + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance * - * @example - * // The start of a year for 2 September 2014 11:55:00: - * const result = startOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Jan 01 2014 00:00:00 + * @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 startOfYear(dirtyDate) { - (0, _index2.default)(1, arguments); - var cleanDate = (0, _index.default)(dirtyDate); - var date = new Date(0); - date.setFullYear(cleanDate.getFullYear(), 0, 1); - date.setHours(0, 0, 0, 0); - return date; -} +function FetchError(message, type, systemError) { + Error.call(this, message); -module.exports = exports.default; + 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; + } -/***/ 81672: -/***/ ((module, exports) => { + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} -"use strict"; +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; +let convert; +try { + convert = (__nccwpck_require__(12628).convert); +} catch (e) {} -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfYesterday; +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; /** - * @name startOfYesterday - * @category Day Helpers - * @summary Return the start of yesterday. - * @pure false - * - * @description - * Return the start of yesterday. - * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `new Date()` internally hence impure and can't be safely curried. + * Body mixin * - * @returns {Date} the start of yesterday + * Ref: https://fetch.spec.whatwg.org/#body * - * @example - * // If today is 6 October 2014: - * const result = startOfYesterday() - * //=> Sun Oct 5 2014 00:00:00 + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void */ -function startOfYesterday() { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - var date = new Date(0); - date.setFullYear(year, month, day - 1); - date.setHours(0, 0, 0, 0); - return date; -} - -module.exports = exports.default; +function Body(body) { + var _this = this; -/***/ }), + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; -/***/ 63875: -/***/ ((module, exports, __nccwpck_require__) => { + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; -"use strict"; + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = sub; +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, -var _index = _interopRequireDefault(__nccwpck_require__(50970)); + get bodyUsed() { + return this[INTERNALS].disturbed; + }, -var _index2 = _interopRequireDefault(__nccwpck_require__(6752)); + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); + /** + * 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 + }); + }); + }, -var _index4 = _interopRequireDefault(__nccwpck_require__(1985)); + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + 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')); + } + }); + }, -/** - * @name sub - * @category Common Helpers - * @summary Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date. - * - * @description - * Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Duration} duration - the object with years, months, weeks, days, hours, minutes and seconds to be subtracted - * - * | Key | Description | - * |---------|------------------------------------| - * | years | Amount of years to be subtracted | - * | months | Amount of months to be subtracted | - * | weeks | Amount of weeks to be subtracted | - * | days | Amount of days to be subtracted | - * | hours | Amount of hours to be subtracted | - * | minutes | Amount of minutes to be subtracted | - * | seconds | Amount of seconds to be subtracted | - * - * All values default to 0 - * - * @returns {Date} the new date with the seconds subtracted - * @throws {TypeError} 2 arguments required - * - * @example - * // Subtract the following duration from 15 June 2017 15:29:20 - * const result = sub(new Date(2017, 5, 15, 15, 29, 20), { - * years: 2, - * months: 9, - * weeks: 1, - * days: 7, - * hours: 5, - * minutes: 9, - * seconds: 30 - * }) - * //=> Mon Sep 1 2014 10:19:50 - */ -function sub(date, duration) { - (0, _index3.default)(2, arguments); - if (!duration || typeof duration !== 'object') return new Date(NaN); - var years = duration.years ? (0, _index4.default)(duration.years) : 0; - var months = duration.months ? (0, _index4.default)(duration.months) : 0; - var weeks = duration.weeks ? (0, _index4.default)(duration.weeks) : 0; - var days = duration.days ? (0, _index4.default)(duration.days) : 0; - var hours = duration.hours ? (0, _index4.default)(duration.hours) : 0; - var minutes = duration.minutes ? (0, _index4.default)(duration.minutes) : 0; - var seconds = duration.seconds ? (0, _index4.default)(duration.seconds) : 0; // Subtract years and months + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, - var dateWithoutMonths = (0, _index2.default)(date, months + years * 12); // Subtract weeks and days + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, - var dateWithoutDays = (0, _index.default)(dateWithoutMonths, days + weeks * 7); // Subtract hours, minutes and seconds + /** + * 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; - var minutestoSub = minutes + hours * 60; - var secondstoSub = seconds + minutestoSub * 60; - var mstoSub = secondstoSub * 1000; - var finalDate = new Date(dateWithoutDays.getTime() - mstoSub); - return finalDate; -} + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; -module.exports = exports.default; +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); -/***/ }), +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; -/***/ 71952: -/***/ ((module, exports, __nccwpck_require__) => { +/** + * 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; -"use strict"; + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + this[INTERNALS].disturbed = true; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = subBusinessDays; + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } -var _index = _interopRequireDefault(__nccwpck_require__(81727)); + let body = this.body; -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); + // body is blob + if (isBlob(body)) { + body = body.stream(); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } -/** - * @name subBusinessDays - * @category Day Helpers - * @summary Substract the specified number of business days (mon - fri) to the given date. - * - * @description - * Substract the specified number of business days (mon - fri) to the given date, ignoring weekends. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} amount - the amount of business days to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. - * @returns {Date} the new date with the business days subtracted - * @throws {TypeError} 2 arguments required - * - * @example - * // Substract 10 business days from 1 September 2014: - * const result = subBusinessDays(new Date(2014, 8, 1), 10) - * //=> Mon Aug 18 2014 00:00:00 (skipped weekend days) - */ -function subBusinessDays(dirtyDate, dirtyAmount) { - (0, _index2.default)(2, arguments); - var amount = (0, _index3.default)(dirtyAmount); - return (0, _index.default)(dirtyDate, -amount); -} + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } -module.exports = exports.default; + // 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; -/***/ 50970: -/***/ ((module, exports, __nccwpck_require__) => { + // 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); + } -"use strict"; + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = subDays; + 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; + } -var _index = _interopRequireDefault(__nccwpck_require__(56227)); + accumBytes += chunk.length; + accum.push(chunk); + }); -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + body.on('end', function () { + if (abort) { + return; + } -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); + clearTimeout(resTimeout); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + 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)); + } + }); + }); +} /** - * @name subDays - * @category Day Helpers - * @summary Subtract the specified number of days from the given date. - * - * @description - * Subtract the specified number of days from the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} amount - the amount of days to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. - * @returns {Date} the new date with the days subtracted - * @throws {TypeError} 2 arguments required + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding * - * @example - * // Subtract 10 days from 1 September 2014: - * const result = subDays(new Date(2014, 8, 1), 10) - * //=> Fri Aug 22 2014 00:00:00 + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String */ -function subDays(dirtyDate, dirtyAmount) { - (0, _index2.default)(2, arguments); - var amount = (0, _index3.default)(dirtyAmount); - return (0, _index.default)(dirtyDate, -amount); -} +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } -module.exports = exports.default; + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; -/***/ }), + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } -/***/ 22481: -/***/ ((module, exports, __nccwpck_require__) => { + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); -"use strict"; + // html5 + if (!res && str) { + res = / Thu Jul 10 2014 23:00:00 + * @param Object obj Object to detect by type or brand + * @return String */ -function subHours(dirtyDate, dirtyAmount) { - (0, _index2.default)(2, arguments); - var amount = (0, _index3.default)(dirtyAmount); - return (0, _index.default)(dirtyDate, -amount); -} - -module.exports = exports.default; - -/***/ }), - -/***/ 33925: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; +function isURLSearchParams(obj) { + // Duck-typing as a necessary condition. + if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') { + return false; + } + // Brand-checking and more duck-typing as optional condition. + return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function'; +} -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = subISOWeekYears; +/** + * Check if `obj` is a W3C `Blob` object (which `File` inherits from) + * @param {*} obj + * @return {boolean} + */ +function isBlob(obj) { + return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]); +} -var _index = _interopRequireDefault(__nccwpck_require__(75318)); +/** + * Clone body given Res/Req instance + * + * @param Mixed instance Response or Request instance + * @return Mixed + */ +function clone(instance) { + let p1, p2; + let body = instance.body; -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + // don't allow cloning a used body + if (instance.bodyUsed) { + throw new Error('cannot clone body after it is used'); + } -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); + // check that body is a stream and not form-data object + // note: we can't clone the form-data object without having it as a dependency + if (body instanceof Stream && typeof body.getBoundary !== 'function') { + // tee instance body + p1 = new PassThrough(); + p2 = new PassThrough(); + body.pipe(p1); + body.pipe(p2); + // set instance body to teed body and return the other teed body + instance[INTERNALS].body = p1; + body = p2; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return body; +} /** - * @name subISOWeekYears - * @category ISO Week-Numbering Year Helpers - * @summary Subtract the specified number of ISO week-numbering years from the given date. + * Performs the operation "extract a `Content-Type` value from |object|" as + * specified in the specification: + * https://fetch.spec.whatwg.org/#concept-bodyinit-extract * - * @description - * Subtract the specified number of ISO week-numbering years from the given date. + * This function assumes that instance.body is present. * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date + * @param Mixed instance Any options.body input + */ +function extractContentType(body) { + if (body === null) { + // body is null + return null; + } else if (typeof body === 'string') { + // body is string + return 'text/plain;charset=UTF-8'; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + return 'application/x-www-form-urlencoded;charset=UTF-8'; + } else if (isBlob(body)) { + // body is blob + return body.type || null; + } else if (Buffer.isBuffer(body)) { + // body is buffer + return null; + } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + return null; + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + return null; + } else if (typeof body.getBoundary === 'function') { + // detect form data input from form-data module + return `multipart/form-data;boundary=${body.getBoundary()}`; + } else if (body instanceof Stream) { + // body is stream + // can't really do much about this + return null; + } else { + // Body constructor defaults other things to string + return 'text/plain;charset=UTF-8'; + } +} + +/** + * The Fetch Standard treats this as if "total bytes" is a property on the body. + * For us, we have to explicitly get it with a function. * - * @param {Date|Number} date - the date to be changed - * @param {Number} amount - the amount of ISO week-numbering years to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. - * @returns {Date} the new date with the ISO week-numbering years subtracted - * @throws {TypeError} 2 arguments required + * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes * - * @example - * // Subtract 5 ISO week-numbering years from 1 September 2014: - * const result = subISOWeekYears(new Date(2014, 8, 1), 5) - * //=> Mon Aug 31 2009 00:00:00 + * @param Body instance Instance of Body + * @return Number? Number of bytes, or null if not possible */ -function subISOWeekYears(dirtyDate, dirtyAmount) { - (0, _index2.default)(2, arguments); - var amount = (0, _index3.default)(dirtyAmount); - return (0, _index.default)(dirtyDate, -amount); -} +function getTotalBytes(instance) { + const body = instance.body; -module.exports = exports.default; -/***/ }), + 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; + } +} -/***/ 97923: -/***/ ((module, exports, __nccwpck_require__) => { +/** + * Write a Body to a Node.js WritableStream (e.g. http.Request) object. + * + * @param Body instance Instance of Body + * @return Void + */ +function writeToStream(dest, instance) { + const body = instance.body; -"use strict"; + 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); + } +} -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = subMilliseconds; +// expose Promise +Body.Promise = global.Promise; -var _index = _interopRequireDefault(__nccwpck_require__(30524)); +/** + * headers.js + * + * Headers class offers convenient helpers + */ -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); +const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/; +const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/; -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); +function validateName(name) { + name = `${name}`; + if (invalidTokenRegex.test(name) || name === '') { + throw new TypeError(`${name} is not a legal HTTP header name`); + } +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function validateValue(value) { + value = `${value}`; + if (invalidHeaderCharRegex.test(value)) { + throw new TypeError(`${value} is not a legal HTTP header value`); + } +} /** - * @name subMilliseconds - * @category Millisecond Helpers - * @summary Subtract the specified number of milliseconds from the given date. - * - * @description - * Subtract the specified number of milliseconds from the given date. + * Find the key in the map object given a header name. * - * @param {Date|Number} date - the date to be changed - * @param {Number} amount - the amount of milliseconds to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. - * @returns {Date} the new date with the milliseconds subtracted - * @throws {TypeError} 2 arguments required + * Returns undefined if not found. * - * @example - * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000: - * const result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) - * //=> Thu Jul 10 2014 12:45:29.250 + * @param String name Header name + * @return String|Undefined */ -function subMilliseconds(dirtyDate, dirtyAmount) { - (0, _index2.default)(2, arguments); - var amount = (0, _index3.default)(dirtyAmount); - return (0, _index.default)(dirtyDate, -amount); +function find(map, name) { + name = name.toLowerCase(); + for (const key in map) { + if (key.toLowerCase() === name) { + return key; + } + } + return undefined; } -module.exports = exports.default; - -/***/ }), - -/***/ 67535: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = subMinutes; - -var _index = _interopRequireDefault(__nccwpck_require__(15268)); +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; -var _index2 = _interopRequireDefault(__nccwpck_require__(82063)); + this[MAP] = Object.create(null); -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } -/** - * @name subMinutes - * @category Minute Helpers - * @summary Subtract the specified number of minutes from the given date. - * - * @description - * Subtract the specified number of minutes from the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} amount - the amount of minutes to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. - * @returns {Date} the new date with the minutes subtracted - * @throws {TypeError} 2 arguments required - * - * @example - * // Subtract 30 minutes from 10 July 2014 12:00:00: - * const result = subMinutes(new Date(2014, 6, 10, 12, 0), 30) - * //=> Thu Jul 10 2014 11:30:00 - */ -function subMinutes(dirtyDate, dirtyAmount) { - (0, _index2.default)(2, arguments); - var amount = (0, _index3.default)(dirtyAmount); - return (0, _index.default)(dirtyDate, -amount); -} + return; + } -module.exports = exports.default; + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } -/***/ }), + // sequence> + // 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)); + } -/***/ 6752: -/***/ ((module, exports, __nccwpck_require__) => { + 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'); + } + } -"use strict"; + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + return this[MAP][key].join(', '); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = subMonths; + /** + * 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; -var _index = _interopRequireDefault(__nccwpck_require__(1985)); + 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]; -var _index2 = _interopRequireDefault(__nccwpck_require__(22995)); + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); + /** + * 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]; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * 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]; + } + } -/** - * @name subMonths - * @category Month Helpers - * @summary Subtract the specified number of months from the given date. - * - * @description - * Subtract the specified number of months from the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} amount - the amount of months to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. - * @returns {Date} the new date with the months subtracted - * @throws {TypeError} 2 arguments required - * - * @example - * // Subtract 5 months from 1 February 2015: - * const result = subMonths(new Date(2015, 1, 1), 5) - * //=> Mon Sep 01 2014 00:00:00 - */ -function subMonths(dirtyDate, dirtyAmount) { - (0, _index3.default)(2, arguments); - var amount = (0, _index.default)(dirtyAmount); - return (0, _index2.default)(dirtyDate, -amount); -} + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } -module.exports = exports.default; + /** + * 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]; + } -/***/ 23139: -/***/ ((module, exports, __nccwpck_require__) => { + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } -"use strict"; + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = subQuarters; +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +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 } +}); -var _index2 = _interopRequireDefault(__nccwpck_require__(25149)); +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); + 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(', ')]; + }); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +const INTERNAL = Symbol('internal'); -/** - * @name subQuarters - * @category Quarter Helpers - * @summary Subtract the specified number of year quarters from the given date. - * - * @description - * Subtract the specified number of year quarters from the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} amount - the amount of quarters to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. - * @returns {Date} the new date with the quarters subtracted - * @throws {TypeError} 2 arguments required - * - * @example - * // Subtract 3 quarters from 1 September 2014: - * const result = subQuarters(new Date(2014, 8, 1), 3) - * //=> Sun Dec 01 2013 00:00:00 - */ -function subQuarters(dirtyDate, dirtyAmount) { - (0, _index3.default)(2, arguments); - var amount = (0, _index.default)(dirtyAmount); - return (0, _index2.default)(dirtyDate, -amount); +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; } -module.exports = exports.default; - -/***/ }), +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } -/***/ 40138: -/***/ ((module, exports, __nccwpck_require__) => { + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; -"use strict"; + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + this[INTERNAL].index = index + 1; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = subSeconds; + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); -var _index = _interopRequireDefault(__nccwpck_require__(1985)); +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); -var _index2 = _interopRequireDefault(__nccwpck_require__(14112)); +/** + * 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]); -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); + // 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]; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return obj; +} /** - * @name subSeconds - * @category Second Helpers - * @summary Subtract the specified number of seconds from the given date. - * - * @description - * Subtract the specified number of seconds from the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} amount - the amount of seconds to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. - * @returns {Date} the new date with the seconds subtracted - * @throws {TypeError} 2 arguments required + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. * - * @example - * // Subtract 30 seconds from 10 July 2014 12:45:00: - * const result = subSeconds(new Date(2014, 6, 10, 12, 45, 0), 30) - * //=> Thu Jul 10 2014 12:44:30 + * @param Object obj Object of headers + * @return Headers */ -function subSeconds(dirtyDate, dirtyAmount) { - (0, _index3.default)(2, arguments); - var amount = (0, _index.default)(dirtyAmount); - return (0, _index2.default)(dirtyDate, -amount); +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; } -module.exports = exports.default; - -/***/ }), - -/***/ 45504: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = subWeeks; - -var _index = _interopRequireDefault(__nccwpck_require__(1985)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(97195)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); +const INTERNALS$1 = Symbol('Response internals'); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; /** - * @name subWeeks - * @category Week Helpers - * @summary Subtract the specified number of weeks from the given date. - * - * @description - * Subtract the specified number of weeks from the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} amount - the amount of weeks to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. - * @returns {Date} the new date with the weeks subtracted - * @throws {TypeError} 2 arguments required + * Response class * - * @example - * // Subtract 4 weeks from 1 September 2014: - * const result = subWeeks(new Date(2014, 8, 1), 4) - * //=> Mon Aug 04 2014 00:00:00 + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void */ -function subWeeks(dirtyDate, dirtyAmount) { - (0, _index3.default)(2, arguments); - var amount = (0, _index.default)(dirtyAmount); - return (0, _index2.default)(dirtyDate, -amount); -} +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; -module.exports = exports.default; + Body.call(this, body, opts); -/***/ }), + const status = opts.status || 200; + const headers = new Headers(opts.headers); -/***/ 80843: -/***/ ((module, exports, __nccwpck_require__) => { + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } -"use strict"; + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + get url() { + return this[INTERNALS$1].url || ''; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = subYears; + get status() { + return this[INTERNALS$1].status; + } -var _index = _interopRequireDefault(__nccwpck_require__(1985)); + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } -var _index2 = _interopRequireDefault(__nccwpck_require__(73367)); + get redirected() { + return this[INTERNALS$1].counter > 0; + } -var _index3 = _interopRequireDefault(__nccwpck_require__(82063)); + get statusText() { + return this[INTERNALS$1].statusText; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + get headers() { + return this[INTERNALS$1].headers; + } -/** - * @name subYears - * @category Year Helpers - * @summary Subtract the specified number of years from the given date. - * - * @description - * Subtract the specified number of years from the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} amount - the amount of years to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. - * @returns {Date} the new date with the years subtracted - * @throws {TypeError} 2 arguments required - * - * @example - * // Subtract 5 years from 1 September 2014: - * const result = subYears(new Date(2014, 8, 1), 5) - * //=> Tue Sep 01 2009 00:00:00 - */ -function subYears(dirtyDate, dirtyAmount) { - (0, _index3.default)(2, arguments); - var amount = (0, _index.default)(dirtyAmount); - return (0, _index2.default)(dirtyDate, -amount); + /** + * 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 + }); + } } -module.exports = exports.default; +Body.mixIn(Response.prototype); -/***/ }), +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); -/***/ 26477: -/***/ ((module, exports, __nccwpck_require__) => { +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); -"use strict"; +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = toDate; +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } -var _index = _interopRequireDefault(__nccwpck_require__(82063)); + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; /** - * @name toDate - * @category Common Helpers - * @summary Convert the given argument to an instance of Date. - * - * @description - * Convert the given argument to an instance of Date. - * - * If the argument is an instance of Date, the function returns its clone. - * - * If the argument is a number, it is treated as a timestamp. - * - * If the argument is none of the above, the function returns Invalid Date. - * - * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`. - * - * @param {Date|Number} argument - the value to convert - * @returns {Date} the parsed date in the local time zone - * @throws {TypeError} 1 argument required - * - * @example - * // Clone the date: - * const result = toDate(new Date(2014, 1, 11, 11, 30, 30)) - * //=> Tue Feb 11 2014 11:30:30 + * Check if a value is an instance of Request. * - * @example - * // Convert the timestamp to date: - * const result = toDate(1392098430000) - * //=> Tue Feb 11 2014 11:30:30 + * @param Mixed input + * @return Boolean */ -function toDate(argument) { - (0, _index.default)(1, arguments); - var argStr = Object.prototype.toString.call(argument); // Clone the date +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} - if (argument instanceof Date || typeof argument === 'object' && argStr === '[object Date]') { - // Prevent the date to lose the milliseconds when passed to new Date() in IE10 - return new Date(argument.getTime()); - } else if (typeof argument === 'number' || argStr === '[object Number]') { - return new Date(argument); - } else { - if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') { - // eslint-disable-next-line no-console - console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: /~https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"); // eslint-disable-next-line no-console +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} - console.warn(new Error().stack); - } +/** + * 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] : {}; - return new Date(NaN); - } -} + let parsedURL; -module.exports = exports.default; + // 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 = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } -/***/ }), + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); -/***/ 56812: -/***/ ((module, exports, __nccwpck_require__) => { + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } -"use strict"; + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + const headers = new Headers(init.headers || input.headers || {}); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = weeksToDays; + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } -var _index = _interopRequireDefault(__nccwpck_require__(82063)); + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; -var _index2 = __nccwpck_require__(25756); + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; -/** - * @name weeksToDays - * @category Conversion Helpers - * @summary Convert weeks to days. - * - * @description - * Convert a number of weeks to a full number of days. - * - * @param {number} weeks - number of weeks to be converted - * - * @returns {number} the number of weeks converted in days - * @throws {TypeError} 1 argument required - * - * @example - * // Convert 2 weeks into days - * const result = weeksToDays(2) - * //=> 14 - */ -function weeksToDays(weeks) { - (0, _index.default)(1, arguments); - return Math.floor(weeks * _index2.daysInWeek); -} + // 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; + } -module.exports = exports.default; + get method() { + return this[INTERNALS$2].method; + } -/***/ }), + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } -/***/ 34616: -/***/ ((module, exports, __nccwpck_require__) => { + get headers() { + return this[INTERNALS$2].headers; + } -"use strict"; + get redirect() { + return this[INTERNALS$2].redirect; + } + get signal() { + return this[INTERNALS$2].signal; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = yearsToMonths; + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} -var _index = _interopRequireDefault(__nccwpck_require__(82063)); +Body.mixIn(Request.prototype); -var _index2 = __nccwpck_require__(25756); +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); /** - * @name yearsToMonths - * @category Conversion Helpers - * @summary Convert years to months. - * - * @description - * Convert a number of years to a full number of months. - * - * @param {number} years - number of years to be converted - * - * @returns {number} the number of years converted in months - * @throws {TypeError} 1 argument required + * Convert a Request to Node.js http request options. * - * @example - * // Convert 2 years into months - * const result = yearsToMonths(2) - * //=> 24 + * @param Request A Request instance + * @return Object The options object to be passed to http.request */ -function yearsToMonths(years) { - (0, _index.default)(1, arguments); - return Math.floor(years * _index2.monthsInYear); -} +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); -module.exports = exports.default; + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } -/***/ }), + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } -/***/ 97384: -/***/ ((module, exports, __nccwpck_require__) => { + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } -"use strict"; + 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)'); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = yearsToQuarters; + // 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); + } -var _index = _interopRequireDefault(__nccwpck_require__(82063)); + if (!headers.has('Connection') && !agent) { + headers.set('Connection', 'close'); + } -var _index2 = __nccwpck_require__(25756); + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} /** - * @name yearsToQuarters - * @category Conversion Helpers - * @summary Convert years to quarters. - * - * @description - * Convert a number of years to a full number of quarters. - * - * @param {number} years - number of years to be converted + * abort-error.js * - * @returns {number} the number of years converted in quarters - * @throws {TypeError} 1 argument required + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance * - * @example - * // Convert 2 years to quarters - * const result = yearsToQuarters(2) - * //=> 8 + * @param String message Error message for human + * @return AbortError */ -function yearsToQuarters(years) { - (0, _index.default)(1, arguments); - return Math.floor(years * _index2.quartersInYear); -} +function AbortError(message) { + Error.call(this, message); -module.exports = exports.default; + this.type = 'aborted'; + this.message = message; -/***/ }), + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} -/***/ 18611: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; -var Stream = (__nccwpck_require__(12781).Stream); -var util = __nccwpck_require__(73837); +const URL$1 = Url.URL || whatwgUrl.URL; -module.exports = DelayedStream; -function DelayedStream() { - this.source = null; - this.dataSize = 0; - this.maxDataSize = 1024 * 1024; - this.pauseStream = true; +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; - this._maxDataSizeExceeded = false; - this._released = false; - this._bufferedEvents = []; -} -util.inherits(DelayedStream, Stream); +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; -DelayedStream.create = function(source, options) { - var delayedStream = new this(); + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; - options = options || {}; - for (var option in options) { - delayedStream[option] = options[option]; - } +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { - delayedStream.source = source; + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } - var realEmit = source.emit; - source.emit = function() { - delayedStream._handleEmit(arguments); - return realEmit.apply(source, arguments); - }; + Body.Promise = fetch.Promise; - source.on('error', function() {}); - if (delayedStream.pauseStream) { - source.pause(); - } + // 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); - return delayedStream; -}; + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; -Object.defineProperty(DelayedStream.prototype, 'readable', { - configurable: true, - enumerable: true, - get: function() { - return this.source.readable; - } -}); + let response = null; -DelayedStream.prototype.setEncoding = function() { - return this.source.setEncoding.apply(this.source, arguments); -}; + 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); + }; -DelayedStream.prototype.resume = function() { - if (!this._released) { - this.release(); - } + if (signal && signal.aborted) { + abort(); + return; + } - this.source.resume(); -}; + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; -DelayedStream.prototype.pause = function() { - this.source.pause(); -}; + // send request + const req = send(options); + let reqTimeout; -DelayedStream.prototype.release = function() { - this._released = true; + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } - this._bufferedEvents.forEach(function(args) { - this.emit.apply(this, args); - }.bind(this)); - this._bufferedEvents = []; -}; + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } -DelayedStream.prototype.pipe = function() { - var r = Stream.prototype.pipe.apply(this, arguments); - this.resume(); - return r; -}; + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } -DelayedStream.prototype._handleEmit = function(args) { - if (this._released) { - this.emit.apply(this, args); - return; - } + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + finalize(); + }); - if (args[0] === 'data') { - this.dataSize += args[1].length; - this._checkIfMaxDataSizeExceeded(); - } + req.on('response', function (res) { + clearTimeout(reqTimeout); - this._bufferedEvents.push(args); -}; + const headers = createHeadersLenient(res.headers); -DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { - if (this._maxDataSizeExceeded) { - return; - } + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } - if (this.dataSize <= this.maxDataSize) { - return; - } + // 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; + } - this._maxDataSizeExceeded = true; - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' - this.emit('error', new Error(message)); -}; + // 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 + }; -/***/ }), + if (!isDomainOrSubdomain(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } -/***/ 58932: -/***/ ((__unused_webpack_module, exports) => { + // 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; + } -"use strict"; + // 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; + } + } -Object.defineProperty(exports, "__esModule", ({ value: true })); + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; - /* istanbul ignore next */ + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } + // HTTP-network fetch step 12.1.1.4: handle content codings - this.name = 'Deprecation'; - } + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } -} + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; -exports.Deprecation = Deprecation; + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + return; + } -/***/ }), + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } -/***/ 63287: -/***/ ((__unused_webpack_module, exports) => { + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); -"use strict"; + writeToStream(req, request); + }); +} +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; +// expose Promise +fetch.Promise = global.Promise; +module.exports = exports = fetch; Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ -function isObject(o) { - return Object.prototype.toString.call(o) === '[object Object]'; -} +/***/ }), -function isPlainObject(o) { - var ctor,prot; +/***/ 86210: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (isObject(o) === false) return false; +var wrappy = __nccwpck_require__(60262) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) - // If has modified constructor - ctor = o.constructor; - if (ctor === undefined) return true; +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) - // If has modified prototype - prot = ctor.prototype; - if (isObject(prot) === false) return false; + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) } - - // Most likely a plain Object - return true; + f.called = false + return f } -exports.isPlainObject = isPlainObject; +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} /***/ }), -/***/ 7129: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 70581: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +/*eslint no-var:0, prefer-arrow-callback: 0, object-shorthand: 0 */ -// A linked list to keep track of recently-used-ness -const Yallist = __nccwpck_require__(40665) -const MAX = Symbol('max') -const LENGTH = Symbol('length') -const LENGTH_CALCULATOR = Symbol('lengthCalculator') -const ALLOW_STALE = Symbol('allowStale') -const MAX_AGE = Symbol('maxAge') -const DISPOSE = Symbol('dispose') -const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') -const LRU_LIST = Symbol('lruList') -const CACHE = Symbol('cache') -const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') +var Punycode = __nccwpck_require__(85477); -const naiveLength = () => 1 -// lruList is a yallist where the head is the youngest -// item, and the tail is the oldest. the list contains the Hit -// objects as the entries. -// Each Hit object has a reference to its Yallist.Node. This -// never changes. -// -// cache is a Map (or PseudoMap) that matches the keys to -// the Yallist.Node object. -class LRUCache { - constructor (options) { - if (typeof options === 'number') - options = { max: options } +var internals = {}; - if (!options) - options = {} - if (options.max && (typeof options.max !== 'number' || options.max < 0)) - throw new TypeError('max must be a non-negative number') - // Kind of weird to have a default max of Infinity, but oh well. - const max = this[MAX] = options.max || Infinity +// +// Read rules from file. +// +internals.rules = (__nccwpck_require__(56381).map)(function (rule) { - const lc = options.length || naiveLength - this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc - this[ALLOW_STALE] = options.stale || false - if (options.maxAge && typeof options.maxAge !== 'number') - throw new TypeError('maxAge must be a number') - this[MAX_AGE] = options.maxAge || 0 - this[DISPOSE] = options.dispose - this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false - this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false - this.reset() - } + return { + rule: rule, + suffix: rule.replace(/^(\*\.|\!)/, ''), + punySuffix: -1, + wildcard: rule.charAt(0) === '*', + exception: rule.charAt(0) === '!' + }; +}); - // resize the cache when the max changes. - set max (mL) { - if (typeof mL !== 'number' || mL < 0) - throw new TypeError('max must be a non-negative number') - this[MAX] = mL || Infinity - trim(this) - } - get max () { - return this[MAX] - } +// +// Check is given string ends with `suffix`. +// +internals.endsWith = function (str, suffix) { - set allowStale (allowStale) { - this[ALLOW_STALE] = !!allowStale - } - get allowStale () { - return this[ALLOW_STALE] - } + return str.indexOf(suffix, str.length - suffix.length) !== -1; +}; - set maxAge (mA) { - if (typeof mA !== 'number') - throw new TypeError('maxAge must be a non-negative number') - this[MAX_AGE] = mA - trim(this) - } - get maxAge () { - return this[MAX_AGE] - } +// +// Find rule for a given domain. +// +internals.findRule = function (domain) { - // resize the cache when the lengthCalculator changes. - set lengthCalculator (lC) { - if (typeof lC !== 'function') - lC = naiveLength + var punyDomain = Punycode.toASCII(domain); + return internals.rules.reduce(function (memo, rule) { - if (lC !== this[LENGTH_CALCULATOR]) { - this[LENGTH_CALCULATOR] = lC - this[LENGTH] = 0 - this[LRU_LIST].forEach(hit => { - hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) - this[LENGTH] += hit.length - }) + if (rule.punySuffix === -1){ + rule.punySuffix = Punycode.toASCII(rule.suffix); } - trim(this) - } - get lengthCalculator () { return this[LENGTH_CALCULATOR] } - - get length () { return this[LENGTH] } - get itemCount () { return this[LRU_LIST].length } - - rforEach (fn, thisp) { - thisp = thisp || this - for (let walker = this[LRU_LIST].tail; walker !== null;) { - const prev = walker.prev - forEachStep(this, fn, walker, thisp) - walker = prev + if (!internals.endsWith(punyDomain, '.' + rule.punySuffix) && punyDomain !== rule.punySuffix) { + return memo; } - } + // This has been commented out as it never seems to run. This is because + // sub tlds always appear after their parents and we never find a shorter + // match. + //if (memo) { + // var memoSuffix = Punycode.toASCII(memo.suffix); + // if (memoSuffix.length >= punySuffix.length) { + // return memo; + // } + //} + return rule; + }, null); +}; - forEach (fn, thisp) { - thisp = thisp || this - for (let walker = this[LRU_LIST].head; walker !== null;) { - const next = walker.next - forEachStep(this, fn, walker, thisp) - walker = next - } - } - keys () { - return this[LRU_LIST].toArray().map(k => k.key) - } +// +// Error codes and messages. +// +exports.errorCodes = { + DOMAIN_TOO_SHORT: 'Domain name too short.', + DOMAIN_TOO_LONG: 'Domain name too long. It should be no more than 255 chars.', + LABEL_STARTS_WITH_DASH: 'Domain name label can not start with a dash.', + LABEL_ENDS_WITH_DASH: 'Domain name label can not end with a dash.', + LABEL_TOO_LONG: 'Domain name label should be at most 63 chars long.', + LABEL_TOO_SHORT: 'Domain name label should be at least 1 character long.', + LABEL_INVALID_CHARS: 'Domain name label can only contain alphanumeric characters or dashes.' +}; - values () { - return this[LRU_LIST].toArray().map(k => k.value) - } - reset () { - if (this[DISPOSE] && - this[LRU_LIST] && - this[LRU_LIST].length) { - this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) - } +// +// Validate domain name and throw if not valid. +// +// From wikipedia: +// +// Hostnames are composed of series of labels concatenated with dots, as are all +// domain names. Each label must be between 1 and 63 characters long, and the +// entire hostname (including the delimiting dots) has a maximum of 255 chars. +// +// Allowed chars: +// +// * `a-z` +// * `0-9` +// * `-` but not as a starting or ending character +// * `.` as a separator for the textual portions of a domain name +// +// * http://en.wikipedia.org/wiki/Domain_name +// * http://en.wikipedia.org/wiki/Hostname +// +internals.validate = function (input) { - this[CACHE] = new Map() // hash of items by key - this[LRU_LIST] = new Yallist() // list of items in order of use recency - this[LENGTH] = 0 // length of items in the list - } + // Before we can validate we need to take care of IDNs with unicode chars. + var ascii = Punycode.toASCII(input); - dump () { - return this[LRU_LIST].map(hit => - isStale(this, hit) ? false : { - k: hit.key, - v: hit.value, - e: hit.now + (hit.maxAge || 0) - }).toArray().filter(h => h) + if (ascii.length < 1) { + return 'DOMAIN_TOO_SHORT'; } - - dumpLru () { - return this[LRU_LIST] + if (ascii.length > 255) { + return 'DOMAIN_TOO_LONG'; } - set (key, value, maxAge) { - maxAge = maxAge || this[MAX_AGE] - - if (maxAge && typeof maxAge !== 'number') - throw new TypeError('maxAge must be a number') - - const now = maxAge ? Date.now() : 0 - const len = this[LENGTH_CALCULATOR](value, key) - - if (this[CACHE].has(key)) { - if (len > this[MAX]) { - del(this, this[CACHE].get(key)) - return false - } - - const node = this[CACHE].get(key) - const item = node.value - - // dispose of the old one before overwriting - // split out into 2 ifs for better coverage tracking - if (this[DISPOSE]) { - if (!this[NO_DISPOSE_ON_SET]) - this[DISPOSE](key, item.value) - } + // Check each part's length and allowed chars. + var labels = ascii.split('.'); + var label; - item.now = now - item.maxAge = maxAge - item.value = value - this[LENGTH] += len - item.length - item.length = len - this.get(key) - trim(this) - return true + for (var i = 0; i < labels.length; ++i) { + label = labels[i]; + if (!label.length) { + return 'LABEL_TOO_SHORT'; } + if (label.length > 63) { + return 'LABEL_TOO_LONG'; + } + if (label.charAt(0) === '-') { + return 'LABEL_STARTS_WITH_DASH'; + } + if (label.charAt(label.length - 1) === '-') { + return 'LABEL_ENDS_WITH_DASH'; + } + if (!/^[a-z0-9\-]+$/.test(label)) { + return 'LABEL_INVALID_CHARS'; + } + } +}; - const hit = new Entry(key, value, len, now, maxAge) - // oversized objects fall out of cache automatically. - if (hit.length > this[MAX]) { - if (this[DISPOSE]) - this[DISPOSE](key, value) +// +// Public API +// + - return false - } +// +// Parse domain. +// +exports.parse = function (input) { - this[LENGTH] += hit.length - this[LRU_LIST].unshift(hit) - this[CACHE].set(key, this[LRU_LIST].head) - trim(this) - return true + if (typeof input !== 'string') { + throw new TypeError('Domain name must be a string.'); } - has (key) { - if (!this[CACHE].has(key)) return false - const hit = this[CACHE].get(key).value - return !isStale(this, hit) - } + // Force domain to lowercase. + var domain = input.slice(0).toLowerCase(); - get (key) { - return get(this, key, true) + // Handle FQDN. + // TODO: Simply remove trailing dot? + if (domain.charAt(domain.length - 1) === '.') { + domain = domain.slice(0, domain.length - 1); } - peek (key) { - return get(this, key, false) + // Validate and sanitise input. + var error = internals.validate(domain); + if (error) { + return { + input: input, + error: { + message: exports.errorCodes[error], + code: error + } + }; } - pop () { - const node = this[LRU_LIST].tail - if (!node) - return null + var parsed = { + input: input, + tld: null, + sld: null, + domain: null, + subdomain: null, + listed: false + }; - del(this, node) - return node.value - } + var domainParts = domain.split('.'); - del (key) { - del(this, this[CACHE].get(key)) + // Non-Internet TLD + if (domainParts[domainParts.length - 1] === 'local') { + return parsed; } - load (arr) { - // reset the cache - this.reset() + var handlePunycode = function () { - const now = Date.now() - // A previous serialized cache has the most recent items first - for (let l = arr.length - 1; l >= 0; l--) { - const hit = arr[l] - const expiresAt = hit.e || 0 - if (expiresAt === 0) - // the item was created without expiration in a non aged cache - this.set(hit.k, hit.v) - else { - const maxAge = expiresAt - now - // dont add already expired items - if (maxAge > 0) { - this.set(hit.k, hit.v, maxAge) - } - } + if (!/xn--/.test(domain)) { + return parsed; } - } + if (parsed.domain) { + parsed.domain = Punycode.toASCII(parsed.domain); + } + if (parsed.subdomain) { + parsed.subdomain = Punycode.toASCII(parsed.subdomain); + } + return parsed; + }; - prune () { - this[CACHE].forEach((value, key) => get(this, key, false)) - } -} + var rule = internals.findRule(domain); -const get = (self, key, doUse) => { - const node = self[CACHE].get(key) - if (node) { - const hit = node.value - if (isStale(self, hit)) { - del(self, node) - if (!self[ALLOW_STALE]) - return undefined - } else { - if (doUse) { - if (self[UPDATE_AGE_ON_GET]) - node.value.now = Date.now() - self[LRU_LIST].unshiftNode(node) - } + // Unlisted tld. + if (!rule) { + if (domainParts.length < 2) { + return parsed; } - return hit.value + parsed.tld = domainParts.pop(); + parsed.sld = domainParts.pop(); + parsed.domain = [parsed.sld, parsed.tld].join('.'); + if (domainParts.length) { + parsed.subdomain = domainParts.pop(); + } + return handlePunycode(); } -} -const isStale = (self, hit) => { - if (!hit || (!hit.maxAge && !self[MAX_AGE])) - return false + // At this point we know the public suffix is listed. + parsed.listed = true; - const diff = Date.now() - hit.now - return hit.maxAge ? diff > hit.maxAge - : self[MAX_AGE] && (diff > self[MAX_AGE]) -} + var tldParts = rule.suffix.split('.'); + var privateParts = domainParts.slice(0, domainParts.length - tldParts.length); -const trim = self => { - if (self[LENGTH] > self[MAX]) { - for (let walker = self[LRU_LIST].tail; - self[LENGTH] > self[MAX] && walker !== null;) { - // We know that we're about to delete this one, and also - // what the next least recently used key will be, so just - // go ahead and set it now. - const prev = walker.prev - del(self, walker) - walker = prev - } + if (rule.exception) { + privateParts.push(tldParts.shift()); } -} -const del = (self, node) => { - if (node) { - const hit = node.value - if (self[DISPOSE]) - self[DISPOSE](hit.key, hit.value) + parsed.tld = tldParts.join('.'); - self[LENGTH] -= hit.length - self[CACHE].delete(hit.key) - self[LRU_LIST].removeNode(node) + if (!privateParts.length) { + return handlePunycode(); } -} -class Entry { - constructor (key, value, length, now, maxAge) { - this.key = key - this.value = value - this.length = length - this.now = now - this.maxAge = maxAge || 0 + if (rule.wildcard) { + tldParts.unshift(privateParts.pop()); + parsed.tld = tldParts.join('.'); } -} -const forEachStep = (self, fn, node, thisp) => { - let hit = node.value - if (isStale(self, hit)) { - del(self, node) - if (!self[ALLOW_STALE]) - hit = undefined + if (!privateParts.length) { + return handlePunycode(); } - if (hit) - fn.call(thisp, hit.value, hit.key, self) -} -module.exports = LRUCache + parsed.sld = privateParts.pop(); + parsed.domain = [parsed.sld, parsed.tld].join('.'); + + if (privateParts.length) { + parsed.subdomain = privateParts.join('.'); + } + return handlePunycode(); +}; -/***/ }), -/***/ 47426: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// +// Get domain. +// +exports.get = function (domain) { -/*! - * mime-db - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015-2022 Douglas Christopher Wilson - * MIT Licensed - */ + if (!domain) { + return null; + } + return exports.parse(domain).domain || null; +}; -/** - * Module exports. - */ -module.exports = __nccwpck_require__(53765) +// +// Check whether domain belongs to a known public suffix. +// +exports.isValid = function (domain) { + + var parsed = exports.parse(domain); + return Boolean(parsed.domain && parsed.listed); +}; /***/ }), -/***/ 43583: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 25174: +/***/ ((module) => { "use strict"; -/*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 -/** - * Module dependencies. - * @private - */ +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' -var db = __nccwpck_require__(47426) -var extname = (__nccwpck_require__(71017).extname) +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators -/** - * Module variables. - * @private - */ +/** Error messages */ +const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; -var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ -var TEXT_TYPE_REGEXP = /^text\//i +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ /** - * Module exports. - * @public + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. */ - -exports.charset = charset -exports.charsets = { lookup: charset } -exports.contentType = contentType -exports.extension = extension -exports.extensions = Object.create(null) -exports.lookup = lookup -exports.types = Object.create(null) - -// Populate the extensions/types maps -populateMaps(exports.extensions, exports.types) +function error(type) { + throw new RangeError(errors[type]); +} /** - * Get the default charset for a MIME type. - * - * @param {string} type - * @return {boolean|string} + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. */ - -function charset (type) { - if (!type || typeof type !== 'string') { - return false - } - - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - var mime = match && db[match[1].toLowerCase()] - - if (mime && mime.charset) { - return mime.charset - } - - // default text/* to utf-8 - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return 'UTF-8' - } - - return false +function map(array, fn) { + const result = []; + let length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; } /** - * Create a full Content-Type header given a MIME type or extension. - * - * @param {string} str - * @return {boolean|string} + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. */ - -function contentType (str) { - // TODO: should this even be in this module? - if (!str || typeof str !== 'string') { - return false - } - - var mime = str.indexOf('/') === -1 - ? exports.lookup(str) - : str - - if (!mime) { - return false - } - - // TODO: use content-type or other module - if (mime.indexOf('charset') === -1) { - var charset = exports.charset(mime) - if (charset) mime += '; charset=' + charset.toLowerCase() - } - - return mime +function mapDomain(string, fn) { + const parts = string.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + const labels = string.split('.'); + const encoded = map(labels, fn).join('.'); + return result + encoded; } /** - * Get the default extension for a MIME type. - * - * @param {string} type - * @return {boolean|string} + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. */ - -function extension (type) { - if (!type || typeof type !== 'string') { - return false - } - - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - - // get extensions - var exts = match && exports.extensions[match[1].toLowerCase()] - - if (!exts || !exts.length) { - return false - } - - return exts[0] +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; } /** - * Lookup the MIME type for a file path/extension. - * - * @param {string} path - * @return {boolean|string} + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). */ - -function lookup (path) { - if (!path || typeof path !== 'string') { - return false - } - - // get the extension ("ext" or ".ext" or full path) - var extension = extname('x.' + path) - .toLowerCase() - .substr(1) - - if (!extension) { - return false - } - - return exports.types[extension] || false -} +const ucs2encode = array => String.fromCodePoint(...array); /** - * Populate the extensions and types maps. + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. */ +const basicToDigit = function(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; -function populateMaps (extensions, types) { - // source preference (least -> most) - var preference = ['nginx', 'apache', undefined, 'iana'] - - Object.keys(db).forEach(function forEachMimeType (type) { - var mime = db[type] - var exts = mime.extensions - - if (!exts || !exts.length) { - return - } - - // mime -> extensions - extensions[type] = exts - - // extension -> mime - for (var i = 0; i < exts.length; i++) { - var extension = exts[i] - - if (types[extension]) { - var from = preference.indexOf(db[types[extension]].source) - var to = preference.indexOf(mime.source) - - if (types[extension] !== 'application/octet-stream' && - (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { - // skip the remapping - continue - } - } - - // set the extension -> mime - types[extension] = type - } - }) -} - +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; -/***/ }), +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function(delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; -/***/ 83973: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function(input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; -module.exports = minimatch -minimatch.Minimatch = Minimatch + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. -var path = (function () { try { return __nccwpck_require__(71017) } catch (e) {}}()) || { - sep: '/' -} -minimatch.sep = path.sep + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } -var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = __nccwpck_require__(33717) + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } -var plTypes = { - '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, - '?': { open: '(?:', close: ')?' }, - '+': { open: '(?:', close: ')+' }, - '*': { open: '(?:', close: ')*' }, - '@': { open: '(?:', close: ')' } -} + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. -// any single thing other than / -// don't need to escape / when using new RegExp() -var qmark = '[^/]' + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { -// * => any number of characters -var star = qmark + '*?' + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + let oldi = i; + for (let w = 1, k = base; /* no condition */; k += base) { -// ** 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})($|\\\/)).)*?' + if (index >= inputLength) { + error('invalid-input'); + } -// not a ^ or / followed by a dot, -// followed by anything, any number of times. -var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + const digit = basicToDigit(input.charCodeAt(index++)); -// characters that need to be escaped in RegExp. -var reSpecials = charSet('().*{}+?[]^$\\!') + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split('').reduce(function (set, c) { - set[c] = true - return set - }, {}) -} + i += digit * w; + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); -// normalizes slashes. -var slashSplit = /\/+/ + if (digit < t) { + break; + } -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } -function ext (a, b) { - b = b || {} - var t = {} - Object.keys(a).forEach(function (k) { - t[k] = a[k] - }) - Object.keys(b).forEach(function (k) { - t[k] = b[k] - }) - return t -} + w *= baseMinusT; -minimatch.defaults = function (def) { - if (!def || typeof def !== 'object' || !Object.keys(def).length) { - return minimatch - } + } - var orig = minimatch + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); - var m = function minimatch (p, pattern, options) { - return orig(p, pattern, ext(def, options)) - } + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } - m.Minimatch = function Minimatch (pattern, options) { - return new orig.Minimatch(pattern, ext(def, options)) - } - m.Minimatch.defaults = function defaults (options) { - return orig.defaults(ext(def, options)).Minimatch - } + n += floor(i / out); + i %= out; - m.filter = function filter (pattern, options) { - return orig.filter(pattern, ext(def, options)) - } + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); - m.defaults = function defaults (options) { - return orig.defaults(ext(def, options)) - } + } - m.makeRe = function makeRe (pattern, options) { - return orig.makeRe(pattern, ext(def, options)) - } + return String.fromCodePoint(...output); +}; - m.braceExpand = function braceExpand (pattern, options) { - return orig.braceExpand(pattern, ext(def, options)) - } +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function(input) { + const output = []; - m.match = function (list, pattern, options) { - return orig.match(list, pattern, ext(def, options)) - } + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); - return m -} + // Cache the length. + let inputLength = input.length; -Minimatch.defaults = function (def) { - return minimatch.defaults(def).Minimatch -} + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; -function minimatch (p, pattern, options) { - assertValidPattern(pattern) + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } - if (!options) options = {} + let basicLength = output.length; + let handledCPCount = basicLength; - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false - } + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. - return new Minimatch(pattern, options).match(p) -} + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options) - } + // Main encoding loop: + while (handledCPCount < inputLength) { - assertValidPattern(pattern) + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } - if (!options) options = {} + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } - pattern = pattern.trim() + delta += (m - n) * handledCPCountPlusOne; + n = m; - // windows support: need to use /, not \ - if (!options.allowWindowsEscape && path.sep !== '/') { - pattern = pattern.split(path.sep).join('/') - } + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue == n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base; /* no condition */; k += base) { + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } - this.options = options - this.set = [] - this.pattern = pattern - this.regexp = null - this.negate = false - this.comment = false - this.empty = false - this.partial = !!options.partial + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } - // make the set of regexps etc. - this.make() -} + ++delta; + ++n; -Minimatch.prototype.debug = function () {} + } + return output.join(''); +}; -Minimatch.prototype.make = make -function make () { - var pattern = this.pattern - var options = this.options +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); +}; - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true - return - } - if (!pattern) { - this.empty = true - return - } +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); +}; - // step 1: figure out negation, etc. - this.parseNegate() +/*--------------------------------------------------------------------------*/ - // step 2: expand braces - var set = this.globSet = this.braceExpand() +/** Define the public API */ +const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; - if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } +module.exports = punycode; - this.debug(this.pattern, set) - // 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) - }) +/***/ }), - this.debug(this.pattern, set) +/***/ 77915: +/***/ ((__unused_webpack_module, exports) => { - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) +"use strict"; - this.debug(this.pattern, set) - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) +var has = Object.prototype.hasOwnProperty + , undef; - this.debug(this.pattern, set) +/** + * Decode a URI encoded string. + * + * @param {String} input The URI encoded string. + * @returns {String|Null} The decoded string. + * @api private + */ +function decode(input) { + try { + return decodeURIComponent(input.replace(/\+/g, ' ')); + } catch (e) { + return null; + } +} - this.set = set +/** + * Attempts to encode a given input. + * + * @param {String} input The string that needs to be encoded. + * @returns {String|Null} The encoded string. + * @api private + */ +function encode(input) { + try { + return encodeURIComponent(input); + } catch (e) { + return null; + } } -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 +/** + * Simple query string parser. + * + * @param {String} query The query string that needs to be parsed. + * @returns {Object} + * @api public + */ +function querystring(query) { + var parser = /([^=?#&]+)=?([^&]*)/g + , result = {} + , part; - if (options.nonegate) return + while (part = parser.exec(query)) { + var key = decode(part[1]) + , value = decode(part[2]); - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ + // + // Prevent overriding of existing properties. This ensures that build-in + // methods like `toString` or __proto__ are not overriden by malicious + // querystrings. + // + // In the case if failed decoding, we want to omit the key/value pairs + // from the result. + // + if (key === null || value === null || key in result) continue; + result[key] = value; } - 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) + return result; } -Minimatch.prototype.braceExpand = braceExpand +/** + * Transform a query string to an object. + * + * @param {Object} obj Object that should be transformed. + * @param {String} prefix Optional prefix. + * @returns {String} + * @api public + */ +function querystringify(obj, prefix) { + prefix = prefix || ''; -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} - } - } + var pairs = [] + , value + , key; - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern + // + // Optionally prefix with a '?' if needed + // + if ('string' !== typeof prefix) prefix = '?'; - assertValidPattern(pattern) + for (key in obj) { + if (has.call(obj, key)) { + value = obj[key]; - // Thanks to Yeting Li for - // improving this regexp to avoid a ReDOS vulnerability. - if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { - // shortcut. no need to expand. - return [pattern] - } + // + // Edge cases where we actually want to encode the value to an empty + // string instead of the stringified value. + // + if (!value && (value === null || value === undef || isNaN(value))) { + value = ''; + } - return expand(pattern) -} + key = encode(key); + value = encode(value); -var MAX_PATTERN_LENGTH = 1024 * 64 -var assertValidPattern = function (pattern) { - if (typeof pattern !== 'string') { - throw new TypeError('invalid pattern') + // + // If we failed to encode the strings, we should bail out as we don't + // want to add invalid strings to the query. + // + if (key === null || value === null) continue; + pairs.push(key +'='+ value); + } } - if (pattern.length > MAX_PATTERN_LENGTH) { - throw new TypeError('pattern is too long') - } + return pairs.length ? prefix + pairs.join('&') : ''; } -// 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) { - assertValidPattern(pattern) +// Expose the module. +// +exports.stringify = querystringify; +exports.parse = querystring; - var options = this.options - // shortcuts - if (pattern === '**') { - if (!options.noglobstar) - return GLOBSTAR - else - pattern = '*' - } - if (pattern === '') return '' +/***/ }), - 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 +/***/ 8006: +/***/ ((module) => { - 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 - } - } +"use strict"; - 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 - } +/** + * Check if we're required to add a port number. + * + * @see https://url.spec.whatwg.org/#default-port + * @param {Number|String} port Port number we need to check + * @param {String} protocol Protocol we need to check against. + * @returns {Boolean} Is it a default port for the given protocol + * @api private + */ +module.exports = function required(port, protocol) { + protocol = protocol.split(':')[0]; + port = +port; - switch (c) { - /* istanbul ignore next */ - case '/': { - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - } + if (!port) return false; - case '\\': - clearStateChar() - escaping = true - continue + switch (protocol) { + case 'http': + case 'ws': + return port !== 80; - // 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) + case 'https': + case 'wss': + return port !== 443; - // 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 - } + case 'ftp': + return port !== 21; - // 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 + case 'gopher': + return port !== 70; - case '(': - if (inClass) { - re += '(' - continue - } + case 'file': + return false; + } - if (!stateChar) { - re += '\\(' - continue - } + return port !== 0; +}; - 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 - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } +/***/ }), - 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 +/***/ 31853: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } +;(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 - clearStateChar() - re += '|' - continue + // 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 - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() + var buffers = [ + 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype', + 'procInstName', 'procInstBody', 'entity', 'attribName', + 'attribValue', 'cdata', 'script' + ] - if (inClass) { - re += '\\' + c - continue - } + sax.EVENTS = [ + 'text', + 'processinginstruction', + 'sgmldeclaration', + 'doctype', + 'comment', + 'opentagstart', + 'attribute', + 'opentag', + 'closetag', + 'opencdata', + 'cdata', + 'closecdata', + 'error', + 'end', + 'ready', + 'script', + 'opennamespace', + 'closenamespace' + ] - inClass = true - classStart = i - reClassStart = re.length - re += c - continue + function SAXParser (strict, opt) { + if (!(this instanceof SAXParser)) { + return new SAXParser(strict, opt) + } - 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 - } + 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 = [] - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - // 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 - } + // 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) + } - // finish up the class. - hasMagic = true - inClass = false - re += c - continue + // mostly just for error reporting + parser.trackPosition = parser.opt.position !== false + if (parser.trackPosition) { + parser.position = parser.line = parser.column = 0 + } + emit(parser, 'onready') + } - default: - // swallow any state char that wasn't consumed - clearStateChar() + if (!Object.create) { + Object.create = function (o) { + function F () {} + F.prototype = o + var newf = new F() + return newf + } + } - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } + if (!Object.keys) { + Object.keys = function (o) { + var a = [] + for (var i in o) if (o.hasOwnProperty(i)) a.push(i) + return a + } + } - re += c + 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 - } // switch - } // for + case 'cdata': + emitNode(parser, 'oncdata', parser.cdata) + parser.cdata = '' + break - // 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] - } + case 'script': + emitNode(parser, 'onscript', parser.script) + parser.script = '' + break - // 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 = '\\' + 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 + } - // 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 + '|' - }) + function clearBuffers (parser) { + for (var i = 0, l = buffers.length; i < l; i++) { + parser[buffers[i]] = '' + } + } - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type + 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 = '' + } + } - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail + 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) } } - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' + var Stream + try { + Stream = (__nccwpck_require__(12781).Stream) + } catch (ex) { + Stream = function () {} } - // 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 + var streamWraps = sax.EVENTS.filter(function (ev) { + return ev !== 'error' && ev !== 'end' + }) + + function createStream (strict, opt) { + return new SAXStream(strict, opt) } - // 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] + function SAXStream (strict, opt) { + if (!(this instanceof SAXStream)) { + return new SAXStream(strict, opt) + } + + Stream.apply(this) + + this._parser = new SAXParser(strict, opt) + this.writable = true + this.readable = true + + var me = this + + this._parser.onend = function () { + me.emit('end') + } + + this._parser.onerror = function (er) { + me.emit('error', er) - 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 didn't throw, then means error was handled. + // go ahead and clear error, so we can write again. + me._parser.error = null + } - nlLast += nlAfter + this._decoder = null - // 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(/\)[+*?]?/, '') + 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 } - nlAfter = cleanAfter + }) - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' + SAXStream.prototype.write = function (data) { + if (typeof Buffer === 'function' && + typeof Buffer.isBuffer === 'function' && + Buffer.isBuffer(data)) { + if (!this._decoder) { + var SD = (__nccwpck_require__(71576).StringDecoder) + this._decoder = new SD('utf8') + } + data = this._decoder.write(data) } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe - } - // 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 + this._parser.write(data.toString()) + this.emit('data', data) + return true } - if (addPatternStart) { - re = patternStart + re + SAXStream.prototype.end = function (chunk) { + if (chunk && chunk.length) { + this.write(chunk) + } + this._parser.end() + return true } - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } + 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) + } + } - // 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) + return Stream.prototype.on.call(me, ev, handler) } - var flags = options.nocase ? 'i' : '' - try { - var regExp = new RegExp('^' + re + '$', flags) - } catch (er) /* istanbul ignore next - should be impossible */ { - // 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('$.') - } + // 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 } - regExp._glob = pattern - regExp._src = re + // 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]/ - return regExp -} + 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-]/ -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} + 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-]/ -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp + function isWhitespace (c) { + return c === ' ' || c === '\n' || c === '\r' || c === '\t' + } - // 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 + function isQuote (c) { + return c === '"' || c === '\'' + } - if (!set.length) { - this.regexp = false - return this.regexp + function isAttribEnd (c) { + return c === '>' || isWhitespace(c) } - var options = this.options - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' + function isMatch (regex, c) { + return regex.test(c) + } - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') + function notMatch (regex, c) { + return !isMatch(regex, c) + } - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' + 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++, //