if (!window.define) { const modules = {}; window.__modules = modules; const modulePromises = {}; const thisScriptSource = document.currentScript.getAttribute('src'); const srcDir = thisScriptSource.substring(0, thisScriptSource.lastIndexOf('/')); const load = (id) => { if (modules[id]) return modules[id]; if (modulePromises[id]) return modulePromises[id]; return modulePromises[id] = new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = srcDir + '/' + id + '.js'; script.onload = () => modules[id].then(resolve); script.onerror = err => reject(new Error('failed to load ' + id)); script.dataset.id = id; document.head.append(script); }); }; const require = (ids, callback) => { Promise.all(ids.map(load)).then(items => { if (items.length === 1) callback(items[0]); else callback(items); }); }; window.require = require; require.context = (dir, useSubdirs) => { if ((dir === "../../images/emoji" || dir === "../images/emoji") && !useSubdirs) { const data = {"chunks.png":"f59b84127fa7b6c48b6c.png","eggbug-classic.png":"41454e429d62b5cb7963.png","eggbug.png":"17aa2d48956926005de9.png","sixty.png":"9a6014af31fb1ca65a1f.png","unyeah.png":"5cf84d596a2c422967de.png","yeah.png":"014b0a8cc35206ef151d.png"}; const f = (n) => data[n]; f.keys = () => Object.keys(data); return f; } else if ((dir === "../../images/plus-emoji" || dir === "../images/plus-emoji") && !useSubdirs) { const data = {"eggbug-asleep.png":"ebbf360236a95b62bdfc.png","eggbug-devious.png":"c4f3f2c6b9ffb85934e7.png","eggbug-heart-sob.png":"b59709333449a01e3e0a.png","eggbug-nervous.png":"d2753b632211c395538e.png","eggbug-pensive.png":"ae53a8b5de7c919100e6.png","eggbug-pleading.png":"11c5493261064ffa82c0.png","eggbug-relieved.png":"3633c116f0941d94d237.png","eggbug-shocked.png":"b25a9fdf230219087003.png","eggbug-smile-hearts.png":"d7ec7f057e6fb15a94cc.png","eggbug-sob.png":"9559ff8058a895328d76.png","eggbug-tuesday.png":"90058099e741e483208a.png","eggbug-uwu.png":"228d3a13bd5f7796b434.png","eggbug-wink.png":"3bc3a1c5272e2ceb8712.png","host-aww.png":"9bb403f3822c6457baf6.png","host-cry.png":"530f8cf75eac87716702.png","host-evil.png":"cb9a5640d7ef7b361a1a.png","host-frown.png":"99c7fbf98de865cc9726.png","host-joy.png":"53635f5fe850274b1a7d.png","host-love.png":"c45b6d8f9de20f725b98.png","host-nervous.png":"e5d55348f39c65a20148.png","host-plead.png":"fa883e2377fea8945237.png","host-shock.png":"bfa6d6316fd95ae76803.png","host-stare.png":"a09d966cd188c9ebaa4c.png"}; const f = (n) => data[n]; f.keys = () => Object.keys(data); return f; } throw new Error('not supported: require.context for ' + dir); }; window.define = (imports, exec) => { if (typeof imports === 'function') { exec = imports; imports = []; } const id = document.currentScript.dataset.id ?? './' + document.currentScript.getAttribute('src').split('/').pop().replace(/\.js$/i, ''); if (modules[id]) return; const exports = {}; modules[id] = Promise.resolve().then(function() { const imported = []; for (const id of imports) { if (id === 'require') imported.push(Promise.resolve(require)); else if (id === 'exports') imported.push(Promise.resolve(exports)); else imported.push(load(id)); } return Promise.all(imported); }).then(function(imported) { const result = exec.apply(window, imported); if (!('default' in exports)) exports.default = result; return exports; }); }; window.process = { env: { NODE_ENV: 'production' } }; } define(['require', 'exports'], (function (require, exports) { 'use strict'; function _mergeNamespaces(n, m) { m.forEach(function (e) { e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { if (k !== 'default' && !(k in n)) { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); }); return Object.freeze(n); } var nothing = /*#__PURE__*/Object.freeze({ __proto__: null }); var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function getAugmentedNamespace(n) { if (n.__esModule) return n; var f = n.default; if (typeof f == "function") { var a = function a () { if (this instanceof a) { return Reflect.construct(f, arguments, this.constructor); } return f.apply(this, arguments); }; a.prototype = f.prototype; } else a = {}; Object.defineProperty(a, '__esModule', {value: true}); Object.keys(n).forEach(function (k) { var d = Object.getOwnPropertyDescriptor(n, k); Object.defineProperty(a, k, d.get ? d : { enumerable: true, get: function () { return n[k]; } }); }); return a; } var axios$3 = {exports: {}}; var bind$4 = function bind(fn, thisArg) { return function wrap() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } return fn.apply(thisArg, args); }; }; var bind$3 = bind$4; // utils is a library of generic helper functions non-specific to axios var toString$2 = Object.prototype.toString; /** * Determine if a value is an Array * * @param {Object} val The value to test * @returns {boolean} True if value is an Array, otherwise false */ function isArray$2(val) { return toString$2.call(val) === '[object Array]'; } /** * Determine if a value is undefined * * @param {Object} val The value to test * @returns {boolean} True if the value is undefined, otherwise false */ function isUndefined$2(val) { return typeof val === 'undefined'; } /** * Determine if a value is a Buffer * * @param {Object} val The value to test * @returns {boolean} True if value is a Buffer, otherwise false */ function isBuffer$2(val) { return val !== null && !isUndefined$2(val) && val.constructor !== null && !isUndefined$2(val.constructor) && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); } /** * Determine if a value is an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ function isArrayBuffer(val) { return toString$2.call(val) === '[object ArrayBuffer]'; } /** * Determine if a value is a FormData * * @param {Object} val The value to test * @returns {boolean} True if value is an FormData, otherwise false */ function isFormData(val) { return (typeof FormData !== 'undefined') && (val instanceof FormData); } /** * Determine if a value is a view on an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ function isArrayBufferView(val) { var result; if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { result = ArrayBuffer.isView(val); } else { result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); } return result; } /** * Determine if a value is a String * * @param {Object} val The value to test * @returns {boolean} True if value is a String, otherwise false */ function isString$3(val) { return typeof val === 'string'; } /** * Determine if a value is a Number * * @param {Object} val The value to test * @returns {boolean} True if value is a Number, otherwise false */ function isNumber$1(val) { return typeof val === 'number'; } /** * Determine if a value is an Object * * @param {Object} val The value to test * @returns {boolean} True if value is an Object, otherwise false */ function isObject$3(val) { return val !== null && typeof val === 'object'; } /** * Determine if a value is a plain Object * * @param {Object} val The value to test * @return {boolean} True if value is a plain Object, otherwise false */ function isPlainObject$5(val) { if (toString$2.call(val) !== '[object Object]') { return false; } var prototype = Object.getPrototypeOf(val); return prototype === null || prototype === Object.prototype; } /** * Determine if a value is a Date * * @param {Object} val The value to test * @returns {boolean} True if value is a Date, otherwise false */ function isDate$1(val) { return toString$2.call(val) === '[object Date]'; } /** * Determine if a value is a File * * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */ function isFile$1(val) { return toString$2.call(val) === '[object File]'; } /** * Determine if a value is a Blob * * @param {Object} val The value to test * @returns {boolean} True if value is a Blob, otherwise false */ function isBlob(val) { return toString$2.call(val) === '[object Blob]'; } /** * Determine if a value is a Function * * @param {Object} val The value to test * @returns {boolean} True if value is a Function, otherwise false */ function isFunction$2(val) { return toString$2.call(val) === '[object Function]'; } /** * Determine if a value is a Stream * * @param {Object} val The value to test * @returns {boolean} True if value is a Stream, otherwise false */ function isStream(val) { return isObject$3(val) && isFunction$2(val.pipe); } /** * Determine if a value is a URLSearchParams object * * @param {Object} val The value to test * @returns {boolean} True if value is a URLSearchParams object, otherwise false */ function isURLSearchParams(val) { return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; } /** * Trim excess whitespace off the beginning and end of a string * * @param {String} str The String to trim * @returns {String} The String freed of excess whitespace */ function trim$1(str) { return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); } /** * Determine if we're running in a standard browser environment * * This allows axios to run in a web worker, and react-native. * Both environments support XMLHttpRequest, but not fully standard globals. * * web workers: * typeof window -> undefined * typeof document -> undefined * * react-native: * navigator.product -> 'ReactNative' * nativescript * navigator.product -> 'NativeScript' or 'NS' */ function isStandardBrowserEnv() { if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || navigator.product === 'NativeScript' || navigator.product === 'NS')) { return false; } return ( typeof window !== 'undefined' && typeof document !== 'undefined' ); } /** * Iterate over an Array or an Object invoking a function for each item. * * If `obj` is an Array callback will be called passing * the value, index, and complete array for each item. * * If 'obj' is an Object callback will be called passing * the value, key, and complete object for each property. * * @param {Object|Array} obj The object to iterate * @param {Function} fn The callback to invoke for each item */ function forEach(obj, fn) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } // Force an array if not already something iterable if (typeof obj !== 'object') { /*eslint no-param-reassign:0*/ obj = [obj]; } if (isArray$2(obj)) { // Iterate over array values for (var i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { // Iterate over object keys for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { fn.call(null, obj[key], key, obj); } } } } /** * Accepts varargs expecting each argument to be an object, then * immutably merges the properties of each object and returns result. * * When multiple objects contain the same key the later object in * the arguments list will take precedence. * * Example: * * ```js * var result = merge({foo: 123}, {foo: 456}); * console.log(result.foo); // outputs 456 * ``` * * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */ function merge$4(/* obj1, obj2, obj3, ... */) { var result = {}; function assignValue(val, key) { if (isPlainObject$5(result[key]) && isPlainObject$5(val)) { result[key] = merge$4(result[key], val); } else if (isPlainObject$5(val)) { result[key] = merge$4({}, val); } else if (isArray$2(val)) { result[key] = val.slice(); } else { result[key] = val; } } for (var i = 0, l = arguments.length; i < l; i++) { forEach(arguments[i], assignValue); } return result; } /** * Extends object a by mutably adding to it the properties of object b. * * @param {Object} a The object to be extended * @param {Object} b The object to copy properties from * @param {Object} thisArg The object to bind function to * @return {Object} The resulting value of object a */ function extend$2(a, b, thisArg) { forEach(b, function assignValue(val, key) { if (thisArg && typeof val === 'function') { a[key] = bind$3(val, thisArg); } else { a[key] = val; } }); return a; } /** * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) * * @param {string} content with BOM * @return {string} content value without BOM */ function stripBOM(content) { if (content.charCodeAt(0) === 0xFEFF) { content = content.slice(1); } return content; } var utils$8 = { isArray: isArray$2, isArrayBuffer: isArrayBuffer, isBuffer: isBuffer$2, isFormData: isFormData, isArrayBufferView: isArrayBufferView, isString: isString$3, isNumber: isNumber$1, isObject: isObject$3, isPlainObject: isPlainObject$5, isUndefined: isUndefined$2, isDate: isDate$1, isFile: isFile$1, isBlob: isBlob, isFunction: isFunction$2, isStream: isStream, isURLSearchParams: isURLSearchParams, isStandardBrowserEnv: isStandardBrowserEnv, forEach: forEach, merge: merge$4, extend: extend$2, trim: trim$1, stripBOM: stripBOM }; var utils$7 = utils$8; function encode$4(val) { return encodeURIComponent(val). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, '+'). replace(/%5B/gi, '['). replace(/%5D/gi, ']'); } /** * Build a URL by appending params to the end * * @param {string} url The base of the url (e.g., http://www.google.com) * @param {object} [params] The params to be appended * @returns {string} The formatted url */ var buildURL$1 = function buildURL(url, params, paramsSerializer) { /*eslint no-param-reassign:0*/ if (!params) { return url; } var serializedParams; if (paramsSerializer) { serializedParams = paramsSerializer(params); } else if (utils$7.isURLSearchParams(params)) { serializedParams = params.toString(); } else { var parts = []; utils$7.forEach(params, function serialize(val, key) { if (val === null || typeof val === 'undefined') { return; } if (utils$7.isArray(val)) { key = key + '[]'; } else { val = [val]; } utils$7.forEach(val, function parseValue(v) { if (utils$7.isDate(v)) { v = v.toISOString(); } else if (utils$7.isObject(v)) { v = JSON.stringify(v); } parts.push(encode$4(key) + '=' + encode$4(v)); }); }); serializedParams = parts.join('&'); } if (serializedParams) { var hashmarkIndex = url.indexOf('#'); if (hashmarkIndex !== -1) { url = url.slice(0, hashmarkIndex); } url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; } return url; }; var utils$6 = utils$8; function InterceptorManager$1() { this.handlers = []; } /** * Add a new interceptor to the stack * * @param {Function} fulfilled The function to handle `then` for a `Promise` * @param {Function} rejected The function to handle `reject` for a `Promise` * * @return {Number} An ID used to remove interceptor later */ InterceptorManager$1.prototype.use = function use(fulfilled, rejected, options) { this.handlers.push({ fulfilled: fulfilled, rejected: rejected, synchronous: options ? options.synchronous : false, runWhen: options ? options.runWhen : null }); return this.handlers.length - 1; }; /** * Remove an interceptor from the stack * * @param {Number} id The ID that was returned by `use` */ InterceptorManager$1.prototype.eject = function eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } }; /** * Iterate over all the registered interceptors * * This method is particularly useful for skipping over any * interceptors that may have become `null` calling `eject`. * * @param {Function} fn The function to call for each interceptor */ InterceptorManager$1.prototype.forEach = function forEach(fn) { utils$6.forEach(this.handlers, function forEachHandler(h) { if (h !== null) { fn(h); } }); }; var InterceptorManager_1 = InterceptorManager$1; var utils$5 = utils$8; var normalizeHeaderName = function normalizeHeaderName(headers, normalizedName) { utils$5.forEach(headers, function processHeader(value, name) { if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { headers[normalizedName] = value; delete headers[name]; } }); }; /** * Update an Error with the specified config, error code, and response. * * @param {Error} error The error to update. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The error. */ var enhanceError = function enhanceError(error, config, code, request, response) { error.config = config; if (code) { error.code = code; } error.request = request; error.response = response; error.isAxiosError = true; error.toJSON = function toJSON() { return { // Standard message: this.message, name: this.name, // Microsoft description: this.description, number: this.number, // Mozilla fileName: this.fileName, lineNumber: this.lineNumber, columnNumber: this.columnNumber, stack: this.stack, // Axios config: this.config, code: this.code, status: this.response && this.response.status ? this.response.status : null }; }; return error; }; var createError; var hasRequiredCreateError; function requireCreateError () { if (hasRequiredCreateError) return createError; hasRequiredCreateError = 1; var enhanceError$1 = enhanceError; /** * Create an Error with the specified message, config, error code, request and response. * * @param {string} message The error message. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The created error. */ createError = function createError(message, config, code, request, response) { var error = new Error(message); return enhanceError$1(error, config, code, request, response); }; return createError; } var settle; var hasRequiredSettle; function requireSettle () { if (hasRequiredSettle) return settle; hasRequiredSettle = 1; var createError = requireCreateError(); /** * Resolve or reject a Promise based on response status. * * @param {Function} resolve A function that resolves the promise. * @param {Function} reject A function that rejects the promise. * @param {object} response The response. */ settle = function settle(resolve, reject, response) { var validateStatus = response.config.validateStatus; if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); } else { reject(createError( 'Request failed with status code ' + response.status, response.config, null, response.request, response )); } }; return settle; } var cookies; var hasRequiredCookies; function requireCookies () { if (hasRequiredCookies) return cookies; hasRequiredCookies = 1; var utils = utils$8; cookies = ( utils.isStandardBrowserEnv() ? // Standard browser envs support document.cookie (function standardBrowserEnv() { return { write: function write(name, value, expires, path, domain, secure) { var cookie = []; cookie.push(name + '=' + encodeURIComponent(value)); if (utils.isNumber(expires)) { cookie.push('expires=' + new Date(expires).toGMTString()); } if (utils.isString(path)) { cookie.push('path=' + path); } if (utils.isString(domain)) { cookie.push('domain=' + domain); } if (secure === true) { cookie.push('secure'); } document.cookie = cookie.join('; '); }, read: function read(name) { var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); return (match ? decodeURIComponent(match[3]) : null); }, remove: function remove(name) { this.write(name, '', Date.now() - 86400000); } }; })() : // Non standard browser env (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return { write: function write() {}, read: function read() { return null; }, remove: function remove() {} }; })() ); return cookies; } var isAbsoluteURL; var hasRequiredIsAbsoluteURL; function requireIsAbsoluteURL () { if (hasRequiredIsAbsoluteURL) return isAbsoluteURL; hasRequiredIsAbsoluteURL = 1; /** * Determines whether the specified URL is absolute * * @param {string} url The URL to test * @returns {boolean} True if the specified URL is absolute, otherwise false */ isAbsoluteURL = function isAbsoluteURL(url) { // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed // by any combination of letters, digits, plus, period, or hyphen. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); }; return isAbsoluteURL; } var combineURLs; var hasRequiredCombineURLs; function requireCombineURLs () { if (hasRequiredCombineURLs) return combineURLs; hasRequiredCombineURLs = 1; /** * Creates a new URL by combining the specified URLs * * @param {string} baseURL The base URL * @param {string} relativeURL The relative URL * @returns {string} The combined URL */ combineURLs = function combineURLs(baseURL, relativeURL) { return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; }; return combineURLs; } var buildFullPath; var hasRequiredBuildFullPath; function requireBuildFullPath () { if (hasRequiredBuildFullPath) return buildFullPath; hasRequiredBuildFullPath = 1; var isAbsoluteURL = requireIsAbsoluteURL(); var combineURLs = requireCombineURLs(); /** * Creates a new URL by combining the baseURL with the requestedURL, * only when the requestedURL is not already an absolute URL. * If the requestURL is absolute, this function returns the requestedURL untouched. * * @param {string} baseURL The base URL * @param {string} requestedURL Absolute or relative URL to combine * @returns {string} The combined full path */ buildFullPath = function buildFullPath(baseURL, requestedURL) { if (baseURL && !isAbsoluteURL(requestedURL)) { return combineURLs(baseURL, requestedURL); } return requestedURL; }; return buildFullPath; } var parseHeaders; var hasRequiredParseHeaders; function requireParseHeaders () { if (hasRequiredParseHeaders) return parseHeaders; hasRequiredParseHeaders = 1; var utils = utils$8; // Headers whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers var ignoreDuplicateOf = [ 'age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent' ]; /** * Parse headers into an object * * ``` * Date: Wed, 27 Aug 2014 08:58:49 GMT * Content-Type: application/json * Connection: keep-alive * Transfer-Encoding: chunked * ``` * * @param {String} headers Headers needing to be parsed * @returns {Object} Headers parsed into an object */ parseHeaders = function parseHeaders(headers) { var parsed = {}; var key; var val; var i; if (!headers) { return parsed; } utils.forEach(headers.split('\n'), function parser(line) { i = line.indexOf(':'); key = utils.trim(line.substr(0, i)).toLowerCase(); val = utils.trim(line.substr(i + 1)); if (key) { if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { return; } if (key === 'set-cookie') { parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); } else { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } } }); return parsed; }; return parseHeaders; } var isURLSameOrigin; var hasRequiredIsURLSameOrigin; function requireIsURLSameOrigin () { if (hasRequiredIsURLSameOrigin) return isURLSameOrigin; hasRequiredIsURLSameOrigin = 1; var utils = utils$8; isURLSameOrigin = ( utils.isStandardBrowserEnv() ? // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. (function standardBrowserEnv() { var msie = /(msie|trident)/i.test(navigator.userAgent); var urlParsingNode = document.createElement('a'); var originURL; /** * Parse a URL to discover it's components * * @param {String} url The URL to be parsed * @returns {Object} */ function resolveURL(url) { var href = url; if (msie) { // IE needs attribute set twice to normalize properties urlParsingNode.setAttribute('href', href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } originURL = resolveURL(window.location.href); /** * Determine if a URL shares the same origin as the current location * * @param {String} requestURL The URL to test * @returns {boolean} True if URL shares the same origin, otherwise false */ return function isURLSameOrigin(requestURL) { var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; return (parsed.protocol === originURL.protocol && parsed.host === originURL.host); }; })() : // Non standard browser envs (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return function isURLSameOrigin() { return true; }; })() ); return isURLSameOrigin; } var Cancel_1; var hasRequiredCancel; function requireCancel () { if (hasRequiredCancel) return Cancel_1; hasRequiredCancel = 1; /** * A `Cancel` is an object that is thrown when an operation is canceled. * * @class * @param {string=} message The message. */ function Cancel(message) { this.message = message; } Cancel.prototype.toString = function toString() { return 'Cancel' + (this.message ? ': ' + this.message : ''); }; Cancel.prototype.__CANCEL__ = true; Cancel_1 = Cancel; return Cancel_1; } var xhr; var hasRequiredXhr; function requireXhr () { if (hasRequiredXhr) return xhr; hasRequiredXhr = 1; var utils = utils$8; var settle = requireSettle(); var cookies = requireCookies(); var buildURL = buildURL$1; var buildFullPath = requireBuildFullPath(); var parseHeaders = requireParseHeaders(); var isURLSameOrigin = requireIsURLSameOrigin(); var createError = requireCreateError(); var defaults = requireDefaults(); var Cancel = requireCancel(); xhr = function xhrAdapter(config) { return new Promise(function dispatchXhrRequest(resolve, reject) { var requestData = config.data; var requestHeaders = config.headers; var responseType = config.responseType; var onCanceled; function done() { if (config.cancelToken) { config.cancelToken.unsubscribe(onCanceled); } if (config.signal) { config.signal.removeEventListener('abort', onCanceled); } } if (utils.isFormData(requestData)) { delete requestHeaders['Content-Type']; // Let the browser set it } var request = new XMLHttpRequest(); // HTTP basic authentication if (config.auth) { var username = config.auth.username || ''; var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); } var fullPath = buildFullPath(config.baseURL, config.url); request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); // Set the request timeout in MS request.timeout = config.timeout; function onloadend() { if (!request) { return; } // Prepare the response var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; var responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response; var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(function _resolve(value) { resolve(value); done(); }, function _reject(err) { reject(err); done(); }, response); // Clean up request request = null; } if ('onloadend' in request) { // Use onloadend if available request.onloadend = onloadend; } else { // Listen for ready state to emulate onloadend request.onreadystatechange = function handleLoad() { if (!request || request.readyState !== 4) { return; } // The request errored out and we didn't get a response, this will be // handled by onerror instead // With one exception: request that using file: protocol, most browsers // will return status as 0 even though it's a successful request if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { return; } // readystate handler is calling before onerror or ontimeout handlers, // so we should call onloadend on the next 'tick' setTimeout(onloadend); }; } // Handle browser request cancellation (as opposed to a manual cancellation) request.onabort = function handleAbort() { if (!request) { return; } reject(createError('Request aborted', config, 'ECONNABORTED', request)); // Clean up request request = null; }; // Handle low level network errors request.onerror = function handleError() { // Real errors are hidden from us by the browser // onerror should only fire if it's a network error reject(createError('Network Error', config, null, request)); // Clean up request request = null; }; // Handle timeout request.ontimeout = function handleTimeout() { var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; var transitional = config.transitional || defaults.transitional; if (config.timeoutErrorMessage) { timeoutErrorMessage = config.timeoutErrorMessage; } reject(createError( timeoutErrorMessage, config, transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED', request)); // Clean up request request = null; }; // Add xsrf header // This is only done if running in a standard browser environment. // Specifically not if we're in a web worker, or react-native. if (utils.isStandardBrowserEnv()) { // Add xsrf header var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? cookies.read(config.xsrfCookieName) : undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName] = xsrfValue; } } // Add headers to the request if ('setRequestHeader' in request) { utils.forEach(requestHeaders, function setRequestHeader(val, key) { if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { // Remove Content-Type if data is undefined delete requestHeaders[key]; } else { // Otherwise add header to the request request.setRequestHeader(key, val); } }); } // Add withCredentials to request if needed if (!utils.isUndefined(config.withCredentials)) { request.withCredentials = !!config.withCredentials; } // Add responseType to request if needed if (responseType && responseType !== 'json') { request.responseType = config.responseType; } // Handle progress if needed if (typeof config.onDownloadProgress === 'function') { request.addEventListener('progress', config.onDownloadProgress); } // Not all browsers support upload events if (typeof config.onUploadProgress === 'function' && request.upload) { request.upload.addEventListener('progress', config.onUploadProgress); } if (config.cancelToken || config.signal) { // Handle cancellation // eslint-disable-next-line func-names onCanceled = function(cancel) { if (!request) { return; } reject(!cancel || (cancel && cancel.type) ? new Cancel('canceled') : cancel); request.abort(); request = null; }; config.cancelToken && config.cancelToken.subscribe(onCanceled); if (config.signal) { config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); } } if (!requestData) { requestData = null; } // Send the request request.send(requestData); }); }; return xhr; } var http = null; var http$1 = /*#__PURE__*/Object.freeze({ __proto__: null, default: http }); var require$$4$1 = /*@__PURE__*/getAugmentedNamespace(http$1); var defaults_1; var hasRequiredDefaults; function requireDefaults () { if (hasRequiredDefaults) return defaults_1; hasRequiredDefaults = 1; var utils = utils$8; var normalizeHeaderName$1 = normalizeHeaderName; var enhanceError$1 = enhanceError; var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' }; function setContentTypeIfUnset(headers, value) { if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = value; } } function getDefaultAdapter() { var adapter; if (typeof XMLHttpRequest !== 'undefined') { // For browsers use XHR adapter adapter = requireXhr(); } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { // For node use HTTP adapter adapter = require$$4$1; } return adapter; } function stringifySafely(rawValue, parser, encoder) { if (utils.isString(rawValue)) { try { (parser || JSON.parse)(rawValue); return utils.trim(rawValue); } catch (e) { if (e.name !== 'SyntaxError') { throw e; } } } return (0, JSON.stringify)(rawValue); } var defaults = { transitional: { silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false }, adapter: getDefaultAdapter(), transformRequest: [function transformRequest(data, headers) { normalizeHeaderName$1(headers, 'Accept'); normalizeHeaderName$1(headers, 'Content-Type'); if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isBuffer(data) || utils.isStream(data) || utils.isFile(data) || utils.isBlob(data) ) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isURLSearchParams(data)) { setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString(); } if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) { setContentTypeIfUnset(headers, 'application/json'); return stringifySafely(data); } return data; }], transformResponse: [function transformResponse(data) { var transitional = this.transitional || defaults.transitional; var silentJSONParsing = transitional && transitional.silentJSONParsing; var forcedJSONParsing = transitional && transitional.forcedJSONParsing; var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) { try { return JSON.parse(data); } catch (e) { if (strictJSONParsing) { if (e.name === 'SyntaxError') { throw enhanceError$1(e, this, 'E_JSON_PARSE'); } throw e; } } } return data; }], /** * A timeout in milliseconds to abort a request. If set to 0 (default) a * timeout is not created. */ timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, maxBodyLength: -1, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; }, headers: { common: { 'Accept': 'application/json, text/plain, */*' } } }; utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { defaults.headers[method] = {}; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); }); defaults_1 = defaults; return defaults_1; } var utils$4 = utils$8; var defaults$2 = requireDefaults(); /** * Transform the data for a request or a response * * @param {Object|String} data The data to be transformed * @param {Array} headers The headers for the request or response * @param {Array|Function} fns A single function or Array of functions * @returns {*} The resulting transformed data */ var transformData$1 = function transformData(data, headers, fns) { var context = this || defaults$2; /*eslint no-param-reassign:0*/ utils$4.forEach(fns, function transform(fn) { data = fn.call(context, data, headers); }); return data; }; var isCancel$1; var hasRequiredIsCancel; function requireIsCancel () { if (hasRequiredIsCancel) return isCancel$1; hasRequiredIsCancel = 1; isCancel$1 = function isCancel(value) { return !!(value && value.__CANCEL__); }; return isCancel$1; } var utils$3 = utils$8; var transformData = transformData$1; var isCancel = requireIsCancel(); var defaults$1 = requireDefaults(); var Cancel = requireCancel(); /** * Throws a `Cancel` if cancellation has been requested. */ function throwIfCancellationRequested(config) { if (config.cancelToken) { config.cancelToken.throwIfRequested(); } if (config.signal && config.signal.aborted) { throw new Cancel('canceled'); } } /** * Dispatch a request to the server using the configured adapter. * * @param {object} config The config that is to be used for the request * @returns {Promise} The Promise to be fulfilled */ var dispatchRequest$1 = function dispatchRequest(config) { throwIfCancellationRequested(config); // Ensure headers exist config.headers = config.headers || {}; // Transform request data config.data = transformData.call( config, config.data, config.headers, config.transformRequest ); // Flatten headers config.headers = utils$3.merge( config.headers.common || {}, config.headers[config.method] || {}, config.headers ); utils$3.forEach( ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], function cleanHeaderConfig(method) { delete config.headers[method]; } ); var adapter = config.adapter || defaults$1.adapter; return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); // Transform response data response.data = transformData.call( config, response.data, response.headers, config.transformResponse ); return response; }, function onAdapterRejection(reason) { if (!isCancel(reason)) { throwIfCancellationRequested(config); // Transform response data if (reason && reason.response) { reason.response.data = transformData.call( config, reason.response.data, reason.response.headers, config.transformResponse ); } } return Promise.reject(reason); }); }; var utils$2 = utils$8; /** * Config-specific merge-function which creates a new config-object * by merging two configuration objects together. * * @param {Object} config1 * @param {Object} config2 * @returns {Object} New object resulting from merging config2 to config1 */ var mergeConfig$2 = function mergeConfig(config1, config2) { // eslint-disable-next-line no-param-reassign config2 = config2 || {}; var config = {}; function getMergedValue(target, source) { if (utils$2.isPlainObject(target) && utils$2.isPlainObject(source)) { return utils$2.merge(target, source); } else if (utils$2.isPlainObject(source)) { return utils$2.merge({}, source); } else if (utils$2.isArray(source)) { return source.slice(); } return source; } // eslint-disable-next-line consistent-return function mergeDeepProperties(prop) { if (!utils$2.isUndefined(config2[prop])) { return getMergedValue(config1[prop], config2[prop]); } else if (!utils$2.isUndefined(config1[prop])) { return getMergedValue(undefined, config1[prop]); } } // eslint-disable-next-line consistent-return function valueFromConfig2(prop) { if (!utils$2.isUndefined(config2[prop])) { return getMergedValue(undefined, config2[prop]); } } // eslint-disable-next-line consistent-return function defaultToConfig2(prop) { if (!utils$2.isUndefined(config2[prop])) { return getMergedValue(undefined, config2[prop]); } else if (!utils$2.isUndefined(config1[prop])) { return getMergedValue(undefined, config1[prop]); } } // eslint-disable-next-line consistent-return function mergeDirectKeys(prop) { if (prop in config2) { return getMergedValue(config1[prop], config2[prop]); } else if (prop in config1) { return getMergedValue(undefined, config1[prop]); } } var mergeMap = { 'url': valueFromConfig2, 'method': valueFromConfig2, 'data': valueFromConfig2, 'baseURL': defaultToConfig2, 'transformRequest': defaultToConfig2, 'transformResponse': defaultToConfig2, 'paramsSerializer': defaultToConfig2, 'timeout': defaultToConfig2, 'timeoutMessage': defaultToConfig2, 'withCredentials': defaultToConfig2, 'adapter': defaultToConfig2, 'responseType': defaultToConfig2, 'xsrfCookieName': defaultToConfig2, 'xsrfHeaderName': defaultToConfig2, 'onUploadProgress': defaultToConfig2, 'onDownloadProgress': defaultToConfig2, 'decompress': defaultToConfig2, 'maxContentLength': defaultToConfig2, 'maxBodyLength': defaultToConfig2, 'transport': defaultToConfig2, 'httpAgent': defaultToConfig2, 'httpsAgent': defaultToConfig2, 'cancelToken': defaultToConfig2, 'socketPath': defaultToConfig2, 'responseEncoding': defaultToConfig2, 'validateStatus': mergeDirectKeys }; utils$2.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { var merge = mergeMap[prop] || mergeDeepProperties; var configValue = merge(prop); (utils$2.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); }); return config; }; var data$2; var hasRequiredData; function requireData () { if (hasRequiredData) return data$2; hasRequiredData = 1; data$2 = { "version": "0.24.0" }; return data$2; } var VERSION$1 = requireData().version; var validators$1 = {}; // eslint-disable-next-line func-names ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) { validators$1[type] = function validator(thing) { return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; }; }); var deprecatedWarnings = {}; /** * Transitional option validator * @param {function|boolean?} validator - set to false if the transitional option has been removed * @param {string?} version - deprecated version / removed since version * @param {string?} message - some message with additional info * @returns {function} */ validators$1.transitional = function transitional(validator, version, message) { function formatMessage(opt, desc) { return '[Axios v' + VERSION$1 + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); } // eslint-disable-next-line func-names return function(value, opt, opts) { if (validator === false) { throw new Error(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : ''))); } if (version && !deprecatedWarnings[opt]) { deprecatedWarnings[opt] = true; // eslint-disable-next-line no-console console.warn( formatMessage( opt, ' has been deprecated since v' + version + ' and will be removed in the near future' ) ); } return validator ? validator(value, opt, opts) : true; }; }; /** * Assert object's properties type * @param {object} options * @param {object} schema * @param {boolean?} allowUnknown */ function assertOptions(options, schema, allowUnknown) { if (typeof options !== 'object') { throw new TypeError('options must be an object'); } var keys = Object.keys(options); var i = keys.length; while (i-- > 0) { var opt = keys[i]; var validator = schema[opt]; if (validator) { var value = options[opt]; var result = value === undefined || validator(value, opt, options); if (result !== true) { throw new TypeError('option ' + opt + ' must be ' + result); } continue; } if (allowUnknown !== true) { throw Error('Unknown option ' + opt); } } } var validator$1 = { assertOptions: assertOptions, validators: validators$1 }; var utils$1 = utils$8; var buildURL = buildURL$1; var InterceptorManager = InterceptorManager_1; var dispatchRequest = dispatchRequest$1; var mergeConfig$1 = mergeConfig$2; var validator = validator$1; var validators = validator.validators; /** * Create a new instance of Axios * * @param {Object} instanceConfig The default config for the instance */ function Axios$1(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() }; } /** * Dispatch a request * * @param {Object} config The config specific for this request (merged with this.defaults) */ Axios$1.prototype.request = function request(config) { /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API if (typeof config === 'string') { config = arguments[1] || {}; config.url = arguments[0]; } else { config = config || {}; } config = mergeConfig$1(this.defaults, config); // Set config.method if (config.method) { config.method = config.method.toLowerCase(); } else if (this.defaults.method) { config.method = this.defaults.method.toLowerCase(); } else { config.method = 'get'; } var transitional = config.transitional; if (transitional !== undefined) { validator.assertOptions(transitional, { silentJSONParsing: validators.transitional(validators.boolean), forcedJSONParsing: validators.transitional(validators.boolean), clarifyTimeoutError: validators.transitional(validators.boolean) }, false); } // filter out skipped interceptors var requestInterceptorChain = []; var synchronousRequestInterceptors = true; this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { return; } synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); }); var responseInterceptorChain = []; this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); }); var promise; if (!synchronousRequestInterceptors) { var chain = [dispatchRequest, undefined]; Array.prototype.unshift.apply(chain, requestInterceptorChain); chain = chain.concat(responseInterceptorChain); promise = Promise.resolve(config); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } return promise; } var newConfig = config; while (requestInterceptorChain.length) { var onFulfilled = requestInterceptorChain.shift(); var onRejected = requestInterceptorChain.shift(); try { newConfig = onFulfilled(newConfig); } catch (error) { onRejected(error); break; } } try { promise = dispatchRequest(newConfig); } catch (error) { return Promise.reject(error); } while (responseInterceptorChain.length) { promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); } return promise; }; Axios$1.prototype.getUri = function getUri(config) { config = mergeConfig$1(this.defaults, config); return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); }; // Provide aliases for supported request methods utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ Axios$1.prototype[method] = function(url, config) { return this.request(mergeConfig$1(config || {}, { method: method, url: url, data: (config || {}).data })); }; }); utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { /*eslint func-names:0*/ Axios$1.prototype[method] = function(url, data, config) { return this.request(mergeConfig$1(config || {}, { method: method, url: url, data: data })); }; }); var Axios_1 = Axios$1; var CancelToken_1; var hasRequiredCancelToken; function requireCancelToken () { if (hasRequiredCancelToken) return CancelToken_1; hasRequiredCancelToken = 1; var Cancel = requireCancel(); /** * A `CancelToken` is an object that can be used to request cancellation of an operation. * * @class * @param {Function} executor The executor function. */ function CancelToken(executor) { if (typeof executor !== 'function') { throw new TypeError('executor must be a function.'); } var resolvePromise; this.promise = new Promise(function promiseExecutor(resolve) { resolvePromise = resolve; }); var token = this; // eslint-disable-next-line func-names this.promise.then(function(cancel) { if (!token._listeners) return; var i; var l = token._listeners.length; for (i = 0; i < l; i++) { token._listeners[i](cancel); } token._listeners = null; }); // eslint-disable-next-line func-names this.promise.then = function(onfulfilled) { var _resolve; // eslint-disable-next-line func-names var promise = new Promise(function(resolve) { token.subscribe(resolve); _resolve = resolve; }).then(onfulfilled); promise.cancel = function reject() { token.unsubscribe(_resolve); }; return promise; }; executor(function cancel(message) { if (token.reason) { // Cancellation has already been requested return; } token.reason = new Cancel(message); resolvePromise(token.reason); }); } /** * Throws a `Cancel` if cancellation has been requested. */ CancelToken.prototype.throwIfRequested = function throwIfRequested() { if (this.reason) { throw this.reason; } }; /** * Subscribe to the cancel signal */ CancelToken.prototype.subscribe = function subscribe(listener) { if (this.reason) { listener(this.reason); return; } if (this._listeners) { this._listeners.push(listener); } else { this._listeners = [listener]; } }; /** * Unsubscribe from the cancel signal */ CancelToken.prototype.unsubscribe = function unsubscribe(listener) { if (!this._listeners) { return; } var index = this._listeners.indexOf(listener); if (index !== -1) { this._listeners.splice(index, 1); } }; /** * Returns an object that contains a new `CancelToken` and a function that, when called, * cancels the `CancelToken`. */ CancelToken.source = function source() { var cancel; var token = new CancelToken(function executor(c) { cancel = c; }); return { token: token, cancel: cancel }; }; CancelToken_1 = CancelToken; return CancelToken_1; } var spread; var hasRequiredSpread; function requireSpread () { if (hasRequiredSpread) return spread; hasRequiredSpread = 1; /** * Syntactic sugar for invoking a function and expanding an array for arguments. * * Common use case would be to use `Function.prototype.apply`. * * ```js * function f(x, y, z) {} * var args = [1, 2, 3]; * f.apply(null, args); * ``` * * With `spread` this example can be re-written. * * ```js * spread(function(x, y, z) {})([1, 2, 3]); * ``` * * @param {Function} callback * @returns {Function} */ spread = function spread(callback) { return function wrap(arr) { return callback.apply(null, arr); }; }; return spread; } var isAxiosError; var hasRequiredIsAxiosError; function requireIsAxiosError () { if (hasRequiredIsAxiosError) return isAxiosError; hasRequiredIsAxiosError = 1; /** * Determines whether the payload is an error thrown by Axios * * @param {*} payload The value to test * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false */ isAxiosError = function isAxiosError(payload) { return (typeof payload === 'object') && (payload.isAxiosError === true); }; return isAxiosError; } var utils = utils$8; var bind$2 = bind$4; var Axios = Axios_1; var mergeConfig = mergeConfig$2; var defaults = requireDefaults(); /** * Create an instance of Axios * * @param {Object} defaultConfig The default config for the instance * @return {Axios} A new instance of Axios */ function createInstance(defaultConfig) { var context = new Axios(defaultConfig); var instance = bind$2(Axios.prototype.request, context); // Copy axios.prototype to instance utils.extend(instance, Axios.prototype, context); // Copy context to instance utils.extend(instance, context); // Factory for creating new instances instance.create = function create(instanceConfig) { return createInstance(mergeConfig(defaultConfig, instanceConfig)); }; return instance; } // Create the default instance to be exported var axios$2 = createInstance(defaults); // Expose Axios class to allow class inheritance axios$2.Axios = Axios; // Expose Cancel & CancelToken axios$2.Cancel = requireCancel(); axios$2.CancelToken = requireCancelToken(); axios$2.isCancel = requireIsCancel(); axios$2.VERSION = requireData().version; // Expose all/spread axios$2.all = function all(promises) { return Promise.all(promises); }; axios$2.spread = requireSpread(); // Expose isAxiosError axios$2.isAxiosError = requireIsAxiosError(); axios$3.exports = axios$2; // Allow use of default import syntax in TypeScript axios$3.exports.default = axios$2; var axiosExports = axios$3.exports; var axios = axiosExports; var axios$1 = /*@__PURE__*/getDefaultExportFromCjs(axios); var react$1 = {exports: {}}; var react_production_min = {}; var l$g=Symbol.for("react.element"),n$g=Symbol.for("react.portal"),p$h=Symbol.for("react.fragment"),q$a=Symbol.for("react.strict_mode"),r$c=Symbol.for("react.profiler"),t$f=Symbol.for("react.provider"),u$h=Symbol.for("react.context"),v$a=Symbol.for("react.forward_ref"),w$b=Symbol.for("react.suspense"),x$7=Symbol.for("react.memo"),y$b=Symbol.for("react.lazy"),z$8=Symbol.iterator;function A$9(a){if(null===a||"object"!==typeof a)return null;a=z$8&&a[z$8]||a["@@iterator"];return "function"===typeof a?a:null} var B$6={isMounted:function(){return !1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C$5=Object.assign,D$a={};function E$7(a,b,e){this.props=a;this.context=b;this.refs=D$a;this.updater=e||B$6;}E$7.prototype.isReactComponent={}; E$7.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,b,"setState");};E$7.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate");};function F$b(){}F$b.prototype=E$7.prototype;function G$6(a,b,e){this.props=a;this.context=b;this.refs=D$a;this.updater=e||B$6;}var H$a=G$6.prototype=new F$b; H$a.constructor=G$6;C$5(H$a,E$7.prototype);H$a.isPureReactComponent=!0;var I$a=Array.isArray,J$5=Object.prototype.hasOwnProperty,K$3={current:null},L$6={key:!0,ref:!0,__self:!0,__source:!0}; function M$c(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=""+b.key),b)J$5.call(b,d)&&!L$6.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1= 0) continue; target[key] = source[key]; } return target; } function _extends$4() { _extends$4 = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$4.apply(this, arguments); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf$1(o, p) { _setPrototypeOf$1 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf$1(o, p); } function _inheritsLoose$1(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf$1(subClass, superClass); } var reactIs$1 = {exports: {}}; var reactIs_production_min = {}; var b$4=60103,c$d=60106,d$d=60107,e$9=60108,f$c=60114,g$5=60109,h$d=60110,k$7=60112,l$f=60113,m$9=60120,n$f=60115,p$g=60116,q$9=60121,r$b=60122,u$g=60117,v$9=60129,w$a=60131; if("function"===typeof Symbol&&Symbol.for){var x$6=Symbol.for;b$4=x$6("react.element");c$d=x$6("react.portal");d$d=x$6("react.fragment");e$9=x$6("react.strict_mode");f$c=x$6("react.profiler");g$5=x$6("react.provider");h$d=x$6("react.context");k$7=x$6("react.forward_ref");l$f=x$6("react.suspense");m$9=x$6("react.suspense_list");n$f=x$6("react.memo");p$g=x$6("react.lazy");q$9=x$6("react.block");r$b=x$6("react.server.block");u$g=x$6("react.fundamental");v$9=x$6("react.debug_trace_mode");w$a=x$6("react.legacy_hidden");} function y$a(a){if("object"===typeof a&&null!==a){var t=a.$$typeof;switch(t){case b$4:switch(a=a.type,a){case d$d:case f$c:case e$9:case l$f:case m$9:return a;default:switch(a=a&&a.$$typeof,a){case h$d:case k$7:case p$g:case n$f:case g$5:return a;default:return t}}case c$d:return t}}}var z$7=g$5,A$8=b$4,B$5=k$7,C$4=d$d,D$9=p$g,E$6=n$f,F$a=c$d,G$5=f$c,H$9=e$9,I$9=l$f;reactIs_production_min.ContextConsumer=h$d;reactIs_production_min.ContextProvider=z$7;reactIs_production_min.Element=A$8;reactIs_production_min.ForwardRef=B$5;reactIs_production_min.Fragment=C$4;reactIs_production_min.Lazy=D$9;reactIs_production_min.Memo=E$6;reactIs_production_min.Portal=F$a;reactIs_production_min.Profiler=G$5;reactIs_production_min.StrictMode=H$9; reactIs_production_min.Suspense=I$9;reactIs_production_min.isAsyncMode=function(){return !1};reactIs_production_min.isConcurrentMode=function(){return !1};reactIs_production_min.isContextConsumer=function(a){return y$a(a)===h$d};reactIs_production_min.isContextProvider=function(a){return y$a(a)===g$5};reactIs_production_min.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===b$4};reactIs_production_min.isForwardRef=function(a){return y$a(a)===k$7};reactIs_production_min.isFragment=function(a){return y$a(a)===d$d};reactIs_production_min.isLazy=function(a){return y$a(a)===p$g};reactIs_production_min.isMemo=function(a){return y$a(a)===n$f}; reactIs_production_min.isPortal=function(a){return y$a(a)===c$d};reactIs_production_min.isProfiler=function(a){return y$a(a)===f$c};reactIs_production_min.isStrictMode=function(a){return y$a(a)===e$9};reactIs_production_min.isSuspense=function(a){return y$a(a)===l$f};reactIs_production_min.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===d$d||a===f$c||a===v$9||a===e$9||a===l$f||a===m$9||a===w$a||"object"===typeof a&&null!==a&&(a.$$typeof===p$g||a.$$typeof===n$f||a.$$typeof===g$5||a.$$typeof===h$d||a.$$typeof===k$7||a.$$typeof===u$g||a.$$typeof===q$9||a[0]===r$b)?!0:!1}; reactIs_production_min.typeOf=y$a; { reactIs$1.exports = reactIs_production_min; } var reactIsExports = reactIs$1.exports; var reactIs = reactIsExports; /** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ var REACT_STATICS = { childContextTypes: true, contextType: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, getDerivedStateFromError: true, getDerivedStateFromProps: true, mixins: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var FORWARD_REF_STATICS = { '$$typeof': true, render: true, defaultProps: true, displayName: true, propTypes: true }; var MEMO_STATICS = { '$$typeof': true, compare: true, defaultProps: true, displayName: true, propTypes: true, type: true }; var TYPE_STATICS = {}; TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS; TYPE_STATICS[reactIs.Memo] = MEMO_STATICS; function getStatics(component) { // React v16.11 and below if (reactIs.isMemo(component)) { return MEMO_STATICS; } // React v16.12 and above return TYPE_STATICS[component['$$typeof']] || REACT_STATICS; } var defineProperty$1 = Object.defineProperty; var getOwnPropertyNames = Object.getOwnPropertyNames; var getOwnPropertySymbols = Object.getOwnPropertySymbols; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var getPrototypeOf$1 = Object.getPrototypeOf; var objectPrototype = Object.prototype; function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components if (objectPrototype) { var inheritedComponent = getPrototypeOf$1(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } } var keys = getOwnPropertyNames(sourceComponent); if (getOwnPropertySymbols) { keys = keys.concat(getOwnPropertySymbols(sourceComponent)); } var targetStatics = getStatics(targetComponent); var sourceStatics = getStatics(sourceComponent); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) { var descriptor = getOwnPropertyDescriptor(sourceComponent, key); try { // Avoid failures from read-only properties defineProperty$1(targetComponent, key, descriptor); } catch (e) {} } } } return targetComponent; } var hoistNonReactStatics_cjs = hoistNonReactStatics; var hoistNonReactStatics$1 = /*@__PURE__*/getDefaultExportFromCjs(hoistNonReactStatics_cjs); /* eslint-disable import/prefer-default-export */ function invariant$5(condition, message) { if (condition) return; var error = new Error("loadable: " + message); error.framesToPop = 1; error.name = 'Invariant Violation'; throw error; } var Context$1 = /*#__PURE__*/ React$2.createContext(); var LOADABLE_SHARED = { initialChunks: {} }; var STATUS_PENDING = 'PENDING'; var STATUS_RESOLVED = 'RESOLVED'; var STATUS_REJECTED = 'REJECTED'; function resolveConstructor(ctor) { if (typeof ctor === 'function') { return { requireAsync: ctor, resolve: function resolve() { return undefined; }, chunkName: function chunkName() { return undefined; } }; } return ctor; } var withChunkExtractor = function withChunkExtractor(Component) { var LoadableWithChunkExtractor = function LoadableWithChunkExtractor(props) { return React$2.createElement(Context$1.Consumer, null, function (extractor) { return React$2.createElement(Component, Object.assign({ __chunkExtractor: extractor }, props)); }); }; if (Component.displayName) { LoadableWithChunkExtractor.displayName = Component.displayName + "WithChunkExtractor"; } return LoadableWithChunkExtractor; }; var identity$2 = function identity(v) { return v; }; function createLoadable(_ref) { var _ref$defaultResolveCo = _ref.defaultResolveComponent, defaultResolveComponent = _ref$defaultResolveCo === void 0 ? identity$2 : _ref$defaultResolveCo, _render = _ref.render, onLoad = _ref.onLoad; function loadable(loadableConstructor, options) { if (options === void 0) { options = {}; } var ctor = resolveConstructor(loadableConstructor); var cache = {}; /** * Cachekey represents the component to be loaded * if key changes - component has to be reloaded * @param props * @returns {null|Component} */ function _getCacheKey(props) { if (options.cacheKey) { return options.cacheKey(props); } if (ctor.resolve) { return ctor.resolve(props); } return 'static'; } /** * Resolves loaded `module` to a specific `Component * @param module * @param props * @param Loadable * @returns Component */ function resolve(module, props, Loadable) { var Component = options.resolveComponent ? options.resolveComponent(module, props) : defaultResolveComponent(module); // FIXME: suppressed due to https://github.com/gregberge/loadable-components/issues/990 // if (options.resolveComponent && !ReactIs.isValidElementType(Component)) { // throw new Error( // `resolveComponent returned something that is not a React component!`, // ) // } hoistNonReactStatics$1(Loadable, Component, { preload: true }); return Component; } var cachedLoad = function cachedLoad(props) { var cacheKey = _getCacheKey(props); var promise = cache[cacheKey]; if (!promise || promise.status === STATUS_REJECTED) { promise = ctor.requireAsync(props); promise.status = STATUS_PENDING; cache[cacheKey] = promise; promise.then(function () { promise.status = STATUS_RESOLVED; }, function (error) { console.error('loadable-components: failed to asynchronously load component', { fileName: ctor.resolve(props), chunkName: ctor.chunkName(props), error: error ? error.message : error }); promise.status = STATUS_REJECTED; }); } return promise; }; var InnerLoadable = /*#__PURE__*/ function (_React$Component) { _inheritsLoose$1(InnerLoadable, _React$Component); InnerLoadable.getDerivedStateFromProps = function getDerivedStateFromProps(props, state) { var cacheKey = _getCacheKey(props); return _extends$4({}, state, { cacheKey: cacheKey, // change of a key triggers loading state automatically loading: state.loading || state.cacheKey !== cacheKey }); }; function InnerLoadable(props) { var _this; _this = _React$Component.call(this, props) || this; _this.state = { result: null, error: null, loading: true, cacheKey: _getCacheKey(props) }; invariant$5(!props.__chunkExtractor || ctor.requireSync, 'SSR requires `@loadable/babel-plugin`, please install it'); // Server-side if (props.__chunkExtractor) { // This module has been marked with no SSR if (options.ssr === false) { return _assertThisInitialized(_this); } // We run load function, we assume that it won't fail and that it // triggers a synchronous loading of the module ctor.requireAsync(props)["catch"](function () { return null; }); // So we can require now the module synchronously _this.loadSync(); props.__chunkExtractor.addChunk(ctor.chunkName(props)); return _assertThisInitialized(_this); } // Client-side with `isReady` method present (SSR probably) // If module is already loaded, we use a synchronous loading // Only perform this synchronous loading if the component has not // been marked with no SSR, else we risk hydration mismatches if (options.ssr !== false && ( // is ready - was loaded in this session ctor.isReady && ctor.isReady(props) || // is ready - was loaded during SSR process ctor.chunkName && LOADABLE_SHARED.initialChunks[ctor.chunkName(props)])) { _this.loadSync(); } return _this; } var _proto = InnerLoadable.prototype; _proto.componentDidMount = function componentDidMount() { this.mounted = true; // retrieve loading promise from a global cache var cachedPromise = this.getCache(); // if promise exists, but rejected - clear cache if (cachedPromise && cachedPromise.status === STATUS_REJECTED) { this.setCache(); } // component might be resolved synchronously in the constructor if (this.state.loading) { this.loadAsync(); } }; _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) { // Component has to be reloaded on cacheKey change if (prevState.cacheKey !== this.state.cacheKey) { this.loadAsync(); } }; _proto.componentWillUnmount = function componentWillUnmount() { this.mounted = false; }; _proto.safeSetState = function safeSetState(nextState, callback) { if (this.mounted) { this.setState(nextState, callback); } } /** * returns a cache key for the current props * @returns {Component|string} */ ; _proto.getCacheKey = function getCacheKey() { return _getCacheKey(this.props); } /** * access the persistent cache */ ; _proto.getCache = function getCache() { return cache[this.getCacheKey()]; } /** * sets the cache value. If called without value sets it as undefined */ ; _proto.setCache = function setCache(value) { if (value === void 0) { value = undefined; } cache[this.getCacheKey()] = value; }; _proto.triggerOnLoad = function triggerOnLoad() { var _this2 = this; if (onLoad) { setTimeout(function () { onLoad(_this2.state.result, _this2.props); }); } } /** * Synchronously loads component * target module is expected to already exists in the module cache * or be capable to resolve synchronously (webpack target=node) */ ; _proto.loadSync = function loadSync() { // load sync is expecting component to be in the "loading" state already // sounds weird, but loading=true is the initial state of InnerLoadable if (!this.state.loading) return; try { var loadedModule = ctor.requireSync(this.props); var result = resolve(loadedModule, this.props, Loadable); this.state.result = result; this.state.loading = false; } catch (error) { console.error('loadable-components: failed to synchronously load component, which expected to be available', { fileName: ctor.resolve(this.props), chunkName: ctor.chunkName(this.props), error: error ? error.message : error }); this.state.error = error; } } /** * Asynchronously loads a component. */ ; _proto.loadAsync = function loadAsync() { var _this3 = this; var promise = this.resolveAsync(); promise.then(function (loadedModule) { var result = resolve(loadedModule, _this3.props, Loadable); _this3.safeSetState({ result: result, loading: false }, function () { return _this3.triggerOnLoad(); }); })["catch"](function (error) { return _this3.safeSetState({ error: error, loading: false }); }); return promise; } /** * Asynchronously resolves(not loads) a component. * Note - this function does not change the state */ ; _proto.resolveAsync = function resolveAsync() { var _this$props = this.props; _this$props.__chunkExtractor; _this$props.forwardedRef; var props = _objectWithoutPropertiesLoose$2(_this$props, ["__chunkExtractor", "forwardedRef"]); return cachedLoad(props); }; _proto.render = function render() { var _this$props2 = this.props, forwardedRef = _this$props2.forwardedRef, propFallback = _this$props2.fallback; _this$props2.__chunkExtractor; var props = _objectWithoutPropertiesLoose$2(_this$props2, ["forwardedRef", "fallback", "__chunkExtractor"]); var _this$state = this.state, error = _this$state.error, loading = _this$state.loading, result = _this$state.result; if (options.suspense) { var cachedPromise = this.getCache() || this.loadAsync(); if (cachedPromise.status === STATUS_PENDING) { throw this.loadAsync(); } } if (error) { throw error; } var fallback = propFallback || options.fallback || null; if (loading) { return fallback; } return _render({ fallback: fallback, result: result, options: options, props: _extends$4({}, props, { ref: forwardedRef }) }); }; return InnerLoadable; }(React$2.Component); var EnhancedInnerLoadable = withChunkExtractor(InnerLoadable); var Loadable = React$2.forwardRef(function (props, ref) { return React$2.createElement(EnhancedInnerLoadable, Object.assign({ forwardedRef: ref }, props)); }); Loadable.displayName = 'Loadable'; // In future, preload could use `` Loadable.preload = function (props) { Loadable.load(props); }; Loadable.load = function (props) { return cachedLoad(props); }; return Loadable; } function lazy(ctor, options) { return loadable(ctor, _extends$4({}, options, { suspense: true })); } return { loadable: loadable, lazy: lazy }; } function defaultResolveComponent(loadedModule) { // eslint-disable-next-line no-underscore-dangle return loadedModule.__esModule ? loadedModule["default"] : loadedModule["default"] || loadedModule; } /* eslint-disable no-use-before-define, react/no-multi-comp */ var _createLoadable = /*#__PURE__*/ createLoadable({ defaultResolveComponent: defaultResolveComponent, render: function render(_ref) { var Component = _ref.result, props = _ref.props; return React$2.createElement(Component, props); } }), loadable = _createLoadable.loadable, lazy = _createLoadable.lazy; /* eslint-disable no-use-before-define, react/no-multi-comp */ var _createLoadable$1 = /*#__PURE__*/ createLoadable({ onLoad: function onLoad(result, props) { if (result && props.forwardedRef) { if (typeof props.forwardedRef === 'function') { props.forwardedRef(result); } else { props.forwardedRef.current = result; } } }, render: function render(_ref) { var result = _ref.result, props = _ref.props; if (props.children) { return props.children(result); } return null; } }), loadable$1 = _createLoadable$1.loadable, lazy$1 = _createLoadable$1.lazy; /* eslint-disable no-underscore-dangle */ var loadable$2 = loadable; loadable$2.lib = loadable$1; var lazy$2 = lazy; lazy$2.lib = lazy$1; var ClientStateID; (function (ClientStateID) { const COHOST_LOADER_STATE = "__COHOST_LOADER_STATE__"; ClientStateID["COHOST_LOADER_STATE"] = COHOST_LOADER_STATE; const COHOST_LAYOUT = "__COHOST_LAYOUT__"; ClientStateID["COHOST_LAYOUT"] = COHOST_LAYOUT; const SITE_CONFIG = "site-config"; ClientStateID["SITE_CONFIG"] = SITE_CONFIG; const USER_INFO = "user-info"; ClientStateID["USER_INFO"] = USER_INFO; const INITIAL_I18N_STORE = "initialI18nStore"; ClientStateID["INITIAL_I18N_STORE"] = INITIAL_I18N_STORE; const INITIAL_LANGUAGE = "initialLanguage"; ClientStateID["INITIAL_LANGUAGE"] = INITIAL_LANGUAGE; const FLASHES = "flashes"; ClientStateID["FLASHES"] = FLASHES; const ROLLBAR_CONFIG = "rollbar-config"; ClientStateID["ROLLBAR_CONFIG"] = ROLLBAR_CONFIG; const UNLEASH_BOOTSTRAP = "unleash-bootstrap"; ClientStateID["UNLEASH_BOOTSTRAP"] = UNLEASH_BOOTSTRAP; const ENV_VARS = "env-vars"; ClientStateID["ENV_VARS"] = ENV_VARS; const TRPC_DEHYRDATED_STATE = "trpc-dehydrated-state"; ClientStateID["TRPC_DEHYRDATED_STATE"] = TRPC_DEHYRDATED_STATE; const INITIAL_MUTABLE_STORE = "initial-mutable-store"; ClientStateID["INITIAL_MUTABLE_STORE"] = INITIAL_MUTABLE_STORE; })(ClientStateID || (ClientStateID = {})); var ClientStateID$1 = ClientStateID; class EnvVars { store = {}; setEnv(newEnv) { this.store = { ...newEnv }; } getEnvVal(key) { if (typeof window === "undefined") { // node return process.env[key]; } else { return this.store[key]; } } get HOME_URL() { return new URL("../..", location.href).toString() } _doNothing() { let defaultVal = ""; // on the client, we already know what our URL is so we can make a Guess // in case this gets called early somehow. if ( typeof window !== "undefined" && typeof window.location !== "undefined" ) { defaultVal = window.location.origin; } return this.getEnvVal("HOME_URL") || defaultVal; } get VERSION() { return this.getEnvVal("VERSION") || ""; } } const env = new EnvVars(); var client = {}; var reactDom = {exports: {}}; var reactDom_production_min = {}; var scheduler = {exports: {}}; var scheduler_production_min = {}; /** * @license React * scheduler.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ (function (exports) { function f(a,b){var c=a.length;a.push(b);a:for(;0>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b} function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()};}else {var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q};}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null; "undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t);}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else {var b=h(t);null!==b&&K(H,b.startTime-a);}} function J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b);}else k(r);v=h(r);}if(null!==v)var w=!0;else {var m=h(t);null!==m&&K(H,m.startTime-b);w=!1;}return w}finally{v=null,y=c,z=!1;}}var N=!1,O=null,L=-1,P=5,Q=-1; function M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a}; exports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c;}}}; } (scheduler_production_min)); { scheduler.exports = scheduler_production_min; } var schedulerExports = scheduler.exports; var aa$3=reactExports,ba$3=schedulerExports;function p$f(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;cb}return !1}function q$8(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g;}var z$6={}; "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){z$6[a]=new q$8(a,0,!1,a,null,!1,!1);});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];z$6[b]=new q$8(b,1,!1,a[1],null,!1,!1);});["contentEditable","draggable","spellCheck","value"].forEach(function(a){z$6[a]=new q$8(a,2,!1,a.toLowerCase(),null,!1,!1);}); ["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){z$6[a]=new q$8(a,2,!1,a,null,!1,!1);});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){z$6[a]=new q$8(a,3,!1,a.toLowerCase(),null,!1,!1);}); ["checked","multiple","muted","selected"].forEach(function(a){z$6[a]=new q$8(a,3,!0,a,null,!1,!1);});["capture","download"].forEach(function(a){z$6[a]=new q$8(a,4,!1,a,null,!1,!1);});["cols","rows","size","span"].forEach(function(a){z$6[a]=new q$8(a,6,!1,a,null,!1,!1);});["rowSpan","start"].forEach(function(a){z$6[a]=new q$8(a,5,!1,a.toLowerCase(),null,!1,!1);});var pa$3=/[\-:]([a-z])/g;function qa$3(a){return a[1].toUpperCase()} "accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(pa$3, qa$3);z$6[b]=new q$8(b,1,!1,a,null,!1,!1);});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(pa$3,qa$3);z$6[b]=new q$8(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1);});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(pa$3,qa$3);z$6[b]=new q$8(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1);});["tabIndex","crossOrigin"].forEach(function(a){z$6[a]=new q$8(a,1,!1,a.toLowerCase(),null,!1,!1);}); z$6.xlinkHref=new q$8("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){z$6[a]=new q$8(a,1,!1,a.toLowerCase(),null,!0,!0);}); function ra$3(a,b,c,d){var e=z$6.hasOwnProperty(b)?z$6[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("")&&(k=k.replace("",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{La$3=!1,Error.prepareStackTrace=c;}return (a=a?a.displayName||a.name:"")?Ka$3(a):""} function Na$3(a){switch(a.tag){case 5:return Ka$3(a.type);case 16:return Ka$3("Lazy");case 13:return Ka$3("Suspense");case 19:return Ka$3("SuspenseList");case 0:case 2:case 15:return a=Ma$3(a.type,!1),a;case 11:return a=Ma$3(a.type.render,!1),a;case 1:return a=Ma$3(a.type,!0),a;default:return ""}} function Oa$3(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case va$3:return "Fragment";case ua$3:return "Portal";case xa$3:return "Profiler";case wa$3:return "StrictMode";case Ca$3:return "Suspense";case Da$3:return "SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Aa$3:return (a.displayName||"Context")+".Consumer";case ya$3:return (a._context.displayName||"Context")+".Provider";case Ba$3:var b=a.render;a=a.displayName;a||(a=b.displayName|| b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case Ea$3:return b=a.displayName||null,null!==b?b:Oa$3(a.type)||"Memo";case Fa$3:b=a._payload;a=a._init;try{return Oa$3(a(b))}catch(c){}}return null} function Pa$3(a){var b=a.type;switch(a.tag){case 24:return "Cache";case 9:return (b.displayName||"Context")+".Consumer";case 10:return (b._context.displayName||"Context")+".Provider";case 18:return "DehydratedFragment";case 11:return a=b.render,a=a.displayName||a.name||"",b.displayName||(""!==a?"ForwardRef("+a+")":"ForwardRef");case 7:return "Fragment";case 5:return b;case 4:return "Portal";case 3:return "Root";case 6:return "Text";case 16:return Oa$3(b);case 8:return b===wa$3?"StrictMode":"Mode";case 22:return "Offscreen"; case 12:return "Profiler";case 21:return "Scope";case 13:return "Suspense";case 19:return "SuspenseList";case 25:return "TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"===typeof b)return b.displayName||b.name||null;if("string"===typeof b)return b}return null}function Qa$3(a){switch(typeof a){case "boolean":case "number":case "string":case "undefined":return a;case "object":return a;default:return ""}} function Ra$3(a){var b=a.type;return (a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b)} function Sa$3(a){var b=Ra$3(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a);}});Object.defineProperty(a,b,{enumerable:c.enumerable});return {getValue:function(){return d},setValue:function(a){d=""+a;},stopTracking:function(){a._valueTracker= null;delete a[b];}}}}function Ta$3(a){a._valueTracker||(a._valueTracker=Sa$3(a));}function Ua$3(a){if(!a)return !1;var b=a._valueTracker;if(!b)return !0;var c=b.getValue();var d="";a&&(d=Ra$3(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Va$3(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}} function Wa$3(a,b){var c=b.checked;return A$7({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Xa$3(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Qa$3(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value};}function Ya$3(a,b){b=b.checked;null!=b&&ra$3(a,"checked",b,!1);} function Za$3(a,b){Ya$3(a,b);var c=Qa$3(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=c)a.value=""+c;}else a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?$a$3(a,b.type,c):b.hasOwnProperty("defaultValue")&&$a$3(a,b.type,Qa$3(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked);} function ab$2(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b;}c=a.name;""!==c&&(a.name="");a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c);} function $a$3(a,b,c){if("number"!==b||Va$3(a.ownerDocument)!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c);}var bb$3=Array.isArray; function cb$2(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e"+b.valueOf().toString()+"";for(b=jb$2.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild);}}); function lb$2(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b;} var mb$2={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0, zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},nb$2=["Webkit","ms","Moz","O"];Object.keys(mb$2).forEach(function(a){nb$2.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);mb$2[b]=mb$2[a];});});function ob$2(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||mb$2.hasOwnProperty(a)&&mb$2[a]?(""+b).trim():b+"px"} function pb$2(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=ob$2(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e;}}var qb$2=A$7({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}); function rb$2(a,b){if(b){if(qb$2[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p$f(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p$f(60));if("object"!==typeof b.dangerouslySetInnerHTML||!("__html"in b.dangerouslySetInnerHTML))throw Error(p$f(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(p$f(62));}} function sb$2(a,b){if(-1===a.indexOf("-"))return "string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return !1;default:return !0}}var tb$2=null;function ub$2(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var vb$3=null,wb$3=null,xb$3=null; function yb$3(a){if(a=zb$2(a)){if("function"!==typeof vb$3)throw Error(p$f(280));var b=a.stateNode;b&&(b=Ab$3(b),vb$3(a.stateNode,a.type,b));}}function Bb$2(a){wb$3?xb$3?xb$3.push(a):xb$3=[a]:wb$3=a;}function Cb$3(){if(wb$3){var a=wb$3,b=xb$3;xb$3=wb$3=null;yb$3(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(mc$2(a)/nc$1|0)|0}var oc$2=64,pc$2=4194304; function qc$2(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824; default:return a}}function rc$2(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=qc$2(h):(f&=g,0!==f&&(d=qc$2(f)));}else g=c&~e,0!==g?d=qc$2(g):0!==f&&(d=qc$2(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}function wc$2(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-lc$2(b);a[b]=c;} function xc$2(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=Xd),$d=String.fromCharCode(32),ae$1=!1; function be$4(a,b){switch(a){case "keyup":return -1!==Vd.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "focusout":return !0;default:return !1}}function ce$3(a){a=a.detail;return "object"===typeof a&&"data"in a?a.data:null}var de$4=!1;function ee$4(a,b){switch(a){case "compositionend":return ce$3(b);case "keypress":if(32!==b.which)return null;ae$1=!0;return $d;case "textInput":return a=b.data,a===$d&&ae$1?null:a;default:return null}} function fe$3(a,b){if(de$4)return "compositionend"===a||!Wd&&be$4(a,b)?(a=id$1(),hd=gd=fd=null,de$4=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return {node:c,offset:b-a};a=d;}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode;}c=void 0;}c=Ee$5(c);}}function Ge$4(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Ge$4(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1} function He$5(){for(var a=window,b=Va$3();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href;}catch(d){c=!1;}if(c)a=b.contentWindow;else break;b=Va$3(a.document);}return b}function Ie$6(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)} function Je$4(a){var b=He$5(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Ge$4(c.ownerDocument.documentElement,c)){if(null!==d&&Ie$6(c))if(b=d.start,a=d.end,void 0===a&&(a=b),"selectionStart"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Fe$4(c,f);var g=Fe$4(c, d);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)));}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Le$2=null,Me$5=null,Ne$5=null,Oe$1=!1; function Pe$4(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Oe$1||null==Le$2||Le$2!==Va$3(d)||(d=Le$2,"selectionStart"in d&&Ie$6(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Ne$5&&De$4(Ne$5,d)||(Ne$5=d,d=je$4(Me$5,"onSelect"),0Nf||(a.current=Mf[Nf],Mf[Nf]=null,Nf--);}function H$8(a,b){Nf++;Mf[Nf]=a.current;a.current=b;}var Pf={},I$8=Of(Pf),Qf=Of(!1),Rf=Pf;function Sf(a,b){var c=a.type.contextTypes;if(!c)return Pf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e} function Tf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function Uf(){G$4(Qf);G$4(I$8);}function Vf(a,b,c){if(I$8.current!==Pf)throw Error(p$f(168));H$8(I$8,b);H$8(Qf,c);}function Wf(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p$f(108,Pa$3(a)||"Unknown",e));return A$7({},c,d)} function Xf(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Pf;Rf=I$8.current;H$8(I$8,a);H$8(Qf,Qf.current);return !0}function Yf(a,b,c){var d=a.stateNode;if(!d)throw Error(p$f(169));c?(a=Wf(a,b,Rf),d.__reactInternalMemoizedMergedChildContext=a,G$4(Qf),G$4(I$8),H$8(I$8,a)):G$4(Qf);H$8(Qf,c);}var Zf=null,$f=!1,ag=!1;function bg(a){null===Zf?Zf=[a]:Zf.push(a);}function cg(a){$f=!0;bg(a);} function dg(){if(!ag&&null!==Zf){ag=!0;var a=0,b=E$5;try{var c=Zf;for(E$5=1;a>=g;e-=g;Rg=1<<32-lc$2(b)+e|c<r?(x=m,m=null):x=m.sibling;var t=u(e,m,h[r],k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,r);null===n?l=t:n.sibling=t;n=t;m=x;}if(r===h.length)return c(e,m),N$4&&Tg(e,r),l;if(null===m){for(;rr?(x=n,n=null):x=n.sibling;var v=u(e,n,t.value,k);if(null===v){null===n&&(n=x);break}a&&n&&null===v.alternate&&b(e,n);g=f(v,g,r);null===m?l=v:m.sibling=v;m=v;n=x;}if(t.done)return c(e, n),N$4&&Tg(e,r),l;if(null===n){for(;!t.done;r++,t=h.next())t=w(e,t.value,k),null!==t&&(g=f(t,g,r),null===m?l=t:m.sibling=t,m=t);N$4&&Tg(e,r);return l}for(n=d(e,n);!t.done;r++,t=h.next())t=y(n,e,r,t.value,k),null!==t&&(a&&null!==t.alternate&&n.delete(null===t.key?r:t.key),g=f(t,g,r),null===m?l=t:m.sibling=t,m=t);a&&n.forEach(function(a){return b(e,a)});N$4&&Tg(e,r);return l}function C(a,d,f,h){"object"===typeof f&&null!==f&&f.type===va$3&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!==f){switch(f.$$typeof){case ta$3:a:{for(var k= f.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===va$3){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===Fa$3&&kh$1(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=ih$1(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling;}f.type===va$3?(d=qh$1(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=oh$1(f.type,f.key,f.props,null,a.mode,h),h.ref=ih$1(a,d,f),h.return=a,a=h);}return g(a);case ua$3:a:{for(l=f.key;null!== d;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else {c(a,d);break}else b(a,d);d=d.sibling;}d=ph$1(f,a.mode,h);d.return=a;a=d;}return g(a);case Fa$3:return l=f._init,C(a,d,l(f._payload),h)}if(bb$3(f))return n(a,d,f,h);if(Ia$3(f))return v(a,d,f,h);jh$1(a,f);}return "string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d): (c(a,d),d=nh$1(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return C}var rh$1=lh$1(!0),sh$1=lh$1(!1),th$1={},uh$1=Of(th$1),vh$1=Of(th$1),wh$1=Of(th$1);function xh$1(a){if(a===th$1)throw Error(p$f(174));return a}function yh$1(a,b){H$8(wh$1,b);H$8(vh$1,a);H$8(uh$1,th$1);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:ib$2(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=ib$2(b,a);}G$4(uh$1);H$8(uh$1,b);}function zh$1(){G$4(uh$1);G$4(vh$1);G$4(wh$1);} function Ah$1(a){xh$1(wh$1.current);var b=xh$1(uh$1.current);var c=ib$2(b,a.type);b!==c&&(H$8(vh$1,a),H$8(uh$1,c));}function Bh$1(a){vh$1.current===a&&(G$4(uh$1),G$4(vh$1));}var P$6=Of(0); function Ch$1(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||"$?"===c.data||"$!"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return;}b.sibling.return=b.return;b=b.sibling;}return null}var Dh$1=[]; function Eh$1(){for(var a=0;ac?c:4;a(!0);var d=Gh.transition;Gh.transition={};try{a(!1),b();}finally{E$5=c,Gh.transition=d;}}function ti(){return Uh$1().memoizedState}function ui(a,b,c){var d=Dg(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};vi$1(a)?wi$1(b,c):(xi$1(a,b,c),c=M$b(),a=Eg(a,d,c),null!==a&&yi$1(a,b,d));} function gi$1(a,b,c){var d=Dg(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(vi$1(a))wi$1(b,e);else {xi$1(a,b,e);var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(Ce$2(h,g))return}catch(k){}finally{}c=M$b();a=Eg(a,d,c);null!==a&&yi$1(a,b,d);}}function vi$1(a){var b=a.alternate;return a===Q$6||null!==b&&b===Q$6} function wi$1(a,b){Jh=Ih$1=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b;}function xi$1(a,b,c){null!==J$4&&0!==(a.mode&1)&&0===(K$2&2)?(a=b.interleaved,null===a?(c.next=c,null===qg?qg=[b]:qg.push(b)):(c.next=a.next,a.next=c),b.interleaved=c):(a=b.pending,null===a?c.next=c:(c.next=a.next,a.next=c),b.pending=c);}function yi$1(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;yc$2(a,c);}} var Rh$1={readContext:pg,useCallback:U$6,useContext:U$6,useEffect:U$6,useImperativeHandle:U$6,useInsertionEffect:U$6,useLayoutEffect:U$6,useMemo:U$6,useReducer:U$6,useRef:U$6,useState:U$6,useDebugValue:U$6,useDeferredValue:U$6,useTransition:U$6,useMutableSource:U$6,useSyncExternalStore:U$6,useId:U$6,unstable_isNewReconciler:!1},Oh$1={readContext:pg,useCallback:function(a,b){Th$1().memoizedState=[a,void 0===b?null:b];return a},useContext:pg,useEffect:ki$1,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ii(4194308, 4,ni.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ii(4194308,4,a,b)},useInsertionEffect:function(a,b){return ii(4,2,a,b)},useMemo:function(a,b){var c=Th$1();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=Th$1();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=ui.bind(null,Q$6,a);return [d.memoizedState,a]},useRef:function(a){var b= Th$1();a={current:a};return b.memoizedState=a},useState:fi$1,useDebugValue:pi$1,useDeferredValue:function(a){var b=fi$1(a),c=b[0],d=b[1];ki$1(function(){var b=Gh.transition;Gh.transition={};try{d(a);}finally{Gh.transition=b;}},[a]);return c},useTransition:function(){var a=fi$1(!1),b=a[0];a=si.bind(null,a[1]);Th$1().memoizedState=a;return [b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=Q$6,e=Th$1();if(N$4){if(void 0===c)throw Error(p$f(407));c=c();}else {c=b();if(null===J$4)throw Error(p$f(349)); 0!==(Hh$1&30)||di(d,b,c);}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;ki$1(ai.bind(null,d,f,a),[a]);d.flags|=2048;bi$1(9,ci.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=Th$1(),b=J$4.identifierPrefix;if(N$4){var c=Sg;var d=Rg;c=(d&~(1<<32-lc$2(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=Kh++;0\x3c/script>",a=a.removeChild(a.firstChild)):"string"===typeof d.is?a=g.createElement(c,{is:d.is}): (a=g.createElement(c),"select"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[If]=b;a[Jf]=d;Li$1(a,b,!1,!1);b.stateNode=a;a:{g=sb$2(c,d);switch(c){case "dialog":F$9("cancel",a);F$9("close",a);e=d;break;case "iframe":case "object":case "embed":F$9("load",a);e=d;break;case "video":case "audio":for(e=0;eTi$1&&(b.flags|=128,d=!0,Pi$1(f,!1),b.lanes=4194304);}else {if(!d)if(a=Ch$1(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue, null!==c&&(b.updateQueue=c,b.flags|=4),Pi$1(f,!0),null===f.tail&&"hidden"===f.tailMode&&!g.alternate&&!N$4)return V$6(b),null}else 2*D$8()-f.renderingStartTime>Ti$1&&1073741824!==c&&(b.flags|=128,d=!0,Pi$1(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g);}if(null!==f.tail)return b=f.tail,f.rendering=b,f.tail=b.sibling,f.renderingStartTime=D$8(),b.sibling=null,c=P$6.current,H$8(P$6,d?c&1|2:c&1),b;V$6(b);return null;case 22:case 23:return Ui$1(),d=null!== b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(Vi$1&1073741824)&&(V$6(b),b.subtreeFlags&6&&(b.flags|=8192)):V$6(b),null;case 24:return null;case 25:return null}throw Error(p$f(156,b.tag));}var Wi$1=sa$3.ReactCurrentOwner,og=!1;function Xi$1(a,b,c,d){b.child=null===a?sh$1(b,null,c,d):rh$1(b,a.child,c,d);} function Yi$1(a,b,c,d,e){c=c.render;var f=b.ref;ng(b,e);d=Nh$1(a,b,c,d,f,e);c=Sh$1();if(null!==a&&!og)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Zi$1(a,b,e);N$4&&c&&Vg(b);b.flags|=1;Xi$1(a,b,d,e);return b.child} function $i$1(a,b,c,d,e){if(null===a){var f=c.type;if("function"===typeof f&&!aj(f)&&void 0===f.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=f,bj(a,b,f,d,e);a=oh$1(c.type,null,d,b,b.mode,e);a.ref=b.ref;a.return=b;return b.child=a}f=a.child;if(0===(a.lanes&e)){var g=f.memoizedProps;c=c.compare;c=null!==c?c:De$4;if(c(g,d)&&a.ref===b.ref)return Zi$1(a,b,e)}b.flags|=1;a=mh$1(f,d);a.ref=b.ref;a.return=b;return b.child=a} function bj(a,b,c,d,e){if(null!==a&&De$4(a.memoizedProps,d)&&a.ref===b.ref)if(og=!1,0!==(a.lanes&e))0!==(a.flags&131072)&&(og=!0);else return b.lanes=a.lanes,Zi$1(a,b,e);return cj(a,b,c,d,e)} function dj(a,b,c){var d=b.pendingProps,e=d.children,f=null!==a?a.memoizedState:null;if("hidden"===d.mode)if(0===(b.mode&1))b.memoizedState={baseLanes:0,cachePool:null},H$8(ej,Vi$1),Vi$1|=c;else if(0!==(c&1073741824))b.memoizedState={baseLanes:0,cachePool:null},d=null!==f?f.baseLanes:c,H$8(ej,Vi$1),Vi$1|=d;else return a=null!==f?f.baseLanes|c:c,b.lanes=b.childLanes=1073741824,b.memoizedState={baseLanes:a,cachePool:null},b.updateQueue=null,H$8(ej,Vi$1),Vi$1|=a,null;else null!==f?(d=f.baseLanes|c,b.memoizedState=null): d=c,H$8(ej,Vi$1),Vi$1|=d;Xi$1(a,b,e,c);return b.child}function fj(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.flags|=512,b.flags|=2097152;}function cj(a,b,c,d,e){var f=Tf(c)?Rf:I$8.current;f=Sf(b,f);ng(b,e);c=Nh$1(a,b,c,d,f,e);d=Sh$1();if(null!==a&&!og)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Zi$1(a,b,e);N$4&&d&&Vg(b);b.flags|=1;Xi$1(a,b,c,e);return b.child} function gj(a,b,c,d,e){if(Tf(c)){var f=!0;Xf(b);}else f=!1;ng(b,e);if(null===b.stateNode)null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2),Hg(b,c,d),Jg(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,l=c.contextType;"object"===typeof l&&null!==l?l=pg(l):(l=Tf(c)?Rf:I$8.current,l=Sf(b,l));var m=c.getDerivedStateFromProps,w="function"===typeof m||"function"===typeof g.getSnapshotBeforeUpdate;w||"function"!==typeof g.UNSAFE_componentWillReceiveProps&& "function"!==typeof g.componentWillReceiveProps||(h!==d||k!==l)&&Ig(b,g,d,l);rg=!1;var u=b.memoizedState;g.state=u;yg(b,d,g,e);k=b.memoizedState;h!==d||u!==k||Qf.current||rg?("function"===typeof m&&(Cg(b,c,m,d),k=b.memoizedState),(h=rg||Gg(b,c,h,d,u,k,l))?(w||"function"!==typeof g.UNSAFE_componentWillMount&&"function"!==typeof g.componentWillMount||("function"===typeof g.componentWillMount&&g.componentWillMount(),"function"===typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),"function"=== typeof g.componentDidMount&&(b.flags|=4194308)):("function"===typeof g.componentDidMount&&(b.flags|=4194308),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=l,d=h):("function"===typeof g.componentDidMount&&(b.flags|=4194308),d=!1);}else {g=b.stateNode;tg(a,b);h=b.memoizedProps;l=b.type===b.elementType?h:fg(b.type,h);g.props=l;w=b.pendingProps;u=g.context;k=c.contextType;"object"===typeof k&&null!==k?k=pg(k):(k=Tf(c)?Rf:I$8.current,k=Sf(b,k));var y=c.getDerivedStateFromProps;(m="function"=== typeof y||"function"===typeof g.getSnapshotBeforeUpdate)||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==w||u!==k)&&Ig(b,g,d,k);rg=!1;u=b.memoizedState;g.state=u;yg(b,d,g,e);var n=b.memoizedState;h!==w||u!==n||Qf.current||rg?("function"===typeof y&&(Cg(b,c,y,d),n=b.memoizedState),(l=rg||Gg(b,c,l,d,u,n,k)||!1)?(m||"function"!==typeof g.UNSAFE_componentWillUpdate&&"function"!==typeof g.componentWillUpdate||("function"===typeof g.componentWillUpdate&& g.componentWillUpdate(d,n,k),"function"===typeof g.UNSAFE_componentWillUpdate&&g.UNSAFE_componentWillUpdate(d,n,k)),"function"===typeof g.componentDidUpdate&&(b.flags|=4),"function"===typeof g.getSnapshotBeforeUpdate&&(b.flags|=1024)):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&u===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&u===a.memoizedState||(b.flags|=1024),b.memoizedProps=d,b.memoizedState=n),g.props=d,g.state=n,g.context= k,d=l):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&u===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&u===a.memoizedState||(b.flags|=1024),d=!1);}return hj(a,b,c,d,f,e)} function hj(a,b,c,d,e,f){fj(a,b);var g=0!==(b.flags&128);if(!d&&!g)return e&&Yf(b,c,!1),Zi$1(a,b,f);d=b.stateNode;Wi$1.current=b;var h=g&&"function"!==typeof c.getDerivedStateFromError?null:d.render();b.flags|=1;null!==a&&g?(b.child=rh$1(b,a.child,null,f),b.child=rh$1(b,null,h,f)):Xi$1(a,b,h,f);b.memoizedState=d.state;e&&Yf(b,c,!0);return b.child}function ij(a){var b=a.stateNode;b.pendingContext?Vf(a,b.pendingContext,b.pendingContext!==b.context):b.context&&Vf(a,b.context,!1);yh$1(a,b.containerInfo);} function jj(a,b,c,d,e){gh$1();hh$1(e);b.flags|=256;Xi$1(a,b,c,d);return b.child}var kj={dehydrated:null,treeContext:null,retryLane:0};function lj(a){return {baseLanes:a,cachePool:null}} function mj(a,b,c){var d=b.pendingProps,e=P$6.current,f=!1,g=0!==(b.flags&128),h;(h=g)||(h=null!==a&&null===a.memoizedState?!1:0!==(e&2));if(h)f=!0,b.flags&=-129;else if(null===a||null!==a.memoizedState)e|=1;H$8(P$6,e&1);if(null===a){dh$1(b);a=b.memoizedState;if(null!==a&&(a=a.dehydrated,null!==a))return 0===(b.mode&1)?b.lanes=1:"$!"===a.data?b.lanes=8:b.lanes=1073741824,null;e=d.children;a=d.fallback;return f?(d=b.mode,f=b.child,e={mode:"hidden",children:e},0===(d&1)&&null!==f?(f.childLanes=0,f.pendingProps= e):f=nj(e,d,0,null),a=qh$1(a,d,c,null),f.return=b,a.return=b,f.sibling=a,b.child=f,b.child.memoizedState=lj(c),b.memoizedState=kj,a):oj(b,e)}e=a.memoizedState;if(null!==e){h=e.dehydrated;if(null!==h){if(g){if(b.flags&256)return b.flags&=-257,pj(a,b,c,Error(p$f(422)));if(null!==b.memoizedState)return b.child=a.child,b.flags|=128,null;f=d.fallback;e=b.mode;d=nj({mode:"visible",children:d.children},e,0,null);f=qh$1(f,e,c,null);f.flags|=2;d.return=b;f.return=b;d.sibling=f;b.child=d;0!==(b.mode&1)&&rh$1(b,a.child, null,c);b.child.memoizedState=lj(c);b.memoizedState=kj;return f}if(0===(b.mode&1))b=pj(a,b,c,null);else if("$!"===h.data)b=pj(a,b,c,Error(p$f(419)));else if(d=0!==(c&a.childLanes),og||d){d=J$4;if(null!==d){switch(c&-c){case 4:f=2;break;case 16:f=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:f=32;break;case 536870912:f= 268435456;break;default:f=0;}d=0!==(f&(d.suspendedLanes|c))?0:f;0!==d&&d!==e.retryLane&&(e.retryLane=d,Eg(a,d,-1));}Si$1();b=pj(a,b,c,Error(p$f(421)));}else "$?"===h.data?(b.flags|=128,b.child=a.child,b=qj.bind(null,a),h._reactRetry=b,b=null):(c=e.treeContext,Yg=Ff(h.nextSibling),Xg=b,N$4=!0,Zg=null,null!==c&&(Og[Pg++]=Rg,Og[Pg++]=Sg,Og[Pg++]=Qg,Rg=c.id,Sg=c.overflow,Qg=b),b=oj(b,b.pendingProps.children),b.flags|=4096);return b}if(f)return d=rj(a,b,d.children,d.fallback,c),f=b.child,e=a.child.memoizedState, f.memoizedState=null===e?lj(c):{baseLanes:e.baseLanes|c,cachePool:null},f.childLanes=a.childLanes&~c,b.memoizedState=kj,d;c=sj(a,b,d.children,c);b.memoizedState=null;return c}if(f)return d=rj(a,b,d.children,d.fallback,c),f=b.child,e=a.child.memoizedState,f.memoizedState=null===e?lj(c):{baseLanes:e.baseLanes|c,cachePool:null},f.childLanes=a.childLanes&~c,b.memoizedState=kj,d;c=sj(a,b,d.children,c);b.memoizedState=null;return c} function oj(a,b){b=nj({mode:"visible",children:b},a.mode,0,null);b.return=a;return a.child=b}function sj(a,b,c,d){var e=a.child;a=e.sibling;c=mh$1(e,{mode:"visible",children:c});0===(b.mode&1)&&(c.lanes=d);c.return=b;c.sibling=null;null!==a&&(d=b.deletions,null===d?(b.deletions=[a],b.flags|=16):d.push(a));return b.child=c} function rj(a,b,c,d,e){var f=b.mode;a=a.child;var g=a.sibling,h={mode:"hidden",children:c};0===(f&1)&&b.child!==a?(c=b.child,c.childLanes=0,c.pendingProps=h,b.deletions=null):(c=mh$1(a,h),c.subtreeFlags=a.subtreeFlags&14680064);null!==g?d=mh$1(g,d):(d=qh$1(d,f,e,null),d.flags|=2);d.return=b;c.return=b;c.sibling=d;b.child=c;return d}function pj(a,b,c,d){null!==d&&hh$1(d);rh$1(b,a.child,null,c);a=oj(b,b.pendingProps.children);a.flags|=2;b.memoizedState=null;return a} function tj(a,b,c){a.lanes|=b;var d=a.alternate;null!==d&&(d.lanes|=b);mg(a.return,b,c);}function uj(a,b,c,d,e){var f=a.memoizedState;null===f?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailMode:e}:(f.isBackwards=b,f.rendering=null,f.renderingStartTime=0,f.last=d,f.tail=c,f.tailMode=e);} function vj(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;Xi$1(a,b,d.children,c);d=P$6.current;if(0!==(d&2))d=d&1|2,b.flags|=128;else {if(null!==a&&0!==(a.flags&128))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&tj(a,c,b);else if(19===a.tag)tj(a,c,b);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return;}a.sibling.return=a.return;a=a.sibling;}d&=1;}H$8(P$6,d);if(0===(b.mode&1))b.memoizedState= null;else switch(e){case "forwards":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===Ch$1(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);uj(b,!1,e,c,f);break;case "backwards":c=null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===Ch$1(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a;}uj(b,!0,c,null,f);break;case "together":uj(b,!1,null,null,void 0);break;default:b.memoizedState=null;}return b.child} function Zi$1(a,b,c){null!==a&&(b.dependencies=a.dependencies);zg|=b.lanes;if(0===(c&b.childLanes))return null;if(null!==a&&b.child!==a.child)throw Error(p$f(153));if(null!==b.child){a=b.child;c=mh$1(a,a.pendingProps);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=mh$1(a,a.pendingProps),c.return=b;c.sibling=null;}return b.child} function wj(a,b,c){switch(b.tag){case 3:ij(b);gh$1();break;case 5:Ah$1(b);break;case 1:Tf(b.type)&&Xf(b);break;case 4:yh$1(b,b.stateNode.containerInfo);break;case 10:var d=b.type._context,e=b.memoizedProps.value;H$8(gg,d._currentValue);d._currentValue=e;break;case 13:d=b.memoizedState;if(null!==d){if(null!==d.dehydrated)return H$8(P$6,P$6.current&1),b.flags|=128,null;if(0!==(c&b.child.childLanes))return mj(a,b,c);H$8(P$6,P$6.current&1);a=Zi$1(a,b,c);return null!==a?a.sibling:null}H$8(P$6,P$6.current&1);break;case 19:d=0!==(c& b.childLanes);if(0!==(a.flags&128)){if(d)return vj(a,b,c);b.flags|=128;}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null,e.lastEffect=null);H$8(P$6,P$6.current);if(d)break;else return null;case 22:case 23:return b.lanes=0,dj(a,b,c)}return Zi$1(a,b,c)} function xj(a,b){Wg(b);switch(b.tag){case 1:return Tf(b.type)&&Uf(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return zh$1(),G$4(Qf),G$4(I$8),Eh$1(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Bh$1(b),null;case 13:G$4(P$6);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p$f(340));gh$1();}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return G$4(P$6),null;case 4:return zh$1(),null;case 10:return lg(b.type._context),null;case 22:case 23:return Ui$1(), null;case 24:return null;default:return null}}var yj=!1,zj=!1,Aj="function"===typeof WeakSet?WeakSet:Set,X$8=null;function Bj(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{c(null);}catch(d){Cj(a,b,d);}else c.current=null;}function Dj(a,b,c){try{c();}catch(d){Cj(a,b,d);}}var Ej=!1; function Fj(a,b){a=He$5();if(Ie$6(a)){if("selectionStart"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType;}catch(O){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,w=a,u=null;b:for(;;){for(var y;;){w!==c||0!==e&&3!==w.nodeType||(h=g+e);w!==f||0!==d&&3!==w.nodeType||(k=g+d);3===w.nodeType&&(g+=w.nodeValue.length); if(null===(y=w.firstChild))break;u=w;w=y;}for(;;){if(w===a)break b;u===c&&++l===e&&(h=g);u===f&&++m===d&&(k=g);if(null!==(y=w.nextSibling))break;w=u;u=w.parentNode;}w=y;}c=-1===h||-1===k?null:{start:h,end:k};}else c=null;}c=c||{start:0,end:0};}else c=null;xf={focusedElem:a,selectionRange:c};for(X$8=b;null!==X$8;)if(b=X$8,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,X$8=a;else for(;null!==X$8;){b=X$8;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;case 1:if(null!== n){var v=n.memoizedProps,C=n.memoizedState,t=b.stateNode,r=t.getSnapshotBeforeUpdate(b.elementType===b.type?v:fg(b.type,v),C);t.__reactInternalSnapshotBeforeUpdate=r;}break;case 3:var x=b.stateNode.containerInfo;if(1===x.nodeType)x.textContent="";else if(9===x.nodeType){var B=x.body;null!=B&&(B.textContent="");}break;case 5:case 6:case 4:case 17:break;default:throw Error(p$f(163));}}catch(O){Cj(b,b.return,O);}a=b.sibling;if(null!==a){a.return=b.return;X$8=a;break}X$8=b.return;}n=Ej;Ej=!1;return n} function Gj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Dj(b,c,f);}e=e.next;}while(e!==d)}}function Hj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d();}c=c.next;}while(c!==b)}}function Ij(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c;}"function"===typeof b?b(a):b.current=a;}} function Jj(a,b,c){if(ic$2&&"function"===typeof ic$2.onCommitFiberUnmount)try{ic$2.onCommitFiberUnmount(hc$2,b);}catch(g){}switch(b.tag){case 0:case 11:case 14:case 15:a=b.updateQueue;if(null!==a&&(a=a.lastEffect,null!==a)){var d=a=a.next;do{var e=d,f=e.destroy;e=e.tag;void 0!==f&&(0!==(e&2)?Dj(b,c,f):0!==(e&4)&&Dj(b,c,f));d=d.next;}while(d!==a)}break;case 1:Bj(b,c);a=b.stateNode;if("function"===typeof a.componentWillUnmount)try{a.props=b.memoizedProps,a.state=b.memoizedState,a.componentWillUnmount();}catch(g){Cj(b, c,g);}break;case 5:Bj(b,c);break;case 4:Kj(a,b,c);}}function Lj(a){var b=a.alternate;null!==b&&(a.alternate=null,Lj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[If],delete b[Jf],delete b[jf],delete b[Kf],delete b[Lf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null;}function Mj(a){return 5===a.tag||3===a.tag||4===a.tag} function Nj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Mj(a.return))return null;a=a.return;}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child;}if(!(a.flags&2))return a.stateNode}} function Oj(a){a:{for(var b=a.return;null!==b;){if(Mj(b))break a;b=b.return;}throw Error(p$f(160));}var c=b;switch(c.tag){case 5:b=c.stateNode;c.flags&32&&(lb$2(b,""),c.flags&=-33);c=Nj(a);Pj(a,c,b);break;case 3:case 4:b=c.stateNode.containerInfo;c=Nj(a);Qj(a,c,b);break;default:throw Error(p$f(161));}} function Qj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=wf));else if(4!==d&&(a=a.child,null!==a))for(Qj(a,b,c),a=a.sibling;null!==a;)Qj(a,b,c),a=a.sibling;} function Pj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Pj(a,b,c),a=a.sibling;null!==a;)Pj(a,b,c),a=a.sibling;} function Kj(a,b,c){for(var d=b,e=!1,f,g;;){if(!e){e=d.return;a:for(;;){if(null===e)throw Error(p$f(160));f=e.stateNode;switch(e.tag){case 5:g=!1;break a;case 3:f=f.containerInfo;g=!0;break a;case 4:f=f.containerInfo;g=!0;break a}e=e.return;}e=!0;}if(5===d.tag||6===d.tag){a:for(var h=a,k=d,l=c,m=k;;)if(Jj(h,m,l),null!==m.child&&4!==m.tag)m.child.return=m,m=m.child;else {if(m===k)break a;for(;null===m.sibling;){if(null===m.return||m.return===k)break a;m=m.return;}m.sibling.return=m.return;m=m.sibling;}g?(h= f,k=d.stateNode,8===h.nodeType?h.parentNode.removeChild(k):h.removeChild(k)):f.removeChild(d.stateNode);}else if(18===d.tag)g?(h=f,k=d.stateNode,8===h.nodeType?Ef(h.parentNode,k):1===h.nodeType&&Ef(h,k),Yc$1(h)):Ef(f,d.stateNode);else if(4===d.tag){if(null!==d.child){f=d.stateNode.containerInfo;g=!0;d.child.return=d;d=d.child;continue}}else if(Jj(a,d,c),null!==d.child){d.child.return=d;d=d.child;continue}if(d===b)break;for(;null===d.sibling;){if(null===d.return||d.return===b)return;d=d.return;4===d.tag&& (e=!1);}d.sibling.return=d.return;d=d.sibling;}} function Rj(a,b){switch(b.tag){case 0:case 11:case 14:case 15:Gj(3,b,b.return);Hj(3,b);Gj(5,b,b.return);return;case 1:return;case 5:var c=b.stateNode;if(null!=c){var d=b.memoizedProps,e=null!==a?a.memoizedProps:d;a=b.type;var f=b.updateQueue;b.updateQueue=null;if(null!==f){"input"===a&&"radio"===d.type&&null!=d.name&&Ya$3(c,d);sb$2(a,e);b=sb$2(a,d);for(e=0;ee&&(e=g);d&=~f;}d=e;d=D$8()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*bk(d/1960))-d;if(10a?16:a;if(null===lk)var d=!1;else {a=lk;lk=null;mk=0;if(0!==(K$2&6))throw Error(p$f(331));var e=K$2;K$2|=4;for(X$8=a.current;null!==X$8;){var f=X$8,g=f.child;if(0!==(X$8.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kD$8()-Vj?Ak(a,0):hk|=c);tk(a,b);}function Ok(a,b){0===b&&(0===(a.mode&1)?b=1:(b=pc$2,pc$2<<=1,0===(pc$2&130023424)&&(pc$2=4194304)));var c=M$b();a=rk(a,b);null!==a&&(wc$2(a,b,c),tk(a,c));}function qj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Ok(a,c);} function Tj(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p$f(314));}null!==d&&d.delete(b);Ok(a,c);}var Lk; Lk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Qf.current)og=!0;else {if(0===(a.lanes&c)&&0===(b.flags&128))return og=!1,wj(a,b,c);og=0!==(a.flags&131072)?!0:!1;}else og=!1,N$4&&0!==(b.flags&1048576)&&Ug(b,Ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2);a=b.pendingProps;var e=Sf(b,I$8.current);ng(b,c);e=Nh$1(null,b,d,a,e,c);var f=Sh$1();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof? (b.tag=1,b.memoizedState=null,b.updateQueue=null,Tf(d)?(f=!0,Xf(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,sg(b),e.updater=Fg,b.stateNode=e,e._reactInternals=b,Jg(b,d,a,c),b=hj(null,b,d,!0,f,c)):(b.tag=0,N$4&&f&&Vg(b),Xi$1(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=Pk(d);a=fg(d,a);switch(e){case 0:b=cj(null,b,d,a,c);break a;case 1:b=gj(null,b, d,a,c);break a;case 11:b=Yi$1(null,b,d,a,c);break a;case 14:b=$i$1(null,b,d,fg(d.type,a),c);break a}throw Error(p$f(306,d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:fg(d,e),cj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:fg(d,e),gj(a,b,d,e,c);case 3:a:{ij(b);if(null===a)throw Error(p$f(387));d=b.pendingProps;f=b.memoizedState;e=f.element;tg(a,b);yg(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1, cache:g.cache,transitions:g.transitions},b.updateQueue.baseState=f,b.memoizedState=f,b.flags&256){e=Error(p$f(423));b=jj(a,b,d,c,e);break a}else if(d!==e){e=Error(p$f(424));b=jj(a,b,d,c,e);break a}else for(Yg=Ff(b.stateNode.containerInfo.firstChild),Xg=b,N$4=!0,Zg=null,c=sh$1(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else {gh$1();if(d===e){b=Zi$1(a,b,c);break a}Xi$1(a,b,d,c);}b=b.child;}return b;case 5:return Ah$1(b),null===a&&dh$1(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children, yf(d,e)?g=null:null!==f&&yf(d,f)&&(b.flags|=32),fj(a,b),Xi$1(a,b,g,c),b.child;case 6:return null===a&&dh$1(b),null;case 13:return mj(a,b,c);case 4:return yh$1(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=rh$1(b,null,d,c):Xi$1(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:fg(d,e),Yi$1(a,b,d,e,c);case 7:return Xi$1(a,b,b.pendingProps,c),b.child;case 8:return Xi$1(a,b,b.pendingProps.children,c),b.child;case 12:return Xi$1(a,b,b.pendingProps.children,c),b.child;case 10:a:{d= b.type._context;e=b.pendingProps;f=b.memoizedProps;g=e.value;H$8(gg,d._currentValue);d._currentValue=g;if(null!==f)if(Ce$2(f.value,g)){if(f.children===e.children&&!Qf.current){b=Zi$1(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=ug(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k;}}f.lanes|= c;k=f.alternate;null!==k&&(k.lanes|=c);mg(f.return,c,b);h.lanes|=c;break}k=k.next;}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p$f(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);mg(g,c,b);g=f.sibling;}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return;}f=g;}Xi$1(a,b,e.children,c);b=b.child;}return b;case 9:return e=b.type,d=b.pendingProps.children, ng(b,c),e=pg(e),d=d(e),b.flags|=1,Xi$1(a,b,d,c),b.child;case 14:return d=b.type,e=fg(d,b.pendingProps),e=fg(d.type,e),$i$1(a,b,d,e,c);case 15:return bj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:fg(d,e),null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2),b.tag=1,Tf(d)?(a=!0,Xf(b)):a=!1,ng(b,c),Hg(b,d,e),Jg(b,d,e,c),hj(null,b,d,!0,a,c);case 19:return vj(a,b,c);case 22:return dj(a,b,c)}throw Error(p$f(156,b.tag));};function vk(a,b){return Yb$1(a,b)} function Qk(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null;}function ah$1(a,b,c,d){return new Qk(a,b,c,d)}function aj(a){a=a.prototype;return !(!a||!a.isReactComponent)} function Pk(a){if("function"===typeof a)return aj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Ba$3)return 11;if(a===Ea$3)return 14}return 2} function mh$1(a,b){var c=a.alternate;null===c?(c=ah$1(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext}; c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c} function oh$1(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)aj(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case va$3:return qh$1(c.children,e,f,b);case wa$3:g=8;e|=8;break;case xa$3:return a=ah$1(12,c,b,e|2),a.elementType=xa$3,a.lanes=f,a;case Ca$3:return a=ah$1(13,c,b,e),a.elementType=Ca$3,a.lanes=f,a;case Da$3:return a=ah$1(19,c,b,e),a.elementType=Da$3,a.lanes=f,a;case Ga$3:return nj(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case ya$3:g=10;break a;case Aa$3:g=9;break a;case Ba$3:g=11; break a;case Ea$3:g=14;break a;case Fa$3:g=16;d=null;break a}throw Error(p$f(130,null==a?a:typeof a,""));}b=ah$1(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function qh$1(a,b,c,d){a=ah$1(7,a,d,b);a.lanes=c;return a}function nj(a,b,c,d){a=ah$1(22,a,d,b);a.elementType=Ga$3;a.lanes=c;a.stateNode={};return a}function nh$1(a,b,c){a=ah$1(6,a,null,b);a.lanes=c;return a} function ph$1(a,b,c){b=ah$1(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b} function Rk(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=vc$2(0);this.expirationTimes=vc$2(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=vc$2(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData= null;}function Sk(a,b,c,d,e,f,g,h,k){a=new Rk(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=ah$1(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null};sg(f);return a}function Tk(a,b,c){var d=3= 0) { parsedPath.hash = path.substr(hashIndex); path = path.substr(0, hashIndex); } let searchIndex = path.indexOf("?"); if (searchIndex >= 0) { parsedPath.search = path.substr(searchIndex); path = path.substr(0, searchIndex); } if (path) { parsedPath.pathname = path; } } return parsedPath; } function getUrlBasedHistory(getLocation, createHref, validateLocation, options) { if (options === void 0) { options = {}; } let { window = document.defaultView, v5Compat = false } = options; let globalHistory = window.history; let action = Action.Pop; let listener = null; function handlePop() { action = Action.Pop; if (listener) { listener({ action, location: history.location }); } } function push(to, state) { action = Action.Push; let location = createLocation$1(history.location, to, state); let historyState = getHistoryState(location); let url = history.createHref(location); // try...catch because iOS limits us to 100 pushState calls :/ try { globalHistory.pushState(historyState, "", url); } catch (error) { // They are going to lose state here, but there is no real // way to warn them about it since the page will refresh... window.location.assign(url); } if (v5Compat && listener) { listener({ action, location }); } } function replace(to, state) { action = Action.Replace; let location = createLocation$1(history.location, to, state); let historyState = getHistoryState(location); let url = history.createHref(location); globalHistory.replaceState(historyState, "", url); if (v5Compat && listener) { listener({ action, location: location }); } } let history = { get action() { return action; }, get location() { return getLocation(window, globalHistory); }, listen(fn) { if (listener) { throw new Error("A history only accepts one active listener"); } window.addEventListener(PopStateEventType, handlePop); listener = fn; return () => { window.removeEventListener(PopStateEventType, handlePop); listener = null; }; }, createHref(to) { return createHref(window, to); }, push, replace, go(n) { return globalHistory.go(n); } }; return history; } //#endregion var ResultType; (function (ResultType) { ResultType["data"] = "data"; ResultType["deferred"] = "deferred"; ResultType["redirect"] = "redirect"; ResultType["error"] = "error"; })(ResultType || (ResultType = {})); // Walk the route tree generating unique IDs where necessary so we are working /** * Matches the given routes to a location and returns the match data. * * @see https://reactrouter.com/docs/en/v6/utils/match-routes */ function matchRoutes(routes, locationArg, basename) { if (basename === void 0) { basename = "/"; } let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg; let pathname = stripBasename(location.pathname || "/", basename); if (pathname == null) { return null; } let branches = flattenRoutes(routes); rankRouteBranches(branches); let matches = null; for (let i = 0; matches == null && i < branches.length; ++i) { matches = matchRouteBranch(branches[i], pathname); } return matches; } function flattenRoutes(routes, branches, parentsMeta, parentPath) { if (branches === void 0) { branches = []; } if (parentsMeta === void 0) { parentsMeta = []; } if (parentPath === void 0) { parentPath = ""; } routes.forEach((route, index) => { let meta = { relativePath: route.path || "", caseSensitive: route.caseSensitive === true, childrenIndex: index, route }; if (meta.relativePath.startsWith("/")) { invariant$4(meta.relativePath.startsWith(parentPath), "Absolute route path \"" + meta.relativePath + "\" nested under path " + ("\"" + parentPath + "\" is not valid. An absolute child route path ") + "must start with the combined path of all its parent routes."); meta.relativePath = meta.relativePath.slice(parentPath.length); } let path = joinPaths([parentPath, meta.relativePath]); let routesMeta = parentsMeta.concat(meta); // Add the children before adding this route to the array so we traverse the // route tree depth-first and child routes appear before their parents in // the "flattened" version. if (route.children && route.children.length > 0) { invariant$4(route.index !== true, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\".")); flattenRoutes(route.children, branches, routesMeta, path); } // Routes without a path shouldn't ever match by themselves unless they are // index routes, so don't add them to the list of possible branches. if (route.path == null && !route.index) { return; } branches.push({ path, score: computeScore(path, route.index), routesMeta }); }); return branches; } function rankRouteBranches(branches) { branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex))); } const paramRe = /^:\w+$/; const dynamicSegmentValue = 3; const indexRouteValue = 2; const emptySegmentValue = 1; const staticSegmentValue = 10; const splatPenalty = -2; const isSplat = s => s === "*"; function computeScore(path, index) { let segments = path.split("/"); let initialScore = segments.length; if (segments.some(isSplat)) { initialScore += splatPenalty; } if (index) { initialScore += indexRouteValue; } return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore); } function compareIndexes(a, b) { let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]); return siblings ? // If two routes are siblings, we should try to match the earlier sibling // first. This allows people to have fine-grained control over the matching // behavior by simply putting routes with identical paths in the order they // want them tried. a[a.length - 1] - b[b.length - 1] : // Otherwise, it doesn't really make sense to rank non-siblings by index, // so they sort equally. 0; } function matchRouteBranch(branch, pathname) { let { routesMeta } = branch; let matchedParams = {}; let matchedPathname = "/"; let matches = []; for (let i = 0; i < routesMeta.length; ++i) { let meta = routesMeta[i]; let end = i === routesMeta.length - 1; let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/"; let match = matchPath({ path: meta.relativePath, caseSensitive: meta.caseSensitive, end }, remainingPathname); if (!match) return null; Object.assign(matchedParams, match.params); let route = meta.route; matches.push({ // TODO: Can this as be avoided? params: matchedParams, pathname: joinPaths([matchedPathname, match.pathname]), pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])), route }); if (match.pathnameBase !== "/") { matchedPathname = joinPaths([matchedPathname, match.pathnameBase]); } } return matches; } /** * Performs pattern matching on a URL pathname and returns information about * the match. * * @see https://reactrouter.com/docs/en/v6/utils/match-path */ function matchPath(pattern, pathname) { if (typeof pattern === "string") { pattern = { path: pattern, caseSensitive: false, end: true }; } let [matcher, paramNames] = compilePath(pattern.path, pattern.caseSensitive, pattern.end); let match = pathname.match(matcher); if (!match) return null; let matchedPathname = match[0]; let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1"); let captureGroups = match.slice(1); let params = paramNames.reduce((memo, paramName, index) => { // We need to compute the pathnameBase here using the raw splat value // instead of using params["*"] later because it will be decoded then if (paramName === "*") { let splatValue = captureGroups[index] || ""; pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1"); } memo[paramName] = safelyDecodeURIComponent(captureGroups[index] || "", paramName); return memo; }, {}); return { params, pathname: matchedPathname, pathnameBase, pattern }; } function compilePath(path, caseSensitive, end) { if (caseSensitive === void 0) { caseSensitive = false; } if (end === void 0) { end = true; } warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); let paramNames = []; let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below .replace(/^\/*/, "/") // Make sure it has a leading / .replace(/[\\.*+^$?{}|()[\]]/g, "\\$&") // Escape special regex chars .replace(/:(\w+)/g, (_, paramName) => { paramNames.push(paramName); return "([^\\/]+)"; }); if (path.endsWith("*")) { paramNames.push("*"); regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"] } else { regexpSource += end ? "\\/*$" // When matching to the end, ignore trailing slashes : // Otherwise, match a word boundary or a proceeding /. The word boundary restricts // parent routes to matching only their own words and nothing more, e.g. parent // route "/home" should not match "/home2". // Additionally, allow paths starting with `.`, `-`, `~`, and url-encoded entities, // but do not consume the character in the matched path so they can match against // nested paths. "(?:(?=[@.~-]|%[0-9A-F]{2})|\\b|\\/|$)"; } let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i"); return [matcher, paramNames]; } function safelyDecodeURIComponent(value, paramName) { try { return decodeURIComponent(value); } catch (error) { warning(false, "The value for the URL param \"" + paramName + "\" will not be decoded because" + (" the string \"" + value + "\" is a malformed URL segment. This is probably") + (" due to a bad percent encoding (" + error + ").")); return value; } } /** * @private */ function stripBasename(pathname, basename) { if (basename === "/") return pathname; if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) { return null; } // We want to leave trailing slash behavior in the user's control, so if they // specify a basename with a trailing slash, we should support it let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length; let nextChar = pathname.charAt(startIndex); if (nextChar && nextChar !== "/") { // pathname does not start with basename/ return null; } return pathname.slice(startIndex) || "/"; } function invariant$4(value, message) { if (value === false || value === null || typeof value === "undefined") { throw new Error(message); } } /** * @private */ function warning(cond, message) { if (!cond) { // eslint-disable-next-line no-console if (typeof console !== "undefined") console.warn(message); try { // Welcome to debugging React Router! // // This error is thrown as a convenience so you can more easily // find the source for a warning that appears in the console by // enabling "pause on exceptions" in your JavaScript debugger. throw new Error(message); // eslint-disable-next-line no-empty } catch (e) {} } } /** * Returns a resolved path object relative to the given pathname. * * @see https://reactrouter.com/docs/en/v6/utils/resolve-path */ function resolvePath(to, fromPathname) { if (fromPathname === void 0) { fromPathname = "/"; } let { pathname: toPathname, search = "", hash = "" } = typeof to === "string" ? parsePath(to) : to; let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname; return { pathname, search: normalizeSearch(search), hash: normalizeHash(hash) }; } function resolvePathname(relativePath, fromPathname) { let segments = fromPathname.replace(/\/+$/, "").split("/"); let relativeSegments = relativePath.split("/"); relativeSegments.forEach(segment => { if (segment === "..") { // Keep the root "" segment so the pathname starts at / if (segments.length > 1) segments.pop(); } else if (segment !== ".") { segments.push(segment); } }); return segments.length > 1 ? segments.join("/") : "/"; } /** * @private */ function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) { if (isPathRelative === void 0) { isPathRelative = false; } let to = typeof toArg === "string" ? parsePath(toArg) : _extends$3({}, toArg); let isEmptyPath = toArg === "" || to.pathname === ""; let toPathname = isEmptyPath ? "/" : to.pathname; let from; // Routing is relative to the current pathname if explicitly requested. // // If a pathname is explicitly provided in `to`, it should be relative to the // route context. This is explained in `Note on `` values` in our // migration guide from v5 as a means of disambiguation between `to` values // that begin with `/` and those that do not. However, this is problematic for // `to` values that do not provide a pathname. `to` can simply be a search or // hash string, in which case we should assume that the navigation is relative // to the current location's pathname and *not* the route pathname. if (isPathRelative || toPathname == null) { from = locationPathname; } else { let routePathnameIndex = routePathnames.length - 1; if (toPathname.startsWith("..")) { let toSegments = toPathname.split("/"); // Each leading .. segment means "go up one route" instead of "go up one // URL segment". This is a key difference from how works and a // major reason we call this a "to" value instead of a "href". while (toSegments[0] === "..") { toSegments.shift(); routePathnameIndex -= 1; } to.pathname = toSegments.join("/"); } // If there are more ".." segments than parent routes, resolve relative to // the root / URL. from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/"; } let path = resolvePath(to, from); // Ensure the pathname has a trailing slash if the original "to" had one let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/"); // Or if this was a link to the current path which has a trailing slash let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/"); if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) { path.pathname += "/"; } return path; } /** * @private */ const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/"); /** * @private */ const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/"); /** * @private */ const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search; /** * @private */ const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash; /** * @private * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies */ class ErrorResponse { constructor(status, statusText, data) { this.status = status; this.statusText = statusText || ""; this.data = data; } } /** * Check if the given error is an ErrorResponse generated from a 4xx/5xx * Response throw from an action/loader */ function isRouteErrorResponse(e) { return e instanceof ErrorResponse; } /** * React Router v6.4.0 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */ function _extends$2() { _extends$2 = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$2.apply(this, arguments); } // Contexts for data routers const DataStaticRouterContext = /*#__PURE__*/reactExports.createContext(null); const DataRouterContext = /*#__PURE__*/reactExports.createContext(null); const DataRouterStateContext = /*#__PURE__*/reactExports.createContext(null); const NavigationContext = /*#__PURE__*/reactExports.createContext(null); const LocationContext = /*#__PURE__*/reactExports.createContext(null); const RouteContext = /*#__PURE__*/reactExports.createContext({ outlet: null, matches: [] }); const RouteErrorContext = /*#__PURE__*/reactExports.createContext(null); /** * Returns the full href for the given "to" value. This is useful for building * custom links that are also accessible and preserve right-click behavior. * * @see https://reactrouter.com/docs/en/v6/hooks/use-href */ function useHref(to, _temp) { let { relative } = {} ; !useInRouterContext() ? invariant$4(false) : void 0; let { basename, navigator } = reactExports.useContext(NavigationContext); let { hash, pathname, search } = useResolvedPath(to, { relative }); let joinedPathname = pathname; // If we're operating within a basename, prepend it to the pathname prior // to creating the href. If this is a root navigation, then just use the raw // basename which allows the basename to have full control over the presence // of a trailing slash on root links if (basename !== "/") { joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]); } return navigator.createHref({ pathname: joinedPathname, search, hash }); } /** * Returns true if this component is a descendant of a . * * @see https://reactrouter.com/docs/en/v6/hooks/use-in-router-context */ function useInRouterContext() { return reactExports.useContext(LocationContext) != null; } /** * Returns the current location object, which represents the current URL in web * browsers. * * Note: If you're using this it may mean you're doing some of your own * "routing" in your app, and we'd like to know what your use case is. We may * be able to provide something higher-level to better suit your needs. * * @see https://reactrouter.com/docs/en/v6/hooks/use-location */ function useLocation() { !useInRouterContext() ? invariant$4(false) : void 0; return reactExports.useContext(LocationContext).location; } /** * Returns true if the URL for the given "to" value matches the current URL. * This is useful for components that need to know "active" state, e.g. * . * * @see https://reactrouter.com/docs/en/v6/hooks/use-match */ function useMatch(pattern) { !useInRouterContext() ? invariant$4(false) : void 0; let { pathname } = useLocation(); return reactExports.useMemo(() => matchPath(pattern, pathname), [pathname, pattern]); } /** * The interface for the navigate() function returned from useNavigate(). */ /** * When processing relative navigation we want to ignore ancestor routes that * do not contribute to the path, such that index/pathless layout routes don't * interfere. * * For example, when moving a route element into an index route and/or a * pathless layout route, relative link behavior contained within should stay * the same. Both of the following examples should link back to the root: * * * * * * * * }> // <-- Does not contribute * // <-- Does not contribute * * */ function getPathContributingMatches(matches) { return matches.filter((match, index) => index === 0 || !match.route.index && match.pathnameBase !== matches[index - 1].pathnameBase); } /** * Returns an imperative method for changing the location. Used by s, but * may also be used by other elements to change the location. * * @see https://reactrouter.com/docs/en/v6/hooks/use-navigate */ function useNavigate() { !useInRouterContext() ? invariant$4(false) : void 0; let { basename, navigator } = reactExports.useContext(NavigationContext); let { matches } = reactExports.useContext(RouteContext); let { pathname: locationPathname } = useLocation(); let routePathnamesJson = JSON.stringify(getPathContributingMatches(matches).map(match => match.pathnameBase)); let activeRef = reactExports.useRef(false); reactExports.useEffect(() => { activeRef.current = true; }); let navigate = reactExports.useCallback(function (to, options) { if (options === void 0) { options = {}; } if (!activeRef.current) return; if (typeof to === "number") { navigator.go(to); return; } let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path"); // If we're operating within a basename, prepend it to the pathname prior // to handing off to history. If this is a root navigation, then we // navigate to the raw basename which allows the basename to have full // control over the presence of a trailing slash on root links if (basename !== "/") { path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]); } (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options); }, [basename, navigator, routePathnamesJson, locationPathname]); return navigate; } /** * Returns an object of key/value pairs of the dynamic params from the current * URL that were matched by the route path. * * @see https://reactrouter.com/docs/en/v6/hooks/use-params */ function useParams() { let { matches } = reactExports.useContext(RouteContext); let routeMatch = matches[matches.length - 1]; return routeMatch ? routeMatch.params : {}; } /** * Resolves the pathname of the given `to` value against the current location. * * @see https://reactrouter.com/docs/en/v6/hooks/use-resolved-path */ function useResolvedPath(to, _temp2) { let { relative } = _temp2 === void 0 ? {} : _temp2; let { matches } = reactExports.useContext(RouteContext); let { pathname: locationPathname } = useLocation(); let routePathnamesJson = JSON.stringify(getPathContributingMatches(matches).map(match => match.pathnameBase)); return reactExports.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]); } /** * Returns the element of the route that matched the current location, prepared * with the correct context to render the remainder of the route tree. Route * elements in the tree must render an to render their child route's * element. * * @see https://reactrouter.com/docs/en/v6/hooks/use-routes */ function useRoutes(routes, locationArg) { !useInRouterContext() ? invariant$4(false) : void 0; let dataRouterStateContext = reactExports.useContext(DataRouterStateContext); let { matches: parentMatches } = reactExports.useContext(RouteContext); let routeMatch = parentMatches[parentMatches.length - 1]; let parentParams = routeMatch ? routeMatch.params : {}; routeMatch ? routeMatch.pathname : "/"; let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/"; routeMatch && routeMatch.route; let locationFromContext = useLocation(); let location; if (locationArg) { var _parsedLocationArg$pa; let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg; !(parentPathnameBase === "/" || ((_parsedLocationArg$pa = parsedLocationArg.pathname) == null ? void 0 : _parsedLocationArg$pa.startsWith(parentPathnameBase))) ? invariant$4(false) : void 0; location = parsedLocationArg; } else { location = locationFromContext; } let pathname = location.pathname || "/"; let remainingPathname = parentPathnameBase === "/" ? pathname : pathname.slice(parentPathnameBase.length) || "/"; let matches = matchRoutes(routes, { pathname: remainingPathname }); let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, { params: Object.assign({}, parentParams, match.params), pathname: joinPaths([parentPathnameBase, match.pathname]), pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase, match.pathnameBase]) })), parentMatches, dataRouterStateContext || undefined); // When a user passes in a `locationArg`, the associated routes need to // be wrapped in a new `LocationContext.Provider` in order for `useLocation` // to use the scoped location instead of the global location. if (locationArg) { return /*#__PURE__*/reactExports.createElement(LocationContext.Provider, { value: { location: _extends$2({ pathname: "/", search: "", hash: "", state: null, key: "default" }, location), navigationType: Action.Pop } }, renderedMatches); } return renderedMatches; } function DefaultErrorElement() { let error = useRouteError(); let message = isRouteErrorResponse(error) ? error.status + " " + error.statusText : error instanceof Error ? error.message : JSON.stringify(error); let stack = error instanceof Error ? error.stack : null; let lightgrey = "rgba(200,200,200, 0.5)"; let preStyles = { padding: "0.5rem", backgroundColor: lightgrey }; let codeStyles = { padding: "2px 4px", backgroundColor: lightgrey }; return /*#__PURE__*/reactExports.createElement(reactExports.Fragment, null, /*#__PURE__*/reactExports.createElement("h2", null, "Unhandled Thrown Error!"), /*#__PURE__*/reactExports.createElement("h3", { style: { fontStyle: "italic" } }, message), stack ? /*#__PURE__*/reactExports.createElement("pre", { style: preStyles }, stack) : null, /*#__PURE__*/reactExports.createElement("p", null, "\uD83D\uDCBF Hey developer \uD83D\uDC4B"), /*#__PURE__*/reactExports.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own\xA0", /*#__PURE__*/reactExports.createElement("code", { style: codeStyles }, "errorElement"), " props on\xA0", /*#__PURE__*/reactExports.createElement("code", { style: codeStyles }, ""))); } class RenderErrorBoundary extends reactExports.Component { constructor(props) { super(props); this.state = { location: props.location, error: props.error }; } static getDerivedStateFromError(error) { return { error: error }; } static getDerivedStateFromProps(props, state) { // When we get into an error state, the user will likely click "back" to the // previous page that didn't have an error. Because this wraps the entire // application, that will have no effect--the error page continues to display. // This gives us a mechanism to recover from the error when the location changes. // // Whether we're in an error state or not, we update the location in state // so that when we are in an error state, it gets reset when a new location // comes in and the user recovers from the error. if (state.location !== props.location) { return { error: props.error, location: props.location }; } // If we're not changing locations, preserve the location but still surface // any new errors that may come through. We retain the existing error, we do // this because the error provided from the app state may be cleared without // the location changing. return { error: props.error || state.error, location: state.location }; } componentDidCatch(error, errorInfo) { console.error("React Router caught the following error during render", error, errorInfo); } render() { return this.state.error ? /*#__PURE__*/reactExports.createElement(RouteErrorContext.Provider, { value: this.state.error, children: this.props.component }) : this.props.children; } } function RenderedRoute(_ref) { let { routeContext, match, children } = _ref; let dataStaticRouterContext = reactExports.useContext(DataStaticRouterContext); // Track how deep we got in our render pass to emulate SSR componentDidCatch // in a DataStaticRouter if (dataStaticRouterContext && match.route.errorElement) { dataStaticRouterContext._deepestRenderedBoundaryId = match.route.id; } return /*#__PURE__*/reactExports.createElement(RouteContext.Provider, { value: routeContext }, children); } function _renderMatches(matches, parentMatches, dataRouterState) { if (parentMatches === void 0) { parentMatches = []; } if (matches == null) { if (dataRouterState != null && dataRouterState.errors) { // Don't bail if we have data router errors so we can render them in the // boundary. Use the pre-matched (or shimmed) matches matches = dataRouterState.matches; } else { return null; } } let renderedMatches = matches; // If we have data errors, trim matches to the highest error boundary let errors = dataRouterState == null ? void 0 : dataRouterState.errors; if (errors != null) { let errorIndex = renderedMatches.findIndex(m => m.route.id && (errors == null ? void 0 : errors[m.route.id])); !(errorIndex >= 0) ? invariant$4(false) : void 0; renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1)); } return renderedMatches.reduceRight((outlet, match, index) => { let error = match.route.id ? errors == null ? void 0 : errors[match.route.id] : null; // Only data routers handle errors let errorElement = dataRouterState ? match.route.errorElement || /*#__PURE__*/reactExports.createElement(DefaultErrorElement, null) : null; let getChildren = () => /*#__PURE__*/reactExports.createElement(RenderedRoute, { match: match, routeContext: { outlet, matches: parentMatches.concat(renderedMatches.slice(0, index + 1)) } }, error ? errorElement : match.route.element !== undefined ? match.route.element : outlet); // Only wrap in an error boundary within data router usages when we have an // errorElement on this route. Otherwise let it bubble up to an ancestor // errorElement return dataRouterState && (match.route.errorElement || index === 0) ? /*#__PURE__*/reactExports.createElement(RenderErrorBoundary, { location: dataRouterState.location, component: errorElement, error: error, children: getChildren() }) : getChildren(); }, null); } var DataRouterHook; (function (DataRouterHook) { DataRouterHook["UseLoaderData"] = "useLoaderData"; DataRouterHook["UseActionData"] = "useActionData"; DataRouterHook["UseRouteError"] = "useRouteError"; DataRouterHook["UseNavigation"] = "useNavigation"; DataRouterHook["UseRouteLoaderData"] = "useRouteLoaderData"; DataRouterHook["UseMatches"] = "useMatches"; DataRouterHook["UseRevalidator"] = "useRevalidator"; })(DataRouterHook || (DataRouterHook = {})); function useDataRouterState(hookName) { let state = reactExports.useContext(DataRouterStateContext); !state ? invariant$4(false) : void 0; return state; } /** * Returns the nearest ancestor Route error, which could be a loader/action * error or a render error. This is intended to be called from your * errorElement to display a proper error message. */ function useRouteError() { var _state$errors; let error = reactExports.useContext(RouteErrorContext); let state = useDataRouterState(DataRouterHook.UseRouteError); let route = reactExports.useContext(RouteContext); let thisRoute = route.matches[route.matches.length - 1]; // If this was a render error, we put it in a RouteError context inside // of RenderErrorBoundary if (error) { return error; } !route ? invariant$4(false) : void 0; !thisRoute.route.id ? invariant$4(false) : void 0; // Otherwise look for errors from our data router state return (_state$errors = state.errors) == null ? void 0 : _state$errors[thisRoute.route.id]; } /** * Declares an element that should be rendered at a certain URL path. * * @see https://reactrouter.com/docs/en/v6/components/route */ function Route(_props) { invariant$4(false) ; } /** * Provides location context for the rest of the app. * * Note: You usually won't render a directly. Instead, you'll render a * router that is more specific to your environment such as a * in web browsers or a for server rendering. * * @see https://reactrouter.com/docs/en/v6/routers/router */ function Router(_ref4) { let { basename: basenameProp = "/", children = null, location: locationProp, navigationType = Action.Pop, navigator, static: staticProp = false } = _ref4; !!useInRouterContext() ? invariant$4(false) : void 0; // Preserve trailing slashes on basename, so we can let the user control // the enforcement of trailing slashes throughout the app let basename = basenameProp.replace(/^\/*/, "/"); let navigationContext = reactExports.useMemo(() => ({ basename, navigator, static: staticProp }), [basename, navigator, staticProp]); if (typeof locationProp === "string") { locationProp = parsePath(locationProp); } let { pathname = "/", search = "", hash = "", state = null, key = "default" } = locationProp; let location = reactExports.useMemo(() => { let trailingPathname = stripBasename(pathname, basename); if (trailingPathname == null) { return null; } return { pathname: trailingPathname, search, hash, state, key }; }, [basename, pathname, search, hash, state, key]); if (location == null) { return null; } return /*#__PURE__*/reactExports.createElement(NavigationContext.Provider, { value: navigationContext }, /*#__PURE__*/reactExports.createElement(LocationContext.Provider, { children: children, value: { location, navigationType } })); } /** * A container for a nested tree of elements that renders the branch * that best matches the current location. * * @see https://reactrouter.com/docs/en/v6/components/routes */ function Routes(_ref5) { let { children, location } = _ref5; let dataRouterContext = reactExports.useContext(DataRouterContext); // When in a DataRouterContext _without_ children, we use the router routes // directly. If we have children, then we're in a descendant tree and we // need to use child routes. let routes = dataRouterContext && !children ? dataRouterContext.router.routes : createRoutesFromChildren(children); return useRoutes(routes, location); } var AwaitRenderStatus; (function (AwaitRenderStatus) { AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending"; AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success"; AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error"; })(AwaitRenderStatus || (AwaitRenderStatus = {})); new Promise(() => {}); // UTILS /////////////////////////////////////////////////////////////////////////////// /** * Creates a route config from a React "children" object, which is usually * either a `` element or an array of them. Used internally by * `` to create a route config from its children. * * @see https://reactrouter.com/docs/en/v6/utils/create-routes-from-children */ function createRoutesFromChildren(children, parentPath) { if (parentPath === void 0) { parentPath = []; } let routes = []; reactExports.Children.forEach(children, (element, index) => { if (! /*#__PURE__*/reactExports.isValidElement(element)) { // Ignore non-elements. This allows people to more easily inline // conditionals in their route config. return; } if (element.type === reactExports.Fragment) { // Transparently support React.Fragment and its children. routes.push.apply(routes, createRoutesFromChildren(element.props.children, parentPath)); return; } !(element.type === Route) ? invariant$4(false) : void 0; let treePath = [...parentPath, index]; let route = { id: element.props.id || treePath.join("-"), caseSensitive: element.props.caseSensitive, element: element.props.element, index: element.props.index, path: element.props.path, loader: element.props.loader, action: element.props.action, errorElement: element.props.errorElement, hasErrorBoundary: element.props.errorElement != null, shouldRevalidate: element.props.shouldRevalidate, handle: element.props.handle }; if (element.props.children) { route.children = createRoutesFromChildren(element.props.children, treePath); } routes.push(route); }); return routes; } /** * React Router DOM v6.4.0 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */ /** * Creates a URLSearchParams object using the given initializer. * * This is identical to `new URLSearchParams(init)` except it also * supports arrays as values in the object form of the initializer * instead of just strings. This is convenient when you need multiple * values for a given key, but don't want to use an array initializer. * * For example, instead of: * * let searchParams = new URLSearchParams([ * ['sort', 'name'], * ['sort', 'price'] * ]); * * you can do: * * let searchParams = createSearchParams({ * sort: ['name', 'price'] * }); */ function createSearchParams(init) { if (init === void 0) { init = ""; } return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => { let value = init[key]; return memo.concat(Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]); }, [])); } function getSearchParamsForLocation(locationSearch, defaultSearchParams) { let searchParams = createSearchParams(locationSearch); for (let key of defaultSearchParams.keys()) { if (!searchParams.has(key)) { defaultSearchParams.getAll(key).forEach(value => { searchParams.append(key, value); }); } } return searchParams; } /** * A `` for use in web browsers. Provides the cleanest URLs. */ function BrowserRouter(_ref) { let { basename, children, window } = _ref; let historyRef = reactExports.useRef(); if (historyRef.current == null) { historyRef.current = createBrowserHistory({ window, v5Compat: true }); } let history = historyRef.current; let [state, setState] = reactExports.useState({ action: history.action, location: history.location }); reactExports.useLayoutEffect(() => history.listen(setState), [history]); return /*#__PURE__*/reactExports.createElement(Router, { basename: basename, children: children, location: state.location, navigationType: state.action, navigator: history }); } /** * A convenient wrapper for reading and writing search parameters via the * URLSearchParams interface. */ function useSearchParams(defaultInit) { let defaultSearchParamsRef = reactExports.useRef(createSearchParams(defaultInit)); let location = useLocation(); let searchParams = reactExports.useMemo(() => getSearchParamsForLocation(location.search, defaultSearchParamsRef.current), [location.search]); let navigate = useNavigate(); let setSearchParams = reactExports.useCallback((nextInit, navigateOptions) => { const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit); navigate("?" + newSearchParams, navigateOptions); }, [navigate, searchParams]); return [searchParams, setSearchParams]; } var missingAttachment = "edcc39b1702e4bd4b95e.svg"; /** * Tokenize input string. */ function lexer$1(str) { var tokens = []; var i = 0; while (i < str.length) { var char = str[i]; if (char === "*" || char === "+" || char === "?") { tokens.push({ type: "MODIFIER", index: i, value: str[i++] }); continue; } if (char === "\\") { tokens.push({ type: "ESCAPED_CHAR", index: i++, value: str[i++] }); continue; } if (char === "{") { tokens.push({ type: "OPEN", index: i, value: str[i++] }); continue; } if (char === "}") { tokens.push({ type: "CLOSE", index: i, value: str[i++] }); continue; } if (char === ":") { var name = ""; var j = i + 1; while (j < str.length) { var code = str.charCodeAt(j); if ( // `0-9` (code >= 48 && code <= 57) || // `A-Z` (code >= 65 && code <= 90) || // `a-z` (code >= 97 && code <= 122) || // `_` code === 95) { name += str[j++]; continue; } break; } if (!name) throw new TypeError("Missing parameter name at " + i); tokens.push({ type: "NAME", index: i, value: name }); i = j; continue; } if (char === "(") { var count = 1; var pattern = ""; var j = i + 1; if (str[j] === "?") { throw new TypeError("Pattern cannot start with \"?\" at " + j); } while (j < str.length) { if (str[j] === "\\") { pattern += str[j++] + str[j++]; continue; } if (str[j] === ")") { count--; if (count === 0) { j++; break; } } else if (str[j] === "(") { count++; if (str[j + 1] !== "?") { throw new TypeError("Capturing groups are not allowed at " + j); } } pattern += str[j++]; } if (count) throw new TypeError("Unbalanced pattern at " + i); if (!pattern) throw new TypeError("Missing pattern at " + i); tokens.push({ type: "PATTERN", index: i, value: pattern }); i = j; continue; } tokens.push({ type: "CHAR", index: i, value: str[i++] }); } tokens.push({ type: "END", index: i, value: "" }); return tokens; } /** * Parse a string for the raw tokens. */ function parse$7(str, options) { if (options === void 0) { options = {}; } var tokens = lexer$1(str); var _a = options.prefixes, prefixes = _a === void 0 ? "./" : _a; var defaultPattern = "[^" + escapeString(options.delimiter || "/#?") + "]+?"; var result = []; var key = 0; var i = 0; var path = ""; var tryConsume = function (type) { if (i < tokens.length && tokens[i].type === type) return tokens[i++].value; }; var mustConsume = function (type) { var value = tryConsume(type); if (value !== undefined) return value; var _a = tokens[i], nextType = _a.type, index = _a.index; throw new TypeError("Unexpected " + nextType + " at " + index + ", expected " + type); }; var consumeText = function () { var result = ""; var value; // tslint:disable-next-line while ((value = tryConsume("CHAR") || tryConsume("ESCAPED_CHAR"))) { result += value; } return result; }; while (i < tokens.length) { var char = tryConsume("CHAR"); var name = tryConsume("NAME"); var pattern = tryConsume("PATTERN"); if (name || pattern) { var prefix = char || ""; if (prefixes.indexOf(prefix) === -1) { path += prefix; prefix = ""; } if (path) { result.push(path); path = ""; } result.push({ name: name || key++, prefix: prefix, suffix: "", pattern: pattern || defaultPattern, modifier: tryConsume("MODIFIER") || "" }); continue; } var value = char || tryConsume("ESCAPED_CHAR"); if (value) { path += value; continue; } if (path) { result.push(path); path = ""; } var open = tryConsume("OPEN"); if (open) { var prefix = consumeText(); var name_1 = tryConsume("NAME") || ""; var pattern_1 = tryConsume("PATTERN") || ""; var suffix = consumeText(); mustConsume("CLOSE"); result.push({ name: name_1 || (pattern_1 ? key++ : ""), pattern: name_1 && !pattern_1 ? defaultPattern : pattern_1, prefix: prefix, suffix: suffix, modifier: tryConsume("MODIFIER") || "" }); continue; } mustConsume("END"); } return result; } /** * Compile a string to a template function for the path. */ function compile$1(str, options) { return tokensToFunction(parse$7(str, options), options); } /** * Expose a method for transforming tokens into the path function. */ function tokensToFunction(tokens, options) { if (options === void 0) { options = {}; } var reFlags = flags(options); var _a = options.encode, encode = _a === void 0 ? function (x) { return x; } : _a, _b = options.validate, validate = _b === void 0 ? true : _b; // Compile all the tokens into regexps. var matches = tokens.map(function (token) { if (typeof token === "object") { return new RegExp("^(?:" + token.pattern + ")$", reFlags); } }); return function (data) { var path = ""; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (typeof token === "string") { path += token; continue; } var value = data ? data[token.name] : undefined; var optional = token.modifier === "?" || token.modifier === "*"; var repeat = token.modifier === "*" || token.modifier === "+"; if (Array.isArray(value)) { if (!repeat) { throw new TypeError("Expected \"" + token.name + "\" to not repeat, but got an array"); } if (value.length === 0) { if (optional) continue; throw new TypeError("Expected \"" + token.name + "\" to not be empty"); } for (var j = 0; j < value.length; j++) { var segment = encode(value[j], token); if (validate && !matches[i].test(segment)) { throw new TypeError("Expected all \"" + token.name + "\" to match \"" + token.pattern + "\", but got \"" + segment + "\""); } path += token.prefix + segment + token.suffix; } continue; } if (typeof value === "string" || typeof value === "number") { var segment = encode(String(value), token); if (validate && !matches[i].test(segment)) { throw new TypeError("Expected \"" + token.name + "\" to match \"" + token.pattern + "\", but got \"" + segment + "\""); } path += token.prefix + segment + token.suffix; continue; } if (optional) continue; var typeOfMessage = repeat ? "an array" : "a string"; throw new TypeError("Expected \"" + token.name + "\" to be " + typeOfMessage); } return path; }; } /** * Escape a regular expression string. */ function escapeString(str) { return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, "\\$1"); } /** * Get the flags for a regexp from the options. */ function flags(options) { return options && options.sensitive ? "" : "i"; } /** * 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 */ var requiresPort = function required(port, protocol) { protocol = protocol.split(':')[0]; port = +port; if (!port) return false; switch (protocol) { case 'http': case 'ws': return port !== 80; case 'https': case 'wss': return port !== 443; case 'ftp': return port !== 21; case 'gopher': return port !== 70; case 'file': return false; } return port !== 0; }; var querystringify$1 = {}; var has$2 = Object.prototype.hasOwnProperty , undef; /** * Decode a URI encoded string. * * @param {String} input The URI encoded string. * @returns {String|Null} The decoded string. * @api private */ function decode$2(input) { try { return decodeURIComponent(input.replace(/\+/g, ' ')); } catch (e) { return null; } } /** * 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$3(input) { try { return encodeURIComponent(input); } catch (e) { return null; } } /** * 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; while (part = parser.exec(query)) { var key = decode$2(part[1]) , value = decode$2(part[2]); // // 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; } return result; } /** * 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 || ''; var pairs = [] , value , key; // // Optionally prefix with a '?' if needed // if ('string' !== typeof prefix) prefix = '?'; for (key in obj) { if (has$2.call(obj, key)) { value = obj[key]; // // 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 = ''; } key = encode$3(key); value = encode$3(value); // // 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); } } return pairs.length ? prefix + pairs.join('&') : ''; } // // Expose the module. // querystringify$1.stringify = querystringify; querystringify$1.parse = querystring; var required = requiresPort , qs$1 = querystringify$1 , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\// , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i , windowsDriveLetter = /^[a-zA-Z]:/ , whitespace$2 = '[\\x09\\x0A\\x0B\\x0C\\x0D\\x20\\xA0\\u1680\\u180E\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u202F\\u205F\\u3000\\u2028\\u2029\\uFEFF]' , left = new RegExp('^'+ whitespace$2 +'+'); /** * Trim a given string. * * @param {String} str String to trim. * @public */ function trimLeft(str) { return (str ? str : '').toString().replace(left, ''); } /** * These are the parse rules for the URL parser, it informs the parser * about: * * 0. The char it Needs to parse, if it's a string it should be done using * indexOf, RegExp using exec and NaN means set as current value. * 1. The property we should set when parsing this value. * 2. Indication if it's backwards or forward parsing, when set as number it's * the value of extra chars that should be split off. * 3. Inherit from location if non existing in the parser. * 4. `toLowerCase` the resulting value. */ var rules = [ ['#', 'hash'], // Extract from the back. ['?', 'query'], // Extract from the back. function sanitize(address, url) { // Sanitize what is left of the address return isSpecial$1(url.protocol) ? address.replace(/\\/g, '/') : address; }, ['/', 'pathname'], // Extract from the back. ['@', 'auth', 1], // Extract from the front. [NaN, 'host', undefined, 1, 1], // Set left over value. [/:(\d+)$/, 'port', undefined, 1], // RegExp the back. [NaN, 'hostname', undefined, 1, 1] // Set left over. ]; /** * These properties should not be copied or inherited from. This is only needed * for all non blob URL's as a blob URL does not include a hash, only the * origin. * * @type {Object} * @private */ var ignore$1 = { hash: 1, query: 1 }; /** * The location object differs when your code is loaded through a normal page, * Worker or through a worker using a blob. And with the blobble begins the * trouble as the location object will contain the URL of the blob, not the * location of the page where our code is loaded in. The actual origin is * encoded in the `pathname` so we can thankfully generate a good "default" * location from it so we can generate proper relative URL's again. * * @param {Object|String} loc Optional default location object. * @returns {Object} lolcation object. * @public */ function lolcation(loc) { var globalVar; if (typeof window !== 'undefined') globalVar = window; else if (typeof commonjsGlobal !== 'undefined') globalVar = commonjsGlobal; else if (typeof self !== 'undefined') globalVar = self; else globalVar = {}; var location = globalVar.location || {}; loc = loc || location; var finaldestination = {} , type = typeof loc , key; if ('blob:' === loc.protocol) { finaldestination = new Url(unescape(loc.pathname), {}); } else if ('string' === type) { finaldestination = new Url(loc, {}); for (key in ignore$1) delete finaldestination[key]; } else if ('object' === type) { for (key in loc) { if (key in ignore$1) continue; finaldestination[key] = loc[key]; } if (finaldestination.slashes === undefined) { finaldestination.slashes = slashes.test(loc.href); } } return finaldestination; } /** * Check whether a protocol scheme is special. * * @param {String} The protocol scheme of the URL * @return {Boolean} `true` if the protocol scheme is special, else `false` * @private */ function isSpecial$1(scheme) { return ( scheme === 'file:' || scheme === 'ftp:' || scheme === 'http:' || scheme === 'https:' || scheme === 'ws:' || scheme === 'wss:' ); } /** * @typedef ProtocolExtract * @type Object * @property {String} protocol Protocol matched in the URL, in lowercase. * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`. * @property {String} rest Rest of the URL that is not part of the protocol. */ /** * Extract protocol information from a URL with/without double slash ("//"). * * @param {String} address URL we want to extract from. * @param {Object} location * @return {ProtocolExtract} Extracted information. * @private */ function extractProtocol(address, location) { address = trimLeft(address); location = location || {}; var match = protocolre.exec(address); var protocol = match[1] ? match[1].toLowerCase() : ''; var forwardSlashes = !!match[2]; var otherSlashes = !!match[3]; var slashesCount = 0; var rest; if (forwardSlashes) { if (otherSlashes) { rest = match[2] + match[3] + match[4]; slashesCount = match[2].length + match[3].length; } else { rest = match[2] + match[4]; slashesCount = match[2].length; } } else { if (otherSlashes) { rest = match[3] + match[4]; slashesCount = match[3].length; } else { rest = match[4]; } } if (protocol === 'file:') { if (slashesCount >= 2) { rest = rest.slice(2); } } else if (isSpecial$1(protocol)) { rest = match[4]; } else if (protocol) { if (forwardSlashes) { rest = rest.slice(2); } } else if (slashesCount >= 2 && isSpecial$1(location.protocol)) { rest = match[4]; } return { protocol: protocol, slashes: forwardSlashes || isSpecial$1(protocol), slashesCount: slashesCount, rest: rest }; } /** * Resolve a relative URL pathname against a base URL pathname. * * @param {String} relative Pathname of the relative URL. * @param {String} base Pathname of the base URL. * @return {String} Resolved pathname. * @private */ function resolve(relative, base) { if (relative === '') return base; var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/')) , i = path.length , last = path[i - 1] , unshift = false , up = 0; while (i--) { if (path[i] === '.') { path.splice(i, 1); } else if (path[i] === '..') { path.splice(i, 1); up++; } else if (up) { if (i === 0) unshift = true; path.splice(i, 1); up--; } } if (unshift) path.unshift(''); if (last === '.' || last === '..') path.push(''); return path.join('/'); } /** * The actual URL instance. Instead of returning an object we've opted-in to * create an actual constructor as it's much more memory efficient and * faster and it pleases my OCD. * * It is worth noting that we should not use `URL` as class name to prevent * clashes with the global URL instance that got introduced in browsers. * * @constructor * @param {String} address URL we want to parse. * @param {Object|String} [location] Location defaults for relative paths. * @param {Boolean|Function} [parser] Parser for the query string. * @private */ function Url(address, location, parser) { address = trimLeft(address); if (!(this instanceof Url)) { return new Url(address, location, parser); } var relative, extracted, parse, instruction, index, key , instructions = rules.slice() , type = typeof location , url = this , i = 0; // // The following if statements allows this module two have compatibility with // 2 different API: // // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments // where the boolean indicates that the query string should also be parsed. // // 2. The `URL` interface of the browser which accepts a URL, object as // arguments. The supplied object will be used as default values / fall-back // for relative paths. // if ('object' !== type && 'string' !== type) { parser = location; location = null; } if (parser && 'function' !== typeof parser) parser = qs$1.parse; location = lolcation(location); // // Extract protocol information before running the instructions. // extracted = extractProtocol(address || '', location); relative = !extracted.protocol && !extracted.slashes; url.slashes = extracted.slashes || relative && location.slashes; url.protocol = extracted.protocol || location.protocol || ''; address = extracted.rest; // // When the authority component is absent the URL starts with a path // component. // if ( extracted.protocol === 'file:' && ( extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) || (!extracted.slashes && (extracted.protocol || extracted.slashesCount < 2 || !isSpecial$1(url.protocol))) ) { instructions[3] = [/(.*)/, 'pathname']; } for (; i < instructions.length; i++) { instruction = instructions[i]; if (typeof instruction === 'function') { address = instruction(address, url); continue; } parse = instruction[0]; key = instruction[1]; if (parse !== parse) { url[key] = address; } else if ('string' === typeof parse) { if (~(index = address.indexOf(parse))) { if ('number' === typeof instruction[2]) { url[key] = address.slice(0, index); address = address.slice(index + instruction[2]); } else { url[key] = address.slice(index); address = address.slice(0, index); } } } else if ((index = parse.exec(address))) { url[key] = index[1]; address = address.slice(0, index.index); } url[key] = url[key] || ( relative && instruction[3] ? location[key] || '' : '' ); // // Hostname, host and protocol should be lowercased so they can be used to // create a proper `origin`. // if (instruction[4]) url[key] = url[key].toLowerCase(); } // // Also parse the supplied query string in to an object. If we're supplied // with a custom parser as function use that instead of the default build-in // parser. // if (parser) url.query = parser(url.query); // // If the URL is relative, resolve the pathname against the base URL. // if ( relative && location.slashes && url.pathname.charAt(0) !== '/' && (url.pathname !== '' || location.pathname !== '') ) { url.pathname = resolve(url.pathname, location.pathname); } // // Default to a / for pathname if none exists. This normalizes the URL // to always have a / // if (url.pathname.charAt(0) !== '/' && isSpecial$1(url.protocol)) { url.pathname = '/' + url.pathname; } // // We should not add port numbers if they are already the default port number // for a given protocol. As the host also contains the port number we're going // override it with the hostname which contains no port number. // if (!required(url.port, url.protocol)) { url.host = url.hostname; url.port = ''; } // // Parse down the `auth` for the username and password. // url.username = url.password = ''; if (url.auth) { instruction = url.auth.split(':'); url.username = instruction[0] || ''; url.password = instruction[1] || ''; } url.origin = url.protocol !== 'file:' && isSpecial$1(url.protocol) && url.host ? url.protocol +'//'+ url.host : 'null'; // // The href is just the compiled result. // url.href = url.toString(); } /** * This is convenience method for changing properties in the URL instance to * insure that they all propagate correctly. * * @param {String} part Property we need to adjust. * @param {Mixed} value The newly assigned value. * @param {Boolean|Function} fn When setting the query, it will be the function * used to parse the query. * When setting the protocol, double slash will be * removed from the final url if it is true. * @returns {URL} URL instance for chaining. * @public */ function set$2(part, value, fn) { var url = this; switch (part) { case 'query': if ('string' === typeof value && value.length) { value = (fn || qs$1.parse)(value); } url[part] = value; break; case 'port': url[part] = value; if (!required(value, url.protocol)) { url.host = url.hostname; url[part] = ''; } else if (value) { url.host = url.hostname +':'+ value; } break; case 'hostname': url[part] = value; if (url.port) value += ':'+ url.port; url.host = value; break; case 'host': url[part] = value; if (/:\d+$/.test(value)) { value = value.split(':'); url.port = value.pop(); url.hostname = value.join(':'); } else { url.hostname = value; url.port = ''; } break; case 'protocol': url.protocol = value.toLowerCase(); url.slashes = !fn; break; case 'pathname': case 'hash': if (value) { var char = part === 'pathname' ? '/' : '#'; url[part] = value.charAt(0) !== char ? char + value : value; } else { url[part] = value; } break; default: url[part] = value; } for (var i = 0; i < rules.length; i++) { var ins = rules[i]; if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase(); } url.origin = url.protocol !== 'file:' && isSpecial$1(url.protocol) && url.host ? url.protocol +'//'+ url.host : 'null'; url.href = url.toString(); return url; } /** * Transform the properties back in to a valid and full URL string. * * @param {Function} stringify Optional query stringify function. * @returns {String} Compiled version of the URL. * @public */ function toString$1(stringify) { if (!stringify || 'function' !== typeof stringify) stringify = qs$1.stringify; var query , url = this , protocol = url.protocol; if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':'; var result = protocol + (url.slashes || isSpecial$1(url.protocol) ? '//' : ''); if (url.username) { result += url.username; if (url.password) result += ':'+ url.password; result += '@'; } result += url.host + url.pathname; query = 'object' === typeof url.query ? stringify(url.query) : url.query; if (query) result += '?' !== query.charAt(0) ? '?'+ query : query; if (url.hash) result += url.hash; return result; } Url.prototype = { set: set$2, toString: toString$1 }; // // Expose the URL parser and some additional properties that might be useful for // others or testing. // Url.extractProtocol = extractProtocol; Url.location = lolcation; Url.trimLeft = trimLeft; Url.qs = qs$1; var urlParse = Url; var urlParse$1 = /*@__PURE__*/getDefaultExportFromCjs(urlParse); function vhostUrlForProject(projectName) { const baseHost = urlParse$1(env.HOME_URL).hostname; const basePort = urlParse$1(env.HOME_URL).port; if (basePort) { return new URL(`https://${projectName}.${baseHost}:${basePort}`); } else { return new URL(`https://${projectName}.${baseHost}`); } } function mainDomain( path, args ) { return new URL(compile$1(path)(args), env.HOME_URL); } function apiV1( path, args ) { return new URL( `.${compile$1(path)(args)}`, new URL("/api/v1/", env.HOME_URL) ); } function relationshipAction( path, args ) { return new URL( `.${compile$1(path)(args)}`, new URL("/rc/relationships/", env.HOME_URL) ); } function projectSubdomain( path, args ) { return new URL( compile$1(path)(args), vhostUrlForProject(args.projectHandle) ); } const patterns = { public: { home: "/", dashboard: "/rc/dashboard", welcome: "/rc/welcome", login: "/rc/login", logout: "/rc/logout", signup: "/rc/signup", createProject: "/rc/project/create", switchProject: "/rc/project/switch", settingsMain: "/rc/user/settings", silencedPosts: "/rc/user/silenced-posts", verifyEmail: "/rc/verify_email", cancelVerifyEmail: "/rc/cancel_verify_email", resetPassword: "/rc/reset_password", staticContent: "/rc/content/:slug", search: "/rc/search", composePost: "/rc/post/compose", redirectToAttachment: "/rc/attachment-redirect/:attachmentId", apiV1: { createProject: "/project", getProject: "/project/:projectHandle", updateProject: "/versions", getFollowingState: "/project/:projectHandle/following", getProjectPosts: "/project/:projectHandle/posts", createPost: "/project/:projectHandle/posts", updatePost: "/project/:projectHandle/posts/:postId", getCommentsForPost: "/project_post/:postId/comments", // hit by eggbug.rs startAttachment: "/project/:projectHandle/posts/:postId/attach/start", // hit by eggbug.rs finishAttachment: "/project/:projectHandle/posts/:postId/attach/finish/:attachmentId", redirectToAttachment: "/attachments/:attachmentId", changePostState: "/project/:projectHandle/posts/:postId/:operation", listEditedProjects: "/projects/edited", createComment: "/comments", editDeleteComment: "/comments/:commentId", register: "/register", changePassword: "/change-password", requestPasswordReset: "/reset-password", /** @deprecated */ login: "/login", /** @deprecated */ logout: "/logout", checkEmail: "/register/check-email", projects: { followers: "/projects/followers", }, moderation: { changeSettings: "/moderation/settings", grantOrRevokePermission: "/moderation/permission", }, notifications: { list: "/notifications/list", }, reporting: { listReasons: "/reporting/reasons", reportPost: "/reporting/report-post", }, trpc: "/trpc", }, unleashProxy: "/api/unleash-proxy", relationshipAction: "/:fromEntityType-:fromEntityId/to-:toEntityType-:toEntityId/:operation", tags: "/rc/tagged/:tagSlug", bookmarkedTagFeed: "/rc/bookmarks", likedPosts: "/rc/liked-posts", project: { home: "/", mainAppProfile: "/:projectHandle", profileEdit: "/rc/project/edit", followers: "/rc/project/followers", following: "/rc/project/following", notifications: "/rc/project/notifications", followRequests: "/:projectHandle/follow-requests", composePost: "/:projectHandle/post/compose", editPost: "/:projectHandle/post/:filename/edit", singlePost: { published: "/:projectHandle/post/:filename", unpublished: "/:projectHandle/post/:filename/:draftNonce", }, unpublishedPosts: "/rc/posts/unpublished", subdomainTags: "/tagged/:tagSlug", tags: "/:projectHandle/tagged/:tagSlug", rss: { publicRss: "/:projectHandle/rss/public.rss", publicAtom: "/:projectHandle/rss/public.atom", publicJson: "/:projectHandle/rss/public.json", }, defaultAvatar: "/rc/default-avatar/:projectId.png", settings: "/rc/project/settings", ask: "/:projectHandle/ask", inbox: "/rc/project/inbox", }, invites: { manage: "/rc/moderation/invites/manage", activate: "/rc/activate", create: "/rc/moderation/invites/create", }, moderation: { home: "/rc/moderation", manageArtistAlleyListing: "/rc/moderation/manage-artist-alley-listing", manageAsk: "/rc/moderation/manage-ask", managePage: "/rc/moderation/manage-project", managePost: "/rc/moderation/manage-post", manageUser: "/rc/moderation/manage-user", cacheMaintenance: "/rc/moderation/cache-maintenance", bulkActivate: "/rc/moderation/bulk-activate", createOAuthClient: "/rc/moderation/create-oauth-client", artistAlleyPendingQueue: "/rc/moderation/artist-alley/pending", tagOntology: { manageTags: "/rc/moderation/tag-ontology/manage-tags", pendingRequests: "/rc/moderation/tag-ontology/pending-requests", }, }, subscriptions: { createCheckoutSession: "/rc/subscriptions/create-checkout-session", // POST createPortalSession: "/rc/subscriptions/create-portal-session", // POST, success: "/rc/subscriptions/success", cancelled: "/rc/subscriptions/cancelled", }, artistAlley: { home: "/rc/artist-alley", success: "/rc/artist-alley/success/:sessionId", cancelled: "/rc/artist-alley/cancelled/:sessionId", create: "/rc/artist-alley/create", ownerManage: "/rc/artist-alley/manage-listings", }, }, } ; const sitemap = { public: { home: (args ) => { const url = mainDomain(patterns.public.home, {}); const params = new URLSearchParams(); if (args?.refTimestamp !== undefined) { params.set("refTimestamp", args.refTimestamp.toString()); } if (args?.skipPosts !== undefined) { params.set("skipPosts", args.skipPosts.toString()); } url.search = params.toString(); return url; }, dashboard: (args ) => { const url = mainDomain(patterns.public.dashboard, {}); const params = new URLSearchParams(); if (args?.refTimestamp !== undefined) { params.set("refTimestamp", args.refTimestamp.toString()); } if (args?.skipPosts !== undefined) { params.set("skipPosts", args.skipPosts.toString()); } url.search = params.toString(); return url; }, welcome: () => mainDomain(patterns.public.welcome, {}), login: (args) => { const url = mainDomain(patterns.public.login, {}); if (args?.originalUrl) { const searchParams = new URLSearchParams(); searchParams.set("originalUrl", args.originalUrl); url.search = searchParams.toString(); } return url; }, logout: () => mainDomain(patterns.public.logout, {}), signup: () => mainDomain(patterns.public.signup, {}), createProject: () => mainDomain(patterns.public.createProject, {}), switchProject: () => mainDomain(patterns.public.switchProject, {}), userSettings: () => mainDomain(patterns.public.settingsMain, {}), silencedPosts: (args) => { const url = mainDomain(patterns.public.silencedPosts, {}); const params = new URLSearchParams(); if (args?.beforeTime !== undefined) { params.set("beforeTime", args.beforeTime.toString()); } if (args?.afterTime !== undefined) { params.set("afterTime", args.afterTime.toString()); } url.search = params.toString(); return url; }, verifyEmail: ({ userId, nonce }) => { const url = mainDomain(patterns.public.verifyEmail, {}); url.search = new URLSearchParams({ userId: userId.toString(), nonce, }).toString(); return url; }, cancelVerifyEmail: ({ userId, nonce, } ) => { const url = mainDomain(patterns.public.cancelVerifyEmail, {}); url.search = new URLSearchParams({ userId: userId.toString(), nonce, }).toString(); return url; }, redirectToAttachment: (args) => mainDomain(patterns.public.redirectToAttachment, args), resetPassword: ({ email, nonce, } ) => { const url = mainDomain(patterns.public.resetPassword, {}); if (email && nonce) { url.search = new URLSearchParams({ email, nonce, }).toString(); } return url; }, staticContent: (args) => mainDomain(patterns.public.staticContent, args), static: { staticAsset: (args) => { let path = args.path; return `../../static/${path}`; }, }, apiV1: { createProject: () => apiV1(patterns.public.apiV1.createProject, {}), getProject: (args) => apiV1(patterns.public.apiV1.getProject, args), updateProject: () => apiV1(patterns.public.apiV1.updateProject, {}), getFollowingState: (args) => apiV1(patterns.public.apiV1.getFollowingState, args), updatePost: (args ) => apiV1(patterns.public.apiV1.updatePost, args), startAttachment: (args ) => apiV1(patterns.public.apiV1.startAttachment, args), finishAttachment: (args ) => apiV1(patterns.public.apiV1.finishAttachment, args), listEditedProjects: () => apiV1(patterns.public.apiV1.listEditedProjects, {}), createComment: () => apiV1(patterns.public.apiV1.createComment, {}), editDeleteComment: (args) => apiV1(patterns.public.apiV1.editDeleteComment, args), register: () => apiV1(patterns.public.apiV1.register, {}), changePassword: () => apiV1(patterns.public.apiV1.changePassword, {}), requestPasswordReset: () => apiV1(patterns.public.apiV1.requestPasswordReset, {}), /** @deprecated */ login: () => apiV1(patterns.public.apiV1.login, {}), /** @deprecated */ logout: () => apiV1(patterns.public.apiV1.logout, {}), checkEmail: () => apiV1(patterns.public.apiV1.checkEmail, {}), projects: { followers: ({ offset = 0, limit = 10, } ) => { const url = apiV1( patterns.public.apiV1.projects.followers, {} ); url.search = new URLSearchParams({ offset: offset.toString(), limit: limit.toString(), }).toString(); return url; }, }, moderation: { changeSettings: () => apiV1(patterns.public.apiV1.moderation.changeSettings, {}), grantOrRevokePermission: () => apiV1( patterns.public.apiV1.moderation .grantOrRevokePermission, {} ), }, reporting: { listReasons: () => apiV1(patterns.public.apiV1.reporting.listReasons, {}), reportPost: () => apiV1(patterns.public.apiV1.reporting.reportPost, {}), }, trpc: () => apiV1(patterns.public.apiV1.trpc, {}), }, unleashProxy: () => mainDomain(patterns.public.unleashProxy, {}), relationshipAction: ( args ) => relationshipAction(patterns.public.relationshipAction, args), tags: ( args ) => { const url = mainDomain(patterns.public.tags, { tagSlug: encodeURIComponent(args.tagSlug), }); const params = new URLSearchParams(); if (args?.show18PlusPosts !== undefined) { params.set("show18PlusPosts", args.show18PlusPosts.toString()); } if (args?.refTimestamp !== undefined) { params.set("refTimestamp", args.refTimestamp.toString()); } if (args?.skipPosts !== undefined) { params.set("skipPosts", args.skipPosts.toString()); } url.search = params.toString(); return url; }, bookmarkedTagFeed: ( args ) => { const url = mainDomain(patterns.public.bookmarkedTagFeed, {}); const params = new URLSearchParams(); if (args?.show18PlusPosts !== undefined) { params.set("show18PlusPosts", args.show18PlusPosts.toString()); } if (args?.beforeTime !== undefined) { params.set("beforeTime", args.beforeTime.toString()); } if (args?.afterTime !== undefined) { params.set("afterTime", args.afterTime.toString()); } url.search = params.toString(); return url; }, likedPosts: (args) => { const url = mainDomain(patterns.public.likedPosts, {}); const params = new URLSearchParams(); if (args?.refTimestamp !== undefined) { params.set("refTimestamp", args.refTimestamp.toString()); } if (args?.skipPosts !== undefined) { params.set("skipPosts", args.skipPosts.toString()); } url.search = params.toString(); return url; }, composePost: (args ) => { const url = mainDomain(patterns.public.composePost, args); const params = new URLSearchParams(); if (args?.shareOfPostId !== undefined) { params.set("shareOfPostId", args.shareOfPostId.toString()); } if (args?.responseToAskId !== undefined) { params.set("responseToAskId", args.responseToAskId.toString()); } url.search = params.toString(); return url; }, project: { home: (args) => projectSubdomain(patterns.public.project.home, args), mainAppProfile: (args) => mainDomain(patterns.public.project.mainAppProfile, args), profileEdit: () => mainDomain(patterns.public.project.profileEdit, {}), followers: () => mainDomain(patterns.public.project.followers, {}), following: () => mainDomain(patterns.public.project.following, {}), notifications: () => mainDomain(patterns.public.project.notifications, {}), followRequests: (args) => mainDomain(patterns.public.project.followRequests, args), composePost: (args ) => { const url = mainDomain( patterns.public.project.composePost, args ); const params = new URLSearchParams(); if (args?.shareOfPostId !== undefined) { params.set("shareOfPostId", args.shareOfPostId.toString()); } if (args?.responseToAskId !== undefined) { params.set( "responseToAskId", args.responseToAskId.toString() ); } url.search = params.toString(); return url; }, editPost: (args ) => mainDomain(patterns.public.project.editPost, args), singlePost: { published: (args ) => { const url = mainDomain( patterns.public.project.singlePost.published, args ); if (args.commentId) { url.hash = `comment-${args.commentId}`; } return url; }, unpublished: (args ) => mainDomain( patterns.public.project.singlePost.unpublished, args ), }, unpublishedPosts: (args) => { const url = mainDomain( patterns.public.project.unpublishedPosts, {} ); const params = new URLSearchParams(); if (args?.refTimestamp !== undefined) { params.set("refTimestamp", args.refTimestamp.toString()); } if (args?.skipPosts !== undefined) { params.set("skipPosts", args.skipPosts.toString()); } url.search = params.toString(); return url; }, ask: (args) => mainDomain(patterns.public.project.ask, args), inbox: () => mainDomain(patterns.public.project.inbox, {}), rss: { publicRss: (args ) => { const url = mainDomain( patterns.public.project.rss.publicRss, args ); if (args.page !== undefined) { const params = new URLSearchParams({ page: args.page.toString(), }); url.search = `?${params.toString()}`; } return url; }, publicAtom: (args ) => { const url = mainDomain( patterns.public.project.rss.publicAtom, args ); if (args.page !== undefined) { const params = new URLSearchParams({ page: args.page.toString(), }); url.search = `?${params.toString()}`; } return url; }, publicJson: (args ) => { const url = mainDomain( patterns.public.project.rss.publicJson, args ); if (args.page !== undefined) { const params = new URLSearchParams({ page: args.page.toString(), }); url.search = `?${params.toString()}`; } return url; }, }, tags: ( args ) => { const url = mainDomain(patterns.public.project.tags, { tagSlug: encodeURIComponent(args.tagSlug), projectHandle: args.projectHandle, }); const params = new URLSearchParams(); if (args?.refTimestamp !== undefined) { params.set("refTimestamp", args.refTimestamp.toString()); } if (args?.skipPosts !== undefined) { params.set("skipPosts", args.skipPosts.toString()); } url.search = params.toString(); return url; }, defaultAvatar: (args) => mainDomain(patterns.public.project.defaultAvatar, args), settings: () => mainDomain(patterns.public.project.settings, {}), }, invites: { manage: () => mainDomain(patterns.public.invites.manage, {}), activate: (args) => { const url = mainDomain(patterns.public.invites.activate, args); const params = new URLSearchParams({ inviteId: args.inviteId, }); url.search = `?${params.toString()}`; return url; }, create: () => mainDomain(patterns.public.invites.create, {}), }, moderation: { home: () => mainDomain(patterns.public.moderation.home, {}), manageUser: (args) => { const url = mainDomain( patterns.public.moderation.manageUser, args ); const params = new URLSearchParams(); if (args.userId) { params.set("userId", args.userId.toString()); } else if (args.email) { params.set("email", args.email); } url.search = `?${params.toString()}`; return url; }, managePost: (args) => { const url = mainDomain( patterns.public.moderation.managePost, args ); const params = new URLSearchParams({ postId: args.postId.toString(), }); url.search = `?${params.toString()}`; return url; }, manageProject: (args) => { const url = mainDomain( patterns.public.moderation.managePage, {} ); if (args.projectHandle) { const params = new URLSearchParams({ handle: args.projectHandle, }); url.search = `?${params.toString()}`; } return url; }, manageArtistAlleyListing: (args) => { const url = mainDomain( patterns.public.moderation.manageArtistAlleyListing, {} ); const params = new URLSearchParams({ adId: args.adId, }); url.search = `?${params.toString()}`; return url; }, cacheMaintenance: () => mainDomain(patterns.public.moderation.cacheMaintenance, {}), bulkActivate: () => mainDomain(patterns.public.moderation.bulkActivate, {}), createOAuthClient: () => mainDomain(patterns.public.moderation.createOAuthClient, {}), manageAsk: (args) => { const url = mainDomain( patterns.public.moderation.manageAsk, {} ); if (args.askId) { const params = new URLSearchParams({ askId: args.askId, }); url.search = `?${params.toString()}`; } return url; }, artistAlleyPendingQueue: () => mainDomain( patterns.public.moderation.artistAlleyPendingQueue, {} ), tagOntology: { manageTags: () => mainDomain( patterns.public.moderation.tagOntology.manageTags, {} ), pendingRequests: () => mainDomain( patterns.public.moderation.tagOntology.pendingRequests, {} ), }, }, subscriptions: { createCheckoutSession: () => mainDomain( patterns.public.subscriptions.createCheckoutSession, {} ), createPortalSession: () => mainDomain( patterns.public.subscriptions.createPortalSession, {} ), success: (args) => { const url = mainDomain( patterns.public.subscriptions.success, {} ); const params = new URLSearchParams({ sessionId: args.sessionId, }); url.search = `?${params.toString()}`; return url; }, cancelled: (args) => { const url = mainDomain( patterns.public.subscriptions.cancelled, {} ); const params = new URLSearchParams({ sessionId: args.sessionId, }); url.search = `?${params.toString()}`; return url; }, manage: () => { const url = sitemap.public.userSettings(); url.hash = "cohost-plus"; return url; }, }, search: (args = {}) => { const url = mainDomain(patterns.public.search, {}); if (args.query) { const params = new URLSearchParams({ q: args.query, }); url.search = `?${params.toString()}`; } return url; }, artistAlley: { home: () => mainDomain(patterns.public.artistAlley.home, {}), success: (args) => { return mainDomain(patterns.public.artistAlley.success, args); }, cancelled: (args) => { return mainDomain(patterns.public.artistAlley.cancelled, args); }, create: () => mainDomain(patterns.public.artistAlley.create, {}), ownerManage: () => mainDomain(patterns.public.artistAlley.ownerManage, {}), }, }, } ; class Subscribable { constructor() { this.listeners = []; this.subscribe = this.subscribe.bind(this); } subscribe(listener) { this.listeners.push(listener); this.onSubscribe(); return () => { this.listeners = this.listeners.filter(x => x !== listener); this.onUnsubscribe(); }; } hasListeners() { return this.listeners.length > 0; } onSubscribe() {// Do nothing } onUnsubscribe() {// Do nothing } } // TYPES // UTILS const isServer = typeof window === 'undefined' || 'Deno' in window; function noop$5() { return undefined; } function functionalUpdate(updater, input) { return typeof updater === 'function' ? updater(input) : updater; } function isValidTimeout(value) { return typeof value === 'number' && value >= 0 && value !== Infinity; } function difference(array1, array2) { return array1.filter(x => array2.indexOf(x) === -1); } function replaceAt(array, index, value) { const copy = array.slice(0); copy[index] = value; return copy; } function timeUntilStale(updatedAt, staleTime) { return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0); } function parseQueryArgs(arg1, arg2, arg3) { if (!isQueryKey(arg1)) { return arg1; } if (typeof arg2 === 'function') { return { ...arg3, queryKey: arg1, queryFn: arg2 }; } return { ...arg2, queryKey: arg1 }; } function parseMutationArgs(arg1, arg2, arg3) { if (isQueryKey(arg1)) { return { ...arg2, mutationKey: arg1 }; } if (typeof arg1 === 'function') { return { ...arg2, mutationFn: arg1 }; } return { ...arg1 }; } function parseFilterArgs(arg1, arg2, arg3) { return isQueryKey(arg1) ? [{ ...arg2, queryKey: arg1 }, arg3] : [arg1 || {}, arg2]; } function matchQuery(filters, query) { const { type = 'all', exact, fetchStatus, predicate, queryKey, stale } = filters; if (isQueryKey(queryKey)) { if (exact) { if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) { return false; } } else if (!partialMatchKey(query.queryKey, queryKey)) { return false; } } if (type !== 'all') { const isActive = query.isActive(); if (type === 'active' && !isActive) { return false; } if (type === 'inactive' && isActive) { return false; } } if (typeof stale === 'boolean' && query.isStale() !== stale) { return false; } if (typeof fetchStatus !== 'undefined' && fetchStatus !== query.state.fetchStatus) { return false; } if (predicate && !predicate(query)) { return false; } return true; } function matchMutation(filters, mutation) { const { exact, fetching, predicate, mutationKey } = filters; if (isQueryKey(mutationKey)) { if (!mutation.options.mutationKey) { return false; } if (exact) { if (hashQueryKey$1(mutation.options.mutationKey) !== hashQueryKey$1(mutationKey)) { return false; } } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) { return false; } } if (typeof fetching === 'boolean' && mutation.state.status === 'loading' !== fetching) { return false; } if (predicate && !predicate(mutation)) { return false; } return true; } function hashQueryKeyByOptions(queryKey, options) { const hashFn = (options == null ? void 0 : options.queryKeyHashFn) || hashQueryKey$1; return hashFn(queryKey); } /** * Default query keys hash function. * Hashes the value into a stable hash. */ function hashQueryKey$1(queryKey) { return JSON.stringify(queryKey, (_, val) => isPlainObject$4(val) ? Object.keys(val).sort().reduce((result, key) => { result[key] = val[key]; return result; }, {}) : val); } /** * Checks if key `b` partially matches with key `a`. */ function partialMatchKey(a, b) { return partialDeepEqual(a, b); } /** * Checks if `b` partially matches with `a`. */ function partialDeepEqual(a, b) { if (a === b) { return true; } if (typeof a !== typeof b) { return false; } if (a && b && typeof a === 'object' && typeof b === 'object') { return !Object.keys(b).some(key => !partialDeepEqual(a[key], b[key])); } return false; } /** * This function returns `a` if `b` is deeply equal. * If not, it will replace any deeply equal children of `b` with those of `a`. * This can be used for structural sharing between JSON values for example. */ function replaceEqualDeep(a, b) { if (a === b) { return a; } const array = isPlainArray(a) && isPlainArray(b); if (array || isPlainObject$4(a) && isPlainObject$4(b)) { const aSize = array ? a.length : Object.keys(a).length; const bItems = array ? b : Object.keys(b); const bSize = bItems.length; const copy = array ? [] : {}; let equalItems = 0; for (let i = 0; i < bSize; i++) { const key = array ? i : bItems[i]; copy[key] = replaceEqualDeep(a[key], b[key]); if (copy[key] === a[key]) { equalItems++; } } return aSize === bSize && equalItems === aSize ? a : copy; } return b; } /** * Shallow compare objects. Only works with objects that always have the same properties. */ function shallowEqualObjects(a, b) { if (a && !b || b && !a) { return false; } for (const key in a) { if (a[key] !== b[key]) { return false; } } return true; } function isPlainArray(value) { return Array.isArray(value) && value.length === Object.keys(value).length; } // Copied from: https://github.com/jonschlinkert/is-plain-object function isPlainObject$4(o) { if (!hasObjectPrototype(o)) { return false; } // If has modified constructor const ctor = o.constructor; if (typeof ctor === 'undefined') { return true; } // If has modified prototype const prot = ctor.prototype; if (!hasObjectPrototype(prot)) { return false; } // If constructor does not have an Object-specific method if (!prot.hasOwnProperty('isPrototypeOf')) { return false; } // Most likely a plain Object return true; } function hasObjectPrototype(o) { return Object.prototype.toString.call(o) === '[object Object]'; } function isQueryKey(value) { return Array.isArray(value); } function sleep(timeout) { return new Promise(resolve => { setTimeout(resolve, timeout); }); } /** * Schedules a microtask. * This can be useful to schedule state updates after rendering. */ function scheduleMicrotask(callback) { sleep(0).then(callback); } function getAbortController$1() { if (typeof AbortController === 'function') { return new AbortController(); } return; } function replaceData(prevData, data, options) { // Use prev data if an isDataEqual function is defined and returns `true` if (options.isDataEqual != null && options.isDataEqual(prevData, data)) { return prevData; } else if (typeof options.structuralSharing === 'function') { return options.structuralSharing(prevData, data); } else if (options.structuralSharing !== false) { // Structurally share data between prev and new data if needed return replaceEqualDeep(prevData, data); } return data; } class FocusManager extends Subscribable { constructor() { super(); this.setup = onFocus => { // addEventListener does not exist in React Native, but window does // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!isServer && window.addEventListener) { const listener = () => onFocus(); // Listen to visibillitychange and focus window.addEventListener('visibilitychange', listener, false); window.addEventListener('focus', listener, false); return () => { // Be sure to unsubscribe if a new handler is set window.removeEventListener('visibilitychange', listener); window.removeEventListener('focus', listener); }; } return; }; } onSubscribe() { if (!this.cleanup) { this.setEventListener(this.setup); } } onUnsubscribe() { if (!this.hasListeners()) { var _this$cleanup; (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this); this.cleanup = undefined; } } setEventListener(setup) { var _this$cleanup2; this.setup = setup; (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this); this.cleanup = setup(focused => { if (typeof focused === 'boolean') { this.setFocused(focused); } else { this.onFocus(); } }); } setFocused(focused) { this.focused = focused; if (focused) { this.onFocus(); } } onFocus() { this.listeners.forEach(listener => { listener(); }); } isFocused() { if (typeof this.focused === 'boolean') { return this.focused; } // document global can be unavailable in react native if (typeof document === 'undefined') { return true; } return [undefined, 'visible', 'prerender'].includes(document.visibilityState); } } const focusManager = new FocusManager(); // TYPES // FUNCTIONS function hydrate(client, dehydratedState, options) { if (typeof dehydratedState !== 'object' || dehydratedState === null) { return; } const mutationCache = client.getMutationCache(); const queryCache = client.getQueryCache(); // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition const mutations = dehydratedState.mutations || []; // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition const queries = dehydratedState.queries || []; mutations.forEach(dehydratedMutation => { var _options$defaultOptio; mutationCache.build(client, { ...(options == null ? void 0 : (_options$defaultOptio = options.defaultOptions) == null ? void 0 : _options$defaultOptio.mutations), mutationKey: dehydratedMutation.mutationKey }, dehydratedMutation.state); }); queries.forEach(dehydratedQuery => { var _options$defaultOptio2; const query = queryCache.get(dehydratedQuery.queryHash); // Do not hydrate if an existing query exists with newer data if (query) { if (query.state.dataUpdatedAt < dehydratedQuery.state.dataUpdatedAt) { query.setState(dehydratedQuery.state); } return; } // Restore query queryCache.build(client, { ...(options == null ? void 0 : (_options$defaultOptio2 = options.defaultOptions) == null ? void 0 : _options$defaultOptio2.queries), queryKey: dehydratedQuery.queryKey, queryHash: dehydratedQuery.queryHash }, dehydratedQuery.state); }); } function infiniteQueryBehavior() { return { onFetch: context => { context.fetchFn = () => { var _context$fetchOptions, _context$fetchOptions2, _context$fetchOptions3, _context$fetchOptions4, _context$state$data, _context$state$data2; const refetchPage = (_context$fetchOptions = context.fetchOptions) == null ? void 0 : (_context$fetchOptions2 = _context$fetchOptions.meta) == null ? void 0 : _context$fetchOptions2.refetchPage; const fetchMore = (_context$fetchOptions3 = context.fetchOptions) == null ? void 0 : (_context$fetchOptions4 = _context$fetchOptions3.meta) == null ? void 0 : _context$fetchOptions4.fetchMore; const pageParam = fetchMore == null ? void 0 : fetchMore.pageParam; const isFetchingNextPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'forward'; const isFetchingPreviousPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'backward'; const oldPages = ((_context$state$data = context.state.data) == null ? void 0 : _context$state$data.pages) || []; const oldPageParams = ((_context$state$data2 = context.state.data) == null ? void 0 : _context$state$data2.pageParams) || []; let newPageParams = oldPageParams; let cancelled = false; const addSignalProperty = object => { Object.defineProperty(object, 'signal', { enumerable: true, get: () => { var _context$signal; if ((_context$signal = context.signal) != null && _context$signal.aborted) { cancelled = true; } else { var _context$signal2; (_context$signal2 = context.signal) == null ? void 0 : _context$signal2.addEventListener('abort', () => { cancelled = true; }); } return context.signal; } }); }; // Get query function const queryFn = context.options.queryFn || (() => Promise.reject('Missing queryFn')); const buildNewPages = (pages, param, page, previous) => { newPageParams = previous ? [param, ...newPageParams] : [...newPageParams, param]; return previous ? [page, ...pages] : [...pages, page]; }; // Create function to fetch a page const fetchPage = (pages, manual, param, previous) => { if (cancelled) { return Promise.reject('Cancelled'); } if (typeof param === 'undefined' && !manual && pages.length) { return Promise.resolve(pages); } const queryFnContext = { queryKey: context.queryKey, pageParam: param, meta: context.options.meta }; addSignalProperty(queryFnContext); const queryFnResult = queryFn(queryFnContext); const promise = Promise.resolve(queryFnResult).then(page => buildNewPages(pages, param, page, previous)); return promise; }; let promise; // Fetch first page? if (!oldPages.length) { promise = fetchPage([]); } // Fetch next page? else if (isFetchingNextPage) { const manual = typeof pageParam !== 'undefined'; const param = manual ? pageParam : getNextPageParam(context.options, oldPages); promise = fetchPage(oldPages, manual, param); } // Fetch previous page? else if (isFetchingPreviousPage) { const manual = typeof pageParam !== 'undefined'; const param = manual ? pageParam : getPreviousPageParam(context.options, oldPages); promise = fetchPage(oldPages, manual, param, true); } // Refetch pages else { newPageParams = []; const manual = typeof context.options.getNextPageParam === 'undefined'; const shouldFetchFirstPage = refetchPage && oldPages[0] ? refetchPage(oldPages[0], 0, oldPages) : true; // Fetch first page promise = shouldFetchFirstPage ? fetchPage([], manual, oldPageParams[0]) : Promise.resolve(buildNewPages([], oldPageParams[0], oldPages[0])); // Fetch remaining pages for (let i = 1; i < oldPages.length; i++) { promise = promise.then(pages => { const shouldFetchNextPage = refetchPage && oldPages[i] ? refetchPage(oldPages[i], i, oldPages) : true; if (shouldFetchNextPage) { const param = manual ? oldPageParams[i] : getNextPageParam(context.options, pages); return fetchPage(pages, manual, param); } return Promise.resolve(buildNewPages(pages, oldPageParams[i], oldPages[i])); }); } } const finalPromise = promise.then(pages => ({ pages, pageParams: newPageParams })); return finalPromise; }; } }; } function getNextPageParam(options, pages) { return options.getNextPageParam == null ? void 0 : options.getNextPageParam(pages[pages.length - 1], pages); } function getPreviousPageParam(options, pages) { return options.getPreviousPageParam == null ? void 0 : options.getPreviousPageParam(pages[0], pages); } /** * Checks if there is a next page. * Returns `undefined` if it cannot be determined. */ function hasNextPage(options, pages) { if (options.getNextPageParam && Array.isArray(pages)) { const nextPageParam = getNextPageParam(options, pages); return typeof nextPageParam !== 'undefined' && nextPageParam !== null && nextPageParam !== false; } return; } /** * Checks if there is a previous page. * Returns `undefined` if it cannot be determined. */ function hasPreviousPage(options, pages) { if (options.getPreviousPageParam && Array.isArray(pages)) { const previousPageParam = getPreviousPageParam(options, pages); return typeof previousPageParam !== 'undefined' && previousPageParam !== null && previousPageParam !== false; } return; } function createNotifyManager() { let queue = []; let transactions = 0; let notifyFn = callback => { callback(); }; let batchNotifyFn = callback => { callback(); }; const batch = callback => { let result; transactions++; try { result = callback(); } finally { transactions--; if (!transactions) { flush(); } } return result; }; const schedule = callback => { if (transactions) { queue.push(callback); } else { scheduleMicrotask(() => { notifyFn(callback); }); } }; /** * All calls to the wrapped function will be batched. */ const batchCalls = callback => { return (...args) => { schedule(() => { callback(...args); }); }; }; const flush = () => { const originalQueue = queue; queue = []; if (originalQueue.length) { scheduleMicrotask(() => { batchNotifyFn(() => { originalQueue.forEach(callback => { notifyFn(callback); }); }); }); } }; /** * Use this method to set a custom notify function. * This can be used to for example wrap notifications with `React.act` while running tests. */ const setNotifyFunction = fn => { notifyFn = fn; }; /** * Use this method to set a custom function to batch notifications together into a single tick. * By default React Query will use the batch function provided by ReactDOM or React Native. */ const setBatchNotifyFunction = fn => { batchNotifyFn = fn; }; return { batch, batchCalls, schedule, setNotifyFunction, setBatchNotifyFunction }; } // SINGLETON const notifyManager = createNotifyManager(); class OnlineManager extends Subscribable { constructor() { super(); this.setup = onOnline => { // addEventListener does not exist in React Native, but window does // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!isServer && window.addEventListener) { const listener = () => onOnline(); // Listen to online window.addEventListener('online', listener, false); window.addEventListener('offline', listener, false); return () => { // Be sure to unsubscribe if a new handler is set window.removeEventListener('online', listener); window.removeEventListener('offline', listener); }; } return; }; } onSubscribe() { if (!this.cleanup) { this.setEventListener(this.setup); } } onUnsubscribe() { if (!this.hasListeners()) { var _this$cleanup; (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this); this.cleanup = undefined; } } setEventListener(setup) { var _this$cleanup2; this.setup = setup; (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this); this.cleanup = setup(online => { if (typeof online === 'boolean') { this.setOnline(online); } else { this.onOnline(); } }); } setOnline(online) { this.online = online; if (online) { this.onOnline(); } } onOnline() { this.listeners.forEach(listener => { listener(); }); } isOnline() { if (typeof this.online === 'boolean') { return this.online; } if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') { return true; } return navigator.onLine; } } const onlineManager = new OnlineManager(); function defaultRetryDelay(failureCount) { return Math.min(1000 * 2 ** failureCount, 30000); } function canFetch(networkMode) { return (networkMode != null ? networkMode : 'online') === 'online' ? onlineManager.isOnline() : true; } class CancelledError { constructor(options) { this.revert = options == null ? void 0 : options.revert; this.silent = options == null ? void 0 : options.silent; } } function isCancelledError(value) { return value instanceof CancelledError; } function createRetryer(config) { let isRetryCancelled = false; let failureCount = 0; let isResolved = false; let continueFn; let promiseResolve; let promiseReject; const promise = new Promise((outerResolve, outerReject) => { promiseResolve = outerResolve; promiseReject = outerReject; }); const cancel = cancelOptions => { if (!isResolved) { reject(new CancelledError(cancelOptions)); config.abort == null ? void 0 : config.abort(); } }; const cancelRetry = () => { isRetryCancelled = true; }; const continueRetry = () => { isRetryCancelled = false; }; const shouldPause = () => !focusManager.isFocused() || config.networkMode !== 'always' && !onlineManager.isOnline(); const resolve = value => { if (!isResolved) { isResolved = true; config.onSuccess == null ? void 0 : config.onSuccess(value); continueFn == null ? void 0 : continueFn(); promiseResolve(value); } }; const reject = value => { if (!isResolved) { isResolved = true; config.onError == null ? void 0 : config.onError(value); continueFn == null ? void 0 : continueFn(); promiseReject(value); } }; const pause = () => { return new Promise(continueResolve => { continueFn = value => { if (isResolved || !shouldPause()) { return continueResolve(value); } }; config.onPause == null ? void 0 : config.onPause(); }).then(() => { continueFn = undefined; if (!isResolved) { config.onContinue == null ? void 0 : config.onContinue(); } }); }; // Create loop function const run = () => { // Do nothing if already resolved if (isResolved) { return; } let promiseOrValue; // Execute query try { promiseOrValue = config.fn(); } catch (error) { promiseOrValue = Promise.reject(error); } Promise.resolve(promiseOrValue).then(resolve).catch(error => { var _config$retry, _config$retryDelay; // Stop if the fetch is already resolved if (isResolved) { return; } // Do we need to retry the request? const retry = (_config$retry = config.retry) != null ? _config$retry : 3; const retryDelay = (_config$retryDelay = config.retryDelay) != null ? _config$retryDelay : defaultRetryDelay; const delay = typeof retryDelay === 'function' ? retryDelay(failureCount, error) : retryDelay; const shouldRetry = retry === true || typeof retry === 'number' && failureCount < retry || typeof retry === 'function' && retry(failureCount, error); if (isRetryCancelled || !shouldRetry) { // We are done if the query does not need to be retried reject(error); return; } failureCount++; // Notify on fail config.onFail == null ? void 0 : config.onFail(failureCount, error); // Delay sleep(delay) // Pause if the document is not visible or when the device is offline .then(() => { if (shouldPause()) { return pause(); } return; }).then(() => { if (isRetryCancelled) { reject(error); } else { run(); } }); }); }; // Start loop if (canFetch(config.networkMode)) { run(); } else { pause().then(run); } return { promise, cancel, continue: () => { continueFn == null ? void 0 : continueFn(); }, cancelRetry, continueRetry }; } class QueryObserver extends Subscribable { constructor(client, options) { super(); this.client = client; this.options = options; this.trackedProps = new Set(); this.selectError = null; this.bindMethods(); this.setOptions(options); } bindMethods() { this.remove = this.remove.bind(this); this.refetch = this.refetch.bind(this); } onSubscribe() { if (this.listeners.length === 1) { this.currentQuery.addObserver(this); if (shouldFetchOnMount(this.currentQuery, this.options)) { this.executeFetch(); } this.updateTimers(); } } onUnsubscribe() { if (!this.listeners.length) { this.destroy(); } } shouldFetchOnReconnect() { return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnReconnect); } shouldFetchOnWindowFocus() { return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnWindowFocus); } destroy() { this.listeners = []; this.clearStaleTimeout(); this.clearRefetchInterval(); this.currentQuery.removeObserver(this); } setOptions(options, notifyOptions) { const prevOptions = this.options; const prevQuery = this.currentQuery; this.options = this.client.defaultQueryOptions(options); if (!shallowEqualObjects(prevOptions, this.options)) { this.client.getQueryCache().notify({ type: 'observerOptionsUpdated', query: this.currentQuery, observer: this }); } if (typeof this.options.enabled !== 'undefined' && typeof this.options.enabled !== 'boolean') { throw new Error('Expected enabled to be a boolean'); } // Keep previous query key if the user does not supply one if (!this.options.queryKey) { this.options.queryKey = prevOptions.queryKey; } this.updateQuery(); const mounted = this.hasListeners(); // Fetch if there are subscribers if (mounted && shouldFetchOptionally(this.currentQuery, prevQuery, this.options, prevOptions)) { this.executeFetch(); } // Update result this.updateResult(notifyOptions); // Update stale interval if needed if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) { this.updateStaleTimeout(); } const nextRefetchInterval = this.computeRefetchInterval(); // Update refetch interval if needed if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.currentRefetchInterval)) { this.updateRefetchInterval(nextRefetchInterval); } } getOptimisticResult(options) { const query = this.client.getQueryCache().build(this.client, options); return this.createResult(query, options); } getCurrentResult() { return this.currentResult; } trackResult(result) { const trackedResult = {}; Object.keys(result).forEach(key => { Object.defineProperty(trackedResult, key, { configurable: false, enumerable: true, get: () => { this.trackedProps.add(key); return result[key]; } }); }); return trackedResult; } getCurrentQuery() { return this.currentQuery; } remove() { this.client.getQueryCache().remove(this.currentQuery); } refetch({ refetchPage, ...options } = {}) { return this.fetch({ ...options, meta: { refetchPage } }); } fetchOptimistic(options) { const defaultedOptions = this.client.defaultQueryOptions(options); const query = this.client.getQueryCache().build(this.client, defaultedOptions); query.isFetchingOptimistic = true; return query.fetch().then(() => this.createResult(query, defaultedOptions)); } fetch(fetchOptions) { var _fetchOptions$cancelR; return this.executeFetch({ ...fetchOptions, cancelRefetch: (_fetchOptions$cancelR = fetchOptions.cancelRefetch) != null ? _fetchOptions$cancelR : true }).then(() => { this.updateResult(); return this.currentResult; }); } executeFetch(fetchOptions) { // Make sure we reference the latest query as the current one might have been removed this.updateQuery(); // Fetch let promise = this.currentQuery.fetch(this.options, fetchOptions); if (!(fetchOptions != null && fetchOptions.throwOnError)) { promise = promise.catch(noop$5); } return promise; } updateStaleTimeout() { this.clearStaleTimeout(); if (isServer || this.currentResult.isStale || !isValidTimeout(this.options.staleTime)) { return; } const time = timeUntilStale(this.currentResult.dataUpdatedAt, this.options.staleTime); // The timeout is sometimes triggered 1 ms before the stale time expiration. // To mitigate this issue we always add 1 ms to the timeout. const timeout = time + 1; this.staleTimeoutId = setTimeout(() => { if (!this.currentResult.isStale) { this.updateResult(); } }, timeout); } computeRefetchInterval() { var _this$options$refetch; return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(this.currentResult.data, this.currentQuery) : (_this$options$refetch = this.options.refetchInterval) != null ? _this$options$refetch : false; } updateRefetchInterval(nextInterval) { this.clearRefetchInterval(); this.currentRefetchInterval = nextInterval; if (isServer || this.options.enabled === false || !isValidTimeout(this.currentRefetchInterval) || this.currentRefetchInterval === 0) { return; } this.refetchIntervalId = setInterval(() => { if (this.options.refetchIntervalInBackground || focusManager.isFocused()) { this.executeFetch(); } }, this.currentRefetchInterval); } updateTimers() { this.updateStaleTimeout(); this.updateRefetchInterval(this.computeRefetchInterval()); } clearStaleTimeout() { if (this.staleTimeoutId) { clearTimeout(this.staleTimeoutId); this.staleTimeoutId = undefined; } } clearRefetchInterval() { if (this.refetchIntervalId) { clearInterval(this.refetchIntervalId); this.refetchIntervalId = undefined; } } createResult(query, options) { const prevQuery = this.currentQuery; const prevOptions = this.options; const prevResult = this.currentResult; const prevResultState = this.currentResultState; const prevResultOptions = this.currentResultOptions; const queryChange = query !== prevQuery; const queryInitialState = queryChange ? query.state : this.currentQueryInitialState; const prevQueryResult = queryChange ? this.currentResult : this.previousQueryResult; const { state } = query; let { dataUpdatedAt, error, errorUpdatedAt, fetchStatus, status } = state; let isPreviousData = false; let isPlaceholderData = false; let data; // Optimistically set result in fetching state if needed if (options._optimisticResults) { const mounted = this.hasListeners(); const fetchOnMount = !mounted && shouldFetchOnMount(query, options); const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions); if (fetchOnMount || fetchOptionally) { fetchStatus = canFetch(query.options.networkMode) ? 'fetching' : 'paused'; if (!dataUpdatedAt) { status = 'loading'; } } if (options._optimisticResults === 'isRestoring') { fetchStatus = 'idle'; } } // Keep previous data if needed if (options.keepPreviousData && !state.dataUpdatedAt && prevQueryResult != null && prevQueryResult.isSuccess && status !== 'error') { data = prevQueryResult.data; dataUpdatedAt = prevQueryResult.dataUpdatedAt; status = prevQueryResult.status; isPreviousData = true; } // Select data if needed else if (options.select && typeof state.data !== 'undefined') { // Memoize select result if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === this.selectFn) { data = this.selectResult; } else { try { this.selectFn = options.select; data = options.select(state.data); data = replaceData(prevResult == null ? void 0 : prevResult.data, data, options); this.selectResult = data; this.selectError = null; } catch (selectError) { this.selectError = selectError; } } } // Use query data else { data = state.data; } // Show placeholder data if needed if (typeof options.placeholderData !== 'undefined' && typeof data === 'undefined' && status === 'loading') { let placeholderData; // Memoize placeholder data if (prevResult != null && prevResult.isPlaceholderData && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) { placeholderData = prevResult.data; } else { placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData() : options.placeholderData; if (options.select && typeof placeholderData !== 'undefined') { try { placeholderData = options.select(placeholderData); this.selectError = null; } catch (selectError) { this.selectError = selectError; } } } if (typeof placeholderData !== 'undefined') { status = 'success'; data = replaceData(prevResult == null ? void 0 : prevResult.data, placeholderData, options); isPlaceholderData = true; } } if (this.selectError) { error = this.selectError; data = this.selectResult; errorUpdatedAt = Date.now(); status = 'error'; } const isFetching = fetchStatus === 'fetching'; const isLoading = status === 'loading'; const isError = status === 'error'; const result = { status, fetchStatus, isLoading, isSuccess: status === 'success', isError, isInitialLoading: isLoading && isFetching, data, dataUpdatedAt, error, errorUpdatedAt, failureCount: state.fetchFailureCount, failureReason: state.fetchFailureReason, errorUpdateCount: state.errorUpdateCount, isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0, isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount, isFetching, isRefetching: isFetching && !isLoading, isLoadingError: isError && state.dataUpdatedAt === 0, isPaused: fetchStatus === 'paused', isPlaceholderData, isPreviousData, isRefetchError: isError && state.dataUpdatedAt !== 0, isStale: isStale(query, options), refetch: this.refetch, remove: this.remove }; return result; } updateResult(notifyOptions) { const prevResult = this.currentResult; const nextResult = this.createResult(this.currentQuery, this.options); this.currentResultState = this.currentQuery.state; this.currentResultOptions = this.options; // Only notify and update result if something has changed if (shallowEqualObjects(nextResult, prevResult)) { return; } this.currentResult = nextResult; // Determine which callbacks to trigger const defaultNotifyOptions = { cache: true }; const shouldNotifyListeners = () => { if (!prevResult) { return true; } const { notifyOnChangeProps } = this.options; if (notifyOnChangeProps === 'all' || !notifyOnChangeProps && !this.trackedProps.size) { return true; } const includedProps = new Set(notifyOnChangeProps != null ? notifyOnChangeProps : this.trackedProps); if (this.options.useErrorBoundary) { includedProps.add('error'); } return Object.keys(this.currentResult).some(key => { const typedKey = key; const changed = this.currentResult[typedKey] !== prevResult[typedKey]; return changed && includedProps.has(typedKey); }); }; if ((notifyOptions == null ? void 0 : notifyOptions.listeners) !== false && shouldNotifyListeners()) { defaultNotifyOptions.listeners = true; } this.notify({ ...defaultNotifyOptions, ...notifyOptions }); } updateQuery() { const query = this.client.getQueryCache().build(this.client, this.options); if (query === this.currentQuery) { return; } const prevQuery = this.currentQuery; this.currentQuery = query; this.currentQueryInitialState = query.state; this.previousQueryResult = this.currentResult; if (this.hasListeners()) { prevQuery == null ? void 0 : prevQuery.removeObserver(this); query.addObserver(this); } } onQueryUpdate(action) { const notifyOptions = {}; if (action.type === 'success') { notifyOptions.onSuccess = !action.manual; } else if (action.type === 'error' && !isCancelledError(action.error)) { notifyOptions.onError = true; } this.updateResult(notifyOptions); if (this.hasListeners()) { this.updateTimers(); } } notify(notifyOptions) { notifyManager.batch(() => { // First trigger the configuration callbacks if (notifyOptions.onSuccess) { var _this$options$onSucce, _this$options, _this$options$onSettl, _this$options2; (_this$options$onSucce = (_this$options = this.options).onSuccess) == null ? void 0 : _this$options$onSucce.call(_this$options, this.currentResult.data); (_this$options$onSettl = (_this$options2 = this.options).onSettled) == null ? void 0 : _this$options$onSettl.call(_this$options2, this.currentResult.data, null); } else if (notifyOptions.onError) { var _this$options$onError, _this$options3, _this$options$onSettl2, _this$options4; (_this$options$onError = (_this$options3 = this.options).onError) == null ? void 0 : _this$options$onError.call(_this$options3, this.currentResult.error); (_this$options$onSettl2 = (_this$options4 = this.options).onSettled) == null ? void 0 : _this$options$onSettl2.call(_this$options4, undefined, this.currentResult.error); } // Then trigger the listeners if (notifyOptions.listeners) { this.listeners.forEach(listener => { listener(this.currentResult); }); } // Then the cache listeners if (notifyOptions.cache) { this.client.getQueryCache().notify({ query: this.currentQuery, type: 'observerResultsUpdated' }); } }); } } function shouldLoadOnMount(query, options) { return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false); } function shouldFetchOnMount(query, options) { return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount); } function shouldFetchOn(query, options, field) { if (options.enabled !== false) { const value = typeof field === 'function' ? field(query) : field; return value === 'always' || value !== false && isStale(query, options); } return false; } function shouldFetchOptionally(query, prevQuery, options, prevOptions) { return options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== 'error') && isStale(query, options); } function isStale(query, options) { return query.isStaleByTime(options.staleTime); } class InfiniteQueryObserver extends QueryObserver { // Type override // Type override // Type override // eslint-disable-next-line @typescript-eslint/no-useless-constructor constructor(client, options) { super(client, options); } bindMethods() { super.bindMethods(); this.fetchNextPage = this.fetchNextPage.bind(this); this.fetchPreviousPage = this.fetchPreviousPage.bind(this); } setOptions(options, notifyOptions) { super.setOptions({ ...options, behavior: infiniteQueryBehavior() }, notifyOptions); } getOptimisticResult(options) { options.behavior = infiniteQueryBehavior(); return super.getOptimisticResult(options); } fetchNextPage({ pageParam, ...options } = {}) { return this.fetch({ ...options, meta: { fetchMore: { direction: 'forward', pageParam } } }); } fetchPreviousPage({ pageParam, ...options } = {}) { return this.fetch({ ...options, meta: { fetchMore: { direction: 'backward', pageParam } } }); } createResult(query, options) { var _state$fetchMeta, _state$fetchMeta$fetc, _state$fetchMeta2, _state$fetchMeta2$fet, _state$data, _state$data2; const { state } = query; const result = super.createResult(query, options); const { isFetching, isRefetching } = result; const isFetchingNextPage = isFetching && ((_state$fetchMeta = state.fetchMeta) == null ? void 0 : (_state$fetchMeta$fetc = _state$fetchMeta.fetchMore) == null ? void 0 : _state$fetchMeta$fetc.direction) === 'forward'; const isFetchingPreviousPage = isFetching && ((_state$fetchMeta2 = state.fetchMeta) == null ? void 0 : (_state$fetchMeta2$fet = _state$fetchMeta2.fetchMore) == null ? void 0 : _state$fetchMeta2$fet.direction) === 'backward'; return { ...result, fetchNextPage: this.fetchNextPage, fetchPreviousPage: this.fetchPreviousPage, hasNextPage: hasNextPage(options, (_state$data = state.data) == null ? void 0 : _state$data.pages), hasPreviousPage: hasPreviousPage(options, (_state$data2 = state.data) == null ? void 0 : _state$data2.pages), isFetchingNextPage, isFetchingPreviousPage, isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage }; } } const defaultLogger = console; class Removable { destroy() { this.clearGcTimeout(); } scheduleGc() { this.clearGcTimeout(); if (isValidTimeout(this.cacheTime)) { this.gcTimeout = setTimeout(() => { this.optionalRemove(); }, this.cacheTime); } } updateCacheTime(newCacheTime) { // Default to 5 minutes (Infinity for server-side) if no cache time is set this.cacheTime = Math.max(this.cacheTime || 0, newCacheTime != null ? newCacheTime : isServer ? Infinity : 5 * 60 * 1000); } clearGcTimeout() { if (this.gcTimeout) { clearTimeout(this.gcTimeout); this.gcTimeout = undefined; } } } // CLASS class Mutation extends Removable { constructor(config) { super(); this.options = { ...config.defaultOptions, ...config.options }; this.mutationId = config.mutationId; this.mutationCache = config.mutationCache; this.logger = config.logger || defaultLogger; this.observers = []; this.state = config.state || getDefaultState$1(); this.updateCacheTime(this.options.cacheTime); this.scheduleGc(); } get meta() { return this.options.meta; } setState(state) { this.dispatch({ type: 'setState', state }); } addObserver(observer) { if (this.observers.indexOf(observer) === -1) { this.observers.push(observer); // Stop the mutation from being garbage collected this.clearGcTimeout(); this.mutationCache.notify({ type: 'observerAdded', mutation: this, observer }); } } removeObserver(observer) { this.observers = this.observers.filter(x => x !== observer); this.scheduleGc(); this.mutationCache.notify({ type: 'observerRemoved', mutation: this, observer }); } optionalRemove() { if (!this.observers.length) { if (this.state.status === 'loading') { this.scheduleGc(); } else { this.mutationCache.remove(this); } } } continue() { if (this.retryer) { this.retryer.continue(); return this.retryer.promise; } return this.execute(); } async execute() { const executeMutation = () => { var _this$options$retry; this.retryer = createRetryer({ fn: () => { if (!this.options.mutationFn) { return Promise.reject('No mutationFn found'); } return this.options.mutationFn(this.state.variables); }, onFail: (failureCount, error) => { this.dispatch({ type: 'failed', failureCount, error }); }, onPause: () => { this.dispatch({ type: 'pause' }); }, onContinue: () => { this.dispatch({ type: 'continue' }); }, retry: (_this$options$retry = this.options.retry) != null ? _this$options$retry : 0, retryDelay: this.options.retryDelay, networkMode: this.options.networkMode }); return this.retryer.promise; }; const restored = this.state.status === 'loading'; try { var _this$mutationCache$c3, _this$mutationCache$c4, _this$options$onSucce, _this$options2, _this$options$onSettl, _this$options3; if (!restored) { var _this$mutationCache$c, _this$mutationCache$c2, _this$options$onMutat, _this$options; this.dispatch({ type: 'loading', variables: this.options.variables }); // Notify cache callback await ((_this$mutationCache$c = (_this$mutationCache$c2 = this.mutationCache.config).onMutate) == null ? void 0 : _this$mutationCache$c.call(_this$mutationCache$c2, this.state.variables, this)); const context = await ((_this$options$onMutat = (_this$options = this.options).onMutate) == null ? void 0 : _this$options$onMutat.call(_this$options, this.state.variables)); if (context !== this.state.context) { this.dispatch({ type: 'loading', context, variables: this.state.variables }); } } const data = await executeMutation(); // Notify cache callback await ((_this$mutationCache$c3 = (_this$mutationCache$c4 = this.mutationCache.config).onSuccess) == null ? void 0 : _this$mutationCache$c3.call(_this$mutationCache$c4, data, this.state.variables, this.state.context, this)); await ((_this$options$onSucce = (_this$options2 = this.options).onSuccess) == null ? void 0 : _this$options$onSucce.call(_this$options2, data, this.state.variables, this.state.context)); await ((_this$options$onSettl = (_this$options3 = this.options).onSettled) == null ? void 0 : _this$options$onSettl.call(_this$options3, data, null, this.state.variables, this.state.context)); this.dispatch({ type: 'success', data }); return data; } catch (error) { try { var _this$mutationCache$c5, _this$mutationCache$c6, _this$options$onError, _this$options4, _this$options$onSettl2, _this$options5; // Notify cache callback await ((_this$mutationCache$c5 = (_this$mutationCache$c6 = this.mutationCache.config).onError) == null ? void 0 : _this$mutationCache$c5.call(_this$mutationCache$c6, error, this.state.variables, this.state.context, this)); if ('production' !== 'production') ; await ((_this$options$onError = (_this$options4 = this.options).onError) == null ? void 0 : _this$options$onError.call(_this$options4, error, this.state.variables, this.state.context)); await ((_this$options$onSettl2 = (_this$options5 = this.options).onSettled) == null ? void 0 : _this$options$onSettl2.call(_this$options5, undefined, error, this.state.variables, this.state.context)); throw error; } finally { this.dispatch({ type: 'error', error: error }); } } } dispatch(action) { const reducer = state => { switch (action.type) { case 'failed': return { ...state, failureCount: action.failureCount, failureReason: action.error }; case 'pause': return { ...state, isPaused: true }; case 'continue': return { ...state, isPaused: false }; case 'loading': return { ...state, context: action.context, data: undefined, failureCount: 0, failureReason: null, error: null, isPaused: !canFetch(this.options.networkMode), status: 'loading', variables: action.variables }; case 'success': return { ...state, data: action.data, failureCount: 0, failureReason: null, error: null, status: 'success', isPaused: false }; case 'error': return { ...state, data: undefined, error: action.error, failureCount: state.failureCount + 1, failureReason: action.error, isPaused: false, status: 'error' }; case 'setState': return { ...state, ...action.state }; } }; this.state = reducer(this.state); notifyManager.batch(() => { this.observers.forEach(observer => { observer.onMutationUpdate(action); }); this.mutationCache.notify({ mutation: this, type: 'updated', action }); }); } } function getDefaultState$1() { return { context: undefined, data: undefined, error: null, failureCount: 0, failureReason: null, isPaused: false, status: 'idle', variables: undefined }; } // CLASS class MutationCache extends Subscribable { constructor(config) { super(); this.config = config || {}; this.mutations = []; this.mutationId = 0; } build(client, options, state) { const mutation = new Mutation({ mutationCache: this, logger: client.getLogger(), mutationId: ++this.mutationId, options: client.defaultMutationOptions(options), state, defaultOptions: options.mutationKey ? client.getMutationDefaults(options.mutationKey) : undefined }); this.add(mutation); return mutation; } add(mutation) { this.mutations.push(mutation); this.notify({ type: 'added', mutation }); } remove(mutation) { this.mutations = this.mutations.filter(x => x !== mutation); this.notify({ type: 'removed', mutation }); } clear() { notifyManager.batch(() => { this.mutations.forEach(mutation => { this.remove(mutation); }); }); } getAll() { return this.mutations; } find(filters) { if (typeof filters.exact === 'undefined') { filters.exact = true; } return this.mutations.find(mutation => matchMutation(filters, mutation)); } findAll(filters) { return this.mutations.filter(mutation => matchMutation(filters, mutation)); } notify(event) { notifyManager.batch(() => { this.listeners.forEach(listener => { listener(event); }); }); } resumePausedMutations() { const pausedMutations = this.mutations.filter(x => x.state.isPaused); return notifyManager.batch(() => pausedMutations.reduce((promise, mutation) => promise.then(() => mutation.continue().catch(noop$5)), Promise.resolve())); } } // CLASS let MutationObserver$1 = class MutationObserver extends Subscribable { constructor(client, options) { super(); this.client = client; this.setOptions(options); this.bindMethods(); this.updateResult(); } bindMethods() { this.mutate = this.mutate.bind(this); this.reset = this.reset.bind(this); } setOptions(options) { const prevOptions = this.options; this.options = this.client.defaultMutationOptions(options); if (!shallowEqualObjects(prevOptions, this.options)) { this.client.getMutationCache().notify({ type: 'observerOptionsUpdated', mutation: this.currentMutation, observer: this }); } } onUnsubscribe() { if (!this.listeners.length) { var _this$currentMutation; (_this$currentMutation = this.currentMutation) == null ? void 0 : _this$currentMutation.removeObserver(this); } } onMutationUpdate(action) { this.updateResult(); // Determine which callbacks to trigger const notifyOptions = { listeners: true }; if (action.type === 'success') { notifyOptions.onSuccess = true; } else if (action.type === 'error') { notifyOptions.onError = true; } this.notify(notifyOptions); } getCurrentResult() { return this.currentResult; } reset() { this.currentMutation = undefined; this.updateResult(); this.notify({ listeners: true }); } mutate(variables, options) { this.mutateOptions = options; if (this.currentMutation) { this.currentMutation.removeObserver(this); } this.currentMutation = this.client.getMutationCache().build(this.client, { ...this.options, variables: typeof variables !== 'undefined' ? variables : this.options.variables }); this.currentMutation.addObserver(this); return this.currentMutation.execute(); } updateResult() { const state = this.currentMutation ? this.currentMutation.state : getDefaultState$1(); const result = { ...state, isLoading: state.status === 'loading', isSuccess: state.status === 'success', isError: state.status === 'error', isIdle: state.status === 'idle', mutate: this.mutate, reset: this.reset }; this.currentResult = result; } notify(options) { notifyManager.batch(() => { // First trigger the mutate callbacks if (this.mutateOptions) { if (options.onSuccess) { var _this$mutateOptions$o, _this$mutateOptions, _this$mutateOptions$o2, _this$mutateOptions2; (_this$mutateOptions$o = (_this$mutateOptions = this.mutateOptions).onSuccess) == null ? void 0 : _this$mutateOptions$o.call(_this$mutateOptions, this.currentResult.data, this.currentResult.variables, this.currentResult.context); (_this$mutateOptions$o2 = (_this$mutateOptions2 = this.mutateOptions).onSettled) == null ? void 0 : _this$mutateOptions$o2.call(_this$mutateOptions2, this.currentResult.data, null, this.currentResult.variables, this.currentResult.context); } else if (options.onError) { var _this$mutateOptions$o3, _this$mutateOptions3, _this$mutateOptions$o4, _this$mutateOptions4; (_this$mutateOptions$o3 = (_this$mutateOptions3 = this.mutateOptions).onError) == null ? void 0 : _this$mutateOptions$o3.call(_this$mutateOptions3, this.currentResult.error, this.currentResult.variables, this.currentResult.context); (_this$mutateOptions$o4 = (_this$mutateOptions4 = this.mutateOptions).onSettled) == null ? void 0 : _this$mutateOptions$o4.call(_this$mutateOptions4, undefined, this.currentResult.error, this.currentResult.variables, this.currentResult.context); } } // Then trigger the listeners if (options.listeners) { this.listeners.forEach(listener => { listener(this.currentResult); }); } }); } }; class QueriesObserver extends Subscribable { constructor(client, queries) { super(); this.client = client; this.queries = []; this.result = []; this.observers = []; this.observersMap = {}; if (queries) { this.setQueries(queries); } } onSubscribe() { if (this.listeners.length === 1) { this.observers.forEach(observer => { observer.subscribe(result => { this.onUpdate(observer, result); }); }); } } onUnsubscribe() { if (!this.listeners.length) { this.destroy(); } } destroy() { this.listeners = []; this.observers.forEach(observer => { observer.destroy(); }); } setQueries(queries, notifyOptions) { this.queries = queries; notifyManager.batch(() => { const prevObservers = this.observers; const newObserverMatches = this.findMatchingObservers(this.queries); // set options for the new observers to notify of changes newObserverMatches.forEach(match => match.observer.setOptions(match.defaultedQueryOptions, notifyOptions)); const newObservers = newObserverMatches.map(match => match.observer); const newObserversMap = Object.fromEntries(newObservers.map(observer => [observer.options.queryHash, observer])); const newResult = newObservers.map(observer => observer.getCurrentResult()); const hasIndexChange = newObservers.some((observer, index) => observer !== prevObservers[index]); if (prevObservers.length === newObservers.length && !hasIndexChange) { return; } this.observers = newObservers; this.observersMap = newObserversMap; this.result = newResult; if (!this.hasListeners()) { return; } difference(prevObservers, newObservers).forEach(observer => { observer.destroy(); }); difference(newObservers, prevObservers).forEach(observer => { observer.subscribe(result => { this.onUpdate(observer, result); }); }); this.notify(); }); } getCurrentResult() { return this.result; } getQueries() { return this.observers.map(observer => observer.getCurrentQuery()); } getObservers() { return this.observers; } getOptimisticResult(queries) { return this.findMatchingObservers(queries).map(match => match.observer.getOptimisticResult(match.defaultedQueryOptions)); } findMatchingObservers(queries) { const prevObservers = this.observers; const defaultedQueryOptions = queries.map(options => this.client.defaultQueryOptions(options)); const matchingObservers = defaultedQueryOptions.flatMap(defaultedOptions => { const match = prevObservers.find(observer => observer.options.queryHash === defaultedOptions.queryHash); if (match != null) { return [{ defaultedQueryOptions: defaultedOptions, observer: match }]; } return []; }); const matchedQueryHashes = matchingObservers.map(match => match.defaultedQueryOptions.queryHash); const unmatchedQueries = defaultedQueryOptions.filter(defaultedOptions => !matchedQueryHashes.includes(defaultedOptions.queryHash)); const unmatchedObservers = prevObservers.filter(prevObserver => !matchingObservers.some(match => match.observer === prevObserver)); const getObserver = options => { const defaultedOptions = this.client.defaultQueryOptions(options); const currentObserver = this.observersMap[defaultedOptions.queryHash]; return currentObserver != null ? currentObserver : new QueryObserver(this.client, defaultedOptions); }; const newOrReusedObservers = unmatchedQueries.map((options, index) => { if (options.keepPreviousData) { // return previous data from one of the observers that no longer match const previouslyUsedObserver = unmatchedObservers[index]; if (previouslyUsedObserver !== undefined) { return { defaultedQueryOptions: options, observer: previouslyUsedObserver }; } } return { defaultedQueryOptions: options, observer: getObserver(options) }; }); const sortMatchesByOrderOfQueries = (a, b) => defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - defaultedQueryOptions.indexOf(b.defaultedQueryOptions); return matchingObservers.concat(newOrReusedObservers).sort(sortMatchesByOrderOfQueries); } onUpdate(observer, result) { const index = this.observers.indexOf(observer); if (index !== -1) { this.result = replaceAt(this.result, index, result); this.notify(); } } notify() { notifyManager.batch(() => { this.listeners.forEach(listener => { listener(this.result); }); }); } } // CLASS class Query extends Removable { constructor(config) { super(); this.abortSignalConsumed = false; this.defaultOptions = config.defaultOptions; this.setOptions(config.options); this.observers = []; this.cache = config.cache; this.logger = config.logger || defaultLogger; this.queryKey = config.queryKey; this.queryHash = config.queryHash; this.initialState = config.state || getDefaultState(this.options); this.state = this.initialState; } get meta() { return this.options.meta; } setOptions(options) { this.options = { ...this.defaultOptions, ...options }; this.updateCacheTime(this.options.cacheTime); } optionalRemove() { if (!this.observers.length && this.state.fetchStatus === 'idle') { this.cache.remove(this); } } setData(newData, options) { const data = replaceData(this.state.data, newData, this.options); // Set data and mark it as cached this.dispatch({ data, type: 'success', dataUpdatedAt: options == null ? void 0 : options.updatedAt, manual: options == null ? void 0 : options.manual }); return data; } setState(state, setStateOptions) { this.dispatch({ type: 'setState', state, setStateOptions }); } cancel(options) { var _this$retryer; const promise = this.promise; (_this$retryer = this.retryer) == null ? void 0 : _this$retryer.cancel(options); return promise ? promise.then(noop$5).catch(noop$5) : Promise.resolve(); } destroy() { super.destroy(); this.cancel({ silent: true }); } reset() { this.destroy(); this.setState(this.initialState); } isActive() { return this.observers.some(observer => observer.options.enabled !== false); } isDisabled() { return this.getObserversCount() > 0 && !this.isActive(); } isStale() { return this.state.isInvalidated || !this.state.dataUpdatedAt || this.observers.some(observer => observer.getCurrentResult().isStale); } isStaleByTime(staleTime = 0) { return this.state.isInvalidated || !this.state.dataUpdatedAt || !timeUntilStale(this.state.dataUpdatedAt, staleTime); } onFocus() { var _this$retryer2; const observer = this.observers.find(x => x.shouldFetchOnWindowFocus()); if (observer) { observer.refetch({ cancelRefetch: false }); } // Continue fetch if currently paused (_this$retryer2 = this.retryer) == null ? void 0 : _this$retryer2.continue(); } onOnline() { var _this$retryer3; const observer = this.observers.find(x => x.shouldFetchOnReconnect()); if (observer) { observer.refetch({ cancelRefetch: false }); } // Continue fetch if currently paused (_this$retryer3 = this.retryer) == null ? void 0 : _this$retryer3.continue(); } addObserver(observer) { if (this.observers.indexOf(observer) === -1) { this.observers.push(observer); // Stop the query from being garbage collected this.clearGcTimeout(); this.cache.notify({ type: 'observerAdded', query: this, observer }); } } removeObserver(observer) { if (this.observers.indexOf(observer) !== -1) { this.observers = this.observers.filter(x => x !== observer); if (!this.observers.length) { // If the transport layer does not support cancellation // we'll let the query continue so the result can be cached if (this.retryer) { if (this.abortSignalConsumed) { this.retryer.cancel({ revert: true }); } else { this.retryer.cancelRetry(); } } this.scheduleGc(); } this.cache.notify({ type: 'observerRemoved', query: this, observer }); } } getObserversCount() { return this.observers.length; } invalidate() { if (!this.state.isInvalidated) { this.dispatch({ type: 'invalidate' }); } } fetch(options, fetchOptions) { var _this$options$behavio, _context$fetchOptions; if (this.state.fetchStatus !== 'idle') { if (this.state.dataUpdatedAt && fetchOptions != null && fetchOptions.cancelRefetch) { // Silently cancel current fetch if the user wants to cancel refetches this.cancel({ silent: true }); } else if (this.promise) { var _this$retryer4; // make sure that retries that were potentially cancelled due to unmounts can continue (_this$retryer4 = this.retryer) == null ? void 0 : _this$retryer4.continueRetry(); // Return current promise if we are already fetching return this.promise; } } // Update config if passed, otherwise the config from the last execution is used if (options) { this.setOptions(options); } // Use the options from the first observer with a query function if no function is found. // This can happen when the query is hydrated or created with setQueryData. if (!this.options.queryFn) { const observer = this.observers.find(x => x.options.queryFn); if (observer) { this.setOptions(observer.options); } } if (!Array.isArray(this.options.queryKey)) ; const abortController = getAbortController$1(); // Create query function context const queryFnContext = { queryKey: this.queryKey, pageParam: undefined, meta: this.meta }; // Adds an enumerable signal property to the object that // which sets abortSignalConsumed to true when the signal // is read. const addSignalProperty = object => { Object.defineProperty(object, 'signal', { enumerable: true, get: () => { if (abortController) { this.abortSignalConsumed = true; return abortController.signal; } return undefined; } }); }; addSignalProperty(queryFnContext); // Create fetch function const fetchFn = () => { if (!this.options.queryFn) { return Promise.reject('Missing queryFn'); } this.abortSignalConsumed = false; return this.options.queryFn(queryFnContext); }; // Trigger behavior hook const context = { fetchOptions, options: this.options, queryKey: this.queryKey, state: this.state, fetchFn }; addSignalProperty(context); (_this$options$behavio = this.options.behavior) == null ? void 0 : _this$options$behavio.onFetch(context); // Store state in case the current fetch needs to be reverted this.revertState = this.state; // Set to fetching state if not already in it if (this.state.fetchStatus === 'idle' || this.state.fetchMeta !== ((_context$fetchOptions = context.fetchOptions) == null ? void 0 : _context$fetchOptions.meta)) { var _context$fetchOptions2; this.dispatch({ type: 'fetch', meta: (_context$fetchOptions2 = context.fetchOptions) == null ? void 0 : _context$fetchOptions2.meta }); } const onError = error => { // Optimistically update state if needed if (!(isCancelledError(error) && error.silent)) { this.dispatch({ type: 'error', error: error }); } if (!isCancelledError(error)) { var _this$cache$config$on, _this$cache$config; // Notify cache callback (_this$cache$config$on = (_this$cache$config = this.cache.config).onError) == null ? void 0 : _this$cache$config$on.call(_this$cache$config, error, this); } if (!this.isFetchingOptimistic) { // Schedule query gc after fetching this.scheduleGc(); } this.isFetchingOptimistic = false; }; // Try to fetch the data this.retryer = createRetryer({ fn: context.fetchFn, abort: abortController == null ? void 0 : abortController.abort.bind(abortController), onSuccess: data => { var _this$cache$config$on2, _this$cache$config2; if (typeof data === 'undefined') { onError(new Error('undefined')); return; } this.setData(data); // Notify cache callback (_this$cache$config$on2 = (_this$cache$config2 = this.cache.config).onSuccess) == null ? void 0 : _this$cache$config$on2.call(_this$cache$config2, data, this); if (!this.isFetchingOptimistic) { // Schedule query gc after fetching this.scheduleGc(); } this.isFetchingOptimistic = false; }, onError, onFail: (failureCount, error) => { this.dispatch({ type: 'failed', failureCount, error }); }, onPause: () => { this.dispatch({ type: 'pause' }); }, onContinue: () => { this.dispatch({ type: 'continue' }); }, retry: context.options.retry, retryDelay: context.options.retryDelay, networkMode: context.options.networkMode }); this.promise = this.retryer.promise; return this.promise; } dispatch(action) { const reducer = state => { var _action$meta, _action$dataUpdatedAt; switch (action.type) { case 'failed': return { ...state, fetchFailureCount: action.failureCount, fetchFailureReason: action.error }; case 'pause': return { ...state, fetchStatus: 'paused' }; case 'continue': return { ...state, fetchStatus: 'fetching' }; case 'fetch': return { ...state, fetchFailureCount: 0, fetchFailureReason: null, fetchMeta: (_action$meta = action.meta) != null ? _action$meta : null, fetchStatus: canFetch(this.options.networkMode) ? 'fetching' : 'paused', ...(!state.dataUpdatedAt && { error: null, status: 'loading' }) }; case 'success': return { ...state, data: action.data, dataUpdateCount: state.dataUpdateCount + 1, dataUpdatedAt: (_action$dataUpdatedAt = action.dataUpdatedAt) != null ? _action$dataUpdatedAt : Date.now(), error: null, isInvalidated: false, status: 'success', ...(!action.manual && { fetchStatus: 'idle', fetchFailureCount: 0, fetchFailureReason: null }) }; case 'error': const error = action.error; if (isCancelledError(error) && error.revert && this.revertState) { return { ...this.revertState }; } return { ...state, error: error, errorUpdateCount: state.errorUpdateCount + 1, errorUpdatedAt: Date.now(), fetchFailureCount: state.fetchFailureCount + 1, fetchFailureReason: error, fetchStatus: 'idle', status: 'error' }; case 'invalidate': return { ...state, isInvalidated: true }; case 'setState': return { ...state, ...action.state }; } }; this.state = reducer(this.state); notifyManager.batch(() => { this.observers.forEach(observer => { observer.onQueryUpdate(action); }); this.cache.notify({ query: this, type: 'updated', action }); }); } } function getDefaultState(options) { const data = typeof options.initialData === 'function' ? options.initialData() : options.initialData; const hasData = typeof data !== 'undefined'; const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === 'function' ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0; return { data, dataUpdateCount: 0, dataUpdatedAt: hasData ? initialDataUpdatedAt != null ? initialDataUpdatedAt : Date.now() : 0, error: null, errorUpdateCount: 0, errorUpdatedAt: 0, fetchFailureCount: 0, fetchFailureReason: null, fetchMeta: null, isInvalidated: false, status: hasData ? 'success' : 'loading', fetchStatus: 'idle' }; } // CLASS class QueryCache extends Subscribable { constructor(config) { super(); this.config = config || {}; this.queries = []; this.queriesMap = {}; } build(client, options, state) { var _options$queryHash; const queryKey = options.queryKey; const queryHash = (_options$queryHash = options.queryHash) != null ? _options$queryHash : hashQueryKeyByOptions(queryKey, options); let query = this.get(queryHash); if (!query) { query = new Query({ cache: this, logger: client.getLogger(), queryKey, queryHash, options: client.defaultQueryOptions(options), state, defaultOptions: client.getQueryDefaults(queryKey) }); this.add(query); } return query; } add(query) { if (!this.queriesMap[query.queryHash]) { this.queriesMap[query.queryHash] = query; this.queries.push(query); this.notify({ type: 'added', query }); } } remove(query) { const queryInMap = this.queriesMap[query.queryHash]; if (queryInMap) { query.destroy(); this.queries = this.queries.filter(x => x !== query); if (queryInMap === query) { delete this.queriesMap[query.queryHash]; } this.notify({ type: 'removed', query }); } } clear() { notifyManager.batch(() => { this.queries.forEach(query => { this.remove(query); }); }); } get(queryHash) { return this.queriesMap[queryHash]; } getAll() { return this.queries; } find(arg1, arg2) { const [filters] = parseFilterArgs(arg1, arg2); if (typeof filters.exact === 'undefined') { filters.exact = true; } return this.queries.find(query => matchQuery(filters, query)); } findAll(arg1, arg2) { const [filters] = parseFilterArgs(arg1, arg2); return Object.keys(filters).length > 0 ? this.queries.filter(query => matchQuery(filters, query)) : this.queries; } notify(event) { notifyManager.batch(() => { this.listeners.forEach(listener => { listener(event); }); }); } onFocus() { notifyManager.batch(() => { this.queries.forEach(query => { query.onFocus(); }); }); } onOnline() { notifyManager.batch(() => { this.queries.forEach(query => { query.onOnline(); }); }); } } // CLASS class QueryClient { constructor(config = {}) { this.queryCache = config.queryCache || new QueryCache(); this.mutationCache = config.mutationCache || new MutationCache(); this.logger = config.logger || defaultLogger; this.defaultOptions = config.defaultOptions || {}; this.queryDefaults = []; this.mutationDefaults = []; } mount() { this.unsubscribeFocus = focusManager.subscribe(() => { if (focusManager.isFocused()) { this.resumePausedMutations(); this.queryCache.onFocus(); } }); this.unsubscribeOnline = onlineManager.subscribe(() => { if (onlineManager.isOnline()) { this.resumePausedMutations(); this.queryCache.onOnline(); } }); } unmount() { var _this$unsubscribeFocu, _this$unsubscribeOnli; (_this$unsubscribeFocu = this.unsubscribeFocus) == null ? void 0 : _this$unsubscribeFocu.call(this); (_this$unsubscribeOnli = this.unsubscribeOnline) == null ? void 0 : _this$unsubscribeOnli.call(this); } isFetching(arg1, arg2) { const [filters] = parseFilterArgs(arg1, arg2); filters.fetchStatus = 'fetching'; return this.queryCache.findAll(filters).length; } isMutating(filters) { return this.mutationCache.findAll({ ...filters, fetching: true }).length; } getQueryData(queryKey, filters) { var _this$queryCache$find; return (_this$queryCache$find = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find.state.data; } ensureQueryData(arg1, arg2, arg3) { const parsedOptions = parseQueryArgs(arg1, arg2, arg3); const cachedData = this.getQueryData(parsedOptions.queryKey); return cachedData ? Promise.resolve(cachedData) : this.fetchQuery(parsedOptions); } getQueriesData(queryKeyOrFilters) { return this.getQueryCache().findAll(queryKeyOrFilters).map(({ queryKey, state }) => { const data = state.data; return [queryKey, data]; }); } setQueryData(queryKey, updater, options) { const query = this.queryCache.find(queryKey); const prevData = query == null ? void 0 : query.state.data; const data = functionalUpdate(updater, prevData); if (typeof data === 'undefined') { return undefined; } const parsedOptions = parseQueryArgs(queryKey); const defaultedOptions = this.defaultQueryOptions(parsedOptions); return this.queryCache.build(this, defaultedOptions).setData(data, { ...options, manual: true }); } setQueriesData(queryKeyOrFilters, updater, options) { return notifyManager.batch(() => this.getQueryCache().findAll(queryKeyOrFilters).map(({ queryKey }) => [queryKey, this.setQueryData(queryKey, updater, options)])); } getQueryState(queryKey, filters) { var _this$queryCache$find2; return (_this$queryCache$find2 = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find2.state; } removeQueries(arg1, arg2) { const [filters] = parseFilterArgs(arg1, arg2); const queryCache = this.queryCache; notifyManager.batch(() => { queryCache.findAll(filters).forEach(query => { queryCache.remove(query); }); }); } resetQueries(arg1, arg2, arg3) { const [filters, options] = parseFilterArgs(arg1, arg2, arg3); const queryCache = this.queryCache; const refetchFilters = { type: 'active', ...filters }; return notifyManager.batch(() => { queryCache.findAll(filters).forEach(query => { query.reset(); }); return this.refetchQueries(refetchFilters, options); }); } cancelQueries(arg1, arg2, arg3) { const [filters, cancelOptions = {}] = parseFilterArgs(arg1, arg2, arg3); if (typeof cancelOptions.revert === 'undefined') { cancelOptions.revert = true; } const promises = notifyManager.batch(() => this.queryCache.findAll(filters).map(query => query.cancel(cancelOptions))); return Promise.all(promises).then(noop$5).catch(noop$5); } invalidateQueries(arg1, arg2, arg3) { const [filters, options] = parseFilterArgs(arg1, arg2, arg3); return notifyManager.batch(() => { var _ref, _filters$refetchType; this.queryCache.findAll(filters).forEach(query => { query.invalidate(); }); if (filters.refetchType === 'none') { return Promise.resolve(); } const refetchFilters = { ...filters, type: (_ref = (_filters$refetchType = filters.refetchType) != null ? _filters$refetchType : filters.type) != null ? _ref : 'active' }; return this.refetchQueries(refetchFilters, options); }); } refetchQueries(arg1, arg2, arg3) { const [filters, options] = parseFilterArgs(arg1, arg2, arg3); const promises = notifyManager.batch(() => this.queryCache.findAll(filters).filter(query => !query.isDisabled()).map(query => { var _options$cancelRefetc; return query.fetch(undefined, { ...options, cancelRefetch: (_options$cancelRefetc = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc : true, meta: { refetchPage: filters.refetchPage } }); })); let promise = Promise.all(promises).then(noop$5); if (!(options != null && options.throwOnError)) { promise = promise.catch(noop$5); } return promise; } fetchQuery(arg1, arg2, arg3) { const parsedOptions = parseQueryArgs(arg1, arg2, arg3); const defaultedOptions = this.defaultQueryOptions(parsedOptions); // https://github.com/tannerlinsley/react-query/issues/652 if (typeof defaultedOptions.retry === 'undefined') { defaultedOptions.retry = false; } const query = this.queryCache.build(this, defaultedOptions); return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data); } prefetchQuery(arg1, arg2, arg3) { return this.fetchQuery(arg1, arg2, arg3).then(noop$5).catch(noop$5); } fetchInfiniteQuery(arg1, arg2, arg3) { const parsedOptions = parseQueryArgs(arg1, arg2, arg3); parsedOptions.behavior = infiniteQueryBehavior(); return this.fetchQuery(parsedOptions); } prefetchInfiniteQuery(arg1, arg2, arg3) { return this.fetchInfiniteQuery(arg1, arg2, arg3).then(noop$5).catch(noop$5); } resumePausedMutations() { return this.mutationCache.resumePausedMutations(); } getQueryCache() { return this.queryCache; } getMutationCache() { return this.mutationCache; } getLogger() { return this.logger; } getDefaultOptions() { return this.defaultOptions; } setDefaultOptions(options) { this.defaultOptions = options; } setQueryDefaults(queryKey, options) { const result = this.queryDefaults.find(x => hashQueryKey$1(queryKey) === hashQueryKey$1(x.queryKey)); if (result) { result.defaultOptions = options; } else { this.queryDefaults.push({ queryKey, defaultOptions: options }); } } getQueryDefaults(queryKey) { if (!queryKey) { return undefined; } // Get the first matching defaults const firstMatchingDefaults = this.queryDefaults.find(x => partialMatchKey(queryKey, x.queryKey)); // Additional checks and error in dev mode return firstMatchingDefaults == null ? void 0 : firstMatchingDefaults.defaultOptions; } setMutationDefaults(mutationKey, options) { const result = this.mutationDefaults.find(x => hashQueryKey$1(mutationKey) === hashQueryKey$1(x.mutationKey)); if (result) { result.defaultOptions = options; } else { this.mutationDefaults.push({ mutationKey, defaultOptions: options }); } } getMutationDefaults(mutationKey) { if (!mutationKey) { return undefined; } // Get the first matching defaults const firstMatchingDefaults = this.mutationDefaults.find(x => partialMatchKey(mutationKey, x.mutationKey)); // Additional checks and error in dev mode return firstMatchingDefaults == null ? void 0 : firstMatchingDefaults.defaultOptions; } defaultQueryOptions(options) { if (options != null && options._defaulted) { return options; } const defaultedOptions = { ...this.defaultOptions.queries, ...this.getQueryDefaults(options == null ? void 0 : options.queryKey), ...options, _defaulted: true }; if (!defaultedOptions.queryHash && defaultedOptions.queryKey) { defaultedOptions.queryHash = hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions); } // dependent default values if (typeof defaultedOptions.refetchOnReconnect === 'undefined') { defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== 'always'; } if (typeof defaultedOptions.useErrorBoundary === 'undefined') { defaultedOptions.useErrorBoundary = !!defaultedOptions.suspense; } return defaultedOptions; } defaultMutationOptions(options) { if (options != null && options._defaulted) { return options; } return { ...this.defaultOptions.mutations, ...this.getMutationDefaults(options == null ? void 0 : options.mutationKey), ...options, _defaulted: true }; } clear() { this.queryCache.clear(); this.mutationCache.clear(); } } function shouldThrowError(_useErrorBoundary, params) { // Allow useErrorBoundary function to override throwing behavior on a per-error basis if (typeof _useErrorBoundary === 'function') { return _useErrorBoundary(...params); } return !!_useErrorBoundary; } const ensurePreventErrorBoundaryRetry = (options, errorResetBoundary) => { if (options.suspense || options.useErrorBoundary) { // Prevent retrying failed query if the error boundary has not been reset yet if (!errorResetBoundary.isReset()) { options.retryOnMount = false; } } }; const useClearResetErrorBoundary = errorResetBoundary => { reactExports.useEffect(() => { errorResetBoundary.clearReset(); }, [errorResetBoundary]); }; const getHasError = ({ result, errorResetBoundary, useErrorBoundary, query }) => { return result.isError && !errorResetBoundary.isReset() && !result.isFetching && shouldThrowError(useErrorBoundary, [result.error, query]); }; const defaultContext = /*#__PURE__*/reactExports.createContext(undefined); const QueryClientSharingContext = /*#__PURE__*/reactExports.createContext(false); // If we are given a context, we will use it. // Otherwise, if contextSharing is on, we share the first and at least one // instance of the context across the window // to ensure that if React Query is used across // different bundles or microfrontends they will // all use the same **instance** of context, regardless // of module scoping. function getQueryClientContext(context, contextSharing) { if (context) { return context; } if (contextSharing && typeof window !== 'undefined') { if (!window.ReactQueryClientContext) { window.ReactQueryClientContext = defaultContext; } return window.ReactQueryClientContext; } return defaultContext; } const useQueryClient = ({ context } = {}) => { const queryClient = reactExports.useContext(getQueryClientContext(context, reactExports.useContext(QueryClientSharingContext))); if (!queryClient) { throw new Error('No QueryClient set, use QueryClientProvider to set one'); } return queryClient; }; const QueryClientProvider = ({ client, children, context, contextSharing = false }) => { reactExports.useEffect(() => { client.mount(); return () => { client.unmount(); }; }, [client]); const Context = getQueryClientContext(context, contextSharing); return /*#__PURE__*/reactExports.createElement(QueryClientSharingContext.Provider, { value: !context && contextSharing }, /*#__PURE__*/reactExports.createElement(Context.Provider, { value: client }, children)); }; function useHydrate(state, options = {}) { const queryClient = useQueryClient({ context: options.context }); const optionsRef = reactExports.useRef(options); optionsRef.current = options; // Running hydrate again with the same queries is safe, // it wont overwrite or initialize existing queries, // relying on useMemo here is only a performance optimization. // hydrate can and should be run *during* render here for SSR to work properly reactExports.useMemo(() => { if (state) { hydrate(queryClient, state, optionsRef.current); } }, [queryClient, state]); } const Hydrate = ({ children, options, state }) => { useHydrate(state, options); return children; }; const IsRestoringContext = /*#__PURE__*/reactExports.createContext(false); const useIsRestoring = () => reactExports.useContext(IsRestoringContext); IsRestoringContext.Provider; function createValue() { let isReset = false; return { clearReset: () => { isReset = false; }, reset: () => { isReset = true; }, isReset: () => { return isReset; } }; } const QueryErrorResetBoundaryContext = /*#__PURE__*/reactExports.createContext(createValue()); // HOOK const useQueryErrorResetBoundary = () => reactExports.useContext(QueryErrorResetBoundaryContext); // COMPONENT const ensureStaleTime = defaultedOptions => { if (defaultedOptions.suspense) { // Always set stale time when using suspense to prevent // fetching again when directly mounting after suspending if (typeof defaultedOptions.staleTime !== 'number') { defaultedOptions.staleTime = 1000; } } }; const willFetch = (result, isRestoring) => result.isLoading && result.isFetching && !isRestoring; const shouldSuspend = (defaultedOptions, result, isRestoring) => (defaultedOptions == null ? void 0 : defaultedOptions.suspense) && willFetch(result, isRestoring); const fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).then(({ data }) => { defaultedOptions.onSuccess == null ? void 0 : defaultedOptions.onSuccess(data); defaultedOptions.onSettled == null ? void 0 : defaultedOptions.onSettled(data, null); }).catch(error => { errorResetBoundary.clearReset(); defaultedOptions.onError == null ? void 0 : defaultedOptions.onError(error); defaultedOptions.onSettled == null ? void 0 : defaultedOptions.onSettled(undefined, error); }); var shim = {exports: {}}; var useSyncExternalStoreShim_production_min = {}; var e$8=reactExports;function h$c(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k$6="function"===typeof Object.is?Object.is:h$c,l$e=e$8.useState,m$7=e$8.useEffect,n$e=e$8.useLayoutEffect,p$e=e$8.useDebugValue;function q$7(a,b){var d=b(),f=l$e({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n$e(function(){c.value=d;c.getSnapshot=b;r$a(c)&&g({inst:c});},[a,d,b]);m$7(function(){r$a(c)&&g({inst:c});return a(function(){r$a(c)&&g({inst:c});})},[a]);p$e(d);return d} function r$a(a){var b=a.getSnapshot;a=a.value;try{var d=b();return !k$6(a,d)}catch(f){return !0}}function t$e(a,b){return b()}var u$f="undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement?t$e:q$7;useSyncExternalStoreShim_production_min.useSyncExternalStore=void 0!==e$8.useSyncExternalStore?e$8.useSyncExternalStore:u$f; { shim.exports = useSyncExternalStoreShim_production_min; } var shimExports = shim.exports; // Temporary workaround due to an issue with react-native uSES - https://github.com/TanStack/query/pull/3601 const useSyncExternalStore$1 = shimExports.useSyncExternalStore; function useBaseQuery(options, Observer) { const queryClient = useQueryClient({ context: options.context }); const isRestoring = useIsRestoring(); const errorResetBoundary = useQueryErrorResetBoundary(); const defaultedOptions = queryClient.defaultQueryOptions(options); // Make sure results are optimistically set in fetching state before subscribing or updating options defaultedOptions._optimisticResults = isRestoring ? 'isRestoring' : 'optimistic'; // Include callbacks in batch renders if (defaultedOptions.onError) { defaultedOptions.onError = notifyManager.batchCalls(defaultedOptions.onError); } if (defaultedOptions.onSuccess) { defaultedOptions.onSuccess = notifyManager.batchCalls(defaultedOptions.onSuccess); } if (defaultedOptions.onSettled) { defaultedOptions.onSettled = notifyManager.batchCalls(defaultedOptions.onSettled); } ensureStaleTime(defaultedOptions); ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary); useClearResetErrorBoundary(errorResetBoundary); const [observer] = reactExports.useState(() => new Observer(queryClient, defaultedOptions)); const result = observer.getOptimisticResult(defaultedOptions); useSyncExternalStore$1(reactExports.useCallback(onStoreChange => isRestoring ? () => undefined : observer.subscribe(notifyManager.batchCalls(onStoreChange)), [observer, isRestoring]), () => observer.getCurrentResult(), () => observer.getCurrentResult()); reactExports.useEffect(() => { // Do not notify on updates because of changes in the options because // these changes should already be reflected in the optimistic result. observer.setOptions(defaultedOptions, { listeners: false }); }, [defaultedOptions, observer]); // Handle suspense if (shouldSuspend(defaultedOptions, result, isRestoring)) { throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary); } // Handle error boundary if (getHasError({ result, errorResetBoundary, useErrorBoundary: defaultedOptions.useErrorBoundary, query: observer.getCurrentQuery() })) { throw result.error; } // Handle result property usage tracking return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result; } function useInfiniteQuery(arg1, arg2, arg3) { const options = parseQueryArgs(arg1, arg2, arg3); return useBaseQuery(options, InfiniteQueryObserver); } function useMutation(arg1, arg2, arg3) { const options = parseMutationArgs(arg1, arg2); const queryClient = useQueryClient({ context: options.context }); const [observer] = reactExports.useState(() => new MutationObserver$1(queryClient, options)); reactExports.useEffect(() => { observer.setOptions(options); }, [observer, options]); const result = useSyncExternalStore$1(reactExports.useCallback(onStoreChange => observer.subscribe(notifyManager.batchCalls(onStoreChange)), [observer]), () => observer.getCurrentResult(), () => observer.getCurrentResult()); const mutate = reactExports.useCallback((variables, mutateOptions) => { observer.mutate(variables, mutateOptions).catch(noop$4); }, [observer]); if (result.error && shouldThrowError(observer.options.useErrorBoundary, [result.error])) { throw result.error; } return { ...result, mutate, mutateAsync: result.mutate }; } // eslint-disable-next-line @typescript-eslint/no-empty-function function noop$4() {} // - `context` is omitted as it is passed as a root-level option to `useQueries` instead. function useQueries({ queries, context }) { const queryClient = useQueryClient({ context }); const isRestoring = useIsRestoring(); const defaultedQueries = reactExports.useMemo(() => queries.map(options => { const defaultedOptions = queryClient.defaultQueryOptions(options); // Make sure the results are already in fetching state before subscribing or updating options defaultedOptions._optimisticResults = isRestoring ? 'isRestoring' : 'optimistic'; return defaultedOptions; }), [queries, queryClient, isRestoring]); const [observer] = reactExports.useState(() => new QueriesObserver(queryClient, defaultedQueries)); const optimisticResult = observer.getOptimisticResult(defaultedQueries); useSyncExternalStore$1(reactExports.useCallback(onStoreChange => isRestoring ? () => undefined : observer.subscribe(notifyManager.batchCalls(onStoreChange)), [observer, isRestoring]), () => observer.getCurrentResult(), () => observer.getCurrentResult()); reactExports.useEffect(() => { // Do not notify on updates because of changes in the options because // these changes should already be reflected in the optimistic result. observer.setQueries(defaultedQueries, { listeners: false }); }, [defaultedQueries, observer]); const errorResetBoundary = useQueryErrorResetBoundary(); defaultedQueries.forEach(query => { ensurePreventErrorBoundaryRetry(query, errorResetBoundary); ensureStaleTime(query); }); useClearResetErrorBoundary(errorResetBoundary); const shouldAtLeastOneSuspend = optimisticResult.some((result, index) => shouldSuspend(defaultedQueries[index], result, isRestoring)); const suspensePromises = shouldAtLeastOneSuspend ? optimisticResult.flatMap((result, index) => { const options = defaultedQueries[index]; const queryObserver = observer.getObservers()[index]; if (options && queryObserver) { if (shouldSuspend(options, result, isRestoring)) { return fetchOptimistic(options, queryObserver, errorResetBoundary); } else if (willFetch(result, isRestoring)) { void fetchOptimistic(options, queryObserver, errorResetBoundary); } } return []; }) : []; if (suspensePromises.length > 0) { throw Promise.all(suspensePromises); } const firstSingleResultWhichShouldThrow = optimisticResult.find((result, index) => { var _defaultedQueries$ind, _defaultedQueries$ind2; return getHasError({ result, errorResetBoundary, useErrorBoundary: (_defaultedQueries$ind = (_defaultedQueries$ind2 = defaultedQueries[index]) == null ? void 0 : _defaultedQueries$ind2.useErrorBoundary) != null ? _defaultedQueries$ind : false, query: observer.getQueries()[index] }); }); if (firstSingleResultWhichShouldThrow != null && firstSingleResultWhichShouldThrow.error) { throw firstSingleResultWhichShouldThrow.error; } return optimisticResult; } function useQuery(arg1, arg2, arg3) { const parsedOptions = parseQueryArgs(arg1, arg2, arg3); return useBaseQuery(parsedOptions, QueryObserver); } function hashQueryKey() { throw new Error('not implemented') } function identity$1(x) { return x; } /** @internal */ function pipeFromArray(fns) { if (fns.length === 0) { return identity$1; } if (fns.length === 1) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return fns[0]; } return function piped(input) { return fns.reduce((prev, fn)=>fn(prev), input); }; } function observable(subscribe) { const self = { subscribe (observer) { let teardownRef = null; let isDone = false; let unsubscribed = false; let teardownImmediately = false; function unsubscribe() { if (teardownRef === null) { teardownImmediately = true; return; } if (unsubscribed) { return; } unsubscribed = true; if (typeof teardownRef === 'function') { teardownRef(); } else if (teardownRef) { teardownRef.unsubscribe(); } } teardownRef = subscribe({ next (value) { if (isDone) { return; } observer.next?.(value); }, error (err) { if (isDone) { return; } isDone = true; observer.error?.(err); unsubscribe(); }, complete () { if (isDone) { return; } isDone = true; observer.complete?.(); unsubscribe(); } }); if (teardownImmediately) { unsubscribe(); } return { unsubscribe }; }, pipe (...operations) { return pipeFromArray(operations)(self); } }; return self; } function share(_opts) { return (originalObserver)=>{ let refCount = 0; let subscription = null; const observers = []; function startIfNeeded() { if (subscription) { return; } subscription = originalObserver.subscribe({ next (value) { for (const observer of observers){ observer.next?.(value); } }, error (error) { for (const observer of observers){ observer.error?.(error); } }, complete () { for (const observer of observers){ observer.complete?.(); } } }); } function resetIfNeeded() { // "resetOnRefCountZero" if (refCount === 0 && subscription) { const _sub = subscription; subscription = null; _sub.unsubscribe(); } } return { subscribe (observer) { refCount++; observers.push(observer); startIfNeeded(); return { unsubscribe () { refCount--; resetIfNeeded(); const index = observers.findIndex((v)=>v === observer); if (index > -1) { observers.splice(index, 1); } } }; } }; }; } class ObservableAbortError extends Error { constructor(message){ super(message); this.name = 'ObservableAbortError'; Object.setPrototypeOf(this, ObservableAbortError.prototype); } } /** @internal */ function observableToPromise(observable) { let abort; const promise = new Promise((resolve, reject)=>{ let isDone = false; function onDone() { if (isDone) { return; } isDone = true; reject(new ObservableAbortError('This operation was aborted.')); obs$.unsubscribe(); } const obs$ = observable.subscribe({ next (data) { isDone = true; resolve(data); onDone(); }, error (data) { isDone = true; reject(data); onDone(); }, complete () { isDone = true; onDone(); } }); abort = onDone; }); return { promise, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion abort: abort }; } function isObject$2(value) { // check that value is object return !!value && !Array.isArray(value) && typeof value === 'object'; } // FIXME: // - the generics here are probably unnecessary // - the RPC-spec could probably be simplified to combine HTTP + WS /** @internal */ function transformResultInner(response, runtime) { if ('error' in response) { const error = runtime.transformer.deserialize(response.error); return { ok: false, error: { ...response, error } }; } const result = { ...response.result, ...(!response.result.type || response.result.type === 'data') && { type: 'data', data: runtime.transformer.deserialize(response.result.data) } }; return { ok: true, result }; } class TransformResultError extends Error { constructor(){ super('Unable to transform response from server'); } } /** * Transforms and validates that the result is a valid TRPCResponse * @internal */ function transformResult(response, runtime) { let result; try { // Use the data transformers on the JSON-response result = transformResultInner(response, runtime); } catch (err) { throw new TransformResultError(); } // check that output of the transformers is a valid TRPCResponse if (!result.ok && (!isObject$2(result.error.error) || typeof result.error.error.code !== 'number')) { throw new TransformResultError(); } if (result.ok && !isObject$2(result.result)) { throw new TransformResultError(); } return result; } function isTRPCClientError(cause) { return cause instanceof TRPCClientError || /** * @deprecated * Delete in next major */ cause instanceof Error && cause.name === 'TRPCClientError'; } function isTRPCErrorResponse(obj) { return isObject$2(obj) && isObject$2(obj.error) && typeof obj.error.code === 'number' && typeof obj.error.message === 'string'; } class TRPCClientError extends Error { static from(_cause, opts = {}) { const cause = _cause; if (isTRPCClientError(cause)) { if (opts.meta) { // Decorate with meta error data cause.meta = { ...cause.meta, ...opts.meta }; } return cause; } if (isTRPCErrorResponse(cause)) { return new TRPCClientError(cause.error.message, { ...opts, result: cause }); } if (!(cause instanceof Error)) { return new TRPCClientError('Unknown error', { ...opts, cause: cause }); } return new TRPCClientError(cause.message, { ...opts, cause }); } constructor(message, opts){ const cause = opts?.cause; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore https://github.com/tc39/proposal-error-cause super(message, { cause }); this.meta = opts?.meta; this.cause = cause; this.shape = opts?.result?.error; this.data = opts?.result?.error.data; this.name = 'TRPCClientError'; Object.setPrototypeOf(this, TRPCClientError.prototype); } } function getAbortController(customAbortControllerImpl) { if (customAbortControllerImpl) { return customAbortControllerImpl; } // eslint-disable-next-line @typescript-eslint/prefer-optional-chain if (typeof window !== 'undefined' && window.AbortController) { return window.AbortController; } // eslint-disable-next-line @typescript-eslint/prefer-optional-chain if (typeof globalThis !== 'undefined' && globalThis.AbortController) { return globalThis.AbortController; } return null; } function resolveHTTPLinkOptions(opts) { return { url: opts.url.toString().replace(/\/$/, ''), fetch: opts.fetch, AbortController: getAbortController(opts.AbortController) }; } // https://github.com/trpc/trpc/pull/669 function arrayToDict(array) { const dict = {}; for(let index = 0; index < array.length; index++){ const element = array[index]; dict[index] = element; } return dict; } function getInput$1(opts) { return 'input' in opts ? opts.runtime.transformer.serialize(opts.input) : arrayToDict(opts.inputs.map((_input)=>opts.runtime.transformer.serialize(_input))); } const getUrl = (opts)=>{ let url = opts.url + '/' + opts.path; const queryParts = []; if ('inputs' in opts) { queryParts.push('batch=1'); } if (opts.type === 'query') { const input = getInput$1(opts); if (input !== undefined) { queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`); } } if (queryParts.length) { url += '?' + queryParts.join('&'); } return url; }; const getBody = (opts)=>{ if (opts.type === 'query') { return undefined; } const input = getInput$1(opts); return input !== undefined ? JSON.stringify(input) : undefined; }; const jsonHttpRequester = (opts)=>{ return httpRequest({ ...opts, contentTypeHeader: 'application/json', getUrl, getBody }); }; async function fetchHTTPResponse(opts, ac) { return new Promise(() => {}); } function httpRequest(opts) { const ac = opts.AbortController ? new opts.AbortController() : null; const meta = {}; let done = false; const promise = new Promise((resolve, reject)=>{ fetchHTTPResponse().then((_res)=>{ meta.response = _res; done = true; return _res.json(); }).then((json)=>{ meta.responseJSON = json; resolve({ json: json, meta }); }).catch((err)=>{ done = true; reject(TRPCClientError.from(err, { meta })); }); }); const cancel = ()=>{ if (!done) { ac?.abort(); } }; return { promise, cancel }; } /* eslint-disable @typescript-eslint/no-non-null-assertion */ /** * A function that should never be called unless we messed something up. */ const throwFatalError = ()=>{ throw new Error('Something went wrong. Please submit an issue at https://github.com/trpc/trpc/issues/new'); }; /** * Dataloader that's very inspired by https://github.com/graphql/dataloader * Less configuration, no caching, and allows you to cancel requests * When cancelling a single fetch the whole batch will be cancelled only when _all_ items are cancelled */ function dataLoader(batchLoader) { let pendingItems = null; let dispatchTimer = null; const destroyTimerAndPendingItems = ()=>{ clearTimeout(dispatchTimer); dispatchTimer = null; pendingItems = null; }; /** * Iterate through the items and split them into groups based on the `batchLoader`'s validate function */ function groupItems(items) { const groupedItems = [ [] ]; let index = 0; while(true){ const item = items[index]; if (!item) { break; } const lastGroup = groupedItems[groupedItems.length - 1]; if (item.aborted) { // Item was aborted before it was dispatched item.reject?.(new Error('Aborted')); index++; continue; } const isValid = batchLoader.validate(lastGroup.concat(item).map((it)=>it.key)); if (isValid) { lastGroup.push(item); index++; continue; } if (lastGroup.length === 0) { item.reject?.(new Error('Input is too big for a single dispatch')); index++; continue; } // Create new group, next iteration will try to add the item to that groupedItems.push([]); } return groupedItems; } function dispatch() { const groupedItems = groupItems(pendingItems); destroyTimerAndPendingItems(); // Create batches for each group of items for (const items of groupedItems){ if (!items.length) { continue; } const batch = { items, cancel: throwFatalError }; for (const item of items){ item.batch = batch; } const unitResolver = (index, value)=>{ const item = batch.items[index]; item.resolve?.(value); item.batch = null; item.reject = null; item.resolve = null; }; const { promise , cancel } = batchLoader.fetch(batch.items.map((_item)=>_item.key), unitResolver); batch.cancel = cancel; promise.then((result)=>{ for(let i = 0; i < result.length; i++){ const value = result[i]; unitResolver(i, value); } for (const item of batch.items){ item.reject?.(new Error('Missing result')); item.batch = null; } }).catch((cause)=>{ for (const item of batch.items){ item.reject?.(cause); item.batch = null; } }); } } function load(key) { const item = { aborted: false, key, batch: null, resolve: throwFatalError, reject: throwFatalError }; const promise = new Promise((resolve, reject)=>{ item.reject = reject; item.resolve = resolve; if (!pendingItems) { pendingItems = []; } pendingItems.push(item); }); if (!dispatchTimer) { dispatchTimer = setTimeout(dispatch); } const cancel = ()=>{ item.aborted = true; if (item.batch?.items.every((item)=>item.aborted)) { // All items in the batch have been cancelled item.batch.cancel(); item.batch = null; } }; return { promise, cancel }; } return { load }; } /** * @internal */ function createHTTPBatchLink(requester) { return function httpBatchLink(opts) { const resolvedOpts = resolveHTTPLinkOptions(opts); const maxURLLength = opts.maxURLLength ?? Infinity; // initialized config return (runtime)=>{ const batchLoader = (type)=>{ const validate = (batchOps)=>{ if (maxURLLength === Infinity) { // escape hatch for quick calcs return true; } const path = batchOps.map((op)=>op.path).join(','); const inputs = batchOps.map((op)=>op.input); const url = getUrl({ ...resolvedOpts, runtime, type, path, inputs }); return url.length <= maxURLLength; }; const fetch = requester({ ...resolvedOpts, runtime, type, opts }); return { validate, fetch }; }; const query = dataLoader(batchLoader('query')); const mutation = dataLoader(batchLoader('mutation')); const subscription = dataLoader(batchLoader('subscription')); const loaders = { query, subscription, mutation }; return ({ op })=>{ return observable((observer)=>{ const loader = loaders[op.type]; const { promise , cancel } = loader.load(op); let _res = undefined; promise.then((res)=>{ _res = res; const transformed = transformResult(res.json, runtime); if (!transformed.ok) { observer.error(TRPCClientError.from(transformed.error, { meta: res.meta })); return; } observer.next({ context: res.meta, result: transformed.result }); observer.complete(); }).catch((err)=>{ observer.error(TRPCClientError.from(err, { meta: _res?.meta })); }); return ()=>{ cancel(); }; }); }; }; }; } const batchRequester = (requesterOpts)=>{ return (batchOps)=>{ const path = batchOps.map((op)=>op.path).join(','); const inputs = batchOps.map((op)=>op.input); const { promise , cancel } = jsonHttpRequester({ ...requesterOpts, path, inputs, headers () { if (!requesterOpts.opts.headers) { return {}; } if (typeof requesterOpts.opts.headers === 'function') { return requesterOpts.opts.headers({ opList: batchOps }); } return requesterOpts.opts.headers; } }); return { promise: promise.then((res)=>{ const resJSON = Array.isArray(res.json) ? res.json : batchOps.map(()=>res.json); const result = resJSON.map((item)=>({ meta: res.meta, json: item })); return result; }), cancel }; }; }; const httpBatchLink = createHTTPBatchLink(batchRequester); var index_browser = {exports: {}}; var build = {}; var tinyEmitter = {exports: {}}; function E$4 () { // Keep this empty so it's easier to inherit from // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3) } E$4.prototype = { on: function (name, callback, ctx) { var e = this.e || (this.e = {}); (e[name] || (e[name] = [])).push({ fn: callback, ctx: ctx }); return this; }, once: function (name, callback, ctx) { var self = this; function listener () { self.off(name, listener); callback.apply(ctx, arguments); } listener._ = callback; return this.on(name, listener, ctx); }, emit: function (name) { var data = [].slice.call(arguments, 1); var evtArr = ((this.e || (this.e = {}))[name] || []).slice(); var i = 0; var len = evtArr.length; for (i; i < len; i++) { evtArr[i].fn.apply(evtArr[i].ctx, data); } return this; }, off: function (name, callback) { var e = this.e || (this.e = {}); var evts = e[name]; var liveEvents = []; if (evts && callback) { for (var i = 0, len = evts.length; i < len; i++) { if (evts[i].fn !== callback && evts[i].fn._ !== callback) liveEvents.push(evts[i]); } } // Remove event from queue to prevent memory leak // Suggested by https://github.com/lazd // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910 (liveEvents.length) ? e[name] = liveEvents : delete e[name]; return this; } }; tinyEmitter.exports = E$4; tinyEmitter.exports.TinyEmitter = E$4; var tinyEmitterExports = tinyEmitter.exports; var metrics = {}; // Simplified version of: https://github.com/Unleash/unleash-client-node/blob/main/src/metrics.ts var __assign$7 = (commonjsGlobal && commonjsGlobal.__assign) || function () { __assign$7 = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign$7.apply(this, arguments); }; var __awaiter$2 = (commonjsGlobal && commonjsGlobal.__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 __generator$2 = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(metrics, "__esModule", { value: true }); var Metrics = /** @class */ (function () { function Metrics(_a) { var onError = _a.onError, appName = _a.appName, metricsInterval = _a.metricsInterval, _b = _a.disableMetrics, disableMetrics = _b === void 0 ? false : _b, url = _a.url, clientKey = _a.clientKey, fetch = _a.fetch, headerName = _a.headerName; this.onError = onError; this.disabled = disableMetrics; this.metricsInterval = metricsInterval * 1000; this.appName = appName; this.url = url instanceof URL ? url : new URL(url); this.clientKey = clientKey; this.bucket = this.createEmptyBucket(); this.fetch = fetch; this.headerName = headerName; } Metrics.prototype.start = function () { var _this = this; if (this.disabled) { return false; } if (typeof this.metricsInterval === 'number' && this.metricsInterval > 0) { // send first metrics after two seconds. setTimeout(function () { _this.startTimer(); _this.sendMetrics(); }, 2000); } }; Metrics.prototype.stop = function () { if (this.timer) { clearTimeout(this.timer); delete this.timer; } }; Metrics.prototype.createEmptyBucket = function () { return { start: new Date(), stop: null, toggles: {}, }; }; Metrics.prototype.sendMetrics = function () { return __awaiter$2(this, void 0, void 0, function () { var url, payload, e_1; var _a; return __generator$2(this, function (_b) { switch (_b.label) { case 0: url = "".concat(this.url, "/client/metrics"); payload = this.getPayload(); if (this.bucketIsEmpty(payload)) { return [2 /*return*/]; } _b.label = 1; case 1: _b.trys.push([1, 3, , 4]); return [4 /*yield*/, this.fetch(url, { cache: 'no-cache', method: 'POST', headers: (_a = {}, _a[this.headerName] = this.clientKey, _a.Accept = 'application/json', _a['Content-Type'] = 'application/json', _a), body: JSON.stringify(payload), })]; case 2: _b.sent(); return [3 /*break*/, 4]; case 3: e_1 = _b.sent(); console.error('Unleash: unable to send feature metrics', e_1); this.onError(e_1); return [3 /*break*/, 4]; case 4: return [2 /*return*/]; } }); }); }; Metrics.prototype.count = function (name, enabled) { if (this.disabled || !this.bucket) { return false; } this.assertBucket(name); this.bucket.toggles[name][enabled ? 'yes' : 'no']++; return true; }; Metrics.prototype.assertBucket = function (name) { if (this.disabled || !this.bucket) { return false; } if (!this.bucket.toggles[name]) { this.bucket.toggles[name] = { yes: 0, no: 0, }; } }; Metrics.prototype.startTimer = function () { var _this = this; this.timer = setInterval(function () { _this.sendMetrics(); }, this.metricsInterval); }; Metrics.prototype.bucketIsEmpty = function (payload) { return Object.keys(payload.bucket.toggles).length === 0; }; Metrics.prototype.getPayload = function () { var bucket = __assign$7(__assign$7({}, this.bucket), { stop: new Date() }); this.bucket = this.createEmptyBucket(); return { bucket: bucket, appName: this.appName, instanceId: 'browser', }; }; return Metrics; }()); metrics.default = Metrics; var storageProviderInmemory = {}; var __awaiter$1 = (commonjsGlobal && commonjsGlobal.__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 __generator$1 = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(storageProviderInmemory, "__esModule", { value: true }); var ImMemoryStorageProvider = /** @class */ (function () { function ImMemoryStorageProvider() { this.store = new Map(); } ImMemoryStorageProvider.prototype.save = function (name, data) { return __awaiter$1(this, void 0, void 0, function () { return __generator$1(this, function (_a) { this.store.set(name, data); return [2 /*return*/]; }); }); }; ImMemoryStorageProvider.prototype.get = function (name) { return __awaiter$1(this, void 0, void 0, function () { return __generator$1(this, function (_a) { return [2 /*return*/, this.store.get(name)]; }); }); }; return ImMemoryStorageProvider; }()); storageProviderInmemory.default = ImMemoryStorageProvider; var storageProviderLocal = {}; var __awaiter = (commonjsGlobal && commonjsGlobal.__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 __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(storageProviderLocal, "__esModule", { value: true }); var LocalStorageProvider = /** @class */ (function () { function LocalStorageProvider() { this.prefix = 'unleash:repository'; } LocalStorageProvider.prototype.save = function (name, data) { return __awaiter(this, void 0, void 0, function () { var repo, key; return __generator(this, function (_a) { repo = JSON.stringify(data); key = "".concat(this.prefix, ":").concat(name); try { window.localStorage.setItem(key, repo); } catch (ex) { console.error(ex); } return [2 /*return*/]; }); }); }; LocalStorageProvider.prototype.get = function (name) { try { var key = "".concat(this.prefix, ":").concat(name); var data = window.localStorage.getItem(key); return data ? JSON.parse(data) : undefined; } catch (e) { console.error(e); } }; return LocalStorageProvider; }()); storageProviderLocal.default = LocalStorageProvider; var eventsHandler = {}; var nil = '00000000-0000-0000-0000-000000000000'; // Unique ID creation requires a high quality random # generator. In the browser we therefore // require the crypto API and do not support built-in fallback to lower quality random number // generators (like Math.random()). var getRandomValues; var rnds8 = new Uint8Array(16); function rng() { // lazy load so that environments that need to polyfill have a chance to do so if (!getRandomValues) { // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, // find the complete implementation of crypto (msCrypto) on IE11. getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto); if (!getRandomValues) { throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); } } return getRandomValues(rnds8); } var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; function validate(uuid) { return typeof uuid === 'string' && REGEX.test(uuid); } /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ var byteToHex = []; for (var i$a = 0; i$a < 256; ++i$a) { byteToHex.push((i$a + 0x100).toString(16).substr(1)); } function stringify$3(arr) { var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; // Note: Be careful editing this code! It's been tuned for performance // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one // of the following: // - One or more input array values don't map to a hex octet (leading to // "undefined" in the uuid) // - Invalid input values for the RFC `version` or `variant` fields if (!validate(uuid)) { throw TypeError('Stringified UUID is invalid'); } return uuid; } function v4(options, buf, offset) { options = options || {}; var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = rnds[6] & 0x0f | 0x40; rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided if (buf) { offset = offset || 0; for (var i = 0; i < 16; ++i) { buf[offset + i] = rnds[i]; } return buf; } return stringify$3(rnds); } var special_uuid_ = /*#__PURE__*/Object.freeze({ __proto__: null, NIL: nil, v4: v4 }); var require$$0$3 = /*@__PURE__*/getAugmentedNamespace(special_uuid_); var __assign$6 = (commonjsGlobal && commonjsGlobal.__assign) || function () { __assign$6 = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign$6.apply(this, arguments); }; Object.defineProperty(eventsHandler, "__esModule", { value: true }); var uuid_1 = require$$0$3; var EventsHandler = /** @class */ (function () { function EventsHandler() { } EventsHandler.prototype.generateEventId = function () { return (0, uuid_1.v4)(); }; EventsHandler.prototype.createImpressionEvent = function (context, enabled, featureName, eventType, variant) { var baseEvent = this.createBaseEvent(context, enabled, featureName, eventType); if (variant) { return __assign$6(__assign$6({}, baseEvent), { variant: variant }); } return baseEvent; }; EventsHandler.prototype.createBaseEvent = function (context, enabled, featureName, eventType) { return { eventType: eventType, eventId: this.generateEventId(), context: context, enabled: enabled, featureName: featureName, }; }; return EventsHandler; }()); eventsHandler.default = EventsHandler; var util$1 = {}; Object.defineProperty(util$1, "__esModule", { value: true }); util$1.notNullOrUndefined = void 0; var notNullOrUndefined = function (_a) { var value = _a[1]; return value !== undefined && value !== null; }; util$1.notNullOrUndefined = notNullOrUndefined; (function (exports) { var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (commonjsGlobal && commonjsGlobal.__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 __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __spreadArray = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.InMemoryStorageProvider = exports.LocalStorageProvider = exports.UnleashClient = exports.resolveFetch = exports.EVENTS = void 0; var tiny_emitter_1 = tinyEmitterExports; var metrics_1 = metrics; var storage_provider_inmemory_1 = storageProviderInmemory; exports.InMemoryStorageProvider = storage_provider_inmemory_1.default; var storage_provider_local_1 = storageProviderLocal; exports.LocalStorageProvider = storage_provider_local_1.default; var events_handler_1 = eventsHandler; var util_1 = util$1; var DEFINED_FIELDS = ['userId', 'sessionId', 'remoteAddress']; exports.EVENTS = { INIT: 'initialized', ERROR: 'error', READY: 'ready', UPDATE: 'update', IMPRESSION: 'impression', }; var IMPRESSION_EVENTS = { IS_ENABLED: 'isEnabled', GET_VARIANT: 'getVariant', }; var defaultVariant = { name: 'disabled', enabled: false }; var storeKey = 'repo'; var resolveFetch = function () { try { if ('fetch' in window) { return fetch.bind(window); } else if ('fetch' in globalThis) { return fetch.bind(globalThis); } } catch (e) { console.error('Unleash failed to resolve "fetch"', e); } return undefined; }; exports.resolveFetch = resolveFetch; var UnleashClient = /** @class */ (function (_super) { __extends(UnleashClient, _super); function UnleashClient(_a) { var storageProvider = _a.storageProvider, url = _a.url, clientKey = _a.clientKey, _b = _a.disableRefresh, disableRefresh = _b === void 0 ? false : _b, _c = _a.refreshInterval, refreshInterval = _c === void 0 ? 30 : _c, _d = _a.metricsInterval, metricsInterval = _d === void 0 ? 30 : _d, _e = _a.disableMetrics, disableMetrics = _e === void 0 ? false : _e, appName = _a.appName, _f = _a.environment, environment = _f === void 0 ? 'default' : _f, context = _a.context, _g = _a.fetch, fetch = _g === void 0 ? (0, exports.resolveFetch)() : _g, bootstrap = _a.bootstrap, _h = _a.bootstrapOverride, bootstrapOverride = _h === void 0 ? true : _h, _j = _a.headerName, headerName = _j === void 0 ? 'Authorization' : _j, _k = _a.customHeaders, customHeaders = _k === void 0 ? {} : _k; var _this = _super.call(this) || this; _this.toggles = []; _this.etag = ''; _this.readyEventEmitted = false; // Validations if (!url) { throw new Error('url is required'); } if (!clientKey) { throw new Error('clientKey is required'); } if (!appName) { throw new Error('appName is required.'); } _this.eventsHandler = new events_handler_1.default(); _this.toggles = bootstrap && bootstrap.length > 0 ? bootstrap : []; _this.url = url instanceof URL ? url : new URL(url); _this.clientKey = clientKey; _this.headerName = headerName; _this.customHeaders = customHeaders; _this.storage = storageProvider || new storage_provider_local_1.default(); _this.refreshInterval = disableRefresh ? 0 : refreshInterval * 1000; _this.context = __assign({ appName: appName, environment: environment }, context); _this.ready = new Promise(function (resolve) { _this.init() .then(resolve) .catch(function (error) { console.error(error); _this.emit(exports.EVENTS.ERROR, error); resolve(); }); }); if (!fetch) { console.error('Unleash: You must either provide your own "fetch" implementation or run in an environment where "fetch" is available.'); } _this.fetch = fetch; _this.bootstrap = bootstrap && bootstrap.length > 0 ? bootstrap : undefined; _this.bootstrapOverride = bootstrapOverride; _this.metrics = new metrics_1.default({ onError: _this.emit.bind(_this, exports.EVENTS.ERROR), appName: appName, metricsInterval: metricsInterval, disableMetrics: disableMetrics, url: _this.url, clientKey: clientKey, fetch: fetch, headerName: headerName, }); return _this; } UnleashClient.prototype.getAllToggles = function () { return __spreadArray([], this.toggles, true); }; UnleashClient.prototype.isEnabled = function (toggleName) { var toggle = this.toggles.find(function (t) { return t.name === toggleName; }); var enabled = toggle ? toggle.enabled : false; this.metrics.count(toggleName, enabled); if (toggle === null || toggle === void 0 ? void 0 : toggle.impressionData) { var event_1 = this.eventsHandler.createImpressionEvent(this.context, enabled, toggleName, IMPRESSION_EVENTS.IS_ENABLED); this.emit(exports.EVENTS.IMPRESSION, event_1); } return enabled; }; UnleashClient.prototype.getVariant = function (toggleName) { var toggle = this.toggles.find(function (t) { return t.name === toggleName; }); if (toggle) { this.metrics.count(toggleName, true); if (toggle.impressionData) { var event_2 = this.eventsHandler.createImpressionEvent(this.context, toggle.enabled, toggleName, IMPRESSION_EVENTS.GET_VARIANT, toggle.variant.name); this.emit(exports.EVENTS.IMPRESSION, event_2); } return toggle.variant; } else { this.metrics.count(toggleName, false); return defaultVariant; } }; UnleashClient.prototype.updateContext = function (context) { return __awaiter(this, void 0, void 0, function () { var staticContext; return __generator(this, function (_a) { switch (_a.label) { case 0: // @ts-expect-error Give the user a nicer error message when // including static fields in the mutable context object if (context.appName || context.environment) { console.warn("appName and environment are static. They can't be updated with updateContext."); } staticContext = { environment: this.context.environment, appName: this.context.appName, }; this.context = __assign(__assign({}, staticContext), context); if (!this.timerRef) return [3 /*break*/, 2]; return [4 /*yield*/, this.fetchToggles()]; case 1: _a.sent(); _a.label = 2; case 2: return [2 /*return*/]; } }); }); }; UnleashClient.prototype.getContext = function () { return __assign({}, this.context); }; UnleashClient.prototype.setContextField = function (field, value) { var _a, _b; if (DEFINED_FIELDS.includes(field)) { this.context = __assign(__assign({}, this.context), (_a = {}, _a[field] = value, _a)); } else { var properties = __assign(__assign({}, this.context.properties), (_b = {}, _b[field] = value, _b)); this.context = __assign(__assign({}, this.context), { properties: properties }); } if (this.timerRef) { this.fetchToggles(); } }; UnleashClient.prototype.init = function () { return __awaiter(this, void 0, void 0, function () { var sessionId, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, this.resolveSessionId()]; case 1: sessionId = _b.sent(); this.context = __assign({ sessionId: sessionId }, this.context); _a = this; return [4 /*yield*/, this.storage.get(storeKey)]; case 2: _a.toggles = (_b.sent()) || []; if (!(this.bootstrap && (this.bootstrapOverride || this.toggles.length === 0))) return [3 /*break*/, 4]; return [4 /*yield*/, this.storage.save(storeKey, this.bootstrap)]; case 3: _b.sent(); this.toggles = this.bootstrap; this.emit(exports.EVENTS.READY); _b.label = 4; case 4: this.emit(exports.EVENTS.INIT); return [2 /*return*/]; } }); }); }; UnleashClient.prototype.start = function () { return __awaiter(this, void 0, void 0, function () { var interval; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: if (this.timerRef) { console.error('Unleash SDK has already started, if you want to restart the SDK you should call client.stop() before starting again.'); return [2 /*return*/]; } return [4 /*yield*/, this.ready]; case 1: _a.sent(); this.metrics.start(); interval = this.refreshInterval; return [4 /*yield*/, this.fetchToggles()]; case 2: _a.sent(); if (interval > 0) { this.timerRef = setInterval(function () { return _this.fetchToggles(); }, interval); } return [2 /*return*/]; } }); }); }; UnleashClient.prototype.stop = function () { if (this.timerRef) { clearInterval(this.timerRef); this.timerRef = undefined; } this.metrics.stop(); }; UnleashClient.prototype.resolveSessionId = function () { return __awaiter(this, void 0, void 0, function () { var sessionId; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this.context.sessionId) return [3 /*break*/, 1]; return [2 /*return*/, this.context.sessionId]; case 1: return [4 /*yield*/, this.storage.get('sessionId')]; case 2: sessionId = _a.sent(); if (!!sessionId) return [3 /*break*/, 4]; sessionId = Math.floor(Math.random() * 1000000000); return [4 /*yield*/, this.storage.save('sessionId', sessionId)]; case 3: _a.sent(); _a.label = 4; case 4: return [2 /*return*/, sessionId]; } }); }); }; UnleashClient.prototype.getHeaders = function () { var _a; var headers = (_a = {}, _a[this.headerName] = this.clientKey, _a.Accept = 'application/json', _a['Content-Type'] = 'application/json', _a['If-None-Match'] = this.etag, _a); Object.entries(this.customHeaders) .filter(util_1.notNullOrUndefined) .forEach(function (_a) { var name = _a[0], value = _a[1]; return (headers[name] = value); }); return headers; }; UnleashClient.prototype.storeToggles = function (toggles) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: this.toggles = toggles; this.emit(exports.EVENTS.UPDATE); return [4 /*yield*/, this.storage.save(storeKey, toggles)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; UnleashClient.prototype.fetchToggles = function () { return __awaiter(this, void 0, void 0, function () { var context, urlWithQuery_1, response, data, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this.fetch) return [3 /*break*/, 7]; _a.label = 1; case 1: _a.trys.push([1, 6, , 7]); context = this.context; urlWithQuery_1 = new URL(this.url.toString()); // Add context information to url search params. If the properties // object is included in the context, flatten it into the search params // e.g. /?...&property.param1=param1Value&property.param2=param2Value Object.entries(context) .filter(util_1.notNullOrUndefined) .forEach(function (_a) { var contextKey = _a[0], contextValue = _a[1]; if (contextKey === 'properties' && contextValue) { Object.entries(contextValue) .filter(util_1.notNullOrUndefined) .forEach(function (_a) { var propertyKey = _a[0], propertyValue = _a[1]; return urlWithQuery_1.searchParams.append("properties[".concat(propertyKey, "]"), propertyValue); }); } else { urlWithQuery_1.searchParams.append(contextKey, contextValue); } }); return [4 /*yield*/, this.fetch(urlWithQuery_1.toString(), { cache: 'no-cache', headers: this.getHeaders(), })]; case 2: response = _a.sent(); if (!(response.ok && response.status !== 304)) return [3 /*break*/, 5]; this.etag = response.headers.get('ETag') || ''; return [4 /*yield*/, response.json()]; case 3: data = _a.sent(); return [4 /*yield*/, this.storeToggles(data.toggles)]; case 4: _a.sent(); if (!this.bootstrap && !this.readyEventEmitted) { this.emit(exports.EVENTS.READY); this.readyEventEmitted = true; } _a.label = 5; case 5: return [3 /*break*/, 7]; case 6: e_1 = _a.sent(); console.error('Unleash: unable to fetch feature toggles', e_1); this.emit(exports.EVENTS.ERROR, e_1); return [3 /*break*/, 7]; case 7: return [2 /*return*/]; } }); }); }; return UnleashClient; }(tiny_emitter_1.TinyEmitter)); exports.UnleashClient = UnleashClient; } (build)); (()=>{var e={n:n=>{var t=n&&n.__esModule?()=>n.default:()=>n;return e.d(t,{a:t}),t},d:(n,t)=>{for(var r in t)e.o(t,r)&&!e.o(n,r)&&Object.defineProperty(n,r,{enumerable:!0,get:t[r]});},o:(e,n)=>Object.prototype.hasOwnProperty.call(e,n),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0});}},n={};e.r(n),e.d(n,{FlagContext:()=>o,FlagProvider:()=>u,InMemoryStorageProvider:()=>t.InMemoryStorageProvider,LocalStorageProvider:()=>t.LocalStorageProvider,UnleashClient:()=>t.UnleashClient,default:()=>f,useFlag:()=>a,useFlagsStatus:()=>i,useUnleashClient:()=>s,useUnleashContext:()=>l,useVariant:()=>c});const t=build,r=reactExports,o=e.n(r)().createContext(null);const u=function(e){var n=e.config,u=e.children,a=e.unleashClient,i=e.startClient,c=void 0===i||i,l=r.useRef(a),s=r.useState(!1),f=s[0],d=s[1],v=r.useState(null),y=v[0],g=v[1];n||a||console.warn("You must provide either a config or an unleash client to the flag provider. If you are initializing the client in useEffect, you can avoid this warning by\n checking if the client exists before rendering."),l.current||(l.current=new t.UnleashClient(n)),l.current.on("ready",(function(){d(!0);})),l.current.on("error",(function(e){g(e);})),r.useEffect((function(){(c||!a)&&l.current.start();}),[]);var h=function(e){return n=void 0,t=void 0,o=function(){return function(e,n){var t,r,o,u,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return u={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(u[Symbol.iterator]=function(){return this}),u;function i(u){return function(i){return function(u){if(t)throw new TypeError("Generator is already executing.");for(;a;)try{if(t=1,r&&(o=2&u[0]?r.return:u[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,u[1])).done)return o;switch(r=0,o&&(u=[2&u[0],o.value]),u[0]){case 0:case 1:o=u;break;case 4:return a.label++,{value:u[1],done:!1};case 5:a.label++,r=u[1],u=[0];continue;case 7:u=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==u[0]&&2!==u[0])){a=0;continue}if(3===u[0]&&(!o||u[1]>o[0]&&u[1] &&` helpers in initial condition allow es6 code // to co-exist with es5. // 2. Replace `for of` with es5 compliant iteration using `for`. // Basically, take: // // ```js // for (i of a.entries()) // if (!b.has(i[0])) return false; // ``` // // ... and convert to: // // ```js // it = a.entries(); // while (!(i = it.next()).done) // if (!b.has(i.value[0])) return false; // ``` // // **Note**: `i` access switches to `i.value`. var it; if (hasMap && (a instanceof Map) && (b instanceof Map)) { if (a.size !== b.size) return false; it = a.entries(); while (!(i = it.next()).done) if (!b.has(i.value[0])) return false; it = a.entries(); while (!(i = it.next()).done) if (!equal$1(i.value[1], b.get(i.value[0]))) return false; return true; } if (hasSet && (a instanceof Set) && (b instanceof Set)) { if (a.size !== b.size) return false; it = a.entries(); while (!(i = it.next()).done) if (!b.has(i.value[0])) return false; return true; } // END: Modifications if (hasArrayBuffer && ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0;) if (a[i] !== b[i]) return false; return true; } if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; // START: Modifications: // Apply guards for `Object.create(null)` handling. See: // - https://github.com/FormidableLabs/react-fast-compare/issues/64 // - https://github.com/epoberezkin/fast-deep-equal/issues/49 if (a.valueOf !== Object.prototype.valueOf && typeof a.valueOf === 'function' && typeof b.valueOf === 'function') return a.valueOf() === b.valueOf(); if (a.toString !== Object.prototype.toString && typeof a.toString === 'function' && typeof b.toString === 'function') return a.toString() === b.toString(); // END: Modifications keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; // END: fast-deep-equal // START: react-fast-compare // custom handling for DOM elements if (hasElementType && a instanceof Element) return false; // custom handling for React/Preact for (i = length; i-- !== 0;) { if ((keys[i] === '_owner' || keys[i] === '__v' || keys[i] === '__o') && a.$$typeof) { // React-specific: avoid traversing React elements' _owner // Preact-specific: avoid traversing Preact elements' __v and __o // __v = $_original / $_vnode // __o = $_owner // These properties contain circular references and are not needed when // comparing the actual elements (and not their owners) // .$$typeof and ._store on just reasonable markers of elements continue; } // all other properties should be traversed as usual if (!equal$1(a[keys[i]], b[keys[i]])) return false; } // END: react-fast-compare // START: fast-deep-equal return true; } return a !== a && b !== b; } // end fast-deep-equal var reactFastCompare = function isEqual(a, b) { try { return equal$1(a, b); } catch (error) { if (((error.message || '').match(/stack|recursion/i))) { // warn on circular references, don't crash // browsers give this different errors name and messages: // chrome/safari: "RangeError", "Maximum call stack size exceeded" // firefox: "InternalError", too much recursion" // edge: "Error", "Out of stack space" console.warn('react-fast-compare cannot handle circular refs'); return false; } // some other error. we should definitely know about these throw error; } }; var fastCompare = /*@__PURE__*/getDefaultExportFromCjs(reactFastCompare); /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant$2 = function(condition, format, a, b, c, d, e, f) { if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; var browser = invariant$2; var invariant$3 = /*@__PURE__*/getDefaultExportFromCjs(browser); // var shallowequal = function shallowEqual(objA, objB, compare, compareContext) { var ret = compare ? compare.call(compareContext, objA, objB) : void 0; if (ret !== void 0) { return !!ret; } if (objA === objB) { return true; } if (typeof objA !== "object" || !objA || typeof objB !== "object" || !objB) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB); // Test for A's keys different from B. for (var idx = 0; idx < keysA.length; idx++) { var key = keysA[idx]; if (!bHasOwnProperty(key)) { return false; } var valueA = objA[key]; var valueB = objB[key]; ret = compare ? compare.call(compareContext, valueA, valueB, key) : void 0; if (ret === false || (ret === void 0 && valueA !== valueB)) { return false; } } return true; }; var shallowEqual$1 = /*@__PURE__*/getDefaultExportFromCjs(shallowequal); // src/index.tsx // src/constants.ts var TAG_NAMES = /* @__PURE__ */ ((TAG_NAMES2) => { TAG_NAMES2["BASE"] = "base"; TAG_NAMES2["BODY"] = "body"; TAG_NAMES2["HEAD"] = "head"; TAG_NAMES2["HTML"] = "html"; TAG_NAMES2["LINK"] = "link"; TAG_NAMES2["META"] = "meta"; TAG_NAMES2["NOSCRIPT"] = "noscript"; TAG_NAMES2["SCRIPT"] = "script"; TAG_NAMES2["STYLE"] = "style"; TAG_NAMES2["TITLE"] = "title"; TAG_NAMES2["FRAGMENT"] = "Symbol(react.fragment)"; return TAG_NAMES2; })(TAG_NAMES || {}); var SEO_PRIORITY_TAGS = { link: { rel: ["amphtml", "canonical", "alternate"] }, script: { type: ["application/ld+json"] }, meta: { charset: "", name: ["generator", "robots", "description"], property: [ "og:type", "og:title", "og:url", "og:image", "og:image:alt", "og:description", "twitter:url", "twitter:title", "twitter:description", "twitter:image", "twitter:image:alt", "twitter:card", "twitter:site" ] } }; var VALID_TAG_NAMES = Object.values(TAG_NAMES); var REACT_TAG_MAP = { accesskey: "accessKey", charset: "charSet", class: "className", contenteditable: "contentEditable", contextmenu: "contextMenu", "http-equiv": "httpEquiv", itemprop: "itemProp", tabindex: "tabIndex" }; var HTML_TAG_MAP = Object.entries(REACT_TAG_MAP).reduce( (carry, [key, value]) => { carry[value] = key; return carry; }, {} ); var HELMET_ATTRIBUTE = "data-rh"; // src/utils.ts var HELMET_PROPS = { DEFAULT_TITLE: "defaultTitle", DEFER: "defer", ENCODE_SPECIAL_CHARACTERS: "encodeSpecialCharacters", ON_CHANGE_CLIENT_STATE: "onChangeClientState", TITLE_TEMPLATE: "titleTemplate", PRIORITIZE_SEO_TAGS: "prioritizeSeoTags" }; var getInnermostProperty = (propsList, property) => { for (let i = propsList.length - 1; i >= 0; i -= 1) { const props = propsList[i]; if (Object.prototype.hasOwnProperty.call(props, property)) { return props[property]; } } return null; }; var getTitleFromPropsList = (propsList) => { let innermostTitle = getInnermostProperty(propsList, "title" /* TITLE */); const innermostTemplate = getInnermostProperty(propsList, HELMET_PROPS.TITLE_TEMPLATE); if (Array.isArray(innermostTitle)) { innermostTitle = innermostTitle.join(""); } if (innermostTemplate && innermostTitle) { return innermostTemplate.replace(/%s/g, () => innermostTitle); } const innermostDefaultTitle = getInnermostProperty(propsList, HELMET_PROPS.DEFAULT_TITLE); return innermostTitle || innermostDefaultTitle || void 0; }; var getOnChangeClientState = (propsList) => getInnermostProperty(propsList, HELMET_PROPS.ON_CHANGE_CLIENT_STATE) || (() => { }); var getAttributesFromPropsList = (tagType, propsList) => propsList.filter((props) => typeof props[tagType] !== "undefined").map((props) => props[tagType]).reduce((tagAttrs, current) => ({ ...tagAttrs, ...current }), {}); var getBaseTagFromPropsList = (primaryAttributes, propsList) => propsList.filter((props) => typeof props["base" /* BASE */] !== "undefined").map((props) => props["base" /* BASE */]).reverse().reduce((innermostBaseTag, tag) => { if (!innermostBaseTag.length) { const keys = Object.keys(tag); for (let i = 0; i < keys.length; i += 1) { const attributeKey = keys[i]; const lowerCaseAttributeKey = attributeKey.toLowerCase(); if (primaryAttributes.indexOf(lowerCaseAttributeKey) !== -1 && tag[lowerCaseAttributeKey]) { return innermostBaseTag.concat(tag); } } } return innermostBaseTag; }, []); var warn$2 = (msg) => console && typeof console.warn === "function" && console.warn(msg); var getTagsFromPropsList = (tagName, primaryAttributes, propsList) => { const approvedSeenTags = {}; return propsList.filter((props) => { if (Array.isArray(props[tagName])) { return true; } if (typeof props[tagName] !== "undefined") { warn$2( `Helmet: ${tagName} should be of type "Array". Instead found type "${typeof props[tagName]}"` ); } return false; }).map((props) => props[tagName]).reverse().reduce((approvedTags, instanceTags) => { const instanceSeenTags = {}; instanceTags.filter((tag) => { let primaryAttributeKey; const keys2 = Object.keys(tag); for (let i = 0; i < keys2.length; i += 1) { const attributeKey = keys2[i]; const lowerCaseAttributeKey = attributeKey.toLowerCase(); if (primaryAttributes.indexOf(lowerCaseAttributeKey) !== -1 && !(primaryAttributeKey === "rel" /* REL */ && tag[primaryAttributeKey].toLowerCase() === "canonical") && !(lowerCaseAttributeKey === "rel" /* REL */ && tag[lowerCaseAttributeKey].toLowerCase() === "stylesheet")) { primaryAttributeKey = lowerCaseAttributeKey; } if (primaryAttributes.indexOf(attributeKey) !== -1 && (attributeKey === "innerHTML" /* INNER_HTML */ || attributeKey === "cssText" /* CSS_TEXT */ || attributeKey === "itemprop" /* ITEM_PROP */)) { primaryAttributeKey = attributeKey; } } if (!primaryAttributeKey || !tag[primaryAttributeKey]) { return false; } const value = tag[primaryAttributeKey].toLowerCase(); if (!approvedSeenTags[primaryAttributeKey]) { approvedSeenTags[primaryAttributeKey] = {}; } if (!instanceSeenTags[primaryAttributeKey]) { instanceSeenTags[primaryAttributeKey] = {}; } if (!approvedSeenTags[primaryAttributeKey][value]) { instanceSeenTags[primaryAttributeKey][value] = true; return true; } return false; }).reverse().forEach((tag) => approvedTags.push(tag)); const keys = Object.keys(instanceSeenTags); for (let i = 0; i < keys.length; i += 1) { const attributeKey = keys[i]; const tagUnion = { ...approvedSeenTags[attributeKey], ...instanceSeenTags[attributeKey] }; approvedSeenTags[attributeKey] = tagUnion; } return approvedTags; }, []).reverse(); }; var getAnyTrueFromPropsList = (propsList, checkedTag) => { if (Array.isArray(propsList) && propsList.length) { for (let index = 0; index < propsList.length; index += 1) { const prop = propsList[index]; if (prop[checkedTag]) { return true; } } } return false; }; var reducePropsToState = (propsList) => ({ baseTag: getBaseTagFromPropsList(["href" /* HREF */], propsList), bodyAttributes: getAttributesFromPropsList("bodyAttributes" /* BODY */, propsList), defer: getInnermostProperty(propsList, HELMET_PROPS.DEFER), encode: getInnermostProperty(propsList, HELMET_PROPS.ENCODE_SPECIAL_CHARACTERS), htmlAttributes: getAttributesFromPropsList("htmlAttributes" /* HTML */, propsList), linkTags: getTagsFromPropsList( "link" /* LINK */, ["rel" /* REL */, "href" /* HREF */], propsList ), metaTags: getTagsFromPropsList( "meta" /* META */, [ "name" /* NAME */, "charset" /* CHARSET */, "http-equiv" /* HTTPEQUIV */, "property" /* PROPERTY */, "itemprop" /* ITEM_PROP */ ], propsList ), noscriptTags: getTagsFromPropsList("noscript" /* NOSCRIPT */, ["innerHTML" /* INNER_HTML */], propsList), onChangeClientState: getOnChangeClientState(propsList), scriptTags: getTagsFromPropsList( "script" /* SCRIPT */, ["src" /* SRC */, "innerHTML" /* INNER_HTML */], propsList ), styleTags: getTagsFromPropsList("style" /* STYLE */, ["cssText" /* CSS_TEXT */], propsList), title: getTitleFromPropsList(propsList), titleAttributes: getAttributesFromPropsList("titleAttributes" /* TITLE */, propsList), prioritizeSeoTags: getAnyTrueFromPropsList(propsList, HELMET_PROPS.PRIORITIZE_SEO_TAGS) }); var flattenArray = (possibleArray) => Array.isArray(possibleArray) ? possibleArray.join("") : possibleArray; var checkIfPropsMatch = (props, toMatch) => { const keys = Object.keys(props); for (let i = 0; i < keys.length; i += 1) { if (toMatch[keys[i]] && toMatch[keys[i]].includes(props[keys[i]])) { return true; } } return false; }; var prioritizer = (elementsList, propsToMatch) => { if (Array.isArray(elementsList)) { return elementsList.reduce( (acc, elementAttrs) => { if (checkIfPropsMatch(elementAttrs, propsToMatch)) { acc.priority.push(elementAttrs); } else { acc.default.push(elementAttrs); } return acc; }, { priority: [], default: [] } ); } return { default: elementsList, priority: [] }; }; var without$2 = (obj, key) => { return { ...obj, [key]: void 0 }; }; // src/server.ts var SELF_CLOSING_TAGS = ["noscript" /* NOSCRIPT */, "script" /* SCRIPT */, "style" /* STYLE */]; var encodeSpecialCharacters = (str, encode = true) => { if (encode === false) { return String(str); } return String(str).replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); }; var generateElementAttributesAsString = (attributes) => Object.keys(attributes).reduce((str, key) => { const attr = typeof attributes[key] !== "undefined" ? `${key}="${attributes[key]}"` : `${key}`; return str ? `${str} ${attr}` : attr; }, ""); var generateTitleAsString = (type, title, attributes, encode) => { const attributeString = generateElementAttributesAsString(attributes); const flattenedTitle = flattenArray(title); return attributeString ? `<${type} ${HELMET_ATTRIBUTE}="true" ${attributeString}>${encodeSpecialCharacters( flattenedTitle, encode )}` : `<${type} ${HELMET_ATTRIBUTE}="true">${encodeSpecialCharacters( flattenedTitle, encode )}`; }; var generateTagsAsString = (type, tags, encode = true) => tags.reduce((str, t) => { const tag = t; const attributeHtml = Object.keys(tag).filter( (attribute) => !(attribute === "innerHTML" /* INNER_HTML */ || attribute === "cssText" /* CSS_TEXT */) ).reduce((string, attribute) => { const attr = typeof tag[attribute] === "undefined" ? attribute : `${attribute}="${encodeSpecialCharacters(tag[attribute], encode)}"`; return string ? `${string} ${attr}` : attr; }, ""); const tagContent = tag.innerHTML || tag.cssText || ""; const isSelfClosing = SELF_CLOSING_TAGS.indexOf(type) === -1; return `${str}<${type} ${HELMET_ATTRIBUTE}="true" ${attributeHtml}${isSelfClosing ? `/>` : `>${tagContent}`}`; }, ""); var convertElementAttributesToReactProps = (attributes, initProps = {}) => Object.keys(attributes).reduce((obj, key) => { const mapped = REACT_TAG_MAP[key]; obj[mapped || key] = attributes[key]; return obj; }, initProps); var generateTitleAsReactComponent = (_type, title, attributes) => { const initProps = { key: title, [HELMET_ATTRIBUTE]: true }; const props = convertElementAttributesToReactProps(attributes, initProps); return [React$2.createElement("title" /* TITLE */, props, title)]; }; var generateTagsAsReactComponent = (type, tags) => tags.map((tag, i) => { const mappedTag = { key: i, [HELMET_ATTRIBUTE]: true }; Object.keys(tag).forEach((attribute) => { const mapped = REACT_TAG_MAP[attribute]; const mappedAttribute = mapped || attribute; if (mappedAttribute === "innerHTML" /* INNER_HTML */ || mappedAttribute === "cssText" /* CSS_TEXT */) { const content = tag.innerHTML || tag.cssText; mappedTag.dangerouslySetInnerHTML = { __html: content }; } else { mappedTag[mappedAttribute] = tag[attribute]; } }); return React$2.createElement(type, mappedTag); }); var getMethodsForTag = (type, tags, encode = true) => { switch (type) { case "title" /* TITLE */: return { toComponent: () => generateTitleAsReactComponent(type, tags.title, tags.titleAttributes), toString: () => generateTitleAsString(type, tags.title, tags.titleAttributes, encode) }; case "bodyAttributes" /* BODY */: case "htmlAttributes" /* HTML */: return { toComponent: () => convertElementAttributesToReactProps(tags), toString: () => generateElementAttributesAsString(tags) }; default: return { toComponent: () => generateTagsAsReactComponent(type, tags), toString: () => generateTagsAsString(type, tags, encode) }; } }; var getPriorityMethods = ({ metaTags, linkTags, scriptTags, encode }) => { const meta = prioritizer(metaTags, SEO_PRIORITY_TAGS.meta); const link = prioritizer(linkTags, SEO_PRIORITY_TAGS.link); const script = prioritizer(scriptTags, SEO_PRIORITY_TAGS.script); const priorityMethods = { toComponent: () => [ ...generateTagsAsReactComponent("meta" /* META */, meta.priority), ...generateTagsAsReactComponent("link" /* LINK */, link.priority), ...generateTagsAsReactComponent("script" /* SCRIPT */, script.priority) ], toString: () => ( // generate all the tags as strings and concatenate them `${getMethodsForTag("meta" /* META */, meta.priority, encode)} ${getMethodsForTag( "link" /* LINK */, link.priority, encode )} ${getMethodsForTag("script" /* SCRIPT */, script.priority, encode)}` ) }; return { priorityMethods, metaTags: meta.default, linkTags: link.default, scriptTags: script.default }; }; var mapStateOnServer = (props) => { const { baseTag, bodyAttributes, encode = true, htmlAttributes, noscriptTags, styleTags, title = "", titleAttributes, prioritizeSeoTags } = props; let { linkTags, metaTags, scriptTags } = props; let priorityMethods = { toComponent: () => { }, toString: () => "" }; if (prioritizeSeoTags) { ({ priorityMethods, linkTags, metaTags, scriptTags } = getPriorityMethods(props)); } return { priority: priorityMethods, base: getMethodsForTag("base" /* BASE */, baseTag, encode), bodyAttributes: getMethodsForTag("bodyAttributes" /* BODY */, bodyAttributes, encode), htmlAttributes: getMethodsForTag("htmlAttributes" /* HTML */, htmlAttributes, encode), link: getMethodsForTag("link" /* LINK */, linkTags, encode), meta: getMethodsForTag("meta" /* META */, metaTags, encode), noscript: getMethodsForTag("noscript" /* NOSCRIPT */, noscriptTags, encode), script: getMethodsForTag("script" /* SCRIPT */, scriptTags, encode), style: getMethodsForTag("style" /* STYLE */, styleTags, encode), title: getMethodsForTag("title" /* TITLE */, { title, titleAttributes }, encode) }; }; var server_default = mapStateOnServer; // src/HelmetData.ts var instances = []; var isDocument$1 = !!(typeof window !== "undefined" && window.document && window.document.createElement); var HelmetData = class { instances = []; canUseDOM = isDocument$1; context; value = { setHelmet: (serverState) => { this.context.helmet = serverState; }, helmetInstances: { get: () => this.canUseDOM ? instances : this.instances, add: (instance) => { (this.canUseDOM ? instances : this.instances).push(instance); }, remove: (instance) => { const index = (this.canUseDOM ? instances : this.instances).indexOf(instance); (this.canUseDOM ? instances : this.instances).splice(index, 1); } } }; constructor(context, canUseDOM) { this.context = context; this.canUseDOM = canUseDOM || false; if (!canUseDOM) { context.helmet = server_default({ baseTag: [], bodyAttributes: {}, encodeSpecialCharacters: true, htmlAttributes: {}, linkTags: [], metaTags: [], noscriptTags: [], scriptTags: [], styleTags: [], title: "", titleAttributes: {} }); } } }; // src/Provider.tsx var defaultValue = {}; var Context = React$2.createContext(defaultValue); var HelmetProvider = class _HelmetProvider extends reactExports.Component { static canUseDOM = isDocument$1; helmetData; constructor(props) { super(props); this.helmetData = new HelmetData(this.props.context || {}, _HelmetProvider.canUseDOM); } render() { return /* @__PURE__ */ React$2.createElement(Context.Provider, { value: this.helmetData.value }, this.props.children); } }; // src/client.ts var updateTags = (type, tags) => { const headElement = document.head || document.querySelector("head" /* HEAD */); const tagNodes = headElement.querySelectorAll(`${type}[${HELMET_ATTRIBUTE}]`); const oldTags = [].slice.call(tagNodes); const newTags = []; let indexToDelete; if (tags && tags.length) { tags.forEach((tag) => { const newElement = document.createElement(type); for (const attribute in tag) { if (Object.prototype.hasOwnProperty.call(tag, attribute)) { if (attribute === "innerHTML" /* INNER_HTML */) { newElement.innerHTML = tag.innerHTML; } else if (attribute === "cssText" /* CSS_TEXT */) { if (newElement.styleSheet) { newElement.styleSheet.cssText = tag.cssText; } else { newElement.appendChild(document.createTextNode(tag.cssText)); } } else { const attr = attribute; const value = typeof tag[attr] === "undefined" ? "" : tag[attr]; newElement.setAttribute(attribute, value); } } } newElement.setAttribute(HELMET_ATTRIBUTE, "true"); if (oldTags.some((existingTag, index) => { indexToDelete = index; return newElement.isEqualNode(existingTag); })) { oldTags.splice(indexToDelete, 1); } else { newTags.push(newElement); } }); } oldTags.forEach((tag) => tag.parentNode?.removeChild(tag)); newTags.forEach((tag) => headElement.appendChild(tag)); return { oldTags, newTags }; }; var updateAttributes = (tagName, attributes) => { const elementTag = document.getElementsByTagName(tagName)[0]; if (!elementTag) { return; } const helmetAttributeString = elementTag.getAttribute(HELMET_ATTRIBUTE); const helmetAttributes = helmetAttributeString ? helmetAttributeString.split(",") : []; const attributesToRemove = [...helmetAttributes]; const attributeKeys = Object.keys(attributes); for (const attribute of attributeKeys) { const value = attributes[attribute] || ""; if (elementTag.getAttribute(attribute) !== value) { elementTag.setAttribute(attribute, value); } if (helmetAttributes.indexOf(attribute) === -1) { helmetAttributes.push(attribute); } const indexToSave = attributesToRemove.indexOf(attribute); if (indexToSave !== -1) { attributesToRemove.splice(indexToSave, 1); } } for (let i = attributesToRemove.length - 1; i >= 0; i -= 1) { elementTag.removeAttribute(attributesToRemove[i]); } if (helmetAttributes.length === attributesToRemove.length) { elementTag.removeAttribute(HELMET_ATTRIBUTE); } else if (elementTag.getAttribute(HELMET_ATTRIBUTE) !== attributeKeys.join(",")) { elementTag.setAttribute(HELMET_ATTRIBUTE, attributeKeys.join(",")); } }; var updateTitle = (title, attributes) => { if (typeof title !== "undefined" && document.title !== title) { document.title = flattenArray(title); } updateAttributes("title" /* TITLE */, attributes); }; var commitTagChanges = (newState, cb) => { const { baseTag, bodyAttributes, htmlAttributes, linkTags, metaTags, noscriptTags, onChangeClientState, scriptTags, styleTags, title, titleAttributes } = newState; updateAttributes("body" /* BODY */, bodyAttributes); updateAttributes("html" /* HTML */, htmlAttributes); updateTitle(title, titleAttributes); const tagUpdates = { baseTag: updateTags("base" /* BASE */, baseTag), linkTags: updateTags("link" /* LINK */, linkTags), metaTags: updateTags("meta" /* META */, metaTags), noscriptTags: updateTags("noscript" /* NOSCRIPT */, noscriptTags), scriptTags: updateTags("script" /* SCRIPT */, scriptTags), styleTags: updateTags("style" /* STYLE */, styleTags) }; const addedTags = {}; const removedTags = {}; Object.keys(tagUpdates).forEach((tagType) => { const { newTags, oldTags } = tagUpdates[tagType]; if (newTags.length) { addedTags[tagType] = newTags; } if (oldTags.length) { removedTags[tagType] = tagUpdates[tagType].oldTags; } }); if (cb) { cb(); } onChangeClientState(newState, addedTags, removedTags); }; var _helmetCallback = null; var handleStateChangeOnClient = (newState) => { if (_helmetCallback) { cancelAnimationFrame(_helmetCallback); } if (newState.defer) { _helmetCallback = requestAnimationFrame(() => { commitTagChanges(newState, () => { _helmetCallback = null; }); }); } else { commitTagChanges(newState); _helmetCallback = null; } }; var client_default = handleStateChangeOnClient; // src/Dispatcher.tsx var HelmetDispatcher = class extends reactExports.Component { rendered = false; shouldComponentUpdate(nextProps) { return !shallowEqual$1(nextProps, this.props); } componentDidUpdate() { this.emitChange(); } componentWillUnmount() { const { helmetInstances } = this.props.context; helmetInstances.remove(this); this.emitChange(); } emitChange() { const { helmetInstances, setHelmet } = this.props.context; let serverState = null; const state = reducePropsToState( helmetInstances.get().map((instance) => { const props = { ...instance.props }; delete props.context; return props; }) ); if (HelmetProvider.canUseDOM) { client_default(state); } else if (server_default) { serverState = server_default(state); } setHelmet(serverState); } // componentWillMount will be deprecated // for SSR, initialize on first render // constructor is also unsafe in StrictMode init() { if (this.rendered) { return; } this.rendered = true; const { helmetInstances } = this.props.context; helmetInstances.add(this); this.emitChange(); } render() { this.init(); return null; } }; // src/index.tsx var Helmet = class extends reactExports.Component { static defaultProps = { defer: true, encodeSpecialCharacters: true, prioritizeSeoTags: false }; shouldComponentUpdate(nextProps) { return !fastCompare(without$2(this.props, "helmetData"), without$2(nextProps, "helmetData")); } mapNestedChildrenToProps(child, nestedChildren) { if (!nestedChildren) { return null; } switch (child.type) { case "script" /* SCRIPT */: case "noscript" /* NOSCRIPT */: return { innerHTML: nestedChildren }; case "style" /* STYLE */: return { cssText: nestedChildren }; default: throw new Error( `<${child.type} /> elements are self-closing and can not contain children. Refer to our API for more information.` ); } } flattenArrayTypeChildren(child, arrayTypeChildren, newChildProps, nestedChildren) { return { ...arrayTypeChildren, [child.type]: [ ...arrayTypeChildren[child.type] || [], { ...newChildProps, ...this.mapNestedChildrenToProps(child, nestedChildren) } ] }; } mapObjectTypeChildren(child, newProps, newChildProps, nestedChildren) { switch (child.type) { case "title" /* TITLE */: return { ...newProps, [child.type]: nestedChildren, titleAttributes: { ...newChildProps } }; case "body" /* BODY */: return { ...newProps, bodyAttributes: { ...newChildProps } }; case "html" /* HTML */: return { ...newProps, htmlAttributes: { ...newChildProps } }; default: return { ...newProps, [child.type]: { ...newChildProps } }; } } mapArrayTypeChildrenToProps(arrayTypeChildren, newProps) { let newFlattenedProps = { ...newProps }; Object.keys(arrayTypeChildren).forEach((arrayChildName) => { newFlattenedProps = { ...newFlattenedProps, [arrayChildName]: arrayTypeChildren[arrayChildName] }; }); return newFlattenedProps; } warnOnInvalidChildren(child, nestedChildren) { invariant$3( VALID_TAG_NAMES.some((name) => child.type === name), typeof child.type === "function" ? `You may be attempting to nest components within each other, which is not allowed. Refer to our API for more information.` : `Only elements types ${VALID_TAG_NAMES.join( ", " )} are allowed. Helmet does not support rendering <${child.type}> elements. Refer to our API for more information.` ); invariant$3( !nestedChildren || typeof nestedChildren === "string" || Array.isArray(nestedChildren) && !nestedChildren.some((nestedChild) => typeof nestedChild !== "string"), `Helmet expects a string as a child of <${child.type}>. Did you forget to wrap your children in braces? ( <${child.type}>{\`\`} ) Refer to our API for more information.` ); return true; } mapChildrenToProps(children, newProps) { let arrayTypeChildren = {}; React$2.Children.forEach(children, (child) => { if (!child || !child.props) { return; } const { children: nestedChildren, ...childProps } = child.props; const newChildProps = Object.keys(childProps).reduce((obj, key) => { obj[HTML_TAG_MAP[key] || key] = childProps[key]; return obj; }, {}); let { type } = child; if (typeof type === "symbol") { type = type.toString(); } else { this.warnOnInvalidChildren(child, nestedChildren); } switch (type) { case "Symbol(react.fragment)" /* FRAGMENT */: newProps = this.mapChildrenToProps(nestedChildren, newProps); break; case "link" /* LINK */: case "meta" /* META */: case "noscript" /* NOSCRIPT */: case "script" /* SCRIPT */: case "style" /* STYLE */: arrayTypeChildren = this.flattenArrayTypeChildren( child, arrayTypeChildren, newChildProps, nestedChildren ); break; default: newProps = this.mapObjectTypeChildren(child, newProps, newChildProps, nestedChildren); break; } }); return this.mapArrayTypeChildrenToProps(arrayTypeChildren, newProps); } render() { const { children, ...props } = this.props; let newProps = { ...props }; let { helmetData } = props; if (children) { newProps = this.mapChildrenToProps(children, newProps); } if (helmetData && !(helmetData instanceof HelmetData)) { const data = helmetData; helmetData = new HelmetData(data.context, true); delete newProps.helmetData; } return helmetData ? /* @__PURE__ */ React$2.createElement(HelmetDispatcher, { ...newProps, context: helmetData.value }) : /* @__PURE__ */ React$2.createElement(Context.Consumer, null, (context) => /* @__PURE__ */ React$2.createElement(HelmetDispatcher, { ...newProps, context })); } }; const matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g; const htmlEntities = { '&': '&', '&': '&', '<': '<', '<': '<', '>': '>', '>': '>', ''': "'", ''': "'", '"': '"', '"': '"', ' ': ' ', ' ': ' ', '©': '©', '©': '©', '®': '®', '®': '®', '…': '…', '…': '…', '/': '/', '/': '/' }; const unescapeHtmlEntity = m => htmlEntities[m]; const unescape$1 = text => text.replace(matchHtmlEntity, unescapeHtmlEntity); let defaultOptions$2 = { bindI18n: 'languageChanged', bindI18nStore: '', transEmptyNodeValue: '', transSupportBasicHtmlNodes: true, transWrapTextNodes: '', transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'], useSuspense: true, unescape: unescape$1 }; function setDefaults() { let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; defaultOptions$2 = { ...defaultOptions$2, ...options }; } function getDefaults() { return defaultOptions$2; } let i18nInstance; function setI18n(instance) { i18nInstance = instance; } function getI18n() { return i18nInstance; } const I18nContext = reactExports.createContext(); class ReportNamespaces { constructor() { this.usedNamespaces = {}; } addUsedNamespaces(namespaces) { namespaces.forEach(ns => { if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true; }); } getUsedNamespaces() { return Object.keys(this.usedNamespaces); } } function _extends$1() { _extends$1 = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$1.apply(this, arguments); } /** * This file automatically generated from `pre-publish.js`. * Do not manually edit. */ var voidElements$1 = { "area": true, "base": true, "br": true, "col": true, "embed": true, "hr": true, "img": true, "input": true, "link": true, "meta": true, "param": true, "source": true, "track": true, "wbr": true }; var e$7 = /*@__PURE__*/getDefaultExportFromCjs(voidElements$1); var t$d=/\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;function n$d(n){var r={type:"tag",name:"",voidElement:!1,attrs:{},children:[]},i=n.match(/<\/?([^\s]+?)[/\s>]/);if(i&&(r.name=i[1],(e$7[i[1]]||"/"===n.charAt(n.length-2))&&(r.voidElement=!0),r.name.startsWith("!--"))){var s=n.indexOf("--\x3e");return {type:"comment",comment:-1!==s?n.slice(4,s):""}}for(var a=new RegExp(t$d),c=null;null!==(c=a.exec(n));)if(c[0].trim())if(c[1]){var o=c[1].trim(),l=[o,""];o.indexOf("=")>-1&&(l=o.split("=")),r.attrs[l[0]]=l[1],a.lastIndex--;}else c[2]&&(r.attrs[c[2]]=c[3].trim().substring(1,c[3].length-1));return r}var r$9=/<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g,i$9=/^\s*$/,s$g=Object.create(null);function a$c(e,t){switch(t.type){case"text":return e+t.content;case"tag":return e+="<"+t.name+(t.attrs?function(e){var t=[];for(var n in e)t.push(n+'="'+e[n]+'"');return t.length?" "+t.join(" "):""}(t.attrs):"")+(t.voidElement?"/>":">"),t.voidElement?e:e+t.children.reduce(a$c,"")+"";case"comment":return e+"\x3c!--"+t.comment+"--\x3e"}}var c$c={parse:function(e,t){t||(t={}),t.components||(t.components=s$g);var a,c=[],o=[],l=-1,m=!1;if(0!==e.indexOf("<")){var u=e.indexOf("<");c.push({type:"text",content:-1===u?e:e.substring(0,u)});}return e.replace(r$9,function(r,s){if(m){if(r!=="")return;m=!1;}var u,f="/"!==r.charAt(1),h=r.startsWith("\x3c!--"),p=s+r.length,d=e.charAt(p);if(h){var v=n$d(r);return l<0?(c.push(v),c):((u=o[l]).children.push(v),c)}if(f&&(l++,"tag"===(a=n$d(r)).type&&t.components[a.name]&&(a.type="component",m=!0),a.voidElement||m||!d||"<"===d||a.children.push({type:"text",content:e.slice(p,e.indexOf("<",p))}),0===l&&c.push(a),(u=o[l-1])&&u.children.push(a),o[l]=a),(!f||a.voidElement)&&(l>-1&&(a.voidElement||a.name===r.slice(2,-1))&&(l--,a=-1===l?c:o[l]),!m&&"<"!==d&&d)){u=-1===l?c:o[l].children;var x=e.indexOf("<",p),g=e.slice(p,-1===x?void 0:x);i$9.test(g)&&(g=" "),(x>-1&&l+u.length>=0||" "!==g)&&u.push({type:"text",content:g});}}),c},stringify:function(e){return e.reduce(function(e,t){return e+a$c("",t)},"")}}; function warn$1() { if (console && console.warn) { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (typeof args[0] === 'string') args[0] = `react-i18next:: ${args[0]}`; console.warn(...args); } } const alreadyWarned = {}; function warnOnce() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } if (typeof args[0] === 'string' && alreadyWarned[args[0]]) return; if (typeof args[0] === 'string') alreadyWarned[args[0]] = new Date(); warn$1(...args); } const loadedClb = (i18n, cb) => () => { if (i18n.isInitialized) { cb(); } else { const initialized = () => { setTimeout(() => { i18n.off('initialized', initialized); }, 0); cb(); }; i18n.on('initialized', initialized); } }; function loadNamespaces(i18n, ns, cb) { i18n.loadNamespaces(ns, loadedClb(i18n, cb)); } function loadLanguages(i18n, lng, ns, cb) { if (typeof ns === 'string') ns = [ns]; ns.forEach(n => { if (i18n.options.ns.indexOf(n) < 0) i18n.options.ns.push(n); }); i18n.loadLanguages(lng, loadedClb(i18n, cb)); } function oldI18nextHasLoadedNamespace(ns, i18n) { let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; const lng = i18n.languages[0]; const fallbackLng = i18n.options ? i18n.options.fallbackLng : false; const lastLng = i18n.languages[i18n.languages.length - 1]; if (lng.toLowerCase() === 'cimode') return true; const loadNotPending = (l, n) => { const loadState = i18n.services.backendConnector.state[`${l}|${n}`]; return loadState === -1 || loadState === 2; }; if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18n.services.backendConnector.backend && i18n.isLanguageChangingTo && !loadNotPending(i18n.isLanguageChangingTo, ns)) return false; if (i18n.hasResourceBundle(lng, ns)) return true; if (!i18n.services.backendConnector.backend || i18n.options.resources && !i18n.options.partialBundledLanguages) return true; if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true; return false; } function hasLoadedNamespace(ns, i18n) { let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (!i18n.languages || !i18n.languages.length) { warnOnce('i18n.languages were undefined or empty', i18n.languages); return true; } const isNewerI18next = i18n.options.ignoreJSONStructure !== undefined; if (!isNewerI18next) { return oldI18nextHasLoadedNamespace(ns, i18n, options); } return i18n.hasLoadedNamespace(ns, { lng: options.lng, precheck: (i18nInstance, loadNotPending) => { if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false; } }); } function hasChildren$1(node, checkLength) { if (!node) return false; const base = node.props ? node.props.children : node.children; if (checkLength) return base.length > 0; return !!base; } function getChildren$2(node) { if (!node) return []; const children = node.props ? node.props.children : node.children; return node.props && node.props.i18nIsDynamicList ? getAsArray(children) : children; } function hasValidReactChildren(children) { if (Object.prototype.toString.call(children) !== '[object Array]') return false; return children.every(child => reactExports.isValidElement(child)); } function getAsArray(data) { return Array.isArray(data) ? data : [data]; } function mergeProps(source, target) { const newTarget = { ...target }; newTarget.props = Object.assign(source.props, target.props); return newTarget; } function nodesToString(children, i18nOptions) { if (!children) return ''; let stringNode = ''; const childrenArray = getAsArray(children); const keepArray = i18nOptions.transSupportBasicHtmlNodes && i18nOptions.transKeepBasicHtmlNodesFor ? i18nOptions.transKeepBasicHtmlNodesFor : []; childrenArray.forEach((child, childIndex) => { if (typeof child === 'string') { stringNode += `${child}`; } else if (reactExports.isValidElement(child)) { const childPropsCount = Object.keys(child.props).length; const shouldKeepChild = keepArray.indexOf(child.type) > -1; const childChildren = child.props.children; if (!childChildren && shouldKeepChild && childPropsCount === 0) { stringNode += `<${child.type}/>`; } else if (!childChildren && (!shouldKeepChild || childPropsCount !== 0)) { stringNode += `<${childIndex}>`; } else if (child.props.i18nIsDynamicList) { stringNode += `<${childIndex}>`; } else if (shouldKeepChild && childPropsCount === 1 && typeof childChildren === 'string') { stringNode += `<${child.type}>${childChildren}`; } else { const content = nodesToString(childChildren, i18nOptions); stringNode += `<${childIndex}>${content}`; } } else if (child === null) { warn$1(`Trans: the passed in value is invalid - seems you passed in a null child.`); } else if (typeof child === 'object') { const { format, ...clone } = child; const keys = Object.keys(clone); if (keys.length === 1) { const value = format ? `${keys[0]}, ${format}` : keys[0]; stringNode += `{{${value}}}`; } else { warn$1(`react-i18next: the passed in object contained more than one variable - the object should look like {{ value, format }} where format is optional.`, child); } } else { warn$1(`Trans: the passed in value is invalid - seems you passed in a variable like {number} - please pass in variables for interpolation as full objects like {{number}}.`, child); } }); return stringNode; } function renderNodes(children, targetString, i18n, i18nOptions, combinedTOpts, shouldUnescape) { if (targetString === '') return []; const keepArray = i18nOptions.transKeepBasicHtmlNodesFor || []; const emptyChildrenButNeedsHandling = targetString && new RegExp(keepArray.map(keep => `<${keep}`).join('|')).test(targetString); if (!children && !emptyChildrenButNeedsHandling && !shouldUnescape) return [targetString]; const data = {}; function getData(childs) { const childrenArray = getAsArray(childs); childrenArray.forEach(child => { if (typeof child === 'string') return; if (hasChildren$1(child)) getData(getChildren$2(child));else if (typeof child === 'object' && !reactExports.isValidElement(child)) Object.assign(data, child); }); } getData(children); const ast = c$c.parse(`<0>${targetString}`); const opts = { ...data, ...combinedTOpts }; function renderInner(child, node, rootReactNode) { const childs = getChildren$2(child); const mappedChildren = mapAST(childs, node.children, rootReactNode); return hasValidReactChildren(childs) && mappedChildren.length === 0 || child.props && child.props.i18nIsDynamicList ? childs : mappedChildren; } function pushTranslatedJSX(child, inner, mem, i, isVoid) { if (child.dummy) { child.children = inner; mem.push(reactExports.cloneElement(child, { key: i }, isVoid ? undefined : inner)); } else { mem.push(...reactExports.Children.map([child], c => { const props = { ...c.props }; delete props.i18nIsDynamicList; return React$2.createElement(c.type, _extends$1({}, props, { key: i, ref: c.ref }, isVoid ? {} : { children: inner })); })); } } function mapAST(reactNode, astNode, rootReactNode) { const reactNodes = getAsArray(reactNode); const astNodes = getAsArray(astNode); return astNodes.reduce((mem, node, i) => { const translationContent = node.children && node.children[0] && node.children[0].content && i18n.services.interpolator.interpolate(node.children[0].content, opts, i18n.language); if (node.type === 'tag') { let tmp = reactNodes[parseInt(node.name, 10)]; if (rootReactNode.length === 1 && !tmp) tmp = rootReactNode[0][node.name]; if (!tmp) tmp = {}; const child = Object.keys(node.attrs).length !== 0 ? mergeProps({ props: node.attrs }, tmp) : tmp; const isElement = reactExports.isValidElement(child); const isValidTranslationWithChildren = isElement && hasChildren$1(node, true) && !node.voidElement; const isEmptyTransWithHTML = emptyChildrenButNeedsHandling && typeof child === 'object' && child.dummy && !isElement; const isKnownComponent = typeof children === 'object' && children !== null && Object.hasOwnProperty.call(children, node.name); if (typeof child === 'string') { const value = i18n.services.interpolator.interpolate(child, opts, i18n.language); mem.push(value); } else if (hasChildren$1(child) || isValidTranslationWithChildren) { const inner = renderInner(child, node, rootReactNode); pushTranslatedJSX(child, inner, mem, i); } else if (isEmptyTransWithHTML) { const inner = mapAST(reactNodes, node.children, rootReactNode); pushTranslatedJSX(child, inner, mem, i); } else if (Number.isNaN(parseFloat(node.name))) { if (isKnownComponent) { const inner = renderInner(child, node, rootReactNode); pushTranslatedJSX(child, inner, mem, i, node.voidElement); } else if (i18nOptions.transSupportBasicHtmlNodes && keepArray.indexOf(node.name) > -1) { if (node.voidElement) { mem.push(reactExports.createElement(node.name, { key: `${node.name}-${i}` })); } else { const inner = mapAST(reactNodes, node.children, rootReactNode); mem.push(reactExports.createElement(node.name, { key: `${node.name}-${i}` }, inner)); } } else if (node.voidElement) { mem.push(`<${node.name} />`); } else { const inner = mapAST(reactNodes, node.children, rootReactNode); mem.push(`<${node.name}>${inner}`); } } else if (typeof child === 'object' && !isElement) { const content = node.children[0] ? translationContent : null; if (content) mem.push(content); } else { pushTranslatedJSX(child, translationContent, mem, i, node.children.length !== 1 || !translationContent); } } else if (node.type === 'text') { const wrapTextNodes = i18nOptions.transWrapTextNodes; const content = shouldUnescape ? i18nOptions.unescape(i18n.services.interpolator.interpolate(node.content, opts, i18n.language)) : i18n.services.interpolator.interpolate(node.content, opts, i18n.language); if (wrapTextNodes) { mem.push(reactExports.createElement(wrapTextNodes, { key: `${node.name}-${i}` }, content)); } else { mem.push(content); } } return mem; }, []); } const result = mapAST([{ dummy: true, children: children || [] }], ast, getAsArray(children || [])); return getChildren$2(result[0]); } function Trans$1(_ref) { let { children, count, parent, i18nKey, context, tOptions = {}, values, defaults, components, ns, i18n: i18nFromProps, t: tFromProps, shouldUnescape, ...additionalProps } = _ref; const i18n = i18nFromProps || getI18n(); if (!i18n) { warnOnce('You will need to pass in an i18next instance by using i18nextReactModule'); return children; } const t = tFromProps || i18n.t.bind(i18n) || (k => k); if (context) tOptions.context = context; const reactI18nextOptions = { ...getDefaults(), ...(i18n.options && i18n.options.react) }; let namespaces = ns || t.ns || i18n.options && i18n.options.defaultNS; namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation']; const nodeAsString = nodesToString(children, reactI18nextOptions); const defaultValue = defaults || nodeAsString || reactI18nextOptions.transEmptyNodeValue || i18nKey; const { hashTransKey } = reactI18nextOptions; const key = i18nKey || (hashTransKey ? hashTransKey(nodeAsString || defaultValue) : nodeAsString || defaultValue); let interpolationOverride = values ? tOptions.interpolation : { interpolation: { ...tOptions.interpolation, prefix: '#$?', suffix: '?$#' } }; if (i18n.options && i18n.options.interpolation && i18n.options.interpolation.defaultVariables) { if (!interpolationOverride) interpolationOverride = {}; interpolationOverride.interpolation = { defaultVariables: { ...i18n.options.interpolation.defaultVariables, ...(interpolationOverride.interpolation && interpolationOverride.interpolation.defaultVariables || {}) } }; } const combinedTOpts = { ...tOptions, count, ...values, ...interpolationOverride, defaultValue, ns: namespaces }; const translation = key ? t(key, combinedTOpts) : defaultValue; const content = renderNodes(components || children, translation, i18n, reactI18nextOptions, combinedTOpts, shouldUnescape); const useAsParent = parent !== undefined ? parent : reactI18nextOptions.defaultTransParent; return useAsParent ? reactExports.createElement(useAsParent, additionalProps, content) : content; } function Trans(_ref) { let { children, count, parent, i18nKey, context, tOptions = {}, values, defaults, components, ns, i18n: i18nFromProps, t: tFromProps, shouldUnescape, ...additionalProps } = _ref; const { i18n: i18nFromContext, defaultNS: defaultNSFromContext } = reactExports.useContext(I18nContext) || {}; const i18n = i18nFromProps || i18nFromContext || getI18n(); const t = tFromProps || i18n && i18n.t.bind(i18n); return Trans$1({ children, count, parent, i18nKey, context, tOptions, values, defaults, components, ns: ns || t && t.ns || defaultNSFromContext || i18n && i18n.options && i18n.options.defaultNS, i18n, t: tFromProps, shouldUnescape, ...additionalProps }); } function useSSR$1(initialI18nStore, initialLanguage) { let props = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; const { i18n: i18nFromProps } = props; const { i18n: i18nFromContext } = reactExports.useContext(I18nContext) || {}; const i18n = i18nFromProps || i18nFromContext || getI18n(); if (i18n.options && i18n.options.isClone) return; if (initialI18nStore && !i18n.initializedStoreOnce) { i18n.services.resourceStore.data = initialI18nStore; i18n.options.ns = Object.values(initialI18nStore).reduce((mem, lngResources) => { Object.keys(lngResources).forEach(ns => { if (mem.indexOf(ns) < 0) mem.push(ns); }); return mem; }, i18n.options.ns); i18n.initializedStoreOnce = true; i18n.isInitialized = true; } if (initialLanguage && !i18n.initializedLanguageOnce) { i18n.changeLanguage(initialLanguage); i18n.initializedLanguageOnce = true; } } const usePrevious$1 = (value, ignore) => { const ref = reactExports.useRef(); reactExports.useEffect(() => { ref.current = value; }, [value, ignore]); return ref.current; }; function useTranslation(ns) { let props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; const { i18n: i18nFromProps } = props; const { i18n: i18nFromContext, defaultNS: defaultNSFromContext } = reactExports.useContext(I18nContext) || {}; const i18n = i18nFromProps || i18nFromContext || getI18n(); if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces(); if (!i18n) { warnOnce('You will need to pass in an i18next instance by using initReactI18next'); const notReadyT = (k, optsOrDefaultValue) => { if (typeof optsOrDefaultValue === 'string') return optsOrDefaultValue; if (optsOrDefaultValue && typeof optsOrDefaultValue === 'object' && typeof optsOrDefaultValue.defaultValue === 'string') return optsOrDefaultValue.defaultValue; return Array.isArray(k) ? k[k.length - 1] : k; }; const retNotReady = [notReadyT, {}, false]; retNotReady.t = notReadyT; retNotReady.i18n = {}; retNotReady.ready = false; return retNotReady; } if (i18n.options.react && i18n.options.react.wait !== undefined) warnOnce('It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.'); const i18nOptions = { ...getDefaults(), ...i18n.options.react, ...props }; const { useSuspense, keyPrefix } = i18nOptions; let namespaces = defaultNSFromContext || i18n.options && i18n.options.defaultNS; namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation']; if (i18n.reportNamespaces.addUsedNamespaces) i18n.reportNamespaces.addUsedNamespaces(namespaces); const ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(n => hasLoadedNamespace(n, i18n, i18nOptions)); function getT() { return i18n.getFixedT(props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix); } const [t, setT] = reactExports.useState(getT); let joinedNS = namespaces.join(); if (props.lng) joinedNS = `${props.lng}${joinedNS}`; const previousJoinedNS = usePrevious$1(joinedNS); const isMounted = reactExports.useRef(true); reactExports.useEffect(() => { const { bindI18n, bindI18nStore } = i18nOptions; isMounted.current = true; if (!ready && !useSuspense) { if (props.lng) { loadLanguages(i18n, props.lng, namespaces, () => { if (isMounted.current) setT(getT); }); } else { loadNamespaces(i18n, namespaces, () => { if (isMounted.current) setT(getT); }); } } if (ready && previousJoinedNS && previousJoinedNS !== joinedNS && isMounted.current) { setT(getT); } function boundReset() { if (isMounted.current) setT(getT); } if (bindI18n && i18n) i18n.on(bindI18n, boundReset); if (bindI18nStore && i18n) i18n.store.on(bindI18nStore, boundReset); return () => { isMounted.current = false; if (bindI18n && i18n) bindI18n.split(' ').forEach(e => i18n.off(e, boundReset)); if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(e => i18n.store.off(e, boundReset)); }; }, [i18n, joinedNS]); const isInitial = reactExports.useRef(true); reactExports.useEffect(() => { if (isMounted.current && !isInitial.current) { setT(getT); } isInitial.current = false; }, [i18n, keyPrefix]); const ret = [t, i18n, ready]; ret.t = t; ret.i18n = i18n; ret.ready = ready; if (ready) return ret; if (!ready && !useSuspense) return ret; throw new Promise(resolve => { if (props.lng) { loadLanguages(i18n, props.lng, namespaces, () => resolve()); } else { loadNamespaces(i18n, namespaces, () => resolve()); } }); } const loadJSONFromID = (id) => { const unparsed = document.getElementById(id)?.innerHTML; if (!unparsed) throw new Error(`Couldn't load config from ID: ${id}`); return JSON.parse(unparsed) ; }; /** @internal */ function createChain(opts) { return observable((observer)=>{ function execute(index = 0, op = opts.op) { const next = opts.links[index]; if (!next) { throw new Error('No more links to execute - did you forget to add an ending link?'); } const subscription = next({ op, next (nextOp) { const nextObserver = execute(index + 1, nextOp); return nextObserver; } }); return subscription; } const obs$ = execute(); return obs$.subscribe(observer); }); } /** * @internal */ function invert(obj) { const newObj = Object.create(null); for(const key in obj){ const v = obj[key]; newObj[v] = key; } return newObj; } // reference: https://www.jsonrpc.org/specification /** * JSON-RPC 2.0 Error codes * * `-32000` to `-32099` are reserved for implementation-defined server-errors. * For tRPC we're copying the last digits of HTTP 4XX errors. */ const TRPC_ERROR_CODES_BY_KEY = { /** * Invalid JSON was received by the server. * An error occurred on the server while parsing the JSON text. */ PARSE_ERROR: -32700, /** * The JSON sent is not a valid Request object. */ BAD_REQUEST: -32600, // Internal JSON-RPC error INTERNAL_SERVER_ERROR: -32603, NOT_IMPLEMENTED: -32603, // Implementation specific errors UNAUTHORIZED: -32001, FORBIDDEN: -32003, NOT_FOUND: -32004, METHOD_NOT_SUPPORTED: -32005, TIMEOUT: -32008, CONFLICT: -32009, PRECONDITION_FAILED: -32012, PAYLOAD_TOO_LARGE: -32013, UNPROCESSABLE_CONTENT: -32022, TOO_MANY_REQUESTS: -32029, CLIENT_CLOSED_REQUEST: -32099 }; invert(TRPC_ERROR_CODES_BY_KEY); invert(TRPC_ERROR_CODES_BY_KEY); const noop$3 = ()=>{ // noop }; function createInnerProxy(callback, path) { const proxy = new Proxy(noop$3, { get (_obj, key) { if (typeof key !== 'string' || key === 'then') { // special case for if the proxy is accidentally treated // like a PromiseLike (like in `Promise.resolve(proxy)`) return undefined; } return createInnerProxy(callback, [ ...path, key ]); }, apply (_1, _2, args) { const isApply = path[path.length - 1] === 'apply'; return callback({ args: isApply ? args.length >= 2 ? args[1] : [] : args, path: isApply ? path.slice(0, -1) : path }); } }); return proxy; } /** * Creates a proxy that calls the callback with the path and arguments * * @internal */ const createRecursiveProxy = (callback)=>createInnerProxy(callback, []); /** * Used in place of `new Proxy` where each handler will map 1 level deep to another value. * * @internal */ const createFlatProxy = (callback)=>{ return new Proxy(noop$3, { get (_obj, name) { if (typeof name !== 'string' || name === 'then') { // special case for if the proxy is accidentally treated // like a PromiseLike (like in `Promise.resolve(proxy)`) return undefined; } return callback(name); } }); }; class TRPCUntypedClient { $request({ type , input , path , context ={} }) { const chain$ = createChain({ links: this.links, op: { id: ++this.requestId, type, path, input, context } }); return chain$.pipe(share()); } requestAsPromise(opts) { const req$ = this.$request(opts); const { promise , abort } = observableToPromise(req$); const abortablePromise = new Promise((resolve, reject)=>{ opts.signal?.addEventListener('abort', abort); promise.then((envelope)=>{ resolve(envelope.result.data); }).catch((err)=>{ reject(TRPCClientError.from(err)); }); }); return abortablePromise; } query(path, input, opts) { return this.requestAsPromise({ type: 'query', path, input, context: opts?.context, signal: opts?.signal }); } mutation(path, input, opts) { return this.requestAsPromise({ type: 'mutation', path, input, context: opts?.context, signal: opts?.signal }); } subscription(path, input, opts) { const observable$ = this.$request({ type: 'subscription', path, input, context: opts?.context }); return observable$.subscribe({ next (envelope) { if (envelope.result.type === 'started') { opts.onStarted?.(); } else if (envelope.result.type === 'stopped') { opts.onStopped?.(); } else { opts.onData?.(envelope.result.data); } }, error (err) { opts.onError?.(err); }, complete () { opts.onComplete?.(); } }); } constructor(opts){ this.requestId = 0; const combinedTransformer = (()=>{ const transformer = opts.transformer; if (!transformer) { return { input: { serialize: (data)=>data, deserialize: (data)=>data }, output: { serialize: (data)=>data, deserialize: (data)=>data } }; } if ('input' in transformer) { return opts.transformer; } return { input: transformer, output: transformer }; })(); this.runtime = { transformer: { serialize: (data)=>combinedTransformer.input.serialize(data), deserialize: (data)=>combinedTransformer.output.deserialize(data) }, combinedTransformer }; // Initialize the links this.links = opts.links.map((link)=>link(this.runtime)); } } /** * @deprecated use `createTRPCProxyClient` instead */ function createTRPCClient(opts) { const client = new TRPCUntypedClient(opts); return client; } const clientCallTypeMap = { query: 'query', mutate: 'mutation', subscribe: 'subscription' }; /** @internal */ const clientCallTypeToProcedureType = (clientCallType)=>{ return clientCallTypeMap[clientCallType]; }; /** * @deprecated use `createTRPCProxyClient` instead * @internal */ function createTRPCClientProxy(client) { return createFlatProxy((key)=>{ if (client.hasOwnProperty(key)) { return client[key]; } if (key === '__untypedClient') { return client; } return createRecursiveProxy(({ path , args })=>{ const pathCopy = [ key, ...path ]; const procedureType = clientCallTypeToProcedureType(pathCopy.pop()); const fullPath = pathCopy.join('.'); return client[procedureType](fullPath, ...args); }); }); } function createTRPCProxyClient(opts) { const client = new TRPCUntypedClient(opts); const proxy = createTRPCClientProxy(client); return proxy; } /** * To allow easy interactions with groups of related queries, such as * invalidating all queries of a router, we use an array as the path when * storing in tanstack query. This function converts from the `.` separated * path passed around internally by both the legacy and proxy implementation. * https://github.com/trpc/trpc/issues/2611 **/ function getArrayQueryKey(queryKey, type) { const queryKeyArrayed = Array.isArray(queryKey) ? queryKey : [ queryKey ]; const [path, input] = queryKeyArrayed; const arrayPath = typeof path !== 'string' || path === '' ? [] : path.split('.'); // Construct a query key that is easy to destructure and flexible for // partial selecting etc. // https://github.com/trpc/trpc/issues/3128 if (!input && (!type || type === 'any')) // for `utils.invalidate()` to match all queries (including vanilla react-query) // we don't want nested array if path is empty, i.e. `[]` instead of `[[]]` return arrayPath.length ? [ arrayPath ] : []; return [ arrayPath, { ...typeof input !== 'undefined' && { input: input }, ...type && type !== 'any' && { type: type } } ]; } /** * We treat `undefined` as an input the same as omitting an `input` * https://github.com/trpc/trpc/issues/2290 */ function getQueryKeyInternal(path, input) { if (path.length) return input === undefined ? [ path ] : [ path, input ]; return []; } /** * Create proxy for decorating procedures * @internal */ function createReactProxyDecoration(name, hooks) { return createRecursiveProxy((opts)=>{ const args = opts.args; const pathCopy = [ name, ...opts.path ]; // The last arg is for instance `.useMutation` or `.useQuery()` // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const lastArg = pathCopy.pop(); // The `path` ends up being something like `post.byId` const path = pathCopy.join('.'); if (lastArg === 'useMutation') { return hooks[lastArg](path, ...args); } const [input, ...rest] = args; const queryKey = getQueryKeyInternal(path, input); // Expose queryKey helper if (lastArg === 'getQueryKey') { return getArrayQueryKey(queryKey, rest[0] ?? 'any'); } if (lastArg === '_def') { return { path: pathCopy }; } if (lastArg.startsWith('useSuspense')) { const opts1 = rest[0] || {}; const fn = lastArg === 'useSuspenseQuery' ? 'useQuery' : 'useInfiniteQuery'; const result = hooks[fn](queryKey, { ...opts1, suspense: true, enabled: true }); return [ result.data, result ]; } return hooks[lastArg](queryKey, ...rest); }); } const contextProps = [ 'client', 'ssrContext', 'ssrState', 'abortOnUnmount' ]; const TRPCContext = /*#__PURE__*/ reactExports.createContext(null); /** * @internal */ function createReactQueryUtilsProxy(context) { return createFlatProxy((key)=>{ const contextName = key; if (contextName === 'client') { return createTRPCClientProxy(context.client); } if (contextProps.includes(contextName)) { return context[contextName]; } return createRecursiveProxy(({ path , args })=>{ const pathCopy = [ key, ...path ]; const utilName = pathCopy.pop(); const fullPath = pathCopy.join('.'); const getOpts = (name)=>{ if ([ 'setData', 'setInfiniteData' ].includes(name)) { const [input, updater, ...rest] = args; const queryKey = getQueryKeyInternal(fullPath, input); return { queryKey, updater, rest }; } const [input1, ...rest1] = args; const queryKey1 = getQueryKeyInternal(fullPath, input1); return { queryKey: queryKey1, rest: rest1 }; }; const { queryKey , rest , updater } = getOpts(utilName); const contextMap = { fetch: ()=>context.fetchQuery(queryKey, ...rest), fetchInfinite: ()=>context.fetchInfiniteQuery(queryKey, ...rest), prefetch: ()=>context.prefetchQuery(queryKey, ...rest), prefetchInfinite: ()=>context.prefetchInfiniteQuery(queryKey, ...rest), ensureData: ()=>context.ensureQueryData(queryKey, ...rest), invalidate: ()=>context.invalidateQueries(queryKey, ...rest), reset: ()=>context.resetQueries(queryKey, ...rest), refetch: ()=>context.refetchQueries(queryKey, ...rest), cancel: ()=>context.cancelQuery(queryKey, ...rest), setData: ()=>{ context.setQueryData(queryKey, updater, ...rest); }, setInfiniteData: ()=>{ context.setInfiniteQueryData(queryKey, updater, ...rest); }, getData: ()=>context.getQueryData(queryKey), getInfiniteData: ()=>context.getInfiniteQueryData(queryKey) }; return contextMap[utilName](); }); }); } /** * Create proxy for `useQueries` options * @internal */ function createUseQueriesProxy(client) { return createRecursiveProxy((opts)=>{ const path = opts.path.join('.'); const [input, _opts] = opts.args; const queryKey = getQueryKeyInternal(path, input); const options = { queryKey, queryFn: ()=>{ return client.query(path, input, _opts?.trpc); }, ..._opts }; return options; }); } function getClientArgs(pathAndInput, opts) { const [path, input] = pathAndInput; return [ path, input, opts?.trpc ]; } /** * Makes a stable reference of the `trpc` prop */ function useHookResult(value) { const ref = reactExports.useRef(value); ref.current.path = value.path; return ref.current; } /** * @internal */ function createRootHooks(config) { const mutationSuccessOverride = ((options)=>options.originalFn()); const Context = TRPCContext; const ReactQueryContext = config?.reactQueryContext; const createClient = (opts)=>{ return createTRPCClient(opts); }; const TRPCProvider = (props)=>{ const { abortOnUnmount =false , client , queryClient , ssrContext } = props; const [ssrState, setSSRState] = reactExports.useState(props.ssrState ?? false); reactExports.useEffect(()=>{ // Only updating state to `mounted` if we are using SSR. // This makes it so we don't have an unnecessary re-render when opting out of SSR. setSSRState((state)=>state ? 'mounted' : false); }, []); return /*#__PURE__*/ React$2.createElement(Context.Provider, { value: { abortOnUnmount, queryClient, client, ssrContext: ssrContext ?? null, ssrState, fetchQuery: reactExports.useCallback((pathAndInput, opts)=>{ return queryClient.fetchQuery({ ...opts, queryKey: getArrayQueryKey(pathAndInput, 'query'), queryFn: ()=>client.query(...getClientArgs(pathAndInput, opts)) }); }, [ client, queryClient ]), fetchInfiniteQuery: reactExports.useCallback((pathAndInput, opts)=>{ return queryClient.fetchInfiniteQuery({ ...opts, queryKey: getArrayQueryKey(pathAndInput, 'infinite'), queryFn: ({ pageParam })=>{ const [path, input] = pathAndInput; const actualInput = { ...input, cursor: pageParam }; return client.query(...getClientArgs([ path, actualInput ], opts)); } }); }, [ client, queryClient ]), prefetchQuery: reactExports.useCallback((pathAndInput, opts)=>{ return queryClient.prefetchQuery({ ...opts, queryKey: getArrayQueryKey(pathAndInput, 'query'), queryFn: ()=>client.query(...getClientArgs(pathAndInput, opts)) }); }, [ client, queryClient ]), prefetchInfiniteQuery: reactExports.useCallback((pathAndInput, opts)=>{ return queryClient.prefetchInfiniteQuery({ ...opts, queryKey: getArrayQueryKey(pathAndInput, 'infinite'), queryFn: ({ pageParam })=>{ const [path, input] = pathAndInput; const actualInput = { ...input, cursor: pageParam }; return client.query(...getClientArgs([ path, actualInput ], opts)); } }); }, [ client, queryClient ]), ensureQueryData: reactExports.useCallback((pathAndInput, opts)=>{ return queryClient.ensureQueryData({ ...opts, queryKey: getArrayQueryKey(pathAndInput, 'query'), queryFn: ()=>client.query(...getClientArgs(pathAndInput, opts)) }); }, [ client, queryClient ]), invalidateQueries: reactExports.useCallback((queryKey, filters, options)=>{ return queryClient.invalidateQueries({ ...filters, queryKey: getArrayQueryKey(queryKey, 'any') }, options); }, [ queryClient ]), resetQueries: reactExports.useCallback((...args)=>{ const [queryKey, filters, options] = args; return queryClient.resetQueries({ ...filters, queryKey: getArrayQueryKey(queryKey, 'any') }, options); }, [ queryClient ]), refetchQueries: reactExports.useCallback((...args)=>{ const [queryKey, filters, options] = args; return queryClient.refetchQueries({ ...filters, queryKey: getArrayQueryKey(queryKey, 'any') }, options); }, [ queryClient ]), cancelQuery: reactExports.useCallback((pathAndInput)=>{ return queryClient.cancelQueries({ queryKey: getArrayQueryKey(pathAndInput, 'any') }); }, [ queryClient ]), setQueryData: reactExports.useCallback((...args)=>{ const [queryKey, ...rest] = args; return queryClient.setQueryData(getArrayQueryKey(queryKey, 'query'), ...rest); }, [ queryClient ]), getQueryData: reactExports.useCallback((...args)=>{ const [queryKey, ...rest] = args; return queryClient.getQueryData(getArrayQueryKey(queryKey, 'query'), ...rest); }, [ queryClient ]), setInfiniteQueryData: reactExports.useCallback((...args)=>{ const [queryKey, ...rest] = args; return queryClient.setQueryData(getArrayQueryKey(queryKey, 'infinite'), ...rest); }, [ queryClient ]), getInfiniteQueryData: reactExports.useCallback((...args)=>{ const [queryKey, ...rest] = args; return queryClient.getQueryData(getArrayQueryKey(queryKey, 'infinite'), ...rest); }, [ queryClient ]) } }, props.children); }; function useContext() { return React$2.useContext(Context); } /** * Hack to make sure errors return `status`='error` when doing SSR * @link https://github.com/trpc/trpc/pull/1645 */ function useSSRQueryOptionsIfNeeded(pathAndInput, type, opts) { const { queryClient , ssrState } = useContext(); return ssrState && ssrState !== 'mounted' && queryClient.getQueryCache().find(getArrayQueryKey(pathAndInput, type))?.state.status === 'error' ? { retryOnMount: false, ...opts } : opts; } function useQuery$1(// FIXME path should be a tuple in next major pathAndInput, opts) { const context = useContext(); if (!context) { throw new Error('Unable to retrieve application context. Did you forget to wrap your App inside `withTRPC` HoC?'); } const { abortOnUnmount , client , ssrState , queryClient , prefetchQuery } = context; const defaultOpts = queryClient.getQueryDefaults(getArrayQueryKey(pathAndInput, 'query')); if (typeof window === 'undefined' && ssrState === 'prepass' && opts?.trpc?.ssr !== false && (opts?.enabled ?? defaultOpts?.enabled) !== false && !queryClient.getQueryCache().find(getArrayQueryKey(pathAndInput, 'query'))) { void prefetchQuery(pathAndInput, opts); } const ssrOpts = useSSRQueryOptionsIfNeeded(pathAndInput, 'query', { ...defaultOpts, ...opts }); const shouldAbortOnUnmount = opts?.trpc?.abortOnUnmount ?? config?.abortOnUnmount ?? abortOnUnmount; const hook = useQuery({ ...ssrOpts, queryKey: getArrayQueryKey(pathAndInput, 'query'), queryFn: (queryFunctionContext)=>{ const actualOpts = { ...ssrOpts, trpc: { ...ssrOpts?.trpc, ...shouldAbortOnUnmount ? { signal: queryFunctionContext.signal } : {} } }; return client.query(...getClientArgs(pathAndInput, actualOpts)); }, context: ReactQueryContext }); hook.trpc = useHookResult({ path: pathAndInput[0] }); return hook; } function useMutation$1(// FIXME: this should only be a tuple path in next major path, opts) { const { client } = useContext(); const queryClient = useQueryClient({ context: ReactQueryContext }); const actualPath = Array.isArray(path) ? path[0] : path; const defaultOpts = queryClient.getMutationDefaults([ actualPath.split('.') ]); const hook = useMutation({ ...opts, mutationKey: [ actualPath.split('.') ], mutationFn: (input)=>{ return client.mutation(...getClientArgs([ actualPath, input ], opts)); }, context: ReactQueryContext, onSuccess (...args) { const originalFn = ()=>opts?.onSuccess?.(...args) ?? defaultOpts?.onSuccess?.(...args); return mutationSuccessOverride({ originalFn, queryClient, meta: opts?.meta ?? defaultOpts?.meta ?? {} }); } }); hook.trpc = useHookResult({ path: actualPath }); return hook; } /* istanbul ignore next -- @preserve */ function useSubscription(pathAndInput, opts) { const enabled = opts?.enabled ?? true; const queryKey = hashQueryKey(); const { client } = useContext(); const optsRef = reactExports.useRef(opts); optsRef.current = opts; reactExports.useEffect(()=>{ if (!enabled) { return; } const [path, input] = pathAndInput; let isStopped = false; const subscription = client.subscription(path, input ?? undefined, { onStarted: ()=>{ if (!isStopped) { optsRef.current.onStarted?.(); } }, onData: (data)=>{ if (!isStopped) { // FIXME this shouldn't be needed as both should be `unknown` in next major optsRef.current.onData(data); } }, onError: (err)=>{ if (!isStopped) { optsRef.current.onError?.(err); } } }); return ()=>{ isStopped = true; subscription.unsubscribe(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [ queryKey, enabled ]); } function useInfiniteQuery$1(pathAndInput, opts) { const [path, input] = pathAndInput; const { client , ssrState , prefetchInfiniteQuery , queryClient , abortOnUnmount , } = useContext(); const defaultOpts = queryClient.getQueryDefaults(getArrayQueryKey(pathAndInput, 'infinite')); if (typeof window === 'undefined' && ssrState === 'prepass' && opts?.trpc?.ssr !== false && (opts?.enabled ?? defaultOpts?.enabled) !== false && !queryClient.getQueryCache().find(getArrayQueryKey(pathAndInput, 'infinite'))) { void prefetchInfiniteQuery(pathAndInput, { ...defaultOpts, ...opts }); } const ssrOpts = useSSRQueryOptionsIfNeeded(pathAndInput, 'infinite', { ...defaultOpts, ...opts }); // request option should take priority over global const shouldAbortOnUnmount = opts?.trpc?.abortOnUnmount ?? abortOnUnmount; const hook = useInfiniteQuery({ ...ssrOpts, queryKey: getArrayQueryKey(pathAndInput, 'infinite'), queryFn: (queryFunctionContext)=>{ const actualOpts = { ...ssrOpts, trpc: { ...ssrOpts?.trpc, ...shouldAbortOnUnmount ? { signal: queryFunctionContext.signal } : {} } }; const actualInput = { ...input ?? {}, cursor: queryFunctionContext.pageParam ?? opts?.initialCursor }; // FIXME as any shouldn't be needed as client should be untyped too return client.query(...getClientArgs([ path, actualInput ], actualOpts)); }, context: ReactQueryContext }); hook.trpc = useHookResult({ path }); return hook; } const useQueries$1 = (queriesCallback, context)=>{ const { ssrState , queryClient , prefetchQuery , client } = useContext(); const proxy = createUseQueriesProxy(client); const queries = queriesCallback(proxy); if (typeof window === 'undefined' && ssrState === 'prepass') { for (const query of queries){ const queryOption = query; if (queryOption.trpc?.ssr !== false && !queryClient.getQueryCache().find(getArrayQueryKey(queryOption.queryKey, 'query'))) { void prefetchQuery(queryOption.queryKey, queryOption); } } } return useQueries({ queries: queries.map((query)=>({ ...query, queryKey: getArrayQueryKey(query.queryKey, 'query') })), context }); }; const useDehydratedState = (client, trpcState)=>{ const transformed = reactExports.useMemo(()=>{ if (!trpcState) { return trpcState; } return client.runtime.transformer.deserialize(trpcState); }, [ trpcState, client ]); return transformed; }; return { Provider: TRPCProvider, createClient, useContext, useQuery: useQuery$1, useQueries: useQueries$1, useMutation: useMutation$1, useSubscription, useDehydratedState, useInfiniteQuery: useInfiniteQuery$1 }; } /** * Create strongly typed react hooks * @internal * @deprecated */ function createHooksInternal(config) { return createRootHooks(config); } /** * @internal */ function createHooksInternalProxy(trpc) { return createFlatProxy((key)=>{ if (key === 'useContext') { return ()=>{ const context = trpc.useContext(); // create a stable reference of the utils context return reactExports.useMemo(()=>{ return createReactQueryUtilsProxy(context); }, [ context ]); }; } if (trpc.hasOwnProperty(key)) { return trpc[key]; } return createReactProxyDecoration(key, trpc); }); } function createTRPCReact(opts) { const hooks = createHooksInternal(opts); const proxy = createHooksInternalProxy(hooks); return proxy; } const trpc = createTRPCReact(); const FlashesProvider = reactExports.createContext ({ info: [], error: [], }); const defaultMutableStore = { ssrUrl: "", lightThemeOnly: false, }; class ReqMutableStore { constructor( _store) {this._store = _store; this._store = Object.assign({}, _store); } get(key) { return this._store[key]; } assign(newConfig) { Object.assign(this._store, newConfig); } } const ReqMutableStoreContext = reactExports.createContext( new ReqMutableStore({ ...defaultMutableStore }) ); const ReqMutableStoreProvider = React$2.memo(({ children, store }) => { const mutableStore = new ReqMutableStore(store); return ( React$2.createElement(ReqMutableStoreContext.Provider, { value: mutableStore,} , children ) ); }); ReqMutableStoreProvider.displayName = "ReqMutableStoreProvider"; const useReqMutableStore = () => reactExports.useContext(ReqMutableStoreContext); var rollbar_umd_min = {exports: {}}; (function (module, exports) { !function(t,e){module.exports=e();}(commonjsGlobal,(function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n});},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0});},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)r.d(n,o,function(e){return t[e]}.bind(null,o));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=6)}([function(t,e,r){var n=r(12),o={},i=!1;function a(t,e){return e===s(t)}function s(t){var e=typeof t;return "object"!==e?e:t?t instanceof Error?"error":{}.toString.call(t).match(/\s([a-zA-Z]+)/)[1].toLowerCase():"null"}function u(t){return a(t,"function")}function c(t){var e=Function.prototype.toString.call(Object.prototype.hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?"),r=RegExp("^"+e+"$");return l(t)&&r.test(t)}function l(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}function p(){var t=y();return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var r=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"===e?r:7&r|8).toString(16)}))}var f={strictMode:!1,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};function h(t,e){var r,n;try{r=o.stringify(t);}catch(o){if(e&&u(e))try{r=e(t);}catch(t){n=t;}else n=o;}return {error:n,value:r}}function d(t,e){return function(r,n){try{e(r,n);}catch(e){t.error(e);}}}var m=["log","network","dom","navigation","error","manual"],g=["critical","error","warning","info","debug"];function v(t,e){for(var r=0;rs)?(a=e.path,e.path=a.substring(0,s)+i+"&"+a.substring(s+1)):-1!==u?(a=e.path,e.path=a.substring(0,u)+i+a.substring(u)):e.path=e.path+i;},createItem:function(t,e,r,o,i){for(var a,u,c,l,f,h,m=[],g=[],v=0,b=t.length;v0&&((c=n(c)).extraArgs=m);var k={message:a,err:u,custom:c,timestamp:y(),callback:l,notifier:r,diagnostic:{},uuid:p()};return function(t,e){e&&void 0!==e.level&&(t.level=e.level,delete e.level);e&&void 0!==e.skipFrames&&(t.skipFrames=e.skipFrames,delete e.skipFrames);}(k,c),o&&f&&(k.request=f),i&&(k.lambdaContext=i),k._originalArgs=t,k.diagnostic.original_arg_types=g,k},addErrorContext:function(t,e){var r=t.data.custom||{},o=!1;try{for(var i=0;i2){var o=n.slice(0,3),i=o[2].indexOf("/");-1!==i&&(o[2]=o[2].substring(0,i));r=o.concat("0000:0000:0000:0000:0000").join(":");}}else r=null;}catch(t){r=null;}else r=null;t.user_ip=r;}},formatArgsAsString:function(t){var e,r,n,o=[];for(e=0,r=t.length;e500&&(n=n.substr(0,497)+"...");break;case"null":n="null";break;case"undefined":n="undefined";break;case"symbol":n=n.toString();}o.push(n);}return o.join(" ")},formatUrl:function(t,e){if(!(e=e||t.protocol)&&t.port&&(80===t.port?e="http:":443===t.port&&(e="https:")),e=e||"https:",!t.hostname)return null;var r=e+"//"+t.hostname;return t.port&&(r=r+":"+t.port),t.path&&(r+=t.path),r},get:function(t,e){if(t){var r=e.split("."),n=t;try{for(var o=0,i=r.length;o=1&&r>e}function a(t,e,r,n,o,i,a){var s=null;return r&&(r=new Error(r)),r||n||(s=function(t,e,r,n,o){var i,a=e.environment||e.payload&&e.payload.environment;i=o?"item per minute limit reached, ignoring errors until timeout":"maxItems has been hit, ignoring errors until reset.";var s={body:{message:{body:i,extra:{maxItems:r,itemsPerMinute:n}}},language:"javascript",environment:a,notifier:{version:e.notifier&&e.notifier.version||e.version}};"browser"===t?(s.platform="browser",s.framework="browser-js",s.notifier.name="rollbar-browser-js"):"server"===t?(s.framework=e.framework||"node-js",s.notifier.name=e.notifier.name):"react-native"===t&&(s.framework=e.framework||"react-native",s.notifier.name=e.notifier.name);return s}(t,e,o,i,a)),{error:r,shouldSend:n,payload:s}}o.globalSettings={startTime:n.now(),maxItems:void 0,itemsPerMinute:void 0},o.prototype.configureGlobal=function(t){void 0!==t.startTime&&(o.globalSettings.startTime=t.startTime),void 0!==t.maxItems&&(o.globalSettings.maxItems=t.maxItems),void 0!==t.itemsPerMinute&&(o.globalSettings.itemsPerMinute=t.itemsPerMinute);},o.prototype.shouldSend=function(t,e){var r=(e=e||n.now())-this.startTime;(r<0||r>=6e4)&&(this.startTime=e,this.perMinCounter=0);var s=o.globalSettings.maxItems,u=o.globalSettings.itemsPerMinute;if(i(t,s,this.counter))return a(this.platform,this.platformOptions,s+" max items reached",!1);if(i(t,u,this.perMinCounter))return a(this.platform,this.platformOptions,u+" items per minute reached",!1);this.counter++,this.perMinCounter++;var c=!i(t,s,this.counter),l=c;return c=c&&!i(t,u,this.perMinCounter),a(this.platform,this.platformOptions,null,c,s,u,l)},o.prototype.setPlatformOptions=function(t,e){this.platform=t,this.platformOptions=e;},t.exports=o;},function(t,e,r){var n=Object.prototype.hasOwnProperty,o=Object.prototype.toString,i=function(t){if(!t||"[object Object]"!==o.call(t))return !1;var e,r=n.call(t,"constructor"),i=t.constructor&&t.constructor.prototype&&n.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!r&&!i)return !1;for(e in t);return void 0===e||n.call(t,e)};t.exports=function t(){var e,r,n,o,a,s={},u=null,c=arguments.length;for(e=0;e255&&(e.context=e.context.substr(0,255));}return {access_token:t,data:e}},getTransportFromOptions:function(t,e,r){var n=e.hostname,o=e.protocol,i=e.port,a=e.path,s=e.search,u=t.proxy;if(t.endpoint){var c=r.parse(t.endpoint);n=c.hostname,o=c.protocol,i=c.port,a=c.pathname,s=c.search;}return {hostname:n,protocol:o,port:i,path:a,search:s,proxy:u}},transportOptions:function(t,e){var r=t.protocol||"https:",n=t.port||("http:"===r?80:"https:"===r?443:void 0),o=t.hostname,i=t.path;return t.search&&(i+=t.search),t.proxy&&(i=r+"//"+o+i,o=t.proxy.host||t.proxy.hostname,n=t.proxy.port,r=t.proxy.protocol||r),{protocol:r,hostname:o,path:i,port:n,method:e}},appendPathToPath:function(t,e){var r=/\/$/.test(t),n=/^\//.test(e);return r&&n?e=e.substring(1):r||n||(e="/"+e),t+e}};},function(t,e){!function(t){t.console||(t.console={});for(var e,r,n=t.console,o=function(){},i=["memory"],a="assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn".split(",");e=i.pop();)n[e]||(n[e]={});for(;r=a.pop();)n[r]||(n[r]=o);}("undefined"==typeof window?this:window);},function(t,e,r){var n={ieVersion:function(){if("undefined"!=typeof document){for(var t=3,e=document.createElement("div"),r=e.getElementsByTagName("i");e.innerHTML="\x3c!--[if gt IE "+ ++t+"]>4?t:void 0}}};t.exports=n;},function(t,e,r){function n(t,e,r,n){t._rollbarWrappedError&&(n[4]||(n[4]=t._rollbarWrappedError),n[5]||(n[5]=t._rollbarWrappedError._rollbarContext),t._rollbarWrappedError=null);var o=e.handleUncaughtException.apply(e,n);r&&r.apply(t,n),"anonymous"===o&&(e.anonymousErrorsPending+=1);}t.exports={captureUncaughtExceptions:function(t,e,r){if(t){var o;if("function"==typeof e._rollbarOldOnError)o=e._rollbarOldOnError;else if(t.onerror){for(o=t.onerror;o._rollbarOldOnError;)o=o._rollbarOldOnError;e._rollbarOldOnError=o;}e.handleAnonymousErrors();var i=function(){var r=Array.prototype.slice.call(arguments,0);n(t,e,o,r);};r&&(i._rollbarOldOnError=o),t.onerror=i;}},captureUnhandledRejections:function(t,e,r){if(t){"function"==typeof t._rollbarURH&&t._rollbarURH.belongsToShim&&t.removeEventListener("unhandledrejection",t._rollbarURH);var n=function(t){var r,n,o;try{r=t.reason;}catch(t){r=void 0;}try{n=t.promise;}catch(t){n="[unhandledrejection] error getting `promise` from event";}try{o=t.detail,!r&&o&&(r=o.reason,n=o.promise);}catch(t){}r||(r="[unhandledrejection] error getting `reason` from event"),e&&e.handleUnhandledRejection&&e.handleUnhandledRejection(r,n);};n.belongsToShim=r,t._rollbarURH=n,t.addEventListener("unhandledrejection",n);}}};},function(t,e,r){var n=r(0),o=r(1);function i(t){this.truncation=t;}function a(t,e,r,n,o,i){var a="undefined"!=typeof window&&window||"undefined"!=typeof self&&self,u=a&&a.Zone&&a.Zone.current;u&&"angular"===u._name?u._parent.run((function(){s(t,e,r,n,o,i);})):s(t,e,r,n,o,i);}function s(t,e,r,i,a,s){if("undefined"!=typeof RollbarProxy)return function(t,e){(new RollbarProxy).sendJsonPayload(t,(function(t){}),(function(t){e(new Error(t));}));}(i,a);var c;if(!(c=s?s():function(){var t,e,r=[function(){return new XMLHttpRequest},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Msxml3.XMLHTTP")},function(){return new ActiveXObject("Microsoft.XMLHTTP")}],n=r.length;for(e=0;e=400&&t.status<600}(c)){if(403===c.status){var e=t.value&&t.value.message;o.error(e);}a(new Error(String(c.status)));}else {a(u("XHR response had no status code (likely connection failure)"));}}}catch(t){var r;r=t&&t.stack?t:new Error(t),a(r);}var i;};c.open(r,e,!0),c.setRequestHeader&&(c.setRequestHeader("Content-Type","application/json"),c.setRequestHeader("X-Rollbar-Access-Token",t)),c.onreadystatechange=l,c.send(i);}catch(t){if("undefined"!=typeof XDomainRequest){if(!window||!window.location)return a(new Error("No window available during request, unknown environment"));"http:"===window.location.href.substring(0,5)&&"https"===e.substring(0,5)&&(e="http"+e.substring(5));var p=new XDomainRequest;p.onprogress=function(){},p.ontimeout=function(){a(u("Request timed out","ETIMEDOUT"));},p.onerror=function(){a(new Error("Error during request"));},p.onload=function(){var t=n.jsonParse(p.responseText);a(t.error,t.value);},p.open(r,e,!0),p.send(i);}else a(new Error("Cannot find a method to transport a request"));}}catch(t){a(t);}}function u(t,e){var r=new Error(t);return r.code=e||"ENOTFOUND",r}i.prototype.get=function(t,e,r,o,i){o&&n.isFunction(o)||(o=function(){}),n.addParamsAndAccessTokenToPath(t,e,r);a(t,n.formatUrl(e),"GET",null,o,i);},i.prototype.post=function(t,e,r,o,i){if(o&&n.isFunction(o)||(o=function(){}),!r)return o(new Error("Cannot send empty request"));var s;if((s=this.truncation?this.truncation.truncate(r):n.stringify(r)).error)return o(s.error);var u=s.value;a(t,n.formatUrl(e),"POST",u,o,i);},i.prototype.postJsonPayload=function(t,e,r,o,i){o&&n.isFunction(o)||(o=function(){});a(t,n.formatUrl(e),"POST",r,o,i);},t.exports=i;},function(t,e,r){var n=r(0),o=r(3),i=r(1);function a(t,e,r){var o=t.message,i=t.custom;o||(o="Item sent with null or missing arguments.");var a={body:o};i&&(a.extra=n.merge(i)),n.set(t,"data.body",{message:a}),r(null,t);}function s(t){var e=t.stackInfo.stack;return e&&0===e.length&&t._unhandledStackInfo&&t._unhandledStackInfo.stack&&(e=t._unhandledStackInfo.stack),e}function u(t,e,r){var i=t&&t.data.description,a=t&&t.custom,u=s(t),l=o.guessErrorClass(e.message),p={exception:{class:c(e,l[0],r),message:l[1]}};if(i&&(p.exception.description=i),u){var f,h,d,m,g,v,y,b;for(0===u.length&&(p.exception.stack=e.rawStack,p.exception.raw=String(e.rawException)),p.frames=[],y=0;y-1&&(e=e.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(\),.*$)/g,""));var r=e.replace(/^\s+/,"").replace(/\(eval code/g,"("),n=r.match(/ (\((.+):(\d+):(\d+)\)$)/),o=(r=n?r.replace(n[0],""):r).split(/\s+/).slice(1),i=this.extractLocation(n?n[1]:o.pop()),a=o.join(" ")||void 0,s=["eval",""].indexOf(i[0])>-1?void 0:i[0];return new t({functionName:a,fileName:s,lineNumber:i[1],columnNumber:i[2],source:e})}),this)},parseFFOrSafari:function(e){return e.stack.split("\n").filter((function(t){return !t.match(n)}),this).map((function(e){if(e.indexOf(" > eval")>-1&&(e=e.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),-1===e.indexOf("@")&&-1===e.indexOf(":"))return new t({functionName:e});var r=/((.*".+"[^@]*)?[^@]*)(?:@)/,n=e.match(r),o=n&&n[1]?n[1]:void 0,i=this.extractLocation(e.replace(r,""));return new t({functionName:o,fileName:i[0],lineNumber:i[1],columnNumber:i[2],source:e})}),this)},parseOpera:function(t){return !t.stacktrace||t.message.indexOf("\n")>-1&&t.message.split("\n").length>t.stacktrace.split("\n").length?this.parseOpera9(t):t.stack?this.parseOpera11(t):this.parseOpera10(t)},parseOpera9:function(e){for(var r=/Line (\d+).*script (?:in )?(\S+)/i,n=e.message.split("\n"),o=[],i=2,a=n.length;i/,"$2").replace(/\([^)]*\)/g,"")||void 0;i.match(/\(([^)]*)\)/)&&(r=i.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var s=void 0===r||"[arguments not available]"===r?void 0:r.split(",");return new t({functionName:a,args:s,fileName:o[0],lineNumber:o[1],columnNumber:o[2],source:e})}),this)}}})?n.apply(e,o):n)||(t.exports=i);}();},function(t,e,r){var n,o,i;!function(r,a){o=[],void 0===(i="function"==typeof(n=function(){function t(t){return t.charAt(0).toUpperCase()+t.substring(1)}function e(t){return function(){return this[t]}}var r=["isConstructor","isEval","isNative","isToplevel"],n=["columnNumber","lineNumber"],o=["fileName","functionName","source"],i=r.concat(n,o,["args"],["evalOrigin"]);function a(e){if(e)for(var r=0;ro&&(i=this.maxQueueSize-o),this.maxQueueSize=o,this.queue.splice(0,i);},o.prototype.copyEvents=function(){var t=Array.prototype.slice.call(this.queue,0);if(n.isFunction(this.options.filterTelemetry))try{for(var e=t.length;e--;)this.options.filterTelemetry(t[e])&&t.splice(e,1);}catch(t){this.options.filterTelemetry=null;}return t},o.prototype.capture=function(t,e,r,o,a){var s={level:i(t,r),type:t,timestamp_ms:a||n.now(),body:e,source:"client"};o&&(s.uuid=o);try{if(n.isFunction(this.options.filterTelemetry)&&this.options.filterTelemetry(s))return !1}catch(t){this.options.filterTelemetry=null;}return this.push(s),s},o.prototype.captureEvent=function(t,e,r,n){return this.capture(t,e,r,n)},o.prototype.captureError=function(t,e,r,n){var o={message:t.message||String(t)};return t.stack&&(o.stack=t.stack),this.capture("error",o,e,r,n)},o.prototype.captureLog=function(t,e,r,n){return this.capture("log",{message:t},e,r,n)},o.prototype.captureNetwork=function(t,e,r,n){e=e||"xhr",t.subtype=t.subtype||e,n&&(t.request=n);var o=this.levelFromStatus(t.status_code);return this.capture("network",t,o,r)},o.prototype.levelFromStatus=function(t){return t>=200&&t<400?"info":0===t||t>=400?"error":"info"},o.prototype.captureDom=function(t,e,r,n,o){var i={subtype:t,element:e};return void 0!==r&&(i.value=r),void 0!==n&&(i.checked=n),this.capture("dom",i,"info",o)},o.prototype.captureNavigation=function(t,e,r){return this.capture("navigation",{from:t,to:e},"info",r)},o.prototype.captureDomContentLoaded=function(t){return this.capture("navigation",{subtype:"DOMContentLoaded"},"info",void 0,t&&t.getTime())},o.prototype.captureLoad=function(t){return this.capture("navigation",{subtype:"load"},"info",void 0,t&&t.getTime())},o.prototype.captureConnectivityChange=function(t,e){return this.captureNetwork({change:t},"connectivity",e)},o.prototype._captureRollbarItem=function(t){if(this.options.includeItemsInTelemetry)return t.err?this.captureError(t.err,t.level,t.uuid,t.timestamp):t.message?this.captureLog(t.message,t.level,t.uuid,t.timestamp):t.custom?this.capture("log",t.custom,t.level,t.uuid,t.timestamp):void 0},o.prototype.push=function(t){this.queue.push(t),this.queue.length>this.maxQueueSize&&this.queue.shift();},t.exports=o;},function(t,e,r){var n=r(0),o=r(4),i=r(2),a=r(31),s={network:!0,networkResponseHeaders:!1,networkResponseBody:!1,networkRequestHeaders:!1,networkRequestBody:!1,networkErrorOnHttp5xx:!1,networkErrorOnHttp4xx:!1,networkErrorOnHttp0:!1,log:!0,dom:!0,navigation:!0,connectivity:!0};function u(t,e,r,n,o){var i=t[e];t[e]=r(i),n&&n[o].push([t,e,i]);}function c(t,e){for(var r;t[e].length;)(r=t[e].shift())[0][r[1]]=r[2];}function l(t,e,r,o,i){this.options=t;var a=t.autoInstrument;!1===t.enabled||!1===a?this.autoInstrument={}:(n.isType(a,"object")||(a=s),this.autoInstrument=n.merge(s,a)),this.scrubTelemetryInputs=!!t.scrubTelemetryInputs,this.telemetryScrubber=t.telemetryScrubber,this.defaultValueScrubber=function(t){for(var e=[],r=0;r3)){i.__rollbar_xhr.end_time_ms=n.now();var e=null;if(i.__rollbar_xhr.response_content_type=i.getResponseHeader("Content-Type"),t.autoInstrument.networkResponseHeaders){var r=t.autoInstrument.networkResponseHeaders;e={};try{var a,s;if(!0===r){var u=i.getAllResponseHeaders();if(u){var c,l,p=u.trim().split(/[\r\n]+/);for(s=0;s=500&&this.autoInstrument.networkErrorOnHttp5xx||e>=400&&this.autoInstrument.networkErrorOnHttp4xx||0===e&&this.autoInstrument.networkErrorOnHttp0){var r=new Error("HTTP request failed with Status "+e);r.stack=t.stack,this.rollbar.error(r,{skipFrames:1});}},l.prototype.deinstrumentConsole=function(){if("console"in this._window&&this._window.console.log)for(var t;this.replacements.log.length;)t=this.replacements.log.shift(),this._window.console[t[0]]=t[1];},l.prototype.instrumentConsole=function(){if("console"in this._window&&this._window.console.log){var t=this,e=this._window.console,r=["debug","info","warn","error","log"];try{for(var o=0,i=r.length;o=0&&t.options[t.selectedIndex]&&this.captureDomEvent("input",t,t.options[t.selectedIndex].value);},l.prototype.captureDomEvent=function(t,e,r,n){if(void 0!==r)if(this.scrubTelemetryInputs||"password"===a.getElementType(e))r="[scrubbed]";else {var o=a.describeElement(e);this.telemetryScrubber?this.telemetryScrubber(o)&&(r="[scrubbed]"):this.defaultValueScrubber(o)&&(r="[scrubbed]");}var i=a.elementArrayToString(a.treeToArray(e));this.telemeter.captureDom(t,i,r,n);},l.prototype.deinstrumentNavigation=function(){var t=this._window.chrome;!(t&&t.app&&t.app.runtime)&&this._window.history&&this._window.history.pushState&&c(this.replacements,"navigation");},l.prototype.instrumentNavigation=function(){var t=this._window.chrome;if(!(t&&t.app&&t.app.runtime)&&this._window.history&&this._window.history.pushState){var e=this;u(this._window,"onpopstate",(function(t){return function(){var r=e._location.href;e.handleUrlChange(e._lastHref,r),t&&t.apply(this,arguments);}}),this.replacements,"navigation"),u(this._window.history,"pushState",(function(t){return function(){var r=arguments.length>2?arguments[2]:void 0;return r&&e.handleUrlChange(e._lastHref,r+""),t.apply(this,arguments)}}),this.replacements,"navigation");}},l.prototype.handleUrlChange=function(t,e){var r=i.parse(this._location.href),n=i.parse(e),o=i.parse(t);this._lastHref=e,r.protocol===n.protocol&&r.host===n.host&&(e=n.path+(n.hash||"")),r.protocol===o.protocol&&r.host===o.host&&(t=o.path+(o.hash||"")),this.telemeter.captureNavigation(t,e);},l.prototype.deinstrumentConnectivity=function(){("addEventListener"in this._window||"body"in this._document)&&(this._window.addEventListener?this.removeListeners("connectivity"):c(this.replacements,"connectivity"));},l.prototype.instrumentConnectivity=function(){if("addEventListener"in this._window||"body"in this._document)if(this._window.addEventListener)this.addListener("connectivity",this._window,"online",void 0,function(){this.telemeter.captureConnectivityChange("online");}.bind(this),!0),this.addListener("connectivity",this._window,"offline",void 0,function(){this.telemeter.captureConnectivityChange("offline");}.bind(this),!0);else {var t=this;u(this._document.body,"ononline",(function(e){return function(){t.telemeter.captureConnectivityChange("online"),e&&e.apply(this,arguments);}}),this.replacements,"connectivity"),u(this._document.body,"onoffline",(function(e){return function(){t.telemeter.captureConnectivityChange("offline"),e&&e.apply(this,arguments);}}),this.replacements,"connectivity");}},l.prototype.addListener=function(t,e,r,n,o,i){e.addEventListener?(e.addEventListener(r,o,i),this.eventRemovers[t].push((function(){e.removeEventListener(r,o,i);}))):n&&(e.attachEvent(n,o),this.eventRemovers[t].push((function(){e.detachEvent(n,o);})));},l.prototype.removeListeners=function(t){for(;this.eventRemovers[t].length;)this.eventRemovers[t].shift()();},t.exports=l;},function(t,e,r){function n(t){return (t.getAttribute("type")||"").toLowerCase()}function o(t){if(!t||!t.tagName)return "";var e=[t.tagName];t.id&&e.push("#"+t.id),t.classes&&e.push("."+t.classes.join("."));for(var r=0;r=0;s--){if(e=o(t[s]),r=a+i.length*n+e.length,s=83){i.unshift("...");break}i.unshift(e),a+=e.length;}return i.join(" > ")},treeToArray:function(t){for(var e,r=[],n=0;t&&n<5&&"html"!==(e=i(t)).tagName;n++)r.unshift(e),t=t.parentNode;return r},getElementFromEvent:function(t,e){return t.target?t.target:e&&e.elementFromPoint?e.elementFromPoint(t.clientX,t.clientY):void 0},isDescribedElement:function(t,e,r){if(t.tagName.toLowerCase()!==e.toLowerCase())return !1;if(!r)return !0;t=n(t);for(var o=0;o2*e?t.slice(0,e).concat(t.slice(r-e)):t}function s(t,e,r){r=void 0===r?30:r;var o,i=t.data.body;if(i.trace_chain)for(var s=i.trace_chain,u=0;ut?e.slice(0,t-3).concat("..."):e}function c(t,e,r){return [e=o(e,(function e(r,i,a){switch(n.typeName(i)){case"string":return u(t,i);case"object":case"array":return o(i,e,a);default:return i}}),[]),n.stringify(e,r)]}function l(t){return t.exception&&(delete t.exception.description,t.exception.message=u(255,t.exception.message)),t.frames=a(t.frames,1),t}function p(t,e){var r=t.data.body;if(r.trace_chain)for(var o=r.trace_chain,i=0;ie}t.exports={truncate:function(t,e,r){r=void 0===r?524288:r;for(var n,o,a,u=[i,s,c.bind(null,1024),c.bind(null,512),c.bind(null,256),p];n=u.shift();)if(t=(o=n(t,e))[0],(a=o[1]).error||!f(a.value,r))return a;return a},raw:i,truncateFrames:s,truncateStrings:c,maybeTruncateValue:u};}])})); } (rollbar_umd_min)); var rollbar_umd_minExports = rollbar_umd_min.exports; var Rollbar = /*@__PURE__*/getDefaultExportFromCjs(rollbar_umd_minExports); const RollbarContext = reactExports.createContext(null); const RollbarProvider = ({ config, children }) => { const rollbar = new Rollbar({ ...config, // substring match, per https://docs.rollbar.com/docs/javascript/#section-ignoring-specific-exception-messages ignoredMessages: ["Minified React error"], }); return reactExports.createElement( RollbarContext.Provider, { value: rollbar, }, children ); }; const defaultConfig = { HCAPTCHA_SITE_KEY: "", IFRAMELY_KEY: "", UNLEASH_APP_NAME: "", UNLEASH_CLIENT_KEY: "", limits: { attachmentSize: { normal: 5 * 1024 * 1024, cohostPlus: 10 * 1024 * 1024, }, attachmentCount: 10, attachmentContentTypes: { // fastly supports gif, jpeg, png, and webp. we also support svg. see: // https://developer.fastly.com/reference/io/#limitations-and-constraints "image/png": "image", "image/jpeg": "image", "image/gif": "image", "image/webp": "image", "image/svg+xml": "image", // list of audio formats taken from https://caniuse.com/?search=audio%20format, // >= 95% as of 7/10/2023 "audio/aac": "audio", "audio/mp4": "audio", "audio/x-m4a": "audio", "audio/flac": "audio", "audio/x-flac": "audio", "audio/mpeg": "audio", "audio/wav": "audio", }, }, operatingPrime: 1, } ; function isValidAttachmentContentType( siteConfig, contentType ) { for (const supportedContentType in siteConfig.limits .attachmentContentTypes) { const kind = siteConfig.limits.attachmentContentTypes[supportedContentType]; if (supportedContentType.endsWith("/*")) { // wildcard; truncate it off and check the start of the content // type if ( contentType.startsWith( supportedContentType.substring( 0, supportedContentType.length - 1 ) ) ) return { valid: true, kind }; } else { // otherwise check identity if (contentType === supportedContentType) return { valid: true, kind }; } } console.warn(`rejected mime type: ${contentType}`); return { valid: false }; } function listValidAttachmentContentTypes( siteConfig ) { return Object.getOwnPropertyNames(siteConfig.limits.attachmentContentTypes); } class SiteConfig { _currentConfig; constructor(config) { this._currentConfig = config; } get currentConfig() { return this._currentConfig; } assign(changes) { this._currentConfig = { ...this._currentConfig, ...changes, }; } static shared = new SiteConfig({ ...defaultConfig }); } const SiteConfigProvider = reactExports.createContext(defaultConfig); const useSiteConfig = () => { const ctx = reactExports.useContext(SiteConfigProvider); return ctx; }; const usePrevious = (value) => { const ref = reactExports.useRef(); reactExports.useEffect(() => { ref.current = value; }); return ref.current; }; var util; (function (util) { function assertNever(_x) { throw new Error(); } util.assertNever = assertNever; util.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util.getValidEnumValues = (obj) => { const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); const filtered = {}; for (const k of validKeys) { filtered[k] = obj[k]; } return util.objectValues(filtered); }; util.objectValues = (obj) => { return util.objectKeys(obj).map(function (e) { return obj[e]; }); }; util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban : (object) => { const keys = []; for (const key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { keys.push(key); } } return keys; }; util.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return undefined; }; util.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; })(util || (util = {})); const ZodIssueCode = util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", ]); const quotelessJson = (obj) => { const json = JSON.stringify(obj, null, 2); return json.replace(/"([^"]+)":/g, "$1:"); }; class ZodError extends Error { constructor(issues) { super(); this.issues = []; this.format = () => { const fieldErrors = { _errors: [] }; const processError = (error) => { for (const issue of error.issues) { if (issue.code === "invalid_union") { issue.unionErrors.map(processError); } else if (issue.code === "invalid_return_type") { processError(issue.returnTypeError); } else if (issue.code === "invalid_arguments") { processError(issue.argumentsError); } else if (issue.path.length === 0) { fieldErrors._errors.push(issue.message); } else { let curr = fieldErrors; let i = 0; while (i < issue.path.length) { const el = issue.path[i]; const terminal = i === issue.path.length - 1; if (!terminal) { if (typeof el === "string") { curr[el] = curr[el] || { _errors: [] }; } else if (typeof el === "number") { const errorArray = []; errorArray._errors = []; curr[el] = curr[el] || errorArray; } } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(issue.message); } curr = curr[el]; i++; } } } }; processError(this); return fieldErrors; }; this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }; this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; if (Object.setPrototypeOf) { // eslint-disable-next-line ban/ban Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } get errors() { return this.issues; } toString() { return this.message; } get message() { return JSON.stringify(this.issues, null, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue) => issue.message) { const fieldErrors = {}; const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } } ZodError.create = (issues) => { const error = new ZodError(issues); return error; }; const defaultErrorMap = (issue, _ctx) => { let message; switch (issue.code) { case ZodIssueCode.invalid_type: if (issue.received === "undefined") { message = "Required"; } else { message = `Expected ${issue.expected}, received ${issue.received}`; } break; case ZodIssueCode.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue.expected)}`; break; case ZodIssueCode.unrecognized_keys: message = `Unrecognized key(s) in object: ${issue.keys .map((k) => `'${k}'`) .join(", ")}`; break; case ZodIssueCode.invalid_union: message = `Invalid input`; break; case ZodIssueCode.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${issue.options .map((val) => (typeof val === "string" ? `'${val}'` : val)) .join(" | ")}`; break; case ZodIssueCode.invalid_enum_value: message = `Invalid enum value. Expected ${issue.options .map((val) => (typeof val === "string" ? `'${val}'` : val)) .join(" | ")}`; break; case ZodIssueCode.invalid_arguments: message = `Invalid function arguments`; break; case ZodIssueCode.invalid_return_type: message = `Invalid function return type`; break; case ZodIssueCode.invalid_date: message = `Invalid date`; break; case ZodIssueCode.invalid_string: if (issue.validation !== "regex") message = `Invalid ${issue.validation}`; else message = "Invalid"; break; case ZodIssueCode.too_small: if (issue.type === "array") message = `Array must contain ${issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; else if (issue.type === "number") message = `Number must be greater than ${issue.inclusive ? `or equal to ` : ``}${issue.minimum}`; else message = "Invalid input"; break; case ZodIssueCode.too_big: if (issue.type === "array") message = `Array must contain ${issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; else if (issue.type === "number") message = `Number must be less than ${issue.inclusive ? `or equal to ` : ``}${issue.maximum}`; else message = "Invalid input"; break; case ZodIssueCode.custom: message = `Invalid input`; break; case ZodIssueCode.invalid_intersection_types: message = `Intersection results could not be merged`; break; case ZodIssueCode.not_multiple_of: message = `Number must be a multiple of ${issue.multipleOf}`; break; default: message = _ctx.defaultError; util.assertNever(issue); } return { message }; }; let overrideErrorMap = defaultErrorMap; const setErrorMap = (map) => { overrideErrorMap = map; }; const ZodParsedType = util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set", ]); const getParsedType = (data) => { const t = typeof data; switch (t) { case "undefined": return ZodParsedType.undefined; case "string": return ZodParsedType.string; case "number": return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; case "boolean": return ZodParsedType.boolean; case "function": return ZodParsedType.function; case "bigint": return ZodParsedType.bigint; case "object": if (Array.isArray(data)) { return ZodParsedType.array; } if (data === null) { return ZodParsedType.null; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { return ZodParsedType.map; } if (typeof Set !== "undefined" && data instanceof Set) { return ZodParsedType.set; } if (typeof Date !== "undefined" && data instanceof Date) { return ZodParsedType.date; } return ZodParsedType.object; default: return ZodParsedType.unknown; } }; const makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [...path, ...(issueData.path || [])]; const fullIssue = { ...issueData, path: fullPath, }; let errorMessage = ""; const maps = errorMaps .filter((m) => !!m) .slice() .reverse(); for (const map of maps) { errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, path: fullPath, message: issueData.message || errorMessage, }; }; const EMPTY_PATH = []; function addIssueToContext(ctx, issueData) { const issue = makeIssue({ issueData: issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, overrideErrorMap, defaultErrorMap, // then global default map ].filter((x) => !!x), }); ctx.common.issues.push(issue); } class ParseStatus { constructor() { this.value = "valid"; } dirty() { if (this.value === "valid") this.value = "dirty"; } abort() { if (this.value !== "aborted") this.value = "aborted"; } static mergeArray(status, results) { const arrayValue = []; for (const s of results) { if (s.status === "aborted") return INVALID$3; if (s.status === "dirty") status.dirty(); arrayValue.push(s.value); } return { status: status.value, value: arrayValue }; } static async mergeObjectAsync(status, pairs) { const syncPairs = []; for (const pair of pairs) { syncPairs.push({ key: await pair.key, value: await pair.value, }); } return ParseStatus.mergeObjectSync(status, syncPairs); } static mergeObjectSync(status, pairs) { const finalObject = {}; for (const pair of pairs) { const { key, value } = pair; if (key.status === "aborted") return INVALID$3; if (value.status === "aborted") return INVALID$3; if (key.status === "dirty") status.dirty(); if (value.status === "dirty") status.dirty(); if (typeof value.value !== "undefined" || pair.alwaysSet) { finalObject[key.value] = value.value; } } return { status: status.value, value: finalObject }; } } const INVALID$3 = Object.freeze({ status: "aborted", }); const DIRTY = (value) => ({ status: "dirty", value }); const OK = (value) => ({ status: "valid", value }); const isAborted = (x) => x.status === "aborted"; const isDirty = (x) => x.status === "dirty"; const isValid = (x) => x.status === "valid"; const isAsync = (x) => typeof Promise !== undefined && x instanceof Promise; var errorUtil; (function (errorUtil) { errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; })(errorUtil || (errorUtil = {})); class ParseInputLazyPath { constructor(parent, value, path, key) { this.parent = parent; this.data = value; this._path = path; this._key = key; } get path() { return this._path.concat(this._key); } } const handleResult = (ctx, result) => { if (isValid(result)) { return { success: true, data: result.value }; } else { if (!ctx.common.issues.length) { throw new Error("Validation failed but no issues detected."); } const error = new ZodError(ctx.common.issues); return { success: false, error }; } }; function processCreateParams(params) { if (!params) return {}; const { errorMap, invalid_type_error, required_error, description } = params; if (errorMap && (invalid_type_error || required_error)) { throw new Error(`Can't use "invalid" or "required" in conjunction with custom error map.`); } if (errorMap) return { errorMap: errorMap, description }; const customMap = (iss, ctx) => { if (iss.code !== "invalid_type") return { message: ctx.defaultError }; if (typeof ctx.data === "undefined" && required_error) return { message: required_error }; if (params.invalid_type_error) return { message: params.invalid_type_error }; return { message: ctx.defaultError }; }; return { errorMap: customMap, description }; } class ZodType { constructor(def) { /** Alias of safeParseAsync */ this.spa = this.safeParseAsync; this.superRefine = this._refinement; this._def = def; this.parse = this.parse.bind(this); this.safeParse = this.safeParse.bind(this); this.parseAsync = this.parseAsync.bind(this); this.safeParseAsync = this.safeParseAsync.bind(this); this.spa = this.spa.bind(this); this.refine = this.refine.bind(this); this.refinement = this.refinement.bind(this); this.superRefine = this.superRefine.bind(this); this.optional = this.optional.bind(this); this.nullable = this.nullable.bind(this); this.nullish = this.nullish.bind(this); this.array = this.array.bind(this); this.promise = this.promise.bind(this); this.or = this.or.bind(this); this.and = this.and.bind(this); this.transform = this.transform.bind(this); this.default = this.default.bind(this); this.describe = this.describe.bind(this); this.isNullable = this.isNullable.bind(this); this.isOptional = this.isOptional.bind(this); } get description() { return this._def.description; } _getType(input) { return getParsedType(input.data); } _getOrReturnCtx(input, ctx) { return (ctx || { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent, }); } _processInputParams(input) { return { status: new ParseStatus(), ctx: { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent, }, }; } _parseSync(input) { const result = this._parse(input); if (isAsync(result)) { throw new Error("Synchronous parse encountered promise."); } return result; } _parseAsync(input) { const result = this._parse(input); return Promise.resolve(result); } parse(data, params) { const result = this.safeParse(data, params); if (result.success) return result.data; throw result.error; } safeParse(data, params) { var _a; const ctx = { common: { issues: [], async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, }, path: (params === null || params === void 0 ? void 0 : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data), }; const result = this._parseSync({ data, path: ctx.path, parent: ctx }); return handleResult(ctx, result); } async parseAsync(data, params) { const result = await this.safeParseAsync(data, params); if (result.success) return result.data; throw result.error; } async safeParseAsync(data, params) { const ctx = { common: { issues: [], contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, async: true, }, path: (params === null || params === void 0 ? void 0 : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data), }; const maybeAsyncResult = this._parse({ data, path: [], parent: ctx }); const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); return handleResult(ctx, result); } refine(check, message) { const getIssueProperties = (val) => { if (typeof message === "string" || typeof message === "undefined") { return { message }; } else if (typeof message === "function") { return message(val); } else { return message; } }; return this._refinement((val, ctx) => { const result = check(val); const setError = () => ctx.addIssue({ code: ZodIssueCode.custom, ...getIssueProperties(val), }); if (typeof Promise !== "undefined" && result instanceof Promise) { return result.then((data) => { if (!data) { setError(); return false; } else { return true; } }); } if (!result) { setError(); return false; } else { return true; } }); } refinement(check, refinementData) { return this._refinement((val, ctx) => { if (!check(val)) { ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); return false; } else { return true; } }); } _refinement(refinement) { return new ZodEffects({ schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "refinement", refinement }, }); } optional() { return ZodOptional.create(this); } nullable() { return ZodNullable.create(this); } nullish() { return this.optional().nullable(); } array() { return ZodArray.create(this); } promise() { return ZodPromise.create(this); } or(option) { return ZodUnion.create([this, option]); } and(incoming) { return ZodIntersection.create(this, incoming); } transform(transform) { return new ZodEffects({ schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "transform", transform }, }); } default(def) { const defaultValueFunc = typeof def === "function" ? def : () => def; return new ZodDefault({ innerType: this, defaultValue: defaultValueFunc, typeName: ZodFirstPartyTypeKind.ZodDefault, }); } describe(description) { const This = this.constructor; return new This({ ...this._def, description, }); } isOptional() { return this.safeParse(undefined).success; } isNullable() { return this.safeParse(null).success; } } const cuidRegex = /^c[^\s-]{8,}$/i; const uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; // from https://stackoverflow.com/a/46181/1550155 // old version: too slow, didn't support unicode // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; // eslint-disable-next-line const emailRegex = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; class ZodString extends ZodType { constructor() { super(...arguments); this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), { validation, code: ZodIssueCode.invalid_string, ...errorUtil.errToObj(message), }); /** * Deprecated. * Use z.string().min(1) instead. */ this.nonempty = (message) => this.min(1, errorUtil.errToObj(message)); } _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.string) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.string, received: ctx.parsedType, } // ); return INVALID$3; } const status = new ParseStatus(); let ctx = undefined; for (const check of this._def.checks) { if (check.kind === "min") { if (input.data.length < check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, message: check.message, }); status.dirty(); } } else if (check.kind === "max") { if (input.data.length > check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, message: check.message, }); status.dirty(); } } else if (check.kind === "email") { if (!emailRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "email", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "uuid") { if (!uuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "uuid", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "cuid") { if (!cuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "url") { try { new URL(input.data); } catch (_a) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "url", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "regex") { check.regex.lastIndex = 0; const testResult = check.regex.test(input.data); if (!testResult) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "regex", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } } return { status: status.value, value: input.data }; } _addCheck(check) { return new ZodString({ ...this._def, checks: [...this._def.checks, check], }); } email(message) { return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); } url(message) { return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); } uuid(message) { return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); } cuid(message) { return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); } regex(regex, message) { return this._addCheck({ kind: "regex", regex: regex, ...errorUtil.errToObj(message), }); } min(minLength, message) { return this._addCheck({ kind: "min", value: minLength, ...errorUtil.errToObj(message), }); } max(maxLength, message) { return this._addCheck({ kind: "max", value: maxLength, ...errorUtil.errToObj(message), }); } length(len, message) { return this.min(len, message).max(len, message); } get isEmail() { return !!this._def.checks.find((ch) => ch.kind === "email"); } get isURL() { return !!this._def.checks.find((ch) => ch.kind === "url"); } get isUUID() { return !!this._def.checks.find((ch) => ch.kind === "uuid"); } get isCUID() { return !!this._def.checks.find((ch) => ch.kind === "cuid"); } get minLength() { let min = -Infinity; this._def.checks.map((ch) => { if (ch.kind === "min") { if (min === null || ch.value > min) { min = ch.value; } } }); return min; } get maxLength() { let max = null; this._def.checks.map((ch) => { if (ch.kind === "max") { if (max === null || ch.value < max) { max = ch.value; } } }); return max; } } ZodString.create = (params) => { return new ZodString({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, ...processCreateParams(params), }); }; // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 function floatSafeRemainder(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; const stepDecCount = (step.toString().split(".")[1] || "").length; const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); return (valInt % stepInt) / Math.pow(10, decCount); } class ZodNumber extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; this.step = this.multipleOf; } _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.number) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.number, received: ctx.parsedType, }); return INVALID$3; } let ctx = undefined; const status = new ParseStatus(); for (const check of this._def.checks) { if (check.kind === "int") { if (!util.isInteger(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: "integer", received: "float", message: check.message, }); status.dirty(); } } else if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "number", inclusive: check.inclusive, message: check.message, }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "number", inclusive: check.inclusive, message: check.message, }); status.dirty(); } } else if (check.kind === "multipleOf") { if (floatSafeRemainder(input.data, check.value) !== 0) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message, }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message), }, ], }); } _addCheck(check) { return new ZodNumber({ ...this._def, checks: [...this._def.checks, check], }); } int(message) { return this._addCheck({ kind: "int", message: errorUtil.toString(message), }); } positive(message) { return this._addCheck({ kind: "min", value: 0, inclusive: false, message: errorUtil.toString(message), }); } negative(message) { return this._addCheck({ kind: "max", value: 0, inclusive: false, message: errorUtil.toString(message), }); } nonpositive(message) { return this._addCheck({ kind: "max", value: 0, inclusive: true, message: errorUtil.toString(message), }); } nonnegative(message) { return this._addCheck({ kind: "min", value: 0, inclusive: true, message: errorUtil.toString(message), }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value: value, message: errorUtil.toString(message), }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } get isInt() { return !!this._def.checks.find((ch) => ch.kind === "int"); } } ZodNumber.create = (params) => { return new ZodNumber({ checks: [], typeName: ZodFirstPartyTypeKind.ZodNumber, ...processCreateParams(params), }); }; class ZodBigInt extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.bigint) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.bigint, received: ctx.parsedType, }); return INVALID$3; } return OK(input.data); } } ZodBigInt.create = (params) => { return new ZodBigInt({ typeName: ZodFirstPartyTypeKind.ZodBigInt, ...processCreateParams(params), }); }; class ZodBoolean extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.boolean) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.boolean, received: ctx.parsedType, }); return INVALID$3; } return OK(input.data); } } ZodBoolean.create = (params) => { return new ZodBoolean({ typeName: ZodFirstPartyTypeKind.ZodBoolean, ...processCreateParams(params), }); }; class ZodDate extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.date) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.date, received: ctx.parsedType, }); return INVALID$3; } if (isNaN(input.data.getTime())) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_date, }); return INVALID$3; } return { status: "valid", value: new Date(input.data.getTime()), }; } } ZodDate.create = (params) => { return new ZodDate({ typeName: ZodFirstPartyTypeKind.ZodDate, ...processCreateParams(params), }); }; class ZodUndefined extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.undefined, received: ctx.parsedType, }); return INVALID$3; } return OK(input.data); } } ZodUndefined.create = (params) => { return new ZodUndefined({ typeName: ZodFirstPartyTypeKind.ZodUndefined, ...processCreateParams(params), }); }; class ZodNull extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.null) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.null, received: ctx.parsedType, }); return INVALID$3; } return OK(input.data); } } ZodNull.create = (params) => { return new ZodNull({ typeName: ZodFirstPartyTypeKind.ZodNull, ...processCreateParams(params), }); }; class ZodAny extends ZodType { constructor() { super(...arguments); // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. this._any = true; } _parse(input) { return OK(input.data); } } ZodAny.create = (params) => { return new ZodAny({ typeName: ZodFirstPartyTypeKind.ZodAny, ...processCreateParams(params), }); }; class ZodUnknown extends ZodType { constructor() { super(...arguments); // required this._unknown = true; } _parse(input) { return OK(input.data); } } ZodUnknown.create = (params) => { return new ZodUnknown({ typeName: ZodFirstPartyTypeKind.ZodUnknown, ...processCreateParams(params), }); }; class ZodNever extends ZodType { _parse(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.never, received: ctx.parsedType, }); return INVALID$3; } } ZodNever.create = (params) => { return new ZodNever({ typeName: ZodFirstPartyTypeKind.ZodNever, ...processCreateParams(params), }); }; class ZodVoid extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.void, received: ctx.parsedType, }); return INVALID$3; } return OK(input.data); } } ZodVoid.create = (params) => { return new ZodVoid({ typeName: ZodFirstPartyTypeKind.ZodVoid, ...processCreateParams(params), }); }; class ZodArray extends ZodType { _parse(input) { const { ctx, status } = this._processInputParams(input); const def = this._def; if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType, }); return INVALID$3; } if (def.minLength !== null) { if (ctx.data.length < def.minLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minLength.value, type: "array", inclusive: true, message: def.minLength.message, }); status.dirty(); } } if (def.maxLength !== null) { if (ctx.data.length > def.maxLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxLength.value, type: "array", inclusive: true, message: def.maxLength.message, }); status.dirty(); } } if (ctx.common.async) { return Promise.all(ctx.data.map((item, i) => { return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); })).then((result) => { return ParseStatus.mergeArray(status, result); }); } const result = ctx.data.map((item, i) => { return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); }); return ParseStatus.mergeArray(status, result); } get element() { return this._def.type; } min(minLength, message) { return new ZodArray({ ...this._def, minLength: { value: minLength, message: errorUtil.toString(message) }, }); } max(maxLength, message) { return new ZodArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil.toString(message) }, }); } length(len, message) { return this.min(len, message).max(len, message); } nonempty(message) { return this.min(1, message); } } ZodArray.create = (schema, params) => { return new ZodArray({ type: schema, minLength: null, maxLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params), }); }; ///////////////////////////////////////// ///////////////////////////////////////// ////////// ////////// ////////// ZodObject ////////// ////////// ////////// ///////////////////////////////////////// ///////////////////////////////////////// var objectUtil; (function (objectUtil) { objectUtil.mergeShapes = (first, second) => { return { ...first, ...second, // second overwrites first }; }; })(objectUtil || (objectUtil = {})); const AugmentFactory = (def) => (augmentation) => { return new ZodObject({ ...def, shape: () => ({ ...def.shape(), ...augmentation, }), }); }; function deepPartialify(schema) { if (schema instanceof ZodObject) { const newShape = {}; for (const key in schema.shape) { const fieldSchema = schema.shape[key]; newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); } return new ZodObject({ ...schema._def, shape: () => newShape, }); } else if (schema instanceof ZodArray) { return ZodArray.create(deepPartialify(schema.element)); } else if (schema instanceof ZodOptional) { return ZodOptional.create(deepPartialify(schema.unwrap())); } else if (schema instanceof ZodNullable) { return ZodNullable.create(deepPartialify(schema.unwrap())); } else if (schema instanceof ZodTuple) { return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); } else { return schema; } } class ZodObject extends ZodType { constructor() { super(...arguments); this._cached = null; /** * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. * If you want to pass through unknown properties, use `.passthrough()` instead. */ this.nonstrict = this.passthrough; this.augment = AugmentFactory(this._def); this.extend = AugmentFactory(this._def); } _getCached() { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys = util.objectKeys(shape); return (this._cached = { shape, keys }); } _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.object) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType, }); return INVALID$3; } const { status, ctx } = this._processInputParams(input); const { shape, keys: shapeKeys } = this._getCached(); const extraKeys = []; for (const key in ctx.data) { if (!shapeKeys.includes(key)) { extraKeys.push(key); } } const pairs = []; for (const key of shapeKeys) { const keyValidator = shape[key]; const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data, }); } if (this._def.catchall instanceof ZodNever) { const unknownKeys = this._def.unknownKeys; if (unknownKeys === "passthrough") { for (const key of extraKeys) { pairs.push({ key: { status: "valid", value: key }, value: { status: "valid", value: ctx.data[key] }, }); } } else if (unknownKeys === "strict") { if (extraKeys.length > 0) { addIssueToContext(ctx, { code: ZodIssueCode.unrecognized_keys, keys: extraKeys, }); status.dirty(); } } else if (unknownKeys === "strip") ; else { throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } else { // run catchall validation const catchall = this._def.catchall; for (const key of extraKeys) { const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) ), alwaysSet: key in ctx.data, }); } } if (ctx.common.async) { return Promise.resolve() .then(async () => { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; syncPairs.push({ key, value: await pair.value, alwaysSet: pair.alwaysSet, }); } return syncPairs; }) .then((syncPairs) => { return ParseStatus.mergeObjectSync(status, syncPairs); }); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get shape() { return this._def.shape(); } strict(message) { errorUtil.errToObj; return new ZodObject({ ...this._def, unknownKeys: "strict", ...(message !== undefined ? { errorMap: (issue, ctx) => { var _a, _b, _c, _d; const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; if (issue.code === "unrecognized_keys") return { message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, }; return { message: defaultError, }; }, } : {}), }); } strip() { return new ZodObject({ ...this._def, unknownKeys: "strip", }); } passthrough() { return new ZodObject({ ...this._def, unknownKeys: "passthrough", }); } setKey(key, schema) { return this.augment({ [key]: schema }); } /** * Prior to zod@1.0.12 there was a bug in the * inferred type of merged objects. Please * upgrade if you are experiencing issues. */ merge(merging) { // const mergedShape = objectUtil.mergeShapes( // this._def.shape(), // merging._def.shape() // ); const merged = new ZodObject({ unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), typeName: ZodFirstPartyTypeKind.ZodObject, }); return merged; } catchall(index) { return new ZodObject({ ...this._def, catchall: index, }); } pick(mask) { const shape = {}; util.objectKeys(mask).map((key) => { shape[key] = this.shape[key]; }); return new ZodObject({ ...this._def, shape: () => shape, }); } omit(mask) { const shape = {}; util.objectKeys(this.shape).map((key) => { if (util.objectKeys(mask).indexOf(key) === -1) { shape[key] = this.shape[key]; } }); return new ZodObject({ ...this._def, shape: () => shape, }); } deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; if (mask) { util.objectKeys(this.shape).map((key) => { if (util.objectKeys(mask).indexOf(key) === -1) { newShape[key] = this.shape[key]; } else { newShape[key] = this.shape[key].optional(); } }); return new ZodObject({ ...this._def, shape: () => newShape, }); } else { for (const key in this.shape) { const fieldSchema = this.shape[key]; newShape[key] = fieldSchema.optional(); } } return new ZodObject({ ...this._def, shape: () => newShape, }); } required() { const newShape = {}; for (const key in this.shape) { const fieldSchema = this.shape[key]; let newField = fieldSchema; while (newField instanceof ZodOptional) { newField = newField._def.innerType; } newShape[key] = newField; } return new ZodObject({ ...this._def, shape: () => newShape, }); } } ZodObject.create = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; ZodObject.strictCreate = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strict", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; ZodObject.lazycreate = (shape, params) => { return new ZodObject({ shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; class ZodUnion extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const options = this._def.options; function handleResults(results) { // return first issue-free validation if it exists for (const result of results) { if (result.result.status === "valid") { return result.result; } } for (const result of results) { if (result.result.status === "dirty") { // add issues from dirty option ctx.common.issues.push(...result.ctx.common.issues); return result.result; } } // return invalid const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors, }); return INVALID$3; } if (ctx.common.async) { return Promise.all(options.map(async (option) => { const childCtx = { ...ctx, common: { ...ctx.common, issues: [], }, parent: null, }; return { result: await option._parseAsync({ data: ctx.data, path: ctx.path, parent: childCtx, }), ctx: childCtx, }; })).then(handleResults); } else { let dirty = undefined; const issues = []; for (const option of options) { const childCtx = { ...ctx, common: { ...ctx.common, issues: [], }, parent: null, }; const result = option._parseSync({ data: ctx.data, path: ctx.path, parent: childCtx, }); if (result.status === "valid") { return result; } else if (result.status === "dirty" && !dirty) { dirty = { result, ctx: childCtx }; } if (childCtx.common.issues.length) { issues.push(childCtx.common.issues); } } if (dirty) { ctx.common.issues.push(...dirty.ctx.common.issues); return dirty.result; } const unionErrors = issues.map((issues) => new ZodError(issues)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors, }); return INVALID$3; } } get options() { return this._def.options; } } ZodUnion.create = (types, params) => { return new ZodUnion({ options: types, typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(params), }); }; class ZodDiscriminatedUnion extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType, }); return INVALID$3; } const discriminator = this.discriminator; const discriminatorValue = ctx.data[discriminator]; const option = this.options.get(discriminatorValue); if (!option) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_union_discriminator, options: this.validDiscriminatorValues, path: [discriminator], }); return INVALID$3; } if (ctx.common.async) { return option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }); } else { return option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); } } get discriminator() { return this._def.discriminator; } get validDiscriminatorValues() { return Array.from(this.options.keys()); } get options() { return this._def.options; } /** * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must * have a different value for each object in the union. * @param discriminator the name of the discriminator property * @param types an array of object schemas * @param params */ static create(discriminator, types, params) { // Get all the valid discriminator values const options = new Map(); try { types.forEach((type) => { const discriminatorValue = type.shape[discriminator].value; options.set(discriminatorValue, type); }); } catch (e) { throw new Error("The discriminator value could not be extracted from all the provided schemas"); } // Assert that all the discriminator values are unique if (options.size !== types.length) { throw new Error("Some of the discriminator values are not unique"); } return new ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator, options, ...processCreateParams(params), }); } } function mergeValues(a, b) { const aType = getParsedType(a); const bType = getParsedType(b); if (a === b) { return { valid: true, data: a }; } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { const bKeys = util.objectKeys(b); const sharedKeys = util .objectKeys(a) .filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b }; for (const key of sharedKeys) { const sharedValue = mergeValues(a[key], b[key]); if (!sharedValue.valid) { return { valid: false }; } newObj[key] = sharedValue.data; } return { valid: true, data: newObj }; } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { if (a.length !== b.length) { return { valid: false }; } const newArray = []; for (let index = 0; index < a.length; index++) { const itemA = a[index]; const itemB = b[index]; const sharedValue = mergeValues(itemA, itemB); if (!sharedValue.valid) { return { valid: false }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { return { valid: true, data: a }; } else { return { valid: false }; } } class ZodIntersection extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); const handleParsed = (parsedLeft, parsedRight) => { if (isAborted(parsedLeft) || isAborted(parsedRight)) { return INVALID$3; } const merged = mergeValues(parsedLeft.value, parsedRight.value); if (!merged.valid) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types, }); return INVALID$3; } if (isDirty(parsedLeft) || isDirty(parsedRight)) { status.dirty(); } return { status: status.value, value: merged.data }; }; if (ctx.common.async) { return Promise.all([ this._def.left._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }), this._def.right._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }), ]).then(([left, right]) => handleParsed(left, right)); } else { return handleParsed(this._def.left._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }), this._def.right._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, })); } } } ZodIntersection.create = (left, right, params) => { return new ZodIntersection({ left: left, right: right, typeName: ZodFirstPartyTypeKind.ZodIntersection, ...processCreateParams(params), }); }; class ZodTuple extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType, }); return INVALID$3; } if (ctx.data.length < this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: this._def.items.length, inclusive: true, type: "array", }); return INVALID$3; } const rest = this._def.rest; if (!rest && ctx.data.length > this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: this._def.items.length, inclusive: true, type: "array", }); status.dirty(); } const items = ctx.data .map((item, itemIndex) => { const schema = this._def.items[itemIndex] || this._def.rest; if (!schema) return null; return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); }) .filter((x) => !!x); // filter nulls if (ctx.common.async) { return Promise.all(items).then((results) => { return ParseStatus.mergeArray(status, results); }); } else { return ParseStatus.mergeArray(status, items); } } get items() { return this._def.items; } rest(rest) { return new ZodTuple({ ...this._def, rest, }); } } ZodTuple.create = (schemas, params) => { return new ZodTuple({ items: schemas, typeName: ZodFirstPartyTypeKind.ZodTuple, rest: null, ...processCreateParams(params), }); }; class ZodRecord extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType, }); return INVALID$3; } const pairs = []; const keyType = this._def.keyType; const valueType = this._def.valueType; for (const key in ctx.data) { pairs.push({ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), }); } if (ctx.common.async) { return ParseStatus.mergeObjectAsync(status, pairs); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get element() { return this._def.valueType; } static create(first, second, third) { if (second instanceof ZodType) { return new ZodRecord({ keyType: first, valueType: second, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(third), }); } return new ZodRecord({ keyType: ZodString.create(), valueType: first, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(second), }); } } class ZodMap extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.map) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.map, received: ctx.parsedType, }); return INVALID$3; } const keyType = this._def.keyType; const valueType = this._def.valueType; const pairs = [...ctx.data.entries()].map(([key, value], index) => { return { key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), }; }); if (ctx.common.async) { const finalMap = new Map(); return Promise.resolve().then(async () => { for (const pair of pairs) { const key = await pair.key; const value = await pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID$3; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; }); } else { const finalMap = new Map(); for (const pair of pairs) { const key = pair.key; const value = pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID$3; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; } } } ZodMap.create = (keyType, valueType, params) => { return new ZodMap({ valueType, keyType, typeName: ZodFirstPartyTypeKind.ZodMap, ...processCreateParams(params), }); }; class ZodSet extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.set) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.set, received: ctx.parsedType, }); return INVALID$3; } const def = this._def; if (def.minSize !== null) { if (ctx.data.size < def.minSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minSize.value, type: "set", inclusive: true, message: def.minSize.message, }); status.dirty(); } } if (def.maxSize !== null) { if (ctx.data.size > def.maxSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxSize.value, type: "set", inclusive: true, message: def.maxSize.message, }); status.dirty(); } } const valueType = this._def.valueType; function finalizeSet(elements) { const parsedSet = new Set(); for (const element of elements) { if (element.status === "aborted") return INVALID$3; if (element.status === "dirty") status.dirty(); parsedSet.add(element.value); } return { status: status.value, value: parsedSet }; } const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); if (ctx.common.async) { return Promise.all(elements).then((elements) => finalizeSet(elements)); } else { return finalizeSet(elements); } } min(minSize, message) { return new ZodSet({ ...this._def, minSize: { value: minSize, message: errorUtil.toString(message) }, }); } max(maxSize, message) { return new ZodSet({ ...this._def, maxSize: { value: maxSize, message: errorUtil.toString(message) }, }); } size(size, message) { return this.min(size, message).max(size, message); } nonempty(message) { return this.min(1, message); } } ZodSet.create = (valueType, params) => { return new ZodSet({ valueType, minSize: null, maxSize: null, typeName: ZodFirstPartyTypeKind.ZodSet, ...processCreateParams(params), }); }; class ZodFunction extends ZodType { constructor() { super(...arguments); this.validate = this.implement; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.function) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.function, received: ctx.parsedType, }); return INVALID$3; } function makeArgsIssue(args, error) { return makeIssue({ data: args, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, overrideErrorMap, defaultErrorMap, ].filter((x) => !!x), issueData: { code: ZodIssueCode.invalid_arguments, argumentsError: error, }, }); } function makeReturnsIssue(returns, error) { return makeIssue({ data: returns, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, overrideErrorMap, defaultErrorMap, ].filter((x) => !!x), issueData: { code: ZodIssueCode.invalid_return_type, returnTypeError: error, }, }); } const params = { errorMap: ctx.common.contextualErrorMap }; const fn = ctx.data; if (this._def.returns instanceof ZodPromise) { return OK(async (...args) => { const error = new ZodError([]); const parsedArgs = await this._def.args .parseAsync(args, params) .catch((e) => { error.addIssue(makeArgsIssue(args, e)); throw error; }); const result = await fn(...parsedArgs); const parsedReturns = await this._def.returns._def.type .parseAsync(result, params) .catch((e) => { error.addIssue(makeReturnsIssue(result, e)); throw error; }); return parsedReturns; }); } else { return OK((...args) => { const parsedArgs = this._def.args.safeParse(args, params); if (!parsedArgs.success) { throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); } const result = fn(...parsedArgs.data); const parsedReturns = this._def.returns.safeParse(result, params); if (!parsedReturns.success) { throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); } return parsedReturns.data; }); } } parameters() { return this._def.args; } returnType() { return this._def.returns; } args(...items) { return new ZodFunction({ ...this._def, args: ZodTuple.create(items).rest(ZodUnknown.create()), }); } returns(returnType) { return new ZodFunction({ ...this._def, returns: returnType, }); } implement(func) { const validatedFunc = this.parse(func); return validatedFunc; } strictImplement(func) { const validatedFunc = this.parse(func); return validatedFunc; } } ZodFunction.create = (args, returns, params) => { return new ZodFunction({ args: (args ? args.rest(ZodUnknown.create()) : ZodTuple.create([]).rest(ZodUnknown.create())), returns: returns || ZodUnknown.create(), typeName: ZodFirstPartyTypeKind.ZodFunction, ...processCreateParams(params), }); }; class ZodLazy extends ZodType { get schema() { return this._def.getter(); } _parse(input) { const { ctx } = this._processInputParams(input); const lazySchema = this._def.getter(); return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } } ZodLazy.create = (getter, params) => { return new ZodLazy({ getter: getter, typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(params), }); }; class ZodLiteral extends ZodType { _parse(input) { if (input.data !== this._def.value) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_literal, expected: this._def.value, }); return INVALID$3; } return { status: "valid", value: input.data }; } get value() { return this._def.value; } } ZodLiteral.create = (value, params) => { return new ZodLiteral({ value: value, typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(params), }); }; function createZodEnum(values) { return new ZodEnum({ values: values, typeName: ZodFirstPartyTypeKind.ZodEnum, }); } class ZodEnum extends ZodType { _parse(input) { if (this._def.values.indexOf(input.data) === -1) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_enum_value, options: this._def.values, }); return INVALID$3; } return OK(input.data); } get options() { return this._def.values; } get enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Values() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } } ZodEnum.create = createZodEnum; class ZodNativeEnum extends ZodType { _parse(input) { const nativeEnumValues = util.getValidEnumValues(this._def.values); if (nativeEnumValues.indexOf(input.data) === -1) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_enum_value, options: util.objectValues(nativeEnumValues), }); return INVALID$3; } return OK(input.data); } get enum() { return this._def.values; } } ZodNativeEnum.create = (values, params) => { return new ZodNativeEnum({ values: values, typeName: ZodFirstPartyTypeKind.ZodNativeEnum, ...processCreateParams(params), }); }; class ZodPromise extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.promise, received: ctx.parsedType, }); return INVALID$3; } const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); return OK(promisified.then((data) => { return this._def.type.parseAsync(data, { path: ctx.path, errorMap: ctx.common.contextualErrorMap, }); })); } } ZodPromise.create = (schema, params) => { return new ZodPromise({ type: schema, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(params), }); }; class ZodEffects extends ZodType { innerType() { return this._def.schema; } _parse(input) { const { status, ctx } = this._processInputParams(input); const effect = this._def.effect || null; if (effect.type === "preprocess") { const processed = effect.transform(ctx.data); if (ctx.common.async) { return Promise.resolve(processed).then((processed) => { return this._def.schema._parseAsync({ data: processed, path: ctx.path, parent: ctx, }); }); } else { return this._def.schema._parseSync({ data: processed, path: ctx.path, parent: ctx, }); } } if (effect.type === "refinement") { const checkCtx = { addIssue: (arg) => { addIssueToContext(ctx, arg); if (arg.fatal) { status.abort(); } else { status.dirty(); } }, get path() { return ctx.path; }, }; checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); const executeRefinement = (acc // effect: RefinementEffect ) => { const result = effect.refinement(acc, checkCtx); if (ctx.common.async) { return Promise.resolve(result); } if (result instanceof Promise) { throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } return acc; }; if (ctx.common.async === false) { const inner = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); if (inner.status === "aborted") return INVALID$3; if (inner.status === "dirty") status.dirty(); // return value is ignored executeRefinement(inner.value); return { status: status.value, value: inner.value }; } else { return this._def.schema ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) .then((inner) => { if (inner.status === "aborted") return INVALID$3; if (inner.status === "dirty") status.dirty(); return executeRefinement(inner.value).then(() => { return { status: status.value, value: inner.value }; }); }); } } if (effect.type === "transform") { if (ctx.common.async === false) { const base = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); // if (base.status === "aborted") return INVALID; // if (base.status === "dirty") { // return { status: "dirty", value: base.value }; // } if (!isValid(base)) return base; const result = effect.transform(base.value); if (result instanceof Promise) { throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } return OK(result); } else { return this._def.schema ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) .then((base) => { if (!isValid(base)) return base; // if (base.status === "aborted") return INVALID; // if (base.status === "dirty") { // return { status: "dirty", value: base.value }; // } return Promise.resolve(effect.transform(base.value)).then(OK); }); } } util.assertNever(effect); } } ZodEffects.create = (schema, effect, params) => { return new ZodEffects({ schema, typeName: ZodFirstPartyTypeKind.ZodEffects, effect, ...processCreateParams(params), }); }; ZodEffects.createWithPreprocess = (preprocess, schema, params) => { return new ZodEffects({ schema, effect: { type: "preprocess", transform: preprocess }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(params), }); }; class ZodOptional extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.undefined) { return OK(undefined); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } } ZodOptional.create = (type, params) => { return new ZodOptional({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params), }); }; class ZodNullable extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.null) { return OK(null); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } } ZodNullable.create = (type, params) => { return new ZodNullable({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(params), }); }; class ZodDefault extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); let data = ctx.data; if (ctx.parsedType === ZodParsedType.undefined) { data = this._def.defaultValue(); } return this._def.innerType._parse({ data, path: ctx.path, parent: ctx, }); } removeDefault() { return this._def.innerType; } } ZodDefault.create = (type, params) => { return new ZodOptional({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params), }); }; class ZodNaN extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.nan) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.nan, received: ctx.parsedType, }); return INVALID$3; } return { status: "valid", value: input.data }; } } ZodNaN.create = (params) => { return new ZodNaN({ typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params), }); }; const custom = (check, params) => { if (check) return ZodAny.create().refine(check, params); return ZodAny.create(); }; const late = { object: ZodObject.lazycreate, }; var ZodFirstPartyTypeKind; (function (ZodFirstPartyTypeKind) { ZodFirstPartyTypeKind["ZodString"] = "ZodString"; ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); const instanceOfType = (cls, params = { message: `Input not instance of ${cls.name}`, }) => custom((data) => data instanceof cls, params); const stringType = ZodString.create; const numberType = ZodNumber.create; const nanType = ZodNaN.create; const bigIntType = ZodBigInt.create; const booleanType = ZodBoolean.create; const dateType = ZodDate.create; const undefinedType = ZodUndefined.create; const nullType = ZodNull.create; const anyType = ZodAny.create; const unknownType = ZodUnknown.create; const neverType = ZodNever.create; const voidType = ZodVoid.create; const arrayType = ZodArray.create; const objectType = ZodObject.create; const strictObjectType = ZodObject.strictCreate; const unionType = ZodUnion.create; const discriminatedUnionType = ZodDiscriminatedUnion.create; const intersectionType = ZodIntersection.create; const tupleType = ZodTuple.create; const recordType = ZodRecord.create; const mapType = ZodMap.create; const setType = ZodSet.create; const functionType = ZodFunction.create; const lazyType = ZodLazy.create; const literalType = ZodLiteral.create; const enumType = ZodEnum.create; const nativeEnumType = ZodNativeEnum.create; const promiseType = ZodPromise.create; const effectsType = ZodEffects.create; const optionalType = ZodOptional.create; const nullableType = ZodNullable.create; const preprocessType = ZodEffects.createWithPreprocess; const ostring = () => stringType().optional(); const onumber = () => numberType().optional(); const oboolean = () => booleanType().optional(); var mod = /*#__PURE__*/Object.freeze({ __proto__: null, ZodParsedType: ZodParsedType, getParsedType: getParsedType, makeIssue: makeIssue, EMPTY_PATH: EMPTY_PATH, addIssueToContext: addIssueToContext, ParseStatus: ParseStatus, INVALID: INVALID$3, DIRTY: DIRTY, OK: OK, isAborted: isAborted, isDirty: isDirty, isValid: isValid, isAsync: isAsync, ZodType: ZodType, ZodString: ZodString, ZodNumber: ZodNumber, ZodBigInt: ZodBigInt, ZodBoolean: ZodBoolean, ZodDate: ZodDate, ZodUndefined: ZodUndefined, ZodNull: ZodNull, ZodAny: ZodAny, ZodUnknown: ZodUnknown, ZodNever: ZodNever, ZodVoid: ZodVoid, ZodArray: ZodArray, get objectUtil () { return objectUtil; }, ZodObject: ZodObject, ZodUnion: ZodUnion, ZodDiscriminatedUnion: ZodDiscriminatedUnion, ZodIntersection: ZodIntersection, ZodTuple: ZodTuple, ZodRecord: ZodRecord, ZodMap: ZodMap, ZodSet: ZodSet, ZodFunction: ZodFunction, ZodLazy: ZodLazy, ZodLiteral: ZodLiteral, ZodEnum: ZodEnum, ZodNativeEnum: ZodNativeEnum, ZodPromise: ZodPromise, ZodEffects: ZodEffects, ZodTransformer: ZodEffects, ZodOptional: ZodOptional, ZodNullable: ZodNullable, ZodDefault: ZodDefault, ZodNaN: ZodNaN, custom: custom, Schema: ZodType, ZodSchema: ZodType, late: late, get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; }, any: anyType, array: arrayType, bigint: bigIntType, boolean: booleanType, date: dateType, discriminatedUnion: discriminatedUnionType, effect: effectsType, 'enum': enumType, 'function': functionType, 'instanceof': instanceOfType, intersection: intersectionType, lazy: lazyType, literal: literalType, map: mapType, nan: nanType, nativeEnum: nativeEnumType, never: neverType, 'null': nullType, nullable: nullableType, number: numberType, object: objectType, oboolean: oboolean, onumber: onumber, optional: optionalType, ostring: ostring, preprocess: preprocessType, promise: promiseType, record: recordType, set: setType, strictObject: strictObjectType, string: stringType, transformer: effectsType, tuple: tupleType, 'undefined': undefinedType, union: unionType, unknown: unknownType, 'void': voidType, ZodIssueCode: ZodIssueCode, quotelessJson: quotelessJson, ZodError: ZodError, defaultErrorMap: defaultErrorMap, get overrideErrorMap () { return overrideErrorMap; }, setErrorMap: setErrorMap }); mod.enum([ "application-error", "not-authorized", "not-logged-in", "not-found", "explicitly-disallowed", /** @deprecated */ "object-does-not-exist", "user-does-not-exist", "project-does-not-exist", "post-does-not-exist", "ask-does-not-exist", "listing-does-not-exist", "tag-does-not-exist", "object-is-already-in-state", "invalid-operation", "login-failed", "operation-failed", "illegal-handle", "handle-already-in-use", "email-already-in-use", "user-too-young", "illegal-content-type", "attachment-too-large", "incorrect-totp", "invalid-metadata", ]); class RequiresLoginError extends Error { constructor( message = "Requires login", redirectUrl ) { super(message);this.message = message;this.redirectUrl = redirectUrl; } } var luxon = {}; Object.defineProperty(luxon, '__esModule', { value: true }); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _objectWithoutPropertiesLoose$1(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _unsupportedIterableToArray$3(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$3(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$3(o, minLen); } function _arrayLikeToArray$3(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray$3(o)) || allowArrayLike) { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } // these aren't really private, but nor are they really useful to document /** * @private */ var LuxonError = /*#__PURE__*/function (_Error) { _inheritsLoose(LuxonError, _Error); function LuxonError() { return _Error.apply(this, arguments) || this; } return LuxonError; }( /*#__PURE__*/_wrapNativeSuper(Error)); /** * @private */ var InvalidDateTimeError = /*#__PURE__*/function (_LuxonError) { _inheritsLoose(InvalidDateTimeError, _LuxonError); function InvalidDateTimeError(reason) { return _LuxonError.call(this, "Invalid DateTime: " + reason.toMessage()) || this; } return InvalidDateTimeError; }(LuxonError); /** * @private */ var InvalidIntervalError = /*#__PURE__*/function (_LuxonError2) { _inheritsLoose(InvalidIntervalError, _LuxonError2); function InvalidIntervalError(reason) { return _LuxonError2.call(this, "Invalid Interval: " + reason.toMessage()) || this; } return InvalidIntervalError; }(LuxonError); /** * @private */ var InvalidDurationError = /*#__PURE__*/function (_LuxonError3) { _inheritsLoose(InvalidDurationError, _LuxonError3); function InvalidDurationError(reason) { return _LuxonError3.call(this, "Invalid Duration: " + reason.toMessage()) || this; } return InvalidDurationError; }(LuxonError); /** * @private */ var ConflictingSpecificationError = /*#__PURE__*/function (_LuxonError4) { _inheritsLoose(ConflictingSpecificationError, _LuxonError4); function ConflictingSpecificationError() { return _LuxonError4.apply(this, arguments) || this; } return ConflictingSpecificationError; }(LuxonError); /** * @private */ var InvalidUnitError = /*#__PURE__*/function (_LuxonError5) { _inheritsLoose(InvalidUnitError, _LuxonError5); function InvalidUnitError(unit) { return _LuxonError5.call(this, "Invalid unit " + unit) || this; } return InvalidUnitError; }(LuxonError); /** * @private */ var InvalidArgumentError = /*#__PURE__*/function (_LuxonError6) { _inheritsLoose(InvalidArgumentError, _LuxonError6); function InvalidArgumentError() { return _LuxonError6.apply(this, arguments) || this; } return InvalidArgumentError; }(LuxonError); /** * @private */ var ZoneIsAbstractError = /*#__PURE__*/function (_LuxonError7) { _inheritsLoose(ZoneIsAbstractError, _LuxonError7); function ZoneIsAbstractError() { return _LuxonError7.call(this, "Zone is an abstract class") || this; } return ZoneIsAbstractError; }(LuxonError); /** * @private */ var n$c = "numeric", s$f = "short", l$d = "long"; var DATE_SHORT = { year: n$c, month: n$c, day: n$c }; var DATE_MED = { year: n$c, month: s$f, day: n$c }; var DATE_MED_WITH_WEEKDAY = { year: n$c, month: s$f, day: n$c, weekday: s$f }; var DATE_FULL = { year: n$c, month: l$d, day: n$c }; var DATE_HUGE = { year: n$c, month: l$d, day: n$c, weekday: l$d }; var TIME_SIMPLE = { hour: n$c, minute: n$c }; var TIME_WITH_SECONDS = { hour: n$c, minute: n$c, second: n$c }; var TIME_WITH_SHORT_OFFSET = { hour: n$c, minute: n$c, second: n$c, timeZoneName: s$f }; var TIME_WITH_LONG_OFFSET = { hour: n$c, minute: n$c, second: n$c, timeZoneName: l$d }; var TIME_24_SIMPLE = { hour: n$c, minute: n$c, hourCycle: "h23" }; var TIME_24_WITH_SECONDS = { hour: n$c, minute: n$c, second: n$c, hourCycle: "h23" }; var TIME_24_WITH_SHORT_OFFSET = { hour: n$c, minute: n$c, second: n$c, hourCycle: "h23", timeZoneName: s$f }; var TIME_24_WITH_LONG_OFFSET = { hour: n$c, minute: n$c, second: n$c, hourCycle: "h23", timeZoneName: l$d }; var DATETIME_SHORT = { year: n$c, month: n$c, day: n$c, hour: n$c, minute: n$c }; var DATETIME_SHORT_WITH_SECONDS = { year: n$c, month: n$c, day: n$c, hour: n$c, minute: n$c, second: n$c }; var DATETIME_MED = { year: n$c, month: s$f, day: n$c, hour: n$c, minute: n$c }; var DATETIME_MED_WITH_SECONDS = { year: n$c, month: s$f, day: n$c, hour: n$c, minute: n$c, second: n$c }; var DATETIME_MED_WITH_WEEKDAY = { year: n$c, month: s$f, day: n$c, weekday: s$f, hour: n$c, minute: n$c }; var DATETIME_FULL = { year: n$c, month: l$d, day: n$c, hour: n$c, minute: n$c, timeZoneName: s$f }; var DATETIME_FULL_WITH_SECONDS = { year: n$c, month: l$d, day: n$c, hour: n$c, minute: n$c, second: n$c, timeZoneName: s$f }; var DATETIME_HUGE = { year: n$c, month: l$d, day: n$c, weekday: l$d, hour: n$c, minute: n$c, timeZoneName: l$d }; var DATETIME_HUGE_WITH_SECONDS = { year: n$c, month: l$d, day: n$c, weekday: l$d, hour: n$c, minute: n$c, second: n$c, timeZoneName: l$d }; /** * @private */ // TYPES function isUndefined$1(o) { return typeof o === "undefined"; } function isNumber(o) { return typeof o === "number"; } function isInteger(o) { return typeof o === "number" && o % 1 === 0; } function isString$2(o) { return typeof o === "string"; } function isDate(o) { return Object.prototype.toString.call(o) === "[object Date]"; } // CAPABILITIES function hasRelative() { try { return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat; } catch (e) { return false; } } // OBJECTS AND ARRAYS function maybeArray(thing) { return Array.isArray(thing) ? thing : [thing]; } function bestBy(arr, by, compare) { if (arr.length === 0) { return undefined; } return arr.reduce(function (best, next) { var pair = [by(next), next]; if (!best) { return pair; } else if (compare(best[0], pair[0]) === best[0]) { return best; } else { return pair; } }, null)[1]; } function pick(obj, keys) { return keys.reduce(function (a, k) { a[k] = obj[k]; return a; }, {}); } function hasOwnProperty$3(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } // NUMBERS AND STRINGS function integerBetween(thing, bottom, top) { return isInteger(thing) && thing >= bottom && thing <= top; } // x % n but takes the sign of n instead of x function floorMod(x, n) { return x - n * Math.floor(x / n); } function padStart(input, n) { if (n === void 0) { n = 2; } var minus = input < 0 ? "-" : ""; var target = minus ? input * -1 : input; var result; if (target.toString().length < n) { result = ("0".repeat(n) + target).slice(-n); } else { result = target.toString(); } return "" + minus + result; } function parseInteger(string) { if (isUndefined$1(string) || string === null || string === "") { return undefined; } else { return parseInt(string, 10); } } function parseMillis(fraction) { // Return undefined (instead of 0) in these cases, where fraction is not set if (isUndefined$1(fraction) || fraction === null || fraction === "") { return undefined; } else { var f = parseFloat("0." + fraction) * 1000; return Math.floor(f); } } function roundTo$1(number, digits, towardZero) { if (towardZero === void 0) { towardZero = false; } var factor = Math.pow(10, digits), rounder = towardZero ? Math.trunc : Math.round; return rounder(number * factor) / factor; } // DATE BASICS function isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function daysInMonth(year, month) { var modMonth = floorMod(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12; if (modMonth === 2) { return isLeapYear(modYear) ? 29 : 28; } else { return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1]; } } // covert a calendar object to a local timestamp (epoch, but with the offset baked in) function objToLocalTS(obj) { var d = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond); // for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that if (obj.year < 100 && obj.year >= 0) { d = new Date(d); d.setUTCFullYear(d.getUTCFullYear() - 1900); } return +d; } function weeksInWeekYear(weekYear) { var p1 = (weekYear + Math.floor(weekYear / 4) - Math.floor(weekYear / 100) + Math.floor(weekYear / 400)) % 7, last = weekYear - 1, p2 = (last + Math.floor(last / 4) - Math.floor(last / 100) + Math.floor(last / 400)) % 7; return p1 === 4 || p2 === 3 ? 53 : 52; } function untruncateYear(year) { if (year > 99) { return year; } else return year > 60 ? 1900 + year : 2000 + year; } // PARSING function parseZoneInfo(ts, offsetFormat, locale, timeZone) { if (timeZone === void 0) { timeZone = null; } var date = new Date(ts), intlOpts = { hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }; if (timeZone) { intlOpts.timeZone = timeZone; } var modified = _extends({ timeZoneName: offsetFormat }, intlOpts); var parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find(function (m) { return m.type.toLowerCase() === "timezonename"; }); return parsed ? parsed.value : null; } // signedOffset('-5', '30') -> -330 function signedOffset(offHourStr, offMinuteStr) { var offHour = parseInt(offHourStr, 10); // don't || this because we want to preserve -0 if (Number.isNaN(offHour)) { offHour = 0; } var offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin; return offHour * 60 + offMinSigned; } // COERCION function asNumber(value) { var numericValue = Number(value); if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue)) throw new InvalidArgumentError("Invalid unit value " + value); return numericValue; } function normalizeObject(obj, normalizer) { var normalized = {}; for (var u in obj) { if (hasOwnProperty$3(obj, u)) { var v = obj[u]; if (v === undefined || v === null) continue; normalized[normalizer(u)] = asNumber(v); } } return normalized; } function formatOffset(offset, format) { var hours = Math.trunc(Math.abs(offset / 60)), minutes = Math.trunc(Math.abs(offset % 60)), sign = offset >= 0 ? "+" : "-"; switch (format) { case "short": return "" + sign + padStart(hours, 2) + ":" + padStart(minutes, 2); case "narrow": return "" + sign + hours + (minutes > 0 ? ":" + minutes : ""); case "techie": return "" + sign + padStart(hours, 2) + padStart(minutes, 2); default: throw new RangeError("Value format " + format + " is out of range for property format"); } } function timeObject(obj) { return pick(obj, ["hour", "minute", "second", "millisecond"]); } var ianaRegex = /[A-Za-z_+-]{1,256}(:?\/[A-Za-z_+-]{1,256}(\/[A-Za-z_+-]{1,256})?)?/; /** * @private */ var monthsLong = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var monthsShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]; function months(length) { switch (length) { case "narrow": return [].concat(monthsNarrow); case "short": return [].concat(monthsShort); case "long": return [].concat(monthsLong); case "numeric": return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]; case "2-digit": return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; default: return null; } } var weekdaysLong = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; var weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"]; function weekdays(length) { switch (length) { case "narrow": return [].concat(weekdaysNarrow); case "short": return [].concat(weekdaysShort); case "long": return [].concat(weekdaysLong); case "numeric": return ["1", "2", "3", "4", "5", "6", "7"]; default: return null; } } var meridiems = ["AM", "PM"]; var erasLong = ["Before Christ", "Anno Domini"]; var erasShort = ["BC", "AD"]; var erasNarrow = ["B", "A"]; function eras(length) { switch (length) { case "narrow": return [].concat(erasNarrow); case "short": return [].concat(erasShort); case "long": return [].concat(erasLong); default: return null; } } function meridiemForDateTime(dt) { return meridiems[dt.hour < 12 ? 0 : 1]; } function weekdayForDateTime(dt, length) { return weekdays(length)[dt.weekday - 1]; } function monthForDateTime(dt, length) { return months(length)[dt.month - 1]; } function eraForDateTime(dt, length) { return eras(length)[dt.year < 0 ? 0 : 1]; } function formatRelativeTime(unit, count, numeric, narrow) { if (numeric === void 0) { numeric = "always"; } if (narrow === void 0) { narrow = false; } var units = { years: ["year", "yr."], quarters: ["quarter", "qtr."], months: ["month", "mo."], weeks: ["week", "wk."], days: ["day", "day", "days"], hours: ["hour", "hr."], minutes: ["minute", "min."], seconds: ["second", "sec."] }; var lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1; if (numeric === "auto" && lastable) { var isDay = unit === "days"; switch (count) { case 1: return isDay ? "tomorrow" : "next " + units[unit][0]; case -1: return isDay ? "yesterday" : "last " + units[unit][0]; case 0: return isDay ? "today" : "this " + units[unit][0]; } } var isInPast = Object.is(count, -0) || count < 0, fmtValue = Math.abs(count), singular = fmtValue === 1, lilUnits = units[unit], fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit; return isInPast ? fmtValue + " " + fmtUnit + " ago" : "in " + fmtValue + " " + fmtUnit; } function stringifyTokens(splits, tokenToString) { var s = ""; for (var _iterator = _createForOfIteratorHelperLoose(splits), _step; !(_step = _iterator()).done;) { var token = _step.value; if (token.literal) { s += token.val; } else { s += tokenToString(token.val); } } return s; } var _macroTokenToFormatOpts = { D: DATE_SHORT, DD: DATE_MED, DDD: DATE_FULL, DDDD: DATE_HUGE, t: TIME_SIMPLE, tt: TIME_WITH_SECONDS, ttt: TIME_WITH_SHORT_OFFSET, tttt: TIME_WITH_LONG_OFFSET, T: TIME_24_SIMPLE, TT: TIME_24_WITH_SECONDS, TTT: TIME_24_WITH_SHORT_OFFSET, TTTT: TIME_24_WITH_LONG_OFFSET, f: DATETIME_SHORT, ff: DATETIME_MED, fff: DATETIME_FULL, ffff: DATETIME_HUGE, F: DATETIME_SHORT_WITH_SECONDS, FF: DATETIME_MED_WITH_SECONDS, FFF: DATETIME_FULL_WITH_SECONDS, FFFF: DATETIME_HUGE_WITH_SECONDS }; /** * @private */ var Formatter$1 = /*#__PURE__*/function () { Formatter.create = function create(locale, opts) { if (opts === void 0) { opts = {}; } return new Formatter(locale, opts); }; Formatter.parseFormat = function parseFormat(fmt) { var current = null, currentFull = "", bracketed = false; var splits = []; for (var i = 0; i < fmt.length; i++) { var c = fmt.charAt(i); if (c === "'") { if (currentFull.length > 0) { splits.push({ literal: bracketed, val: currentFull }); } current = null; currentFull = ""; bracketed = !bracketed; } else if (bracketed) { currentFull += c; } else if (c === current) { currentFull += c; } else { if (currentFull.length > 0) { splits.push({ literal: false, val: currentFull }); } currentFull = c; current = c; } } if (currentFull.length > 0) { splits.push({ literal: bracketed, val: currentFull }); } return splits; }; Formatter.macroTokenToFormatOpts = function macroTokenToFormatOpts(token) { return _macroTokenToFormatOpts[token]; }; function Formatter(locale, formatOpts) { this.opts = formatOpts; this.loc = locale; this.systemLoc = null; } var _proto = Formatter.prototype; _proto.formatWithSystemDefault = function formatWithSystemDefault(dt, opts) { if (this.systemLoc === null) { this.systemLoc = this.loc.redefaultToSystem(); } var df = this.systemLoc.dtFormatter(dt, _extends({}, this.opts, opts)); return df.format(); }; _proto.formatDateTime = function formatDateTime(dt, opts) { if (opts === void 0) { opts = {}; } var df = this.loc.dtFormatter(dt, _extends({}, this.opts, opts)); return df.format(); }; _proto.formatDateTimeParts = function formatDateTimeParts(dt, opts) { if (opts === void 0) { opts = {}; } var df = this.loc.dtFormatter(dt, _extends({}, this.opts, opts)); return df.formatToParts(); }; _proto.resolvedOptions = function resolvedOptions(dt, opts) { if (opts === void 0) { opts = {}; } var df = this.loc.dtFormatter(dt, _extends({}, this.opts, opts)); return df.resolvedOptions(); }; _proto.num = function num(n, p) { if (p === void 0) { p = 0; } // we get some perf out of doing this here, annoyingly if (this.opts.forceSimple) { return padStart(n, p); } var opts = _extends({}, this.opts); if (p > 0) { opts.padTo = p; } return this.loc.numberFormatter(opts).format(n); }; _proto.formatDateTimeFromString = function formatDateTimeFromString(dt, fmt) { var _this = this; var knownEnglish = this.loc.listingMode() === "en", useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", string = function string(opts, extract) { return _this.loc.extract(dt, opts, extract); }, formatOffset = function formatOffset(opts) { if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) { return "Z"; } return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : ""; }, meridiem = function meridiem() { return knownEnglish ? meridiemForDateTime(dt) : string({ hour: "numeric", hourCycle: "h12" }, "dayperiod"); }, month = function month(length, standalone) { return knownEnglish ? monthForDateTime(dt, length) : string(standalone ? { month: length } : { month: length, day: "numeric" }, "month"); }, weekday = function weekday(length, standalone) { return knownEnglish ? weekdayForDateTime(dt, length) : string(standalone ? { weekday: length } : { weekday: length, month: "long", day: "numeric" }, "weekday"); }, maybeMacro = function maybeMacro(token) { var formatOpts = Formatter.macroTokenToFormatOpts(token); if (formatOpts) { return _this.formatWithSystemDefault(dt, formatOpts); } else { return token; } }, era = function era(length) { return knownEnglish ? eraForDateTime(dt, length) : string({ era: length }, "era"); }, tokenToString = function tokenToString(token) { // Where possible: http://cldr.unicode.org/translation/date-time-1/date-time#TOC-Standalone-vs.-Format-Styles switch (token) { // ms case "S": return _this.num(dt.millisecond); case "u": // falls through case "SSS": return _this.num(dt.millisecond, 3); // seconds case "s": return _this.num(dt.second); case "ss": return _this.num(dt.second, 2); // minutes case "m": return _this.num(dt.minute); case "mm": return _this.num(dt.minute, 2); // hours case "h": return _this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12); case "hh": return _this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2); case "H": return _this.num(dt.hour); case "HH": return _this.num(dt.hour, 2); // offset case "Z": // like +6 return formatOffset({ format: "narrow", allowZ: _this.opts.allowZ }); case "ZZ": // like +06:00 return formatOffset({ format: "short", allowZ: _this.opts.allowZ }); case "ZZZ": // like +0600 return formatOffset({ format: "techie", allowZ: _this.opts.allowZ }); case "ZZZZ": // like EST return dt.zone.offsetName(dt.ts, { format: "short", locale: _this.loc.locale }); case "ZZZZZ": // like Eastern Standard Time return dt.zone.offsetName(dt.ts, { format: "long", locale: _this.loc.locale }); // zone case "z": // like America/New_York return dt.zoneName; // meridiems case "a": return meridiem(); // dates case "d": return useDateTimeFormatter ? string({ day: "numeric" }, "day") : _this.num(dt.day); case "dd": return useDateTimeFormatter ? string({ day: "2-digit" }, "day") : _this.num(dt.day, 2); // weekdays - standalone case "c": // like 1 return _this.num(dt.weekday); case "ccc": // like 'Tues' return weekday("short", true); case "cccc": // like 'Tuesday' return weekday("long", true); case "ccccc": // like 'T' return weekday("narrow", true); // weekdays - format case "E": // like 1 return _this.num(dt.weekday); case "EEE": // like 'Tues' return weekday("short", false); case "EEEE": // like 'Tuesday' return weekday("long", false); case "EEEEE": // like 'T' return weekday("narrow", false); // months - standalone case "L": // like 1 return useDateTimeFormatter ? string({ month: "numeric", day: "numeric" }, "month") : _this.num(dt.month); case "LL": // like 01, doesn't seem to work return useDateTimeFormatter ? string({ month: "2-digit", day: "numeric" }, "month") : _this.num(dt.month, 2); case "LLL": // like Jan return month("short", true); case "LLLL": // like January return month("long", true); case "LLLLL": // like J return month("narrow", true); // months - format case "M": // like 1 return useDateTimeFormatter ? string({ month: "numeric" }, "month") : _this.num(dt.month); case "MM": // like 01 return useDateTimeFormatter ? string({ month: "2-digit" }, "month") : _this.num(dt.month, 2); case "MMM": // like Jan return month("short", false); case "MMMM": // like January return month("long", false); case "MMMMM": // like J return month("narrow", false); // years case "y": // like 2014 return useDateTimeFormatter ? string({ year: "numeric" }, "year") : _this.num(dt.year); case "yy": // like 14 return useDateTimeFormatter ? string({ year: "2-digit" }, "year") : _this.num(dt.year.toString().slice(-2), 2); case "yyyy": // like 0012 return useDateTimeFormatter ? string({ year: "numeric" }, "year") : _this.num(dt.year, 4); case "yyyyyy": // like 000012 return useDateTimeFormatter ? string({ year: "numeric" }, "year") : _this.num(dt.year, 6); // eras case "G": // like AD return era("short"); case "GG": // like Anno Domini return era("long"); case "GGGGG": return era("narrow"); case "kk": return _this.num(dt.weekYear.toString().slice(-2), 2); case "kkkk": return _this.num(dt.weekYear, 4); case "W": return _this.num(dt.weekNumber); case "WW": return _this.num(dt.weekNumber, 2); case "o": return _this.num(dt.ordinal); case "ooo": return _this.num(dt.ordinal, 3); case "q": // like 1 return _this.num(dt.quarter); case "qq": // like 01 return _this.num(dt.quarter, 2); case "X": return _this.num(Math.floor(dt.ts / 1000)); case "x": return _this.num(dt.ts); default: return maybeMacro(token); } }; return stringifyTokens(Formatter.parseFormat(fmt), tokenToString); }; _proto.formatDurationFromString = function formatDurationFromString(dur, fmt) { var _this2 = this; var tokenToField = function tokenToField(token) { switch (token[0]) { case "S": return "millisecond"; case "s": return "second"; case "m": return "minute"; case "h": return "hour"; case "d": return "day"; case "M": return "month"; case "y": return "year"; default: return null; } }, tokenToString = function tokenToString(lildur) { return function (token) { var mapped = tokenToField(token); if (mapped) { return _this2.num(lildur.get(mapped), token.length); } else { return token; } }; }, tokens = Formatter.parseFormat(fmt), realTokens = tokens.reduce(function (found, _ref) { var literal = _ref.literal, val = _ref.val; return literal ? found : found.concat(val); }, []), collapsed = dur.shiftTo.apply(dur, realTokens.map(tokenToField).filter(function (t) { return t; })); return stringifyTokens(tokens, tokenToString(collapsed)); }; return Formatter; }(); var Invalid = /*#__PURE__*/function () { function Invalid(reason, explanation) { this.reason = reason; this.explanation = explanation; } var _proto = Invalid.prototype; _proto.toMessage = function toMessage() { if (this.explanation) { return this.reason + ": " + this.explanation; } else { return this.reason; } }; return Invalid; }(); /** * @interface */ var Zone = /*#__PURE__*/function () { function Zone() {} var _proto = Zone.prototype; /** * Returns the offset's common name (such as EST) at the specified timestamp * @abstract * @param {number} ts - Epoch milliseconds for which to get the name * @param {Object} opts - Options to affect the format * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'. * @param {string} opts.locale - What locale to return the offset name in. * @return {string} */ _proto.offsetName = function offsetName(ts, opts) { throw new ZoneIsAbstractError(); } /** * Returns the offset's value as a string * @abstract * @param {number} ts - Epoch milliseconds for which to get the offset * @param {string} format - What style of offset to return. * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively * @return {string} */ ; _proto.formatOffset = function formatOffset(ts, format) { throw new ZoneIsAbstractError(); } /** * Return the offset in minutes for this zone at the specified timestamp. * @abstract * @param {number} ts - Epoch milliseconds for which to compute the offset * @return {number} */ ; _proto.offset = function offset(ts) { throw new ZoneIsAbstractError(); } /** * Return whether this Zone is equal to another zone * @abstract * @param {Zone} otherZone - the zone to compare * @return {boolean} */ ; _proto.equals = function equals(otherZone) { throw new ZoneIsAbstractError(); } /** * Return whether this Zone is valid. * @abstract * @type {boolean} */ ; _createClass(Zone, [{ key: "type", get: /** * The type of zone * @abstract * @type {string} */ function get() { throw new ZoneIsAbstractError(); } /** * The name of this zone. * @abstract * @type {string} */ }, { key: "name", get: function get() { throw new ZoneIsAbstractError(); } /** * Returns whether the offset is known to be fixed for the whole year. * @abstract * @type {boolean} */ }, { key: "isUniversal", get: function get() { throw new ZoneIsAbstractError(); } }, { key: "isValid", get: function get() { throw new ZoneIsAbstractError(); } }]); return Zone; }(); var singleton$1 = null; /** * Represents the local zone for this JavaScript environment. * @implements {Zone} */ var SystemZone = /*#__PURE__*/function (_Zone) { _inheritsLoose(SystemZone, _Zone); function SystemZone() { return _Zone.apply(this, arguments) || this; } var _proto = SystemZone.prototype; /** @override **/ _proto.offsetName = function offsetName(ts, _ref) { var format = _ref.format, locale = _ref.locale; return parseZoneInfo(ts, format, locale); } /** @override **/ ; _proto.formatOffset = function formatOffset$1(ts, format) { return formatOffset(this.offset(ts), format); } /** @override **/ ; _proto.offset = function offset(ts) { return -new Date(ts).getTimezoneOffset(); } /** @override **/ ; _proto.equals = function equals(otherZone) { return otherZone.type === "system"; } /** @override **/ ; _createClass(SystemZone, [{ key: "type", get: /** @override **/ function get() { return "system"; } /** @override **/ }, { key: "name", get: function get() { return new Intl.DateTimeFormat().resolvedOptions().timeZone; } /** @override **/ }, { key: "isUniversal", get: function get() { return false; } }, { key: "isValid", get: function get() { return true; } }], [{ key: "instance", get: /** * Get a singleton instance of the local zone * @return {SystemZone} */ function get() { if (singleton$1 === null) { singleton$1 = new SystemZone(); } return singleton$1; } }]); return SystemZone; }(Zone); var matchingRegex = RegExp("^" + ianaRegex.source + "$"); var dtfCache = {}; function makeDTF(zone) { if (!dtfCache[zone]) { dtfCache[zone] = new Intl.DateTimeFormat("en-US", { hourCycle: "h23", timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" }); } return dtfCache[zone]; } var typeToPos = { year: 0, month: 1, day: 2, hour: 3, minute: 4, second: 5 }; function hackyOffset(dtf, date) { var formatted = dtf.format(date).replace(/\u200E/g, ""), parsed = /(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(formatted), fMonth = parsed[1], fDay = parsed[2], fYear = parsed[3], fHour = parsed[4], fMinute = parsed[5], fSecond = parsed[6]; return [fYear, fMonth, fDay, fHour, fMinute, fSecond]; } function partsOffset(dtf, date) { var formatted = dtf.formatToParts(date), filled = []; for (var i = 0; i < formatted.length; i++) { var _formatted$i = formatted[i], type = _formatted$i.type, value = _formatted$i.value, pos = typeToPos[type]; if (!isUndefined$1(pos)) { filled[pos] = parseInt(value, 10); } } return filled; } var ianaZoneCache = {}; /** * A zone identified by an IANA identifier, like America/New_York * @implements {Zone} */ var IANAZone = /*#__PURE__*/function (_Zone) { _inheritsLoose(IANAZone, _Zone); /** * @param {string} name - Zone name * @return {IANAZone} */ IANAZone.create = function create(name) { if (!ianaZoneCache[name]) { ianaZoneCache[name] = new IANAZone(name); } return ianaZoneCache[name]; } /** * Reset local caches. Should only be necessary in testing scenarios. * @return {void} */ ; IANAZone.resetCache = function resetCache() { ianaZoneCache = {}; dtfCache = {}; } /** * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that. * @param {string} s - The string to check validity on * @example IANAZone.isValidSpecifier("America/New_York") //=> true * @example IANAZone.isValidSpecifier("Fantasia/Castle") //=> true * @example IANAZone.isValidSpecifier("Sport~~blorp") //=> false * @return {boolean} */ ; IANAZone.isValidSpecifier = function isValidSpecifier(s) { return !!(s && s.match(matchingRegex)); } /** * Returns whether the provided string identifies a real zone * @param {string} zone - The string to check * @example IANAZone.isValidZone("America/New_York") //=> true * @example IANAZone.isValidZone("Fantasia/Castle") //=> false * @example IANAZone.isValidZone("Sport~~blorp") //=> false * @return {boolean} */ ; IANAZone.isValidZone = function isValidZone(zone) { try { new Intl.DateTimeFormat("en-US", { timeZone: zone }).format(); return true; } catch (e) { return false; } } // Etc/GMT+8 -> -480 /** @ignore */ ; IANAZone.parseGMTOffset = function parseGMTOffset(specifier) { if (specifier) { var match = specifier.match(/^Etc\/GMT(0|[+-]\d{1,2})$/i); if (match) { return -60 * parseInt(match[1]); } } return null; }; function IANAZone(name) { var _this; _this = _Zone.call(this) || this; /** @private **/ _this.zoneName = name; /** @private **/ _this.valid = IANAZone.isValidZone(name); return _this; } /** @override **/ var _proto = IANAZone.prototype; /** @override **/ _proto.offsetName = function offsetName(ts, _ref) { var format = _ref.format, locale = _ref.locale; return parseZoneInfo(ts, format, locale, this.name); } /** @override **/ ; _proto.formatOffset = function formatOffset$1(ts, format) { return formatOffset(this.offset(ts), format); } /** @override **/ ; _proto.offset = function offset(ts) { var date = new Date(ts); if (isNaN(date)) return NaN; var dtf = makeDTF(this.name), _ref2 = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date), year = _ref2[0], month = _ref2[1], day = _ref2[2], hour = _ref2[3], minute = _ref2[4], second = _ref2[5]; var asUTC = objToLocalTS({ year: year, month: month, day: day, hour: hour, minute: minute, second: second, millisecond: 0 }); var asTS = +date; var over = asTS % 1000; asTS -= over >= 0 ? over : 1000 + over; return (asUTC - asTS) / (60 * 1000); } /** @override **/ ; _proto.equals = function equals(otherZone) { return otherZone.type === "iana" && otherZone.name === this.name; } /** @override **/ ; _createClass(IANAZone, [{ key: "type", get: function get() { return "iana"; } /** @override **/ }, { key: "name", get: function get() { return this.zoneName; } /** @override **/ }, { key: "isUniversal", get: function get() { return false; } }, { key: "isValid", get: function get() { return this.valid; } }]); return IANAZone; }(Zone); var singleton = null; /** * A zone with a fixed offset (meaning no DST) * @implements {Zone} */ var FixedOffsetZone = /*#__PURE__*/function (_Zone) { _inheritsLoose(FixedOffsetZone, _Zone); /** * Get an instance with a specified offset * @param {number} offset - The offset in minutes * @return {FixedOffsetZone} */ FixedOffsetZone.instance = function instance(offset) { return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset); } /** * Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6" * @param {string} s - The offset string to parse * @example FixedOffsetZone.parseSpecifier("UTC+6") * @example FixedOffsetZone.parseSpecifier("UTC+06") * @example FixedOffsetZone.parseSpecifier("UTC-6:00") * @return {FixedOffsetZone} */ ; FixedOffsetZone.parseSpecifier = function parseSpecifier(s) { if (s) { var r = s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i); if (r) { return new FixedOffsetZone(signedOffset(r[1], r[2])); } } return null; }; function FixedOffsetZone(offset) { var _this; _this = _Zone.call(this) || this; /** @private **/ _this.fixed = offset; return _this; } /** @override **/ var _proto = FixedOffsetZone.prototype; /** @override **/ _proto.offsetName = function offsetName() { return this.name; } /** @override **/ ; _proto.formatOffset = function formatOffset$1(ts, format) { return formatOffset(this.fixed, format); } /** @override **/ ; /** @override **/ _proto.offset = function offset() { return this.fixed; } /** @override **/ ; _proto.equals = function equals(otherZone) { return otherZone.type === "fixed" && otherZone.fixed === this.fixed; } /** @override **/ ; _createClass(FixedOffsetZone, [{ key: "type", get: function get() { return "fixed"; } /** @override **/ }, { key: "name", get: function get() { return this.fixed === 0 ? "UTC" : "UTC" + formatOffset(this.fixed, "narrow"); } }, { key: "isUniversal", get: function get() { return true; } }, { key: "isValid", get: function get() { return true; } }], [{ key: "utcInstance", get: /** * Get a singleton instance of UTC * @return {FixedOffsetZone} */ function get() { if (singleton === null) { singleton = new FixedOffsetZone(0); } return singleton; } }]); return FixedOffsetZone; }(Zone); /** * A zone that failed to parse. You should never need to instantiate this. * @implements {Zone} */ var InvalidZone = /*#__PURE__*/function (_Zone) { _inheritsLoose(InvalidZone, _Zone); function InvalidZone(zoneName) { var _this; _this = _Zone.call(this) || this; /** @private */ _this.zoneName = zoneName; return _this; } /** @override **/ var _proto = InvalidZone.prototype; /** @override **/ _proto.offsetName = function offsetName() { return null; } /** @override **/ ; _proto.formatOffset = function formatOffset() { return ""; } /** @override **/ ; _proto.offset = function offset() { return NaN; } /** @override **/ ; _proto.equals = function equals() { return false; } /** @override **/ ; _createClass(InvalidZone, [{ key: "type", get: function get() { return "invalid"; } /** @override **/ }, { key: "name", get: function get() { return this.zoneName; } /** @override **/ }, { key: "isUniversal", get: function get() { return false; } }, { key: "isValid", get: function get() { return false; } }]); return InvalidZone; }(Zone); /** * @private */ function normalizeZone(input, defaultZone) { var offset; if (isUndefined$1(input) || input === null) { return defaultZone; } else if (input instanceof Zone) { return input; } else if (isString$2(input)) { var lowered = input.toLowerCase(); if (lowered === "local" || lowered === "system") return defaultZone;else if (lowered === "utc" || lowered === "gmt") return FixedOffsetZone.utcInstance;else if ((offset = IANAZone.parseGMTOffset(input)) != null) { // handle Etc/GMT-4, which V8 chokes on return FixedOffsetZone.instance(offset); } else if (IANAZone.isValidSpecifier(lowered)) return IANAZone.create(input);else return FixedOffsetZone.parseSpecifier(lowered) || new InvalidZone(input); } else if (isNumber(input)) { return FixedOffsetZone.instance(input); } else if (typeof input === "object" && input.offset && typeof input.offset === "number") { // This is dumb, but the instanceof check above doesn't seem to really work // so we're duck checking it return input; } else { return new InvalidZone(input); } } var now$1 = function now() { return Date.now(); }, defaultZone = "system", defaultLocale = null, defaultNumberingSystem = null, defaultOutputCalendar = null, throwOnInvalid; /** * Settings contains static getters and setters that control Luxon's overall behavior. Luxon is a simple library with few options, but the ones it does have live here. */ var Settings = /*#__PURE__*/function () { function Settings() {} /** * Reset Luxon's global caches. Should only be necessary in testing scenarios. * @return {void} */ Settings.resetCaches = function resetCaches() { Locale.resetCache(); IANAZone.resetCache(); }; _createClass(Settings, null, [{ key: "now", get: /** * Get the callback for returning the current timestamp. * @type {function} */ function get() { return now$1; } /** * Set the callback for returning the current timestamp. * The function should return a number, which will be interpreted as an Epoch millisecond count * @type {function} * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time */ , set: function set(n) { now$1 = n; } /** * Set the default time zone to create DateTimes in. Does not affect existing instances. * Use the value "system" to reset this value to the system's time zone. * @type {string} */ }, { key: "defaultZone", get: /** * Get the default time zone object currently used to create DateTimes. Does not affect existing instances. * The default value is the system's time zone (the one set on the machine that runs this code). * @type {Zone} */ function get() { return normalizeZone(defaultZone, SystemZone.instance); } /** * Get the default locale to create DateTimes with. Does not affect existing instances. * @type {string} */ , set: function set(zone) { defaultZone = zone; } }, { key: "defaultLocale", get: function get() { return defaultLocale; } /** * Set the default locale to create DateTimes with. Does not affect existing instances. * @type {string} */ , set: function set(locale) { defaultLocale = locale; } /** * Get the default numbering system to create DateTimes with. Does not affect existing instances. * @type {string} */ }, { key: "defaultNumberingSystem", get: function get() { return defaultNumberingSystem; } /** * Set the default numbering system to create DateTimes with. Does not affect existing instances. * @type {string} */ , set: function set(numberingSystem) { defaultNumberingSystem = numberingSystem; } /** * Get the default output calendar to create DateTimes with. Does not affect existing instances. * @type {string} */ }, { key: "defaultOutputCalendar", get: function get() { return defaultOutputCalendar; } /** * Set the default output calendar to create DateTimes with. Does not affect existing instances. * @type {string} */ , set: function set(outputCalendar) { defaultOutputCalendar = outputCalendar; } /** * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals * @type {boolean} */ }, { key: "throwOnInvalid", get: function get() { return throwOnInvalid; } /** * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals * @type {boolean} */ , set: function set(t) { throwOnInvalid = t; } }]); return Settings; }(); var _excluded$2 = ["base"]; var intlDTCache = {}; function getCachedDTF(locString, opts) { if (opts === void 0) { opts = {}; } var key = JSON.stringify([locString, opts]); var dtf = intlDTCache[key]; if (!dtf) { dtf = new Intl.DateTimeFormat(locString, opts); intlDTCache[key] = dtf; } return dtf; } var intlNumCache = {}; function getCachedINF(locString, opts) { if (opts === void 0) { opts = {}; } var key = JSON.stringify([locString, opts]); var inf = intlNumCache[key]; if (!inf) { inf = new Intl.NumberFormat(locString, opts); intlNumCache[key] = inf; } return inf; } var intlRelCache = {}; function getCachedRTF(locString, opts) { if (opts === void 0) { opts = {}; } var _opts = opts; _opts.base; var cacheKeyOpts = _objectWithoutPropertiesLoose$1(_opts, _excluded$2); // exclude `base` from the options var key = JSON.stringify([locString, cacheKeyOpts]); var inf = intlRelCache[key]; if (!inf) { inf = new Intl.RelativeTimeFormat(locString, opts); intlRelCache[key] = inf; } return inf; } var sysLocaleCache = null; function systemLocale() { if (sysLocaleCache) { return sysLocaleCache; } else { sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale; return sysLocaleCache; } } function parseLocaleString(localeStr) { // I really want to avoid writing a BCP 47 parser // see, e.g. https://github.com/wooorm/bcp-47 // Instead, we'll do this: // a) if the string has no -u extensions, just leave it alone // b) if it does, use Intl to resolve everything // c) if Intl fails, try again without the -u var uIndex = localeStr.indexOf("-u-"); if (uIndex === -1) { return [localeStr]; } else { var options; var smaller = localeStr.substring(0, uIndex); try { options = getCachedDTF(localeStr).resolvedOptions(); } catch (e) { options = getCachedDTF(smaller).resolvedOptions(); } var _options = options, numberingSystem = _options.numberingSystem, calendar = _options.calendar; // return the smaller one so that we can append the calendar and numbering overrides to it return [smaller, numberingSystem, calendar]; } } function intlConfigString(localeStr, numberingSystem, outputCalendar) { if (outputCalendar || numberingSystem) { localeStr += "-u"; if (outputCalendar) { localeStr += "-ca-" + outputCalendar; } if (numberingSystem) { localeStr += "-nu-" + numberingSystem; } return localeStr; } else { return localeStr; } } function mapMonths(f) { var ms = []; for (var i = 1; i <= 12; i++) { var dt = DateTime.utc(2016, i, 1); ms.push(f(dt)); } return ms; } function mapWeekdays(f) { var ms = []; for (var i = 1; i <= 7; i++) { var dt = DateTime.utc(2016, 11, 13 + i); ms.push(f(dt)); } return ms; } function listStuff(loc, length, defaultOK, englishFn, intlFn) { var mode = loc.listingMode(defaultOK); if (mode === "error") { return null; } else if (mode === "en") { return englishFn(length); } else { return intlFn(length); } } function supportsFastNumbers(loc) { if (loc.numberingSystem && loc.numberingSystem !== "latn") { return false; } else { return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === "latn"; } } /** * @private */ var PolyNumberFormatter = /*#__PURE__*/function () { function PolyNumberFormatter(intl, forceSimple, opts) { this.padTo = opts.padTo || 0; this.floor = opts.floor || false; if (!forceSimple) { var intlOpts = { useGrouping: false }; if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo; this.inf = getCachedINF(intl, intlOpts); } } var _proto = PolyNumberFormatter.prototype; _proto.format = function format(i) { if (this.inf) { var fixed = this.floor ? Math.floor(i) : i; return this.inf.format(fixed); } else { // to match the browser's numberformatter defaults var _fixed = this.floor ? Math.floor(i) : roundTo$1(i, 3); return padStart(_fixed, this.padTo); } }; return PolyNumberFormatter; }(); /** * @private */ var PolyDateFormatter = /*#__PURE__*/function () { function PolyDateFormatter(dt, intl, opts) { this.opts = opts; var z; if (dt.zone.isUniversal) { // UTC-8 or Etc/UTC-8 are not part of tzdata, only Etc/GMT+8 and the like. // That is why fixed-offset TZ is set to that unless it is: // 1. Representing offset 0 when UTC is used to maintain previous behavior and does not become GMT. // 2. Unsupported by the browser: // - some do not support Etc/ // - < Etc/GMT-14, > Etc/GMT+12, and 30-minute or 45-minute offsets are not part of tzdata var gmtOffset = -1 * (dt.offset / 60); var offsetZ = gmtOffset >= 0 ? "Etc/GMT+" + gmtOffset : "Etc/GMT" + gmtOffset; var isOffsetZoneSupported = IANAZone.isValidZone(offsetZ); if (dt.offset !== 0 && isOffsetZoneSupported) { z = offsetZ; this.dt = dt; } else { // Not all fixed-offset zones like Etc/+4:30 are present in tzdata. // So we have to make do. Two cases: // 1. The format options tell us to show the zone. We can't do that, so the best // we can do is format the date in UTC. // 2. The format options don't tell us to show the zone. Then we can adjust them // the time and tell the formatter to show it to us in UTC, so that the time is right // and the bad zone doesn't show up. z = "UTC"; if (opts.timeZoneName) { this.dt = dt; } else { this.dt = dt.offset === 0 ? dt : DateTime.fromMillis(dt.ts + dt.offset * 60 * 1000); } } } else if (dt.zone.type === "system") { this.dt = dt; } else { this.dt = dt; z = dt.zone.name; } var intlOpts = _extends({}, this.opts); if (z) { intlOpts.timeZone = z; } this.dtf = getCachedDTF(intl, intlOpts); } var _proto2 = PolyDateFormatter.prototype; _proto2.format = function format() { return this.dtf.format(this.dt.toJSDate()); }; _proto2.formatToParts = function formatToParts() { return this.dtf.formatToParts(this.dt.toJSDate()); }; _proto2.resolvedOptions = function resolvedOptions() { return this.dtf.resolvedOptions(); }; return PolyDateFormatter; }(); /** * @private */ var PolyRelFormatter = /*#__PURE__*/function () { function PolyRelFormatter(intl, isEnglish, opts) { this.opts = _extends({ style: "long" }, opts); if (!isEnglish && hasRelative()) { this.rtf = getCachedRTF(intl, opts); } } var _proto3 = PolyRelFormatter.prototype; _proto3.format = function format(count, unit) { if (this.rtf) { return this.rtf.format(count, unit); } else { return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long"); } }; _proto3.formatToParts = function formatToParts(count, unit) { if (this.rtf) { return this.rtf.formatToParts(count, unit); } else { return []; } }; return PolyRelFormatter; }(); /** * @private */ var Locale = /*#__PURE__*/function () { Locale.fromOpts = function fromOpts(opts) { return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN); }; Locale.create = function create(locale, numberingSystem, outputCalendar, defaultToEN) { if (defaultToEN === void 0) { defaultToEN = false; } var specifiedLocale = locale || Settings.defaultLocale; // the system locale is useful for human readable strings but annoying for parsing/formatting known formats var localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale()); var numberingSystemR = numberingSystem || Settings.defaultNumberingSystem; var outputCalendarR = outputCalendar || Settings.defaultOutputCalendar; return new Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale); }; Locale.resetCache = function resetCache() { sysLocaleCache = null; intlDTCache = {}; intlNumCache = {}; intlRelCache = {}; }; Locale.fromObject = function fromObject(_temp) { var _ref = _temp === void 0 ? {} : _temp, locale = _ref.locale, numberingSystem = _ref.numberingSystem, outputCalendar = _ref.outputCalendar; return Locale.create(locale, numberingSystem, outputCalendar); }; function Locale(locale, numbering, outputCalendar, specifiedLocale) { var _parseLocaleString = parseLocaleString(locale), parsedLocale = _parseLocaleString[0], parsedNumberingSystem = _parseLocaleString[1], parsedOutputCalendar = _parseLocaleString[2]; this.locale = parsedLocale; this.numberingSystem = numbering || parsedNumberingSystem || null; this.outputCalendar = outputCalendar || parsedOutputCalendar || null; this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar); this.weekdaysCache = { format: {}, standalone: {} }; this.monthsCache = { format: {}, standalone: {} }; this.meridiemCache = null; this.eraCache = {}; this.specifiedLocale = specifiedLocale; this.fastNumbersCached = null; } var _proto4 = Locale.prototype; _proto4.listingMode = function listingMode(defaultOK) { var isActuallyEn = this.isEnglish(); var hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory"); return isActuallyEn && hasNoWeirdness ? "en" : "intl"; }; _proto4.clone = function clone(alts) { if (!alts || Object.getOwnPropertyNames(alts).length === 0) { return this; } else { return Locale.create(alts.locale || this.specifiedLocale, alts.numberingSystem || this.numberingSystem, alts.outputCalendar || this.outputCalendar, alts.defaultToEN || false); } }; _proto4.redefaultToEN = function redefaultToEN(alts) { if (alts === void 0) { alts = {}; } return this.clone(_extends({}, alts, { defaultToEN: true })); }; _proto4.redefaultToSystem = function redefaultToSystem(alts) { if (alts === void 0) { alts = {}; } return this.clone(_extends({}, alts, { defaultToEN: false })); }; _proto4.months = function months$1(length, format, defaultOK) { var _this = this; if (format === void 0) { format = false; } if (defaultOK === void 0) { defaultOK = true; } return listStuff(this, length, defaultOK, months, function () { var intl = format ? { month: length, day: "numeric" } : { month: length }, formatStr = format ? "format" : "standalone"; if (!_this.monthsCache[formatStr][length]) { _this.monthsCache[formatStr][length] = mapMonths(function (dt) { return _this.extract(dt, intl, "month"); }); } return _this.monthsCache[formatStr][length]; }); }; _proto4.weekdays = function weekdays$1(length, format, defaultOK) { var _this2 = this; if (format === void 0) { format = false; } if (defaultOK === void 0) { defaultOK = true; } return listStuff(this, length, defaultOK, weekdays, function () { var intl = format ? { weekday: length, year: "numeric", month: "long", day: "numeric" } : { weekday: length }, formatStr = format ? "format" : "standalone"; if (!_this2.weekdaysCache[formatStr][length]) { _this2.weekdaysCache[formatStr][length] = mapWeekdays(function (dt) { return _this2.extract(dt, intl, "weekday"); }); } return _this2.weekdaysCache[formatStr][length]; }); }; _proto4.meridiems = function meridiems$1(defaultOK) { var _this3 = this; if (defaultOK === void 0) { defaultOK = true; } return listStuff(this, undefined, defaultOK, function () { return meridiems; }, function () { // In theory there could be aribitrary day periods. We're gonna assume there are exactly two // for AM and PM. This is probably wrong, but it's makes parsing way easier. if (!_this3.meridiemCache) { var intl = { hour: "numeric", hourCycle: "h12" }; _this3.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(function (dt) { return _this3.extract(dt, intl, "dayperiod"); }); } return _this3.meridiemCache; }); }; _proto4.eras = function eras$1(length, defaultOK) { var _this4 = this; if (defaultOK === void 0) { defaultOK = true; } return listStuff(this, length, defaultOK, eras, function () { var intl = { era: length }; // This is problematic. Different calendars are going to define eras totally differently. What I need is the minimum set of dates // to definitely enumerate them. if (!_this4.eraCache[length]) { _this4.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map(function (dt) { return _this4.extract(dt, intl, "era"); }); } return _this4.eraCache[length]; }); }; _proto4.extract = function extract(dt, intlOpts, field) { var df = this.dtFormatter(dt, intlOpts), results = df.formatToParts(), matching = results.find(function (m) { return m.type.toLowerCase() === field; }); return matching ? matching.value : null; }; _proto4.numberFormatter = function numberFormatter(opts) { if (opts === void 0) { opts = {}; } // this forcesimple option is never used (the only caller short-circuits on it, but it seems safer to leave) // (in contrast, the rest of the condition is used heavily) return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts); }; _proto4.dtFormatter = function dtFormatter(dt, intlOpts) { if (intlOpts === void 0) { intlOpts = {}; } return new PolyDateFormatter(dt, this.intl, intlOpts); }; _proto4.relFormatter = function relFormatter(opts) { if (opts === void 0) { opts = {}; } return new PolyRelFormatter(this.intl, this.isEnglish(), opts); }; _proto4.isEnglish = function isEnglish() { return this.locale === "en" || this.locale.toLowerCase() === "en-us" || new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us"); }; _proto4.equals = function equals(other) { return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar; }; _createClass(Locale, [{ key: "fastNumbers", get: function get() { if (this.fastNumbersCached == null) { this.fastNumbersCached = supportsFastNumbers(this); } return this.fastNumbersCached; } }]); return Locale; }(); /* * This file handles parsing for well-specified formats. Here's how it works: * Two things go into parsing: a regex to match with and an extractor to take apart the groups in the match. * An extractor is just a function that takes a regex match array and returns a { year: ..., month: ... } object * parse() does the work of executing the regex and applying the extractor. It takes multiple regex/extractor pairs to try in sequence. * Extractors can take a "cursor" representing the offset in the match to look at. This makes it easy to combine extractors. * combineExtractors() does the work of combining them, keeping track of the cursor through multiple extractions. * Some extractions are super dumb and simpleParse and fromStrings help DRY them. */ function combineRegexes() { for (var _len = arguments.length, regexes = new Array(_len), _key = 0; _key < _len; _key++) { regexes[_key] = arguments[_key]; } var full = regexes.reduce(function (f, r) { return f + r.source; }, ""); return RegExp("^" + full + "$"); } function combineExtractors() { for (var _len2 = arguments.length, extractors = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { extractors[_key2] = arguments[_key2]; } return function (m) { return extractors.reduce(function (_ref, ex) { var mergedVals = _ref[0], mergedZone = _ref[1], cursor = _ref[2]; var _ex = ex(m, cursor), val = _ex[0], zone = _ex[1], next = _ex[2]; return [_extends({}, mergedVals, val), mergedZone || zone, next]; }, [{}, null, 1]).slice(0, 2); }; } function parse$6(s) { if (s == null) { return [null, null]; } for (var _len3 = arguments.length, patterns = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { patterns[_key3 - 1] = arguments[_key3]; } for (var _i = 0, _patterns = patterns; _i < _patterns.length; _i++) { var _patterns$_i = _patterns[_i], regex = _patterns$_i[0], extractor = _patterns$_i[1]; var m = regex.exec(s); if (m) { return extractor(m); } } return [null, null]; } function simpleParse() { for (var _len4 = arguments.length, keys = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { keys[_key4] = arguments[_key4]; } return function (match, cursor) { var ret = {}; var i; for (i = 0; i < keys.length; i++) { ret[keys[i]] = parseInteger(match[cursor + i]); } return [ret, null, cursor + i]; }; } // ISO and SQL parsing var offsetRegex = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/, isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/, isoTimeRegex = RegExp("" + isoTimeBaseRegex.source + offsetRegex.source + "?"), isoTimeExtensionRegex = RegExp("(?:T" + isoTimeRegex.source + ")?"), isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/, isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/, isoOrdinalRegex = /(\d{4})-?(\d{3})/, extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay"), extractISOOrdinalData = simpleParse("year", "ordinal"), sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/, // dumbed-down version of the ISO one sqlTimeRegex = RegExp(isoTimeBaseRegex.source + " ?(?:" + offsetRegex.source + "|(" + ianaRegex.source + "))?"), sqlTimeExtensionRegex = RegExp("(?: " + sqlTimeRegex.source + ")?"); function int(match, pos, fallback) { var m = match[pos]; return isUndefined$1(m) ? fallback : parseInteger(m); } function extractISOYmd(match, cursor) { var item = { year: int(match, cursor), month: int(match, cursor + 1, 1), day: int(match, cursor + 2, 1) }; return [item, null, cursor + 3]; } function extractISOTime(match, cursor) { var item = { hours: int(match, cursor, 0), minutes: int(match, cursor + 1, 0), seconds: int(match, cursor + 2, 0), milliseconds: parseMillis(match[cursor + 3]) }; return [item, null, cursor + 4]; } function extractISOOffset(match, cursor) { var local = !match[cursor] && !match[cursor + 1], fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]), zone = local ? null : FixedOffsetZone.instance(fullOffset); return [{}, zone, cursor + 3]; } function extractIANAZone(match, cursor) { var zone = match[cursor] ? IANAZone.create(match[cursor]) : null; return [{}, zone, cursor + 1]; } // ISO time parsing var isoTimeOnly = RegExp("^T?" + isoTimeBaseRegex.source + "$"); // ISO duration parsing var isoDuration = /^-?P(?:(?:(-?\d{1,9})Y)?(?:(-?\d{1,9})M)?(?:(-?\d{1,9})W)?(?:(-?\d{1,9})D)?(?:T(?:(-?\d{1,9})H)?(?:(-?\d{1,9})M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,9}))?S)?)?)$/; function extractISODuration(match) { var s = match[0], yearStr = match[1], monthStr = match[2], weekStr = match[3], dayStr = match[4], hourStr = match[5], minuteStr = match[6], secondStr = match[7], millisecondsStr = match[8]; var hasNegativePrefix = s[0] === "-"; var negativeSeconds = secondStr && secondStr[0] === "-"; var maybeNegate = function maybeNegate(num, force) { if (force === void 0) { force = false; } return num !== undefined && (force || num && hasNegativePrefix) ? -num : num; }; return [{ years: maybeNegate(parseInteger(yearStr)), months: maybeNegate(parseInteger(monthStr)), weeks: maybeNegate(parseInteger(weekStr)), days: maybeNegate(parseInteger(dayStr)), hours: maybeNegate(parseInteger(hourStr)), minutes: maybeNegate(parseInteger(minuteStr)), seconds: maybeNegate(parseInteger(secondStr), secondStr === "-0"), milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds) }]; } // These are a little braindead. EDT *should* tell us that we're in, say, America/New_York // and not just that we're in -240 *right now*. But since I don't think these are used that often // I'm just going to ignore that var obsOffsets = { GMT: 0, EDT: -4 * 60, EST: -5 * 60, CDT: -5 * 60, CST: -6 * 60, MDT: -6 * 60, MST: -7 * 60, PDT: -7 * 60, PST: -8 * 60 }; function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { var result = { year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr), month: monthsShort.indexOf(monthStr) + 1, day: parseInteger(dayStr), hour: parseInteger(hourStr), minute: parseInteger(minuteStr) }; if (secondStr) result.second = parseInteger(secondStr); if (weekdayStr) { result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1; } return result; } // RFC 2822/5322 var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/; function extractRFC2822(match) { var weekdayStr = match[1], dayStr = match[2], monthStr = match[3], yearStr = match[4], hourStr = match[5], minuteStr = match[6], secondStr = match[7], obsOffset = match[8], milOffset = match[9], offHourStr = match[10], offMinuteStr = match[11], result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); var offset; if (obsOffset) { offset = obsOffsets[obsOffset]; } else if (milOffset) { offset = 0; } else { offset = signedOffset(offHourStr, offMinuteStr); } return [result, new FixedOffsetZone(offset)]; } function preprocessRFC2822(s) { // Remove comments and folding whitespace and replace multiple-spaces with a single space return s.replace(/\([^)]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim(); } // http date var rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/, rfc850 = /^(Monday|Tuesday|Wedsday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/, ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/; function extractRFC1123Or850(match) { var weekdayStr = match[1], dayStr = match[2], monthStr = match[3], yearStr = match[4], hourStr = match[5], minuteStr = match[6], secondStr = match[7], result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); return [result, FixedOffsetZone.utcInstance]; } function extractASCII(match) { var weekdayStr = match[1], monthStr = match[2], dayStr = match[3], hourStr = match[4], minuteStr = match[5], secondStr = match[6], yearStr = match[7], result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); return [result, FixedOffsetZone.utcInstance]; } var isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex); var isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex); var isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex); var isoTimeCombinedRegex = combineRegexes(isoTimeRegex); var extractISOYmdTimeAndOffset = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset); var extractISOWeekTimeAndOffset = combineExtractors(extractISOWeekData, extractISOTime, extractISOOffset); var extractISOOrdinalDateAndTime = combineExtractors(extractISOOrdinalData, extractISOTime, extractISOOffset); var extractISOTimeAndOffset = combineExtractors(extractISOTime, extractISOOffset); /** * @private */ function parseISODate(s) { return parse$6(s, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset]); } function parseRFC2822Date(s) { return parse$6(preprocessRFC2822(s), [rfc2822, extractRFC2822]); } function parseHTTPDate(s) { return parse$6(s, [rfc1123, extractRFC1123Or850], [rfc850, extractRFC1123Or850], [ascii, extractASCII]); } function parseISODuration(s) { return parse$6(s, [isoDuration, extractISODuration]); } var extractISOTimeOnly = combineExtractors(extractISOTime); function parseISOTimeOnly(s) { return parse$6(s, [isoTimeOnly, extractISOTimeOnly]); } var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex); var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex); var extractISOYmdTimeOffsetAndIANAZone = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset, extractIANAZone); var extractISOTimeOffsetAndIANAZone = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone); function parseSQL(s) { return parse$6(s, [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeOffsetAndIANAZone], [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]); } var INVALID$2 = "Invalid Duration"; // unit conversion constants var lowOrderMatrix = { weeks: { days: 7, hours: 7 * 24, minutes: 7 * 24 * 60, seconds: 7 * 24 * 60 * 60, milliseconds: 7 * 24 * 60 * 60 * 1000 }, days: { hours: 24, minutes: 24 * 60, seconds: 24 * 60 * 60, milliseconds: 24 * 60 * 60 * 1000 }, hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1000 }, minutes: { seconds: 60, milliseconds: 60 * 1000 }, seconds: { milliseconds: 1000 } }, casualMatrix = _extends({ years: { quarters: 4, months: 12, weeks: 52, days: 365, hours: 365 * 24, minutes: 365 * 24 * 60, seconds: 365 * 24 * 60 * 60, milliseconds: 365 * 24 * 60 * 60 * 1000 }, quarters: { months: 3, weeks: 13, days: 91, hours: 91 * 24, minutes: 91 * 24 * 60, seconds: 91 * 24 * 60 * 60, milliseconds: 91 * 24 * 60 * 60 * 1000 }, months: { weeks: 4, days: 30, hours: 30 * 24, minutes: 30 * 24 * 60, seconds: 30 * 24 * 60 * 60, milliseconds: 30 * 24 * 60 * 60 * 1000 } }, lowOrderMatrix), daysInYearAccurate = 146097.0 / 400, daysInMonthAccurate = 146097.0 / 4800, accurateMatrix = _extends({ years: { quarters: 4, months: 12, weeks: daysInYearAccurate / 7, days: daysInYearAccurate, hours: daysInYearAccurate * 24, minutes: daysInYearAccurate * 24 * 60, seconds: daysInYearAccurate * 24 * 60 * 60, milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000 }, quarters: { months: 3, weeks: daysInYearAccurate / 28, days: daysInYearAccurate / 4, hours: daysInYearAccurate * 24 / 4, minutes: daysInYearAccurate * 24 * 60 / 4, seconds: daysInYearAccurate * 24 * 60 * 60 / 4, milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000 / 4 }, months: { weeks: daysInMonthAccurate / 7, days: daysInMonthAccurate, hours: daysInMonthAccurate * 24, minutes: daysInMonthAccurate * 24 * 60, seconds: daysInMonthAccurate * 24 * 60 * 60, milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000 } }, lowOrderMatrix); // units ordered by size var orderedUnits$1 = ["years", "quarters", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"]; var reverseUnits = orderedUnits$1.slice(0).reverse(); // clone really means "create another instance just like this one, but with these changes" function clone$1(dur, alts, clear) { if (clear === void 0) { clear = false; } // deep merge for vals var conf = { values: clear ? alts.values : _extends({}, dur.values, alts.values || {}), loc: dur.loc.clone(alts.loc), conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy }; return new Duration(conf); } function antiTrunc(n) { return n < 0 ? Math.floor(n) : Math.ceil(n); } // NB: mutates parameters function convert$9(matrix, fromMap, fromUnit, toMap, toUnit) { var conv = matrix[toUnit][fromUnit], raw = fromMap[fromUnit] / conv, sameSign = Math.sign(raw) === Math.sign(toMap[toUnit]), // ok, so this is wild, but see the matrix in the tests added = !sameSign && toMap[toUnit] !== 0 && Math.abs(raw) <= 1 ? antiTrunc(raw) : Math.trunc(raw); toMap[toUnit] += added; fromMap[fromUnit] -= added * conv; } // NB: mutates parameters function normalizeValues(matrix, vals) { reverseUnits.reduce(function (previous, current) { if (!isUndefined$1(vals[current])) { if (previous) { convert$9(matrix, vals, previous, vals, current); } return current; } else { return previous; } }, null); } /** * A Duration object represents a period of time, like "2 months" or "1 day, 1 hour". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime.plus} to add a Duration object to a DateTime, producing another DateTime. * * Here is a brief overview of commonly used methods and getters in Duration: * * * **Creation** To create a Duration, use {@link Duration.fromMillis}, {@link Duration.fromObject}, or {@link Duration.fromISO}. * * **Unit values** See the {@link Duration#years}, {@link Duration.months}, {@link Duration#weeks}, {@link Duration#days}, {@link Duration#hours}, {@link Duration#minutes}, {@link Duration#seconds}, {@link Duration#milliseconds} accessors. * * **Configuration** See {@link Duration#locale} and {@link Duration#numberingSystem} accessors. * * **Transformation** To create new Durations out of old ones use {@link Duration#plus}, {@link Duration#minus}, {@link Duration#normalize}, {@link Duration#set}, {@link Duration#reconfigure}, {@link Duration#shiftTo}, and {@link Duration#negate}. * * **Output** To convert the Duration into other representations, see {@link Duration#as}, {@link Duration#toISO}, {@link Duration#toFormat}, and {@link Duration#toJSON} * * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation. */ var Duration = /*#__PURE__*/function () { /** * @private */ function Duration(config) { var accurate = config.conversionAccuracy === "longterm" || false; /** * @access private */ this.values = config.values; /** * @access private */ this.loc = config.loc || Locale.create(); /** * @access private */ this.conversionAccuracy = accurate ? "longterm" : "casual"; /** * @access private */ this.invalid = config.invalid || null; /** * @access private */ this.matrix = accurate ? accurateMatrix : casualMatrix; /** * @access private */ this.isLuxonDuration = true; } /** * Create Duration from a number of milliseconds. * @param {number} count of milliseconds * @param {Object} opts - options for parsing * @param {string} [opts.locale='en-US'] - the locale to use * @param {string} opts.numberingSystem - the numbering system to use * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @return {Duration} */ Duration.fromMillis = function fromMillis(count, opts) { return Duration.fromObject({ milliseconds: count }, opts); } /** * Create a Duration from a JavaScript object with keys like 'years' and 'hours'. * If this object is empty then a zero milliseconds duration is returned. * @param {Object} obj - the object to create the DateTime from * @param {number} obj.years * @param {number} obj.quarters * @param {number} obj.months * @param {number} obj.weeks * @param {number} obj.days * @param {number} obj.hours * @param {number} obj.minutes * @param {number} obj.seconds * @param {number} obj.milliseconds * @param {Object} [opts=[]] - options for creating this Duration * @param {string} [opts.locale='en-US'] - the locale to use * @param {string} opts.numberingSystem - the numbering system to use * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @return {Duration} */ ; Duration.fromObject = function fromObject(obj, opts) { if (opts === void 0) { opts = {}; } if (obj == null || typeof obj !== "object") { throw new InvalidArgumentError("Duration.fromObject: argument expected to be an object, got " + (obj === null ? "null" : typeof obj)); } return new Duration({ values: normalizeObject(obj, Duration.normalizeUnit), loc: Locale.fromObject(opts), conversionAccuracy: opts.conversionAccuracy }); } /** * Create a Duration from an ISO 8601 duration string. * @param {string} text - text to parse * @param {Object} opts - options for parsing * @param {string} [opts.locale='en-US'] - the locale to use * @param {string} opts.numberingSystem - the numbering system to use * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @see https://en.wikipedia.org/wiki/ISO_8601#Durations * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 } * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 } * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 } * @return {Duration} */ ; Duration.fromISO = function fromISO(text, opts) { var _parseISODuration = parseISODuration(text), parsed = _parseISODuration[0]; if (parsed) { return Duration.fromObject(parsed, opts); } else { return Duration.invalid("unparsable", "the input \"" + text + "\" can't be parsed as ISO 8601"); } } /** * Create a Duration from an ISO 8601 time string. * @param {string} text - text to parse * @param {Object} opts - options for parsing * @param {string} [opts.locale='en-US'] - the locale to use * @param {string} opts.numberingSystem - the numbering system to use * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @see https://en.wikipedia.org/wiki/ISO_8601#Times * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 } * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } * @return {Duration} */ ; Duration.fromISOTime = function fromISOTime(text, opts) { var _parseISOTimeOnly = parseISOTimeOnly(text), parsed = _parseISOTimeOnly[0]; if (parsed) { return Duration.fromObject(parsed, opts); } else { return Duration.invalid("unparsable", "the input \"" + text + "\" can't be parsed as ISO 8601"); } } /** * Create an invalid Duration. * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information * @return {Duration} */ ; Duration.invalid = function invalid(reason, explanation) { if (explanation === void 0) { explanation = null; } if (!reason) { throw new InvalidArgumentError("need to specify a reason the Duration is invalid"); } var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); if (Settings.throwOnInvalid) { throw new InvalidDurationError(invalid); } else { return new Duration({ invalid: invalid }); } } /** * @private */ ; Duration.normalizeUnit = function normalizeUnit(unit) { var normalized = { year: "years", years: "years", quarter: "quarters", quarters: "quarters", month: "months", months: "months", week: "weeks", weeks: "weeks", day: "days", days: "days", hour: "hours", hours: "hours", minute: "minutes", minutes: "minutes", second: "seconds", seconds: "seconds", millisecond: "milliseconds", milliseconds: "milliseconds" }[unit ? unit.toLowerCase() : unit]; if (!normalized) throw new InvalidUnitError(unit); return normalized; } /** * Check if an object is a Duration. Works across context boundaries * @param {object} o * @return {boolean} */ ; Duration.isDuration = function isDuration(o) { return o && o.isLuxonDuration || false; } /** * Get the locale of a Duration, such 'en-GB' * @type {string} */ ; var _proto = Duration.prototype; /** * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens: * * `S` for milliseconds * * `s` for seconds * * `m` for minutes * * `h` for hours * * `d` for days * * `M` for months * * `y` for years * Notes: * * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits * * The duration will be converted to the set of units in the format string using {@link Duration.shiftTo} and the Durations's conversion accuracy setting. * @param {string} fmt - the format string * @param {Object} opts - options * @param {boolean} [opts.floor=true] - floor numerical values * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2" * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002" * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000" * @return {string} */ _proto.toFormat = function toFormat(fmt, opts) { if (opts === void 0) { opts = {}; } // reverse-compat since 1.2; we always round down now, never up, and we do it by default var fmtOpts = _extends({}, opts, { floor: opts.round !== false && opts.floor !== false }); return this.isValid ? Formatter$1.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID$2; } /** * Returns a JavaScript object with this Duration's values. * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 } * @return {Object} */ ; _proto.toObject = function toObject() { if (!this.isValid) return {}; return _extends({}, this.values); } /** * Returns an ISO 8601-compliant string representation of this Duration. * @see https://en.wikipedia.org/wiki/ISO_8601#Durations * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S' * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S' * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M' * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M' * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S' * @return {string} */ ; _proto.toISO = function toISO() { // we could use the formatter, but this is an easier way to get the minimum string if (!this.isValid) return null; var s = "P"; if (this.years !== 0) s += this.years + "Y"; if (this.months !== 0 || this.quarters !== 0) s += this.months + this.quarters * 3 + "M"; if (this.weeks !== 0) s += this.weeks + "W"; if (this.days !== 0) s += this.days + "D"; if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) s += "T"; if (this.hours !== 0) s += this.hours + "H"; if (this.minutes !== 0) s += this.minutes + "M"; if (this.seconds !== 0 || this.milliseconds !== 0) // this will handle "floating point madness" by removing extra decimal places // https://stackoverflow.com/questions/588004/is-floating-point-math-broken s += roundTo$1(this.seconds + this.milliseconds / 1000, 3) + "S"; if (s === "P") s += "T0S"; return s; } /** * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day. * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours. * @see https://en.wikipedia.org/wiki/ISO_8601#Times * @param {Object} opts - options * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 * @param {boolean} [opts.includePrefix=false] - include the `T` prefix * @param {string} [opts.format='extended'] - choose between the basic and extended format * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000' * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00' * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00' * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000' * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000' * @return {string} */ ; _proto.toISOTime = function toISOTime(opts) { if (opts === void 0) { opts = {}; } if (!this.isValid) return null; var millis = this.toMillis(); if (millis < 0 || millis >= 86400000) return null; opts = _extends({ suppressMilliseconds: false, suppressSeconds: false, includePrefix: false, format: "extended" }, opts); var value = this.shiftTo("hours", "minutes", "seconds", "milliseconds"); var fmt = opts.format === "basic" ? "hhmm" : "hh:mm"; if (!opts.suppressSeconds || value.seconds !== 0 || value.milliseconds !== 0) { fmt += opts.format === "basic" ? "ss" : ":ss"; if (!opts.suppressMilliseconds || value.milliseconds !== 0) { fmt += ".SSS"; } } var str = value.toFormat(fmt); if (opts.includePrefix) { str = "T" + str; } return str; } /** * Returns an ISO 8601 representation of this Duration appropriate for use in JSON. * @return {string} */ ; _proto.toJSON = function toJSON() { return this.toISO(); } /** * Returns an ISO 8601 representation of this Duration appropriate for use in debugging. * @return {string} */ ; _proto.toString = function toString() { return this.toISO(); } /** * Returns an milliseconds value of this Duration. * @return {number} */ ; _proto.toMillis = function toMillis() { return this.as("milliseconds"); } /** * Returns an milliseconds value of this Duration. Alias of {@link toMillis} * @return {number} */ ; _proto.valueOf = function valueOf() { return this.toMillis(); } /** * Make this Duration longer by the specified amount. Return a newly-constructed Duration. * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() * @return {Duration} */ ; _proto.plus = function plus(duration) { if (!this.isValid) return this; var dur = friendlyDuration(duration), result = {}; for (var _iterator = _createForOfIteratorHelperLoose(orderedUnits$1), _step; !(_step = _iterator()).done;) { var k = _step.value; if (hasOwnProperty$3(dur.values, k) || hasOwnProperty$3(this.values, k)) { result[k] = dur.get(k) + this.get(k); } } return clone$1(this, { values: result }, true); } /** * Make this Duration shorter by the specified amount. Return a newly-constructed Duration. * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() * @return {Duration} */ ; _proto.minus = function minus(duration) { if (!this.isValid) return this; var dur = friendlyDuration(duration); return this.plus(dur.negate()); } /** * Scale this Duration by the specified amount. Return a newly-constructed Duration. * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number. * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 } * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hour" ? x * 2 : x) //=> { hours: 2, minutes: 30 } * @return {Duration} */ ; _proto.mapUnits = function mapUnits(fn) { if (!this.isValid) return this; var result = {}; for (var _i = 0, _Object$keys = Object.keys(this.values); _i < _Object$keys.length; _i++) { var k = _Object$keys[_i]; result[k] = asNumber(fn(this.values[k], k)); } return clone$1(this, { values: result }, true); } /** * Get the value of unit. * @param {string} unit - a unit such as 'minute' or 'day' * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2 * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0 * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3 * @return {number} */ ; _proto.get = function get(unit) { return this[Duration.normalizeUnit(unit)]; } /** * "Set" the values of specified units. Return a newly-constructed Duration. * @param {Object} values - a mapping of units to numbers * @example dur.set({ years: 2017 }) * @example dur.set({ hours: 8, minutes: 30 }) * @return {Duration} */ ; _proto.set = function set(values) { if (!this.isValid) return this; var mixed = _extends({}, this.values, normalizeObject(values, Duration.normalizeUnit)); return clone$1(this, { values: mixed }); } /** * "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration. * @example dur.reconfigure({ locale: 'en-GB' }) * @return {Duration} */ ; _proto.reconfigure = function reconfigure(_temp) { var _ref = _temp === void 0 ? {} : _temp, locale = _ref.locale, numberingSystem = _ref.numberingSystem, conversionAccuracy = _ref.conversionAccuracy; var loc = this.loc.clone({ locale: locale, numberingSystem: numberingSystem }), opts = { loc: loc }; if (conversionAccuracy) { opts.conversionAccuracy = conversionAccuracy; } return clone$1(this, opts); } /** * Return the length of the duration in the specified unit. * @param {string} unit - a unit such as 'minutes' or 'days' * @example Duration.fromObject({years: 1}).as('days') //=> 365 * @example Duration.fromObject({years: 1}).as('months') //=> 12 * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5 * @return {number} */ ; _proto.as = function as(unit) { return this.isValid ? this.shiftTo(unit).get(unit) : NaN; } /** * Reduce this Duration to its canonical representation in its current units. * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 } * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 } * @return {Duration} */ ; _proto.normalize = function normalize() { if (!this.isValid) return this; var vals = this.toObject(); normalizeValues(this.matrix, vals); return clone$1(this, { values: vals }, true); } /** * Convert this Duration into its representation in a different set of units. * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 } * @return {Duration} */ ; _proto.shiftTo = function shiftTo() { for (var _len = arguments.length, units = new Array(_len), _key = 0; _key < _len; _key++) { units[_key] = arguments[_key]; } if (!this.isValid) return this; if (units.length === 0) { return this; } units = units.map(function (u) { return Duration.normalizeUnit(u); }); var built = {}, accumulated = {}, vals = this.toObject(); var lastUnit; for (var _iterator2 = _createForOfIteratorHelperLoose(orderedUnits$1), _step2; !(_step2 = _iterator2()).done;) { var k = _step2.value; if (units.indexOf(k) >= 0) { lastUnit = k; var own = 0; // anything we haven't boiled down yet should get boiled to this unit for (var ak in accumulated) { own += this.matrix[ak][k] * accumulated[ak]; accumulated[ak] = 0; } // plus anything that's already in this unit if (isNumber(vals[k])) { own += vals[k]; } var i = Math.trunc(own); built[k] = i; accumulated[k] = own - i; // we'd like to absorb these fractions in another unit // plus anything further down the chain that should be rolled up in to this for (var down in vals) { if (orderedUnits$1.indexOf(down) > orderedUnits$1.indexOf(k)) { convert$9(this.matrix, vals, down, built, k); } } // otherwise, keep it in the wings to boil it later } else if (isNumber(vals[k])) { accumulated[k] = vals[k]; } } // anything leftover becomes the decimal for the last unit // lastUnit must be defined since units is not empty for (var key in accumulated) { if (accumulated[key] !== 0) { built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key]; } } return clone$1(this, { values: built }, true).normalize(); } /** * Return the negative of this Duration. * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 } * @return {Duration} */ ; _proto.negate = function negate() { if (!this.isValid) return this; var negated = {}; for (var _i2 = 0, _Object$keys2 = Object.keys(this.values); _i2 < _Object$keys2.length; _i2++) { var k = _Object$keys2[_i2]; negated[k] = -this.values[k]; } return clone$1(this, { values: negated }, true); } /** * Get the years. * @type {number} */ ; /** * Equality check * Two Durations are equal iff they have the same units and the same values for each unit. * @param {Duration} other * @return {boolean} */ _proto.equals = function equals(other) { if (!this.isValid || !other.isValid) { return false; } if (!this.loc.equals(other.loc)) { return false; } function eq(v1, v2) { // Consider 0 and undefined as equal if (v1 === undefined || v1 === 0) return v2 === undefined || v2 === 0; return v1 === v2; } for (var _iterator3 = _createForOfIteratorHelperLoose(orderedUnits$1), _step3; !(_step3 = _iterator3()).done;) { var u = _step3.value; if (!eq(this.values[u], other.values[u])) { return false; } } return true; }; _createClass(Duration, [{ key: "locale", get: function get() { return this.isValid ? this.loc.locale : null; } /** * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration * * @type {string} */ }, { key: "numberingSystem", get: function get() { return this.isValid ? this.loc.numberingSystem : null; } }, { key: "years", get: function get() { return this.isValid ? this.values.years || 0 : NaN; } /** * Get the quarters. * @type {number} */ }, { key: "quarters", get: function get() { return this.isValid ? this.values.quarters || 0 : NaN; } /** * Get the months. * @type {number} */ }, { key: "months", get: function get() { return this.isValid ? this.values.months || 0 : NaN; } /** * Get the weeks * @type {number} */ }, { key: "weeks", get: function get() { return this.isValid ? this.values.weeks || 0 : NaN; } /** * Get the days. * @type {number} */ }, { key: "days", get: function get() { return this.isValid ? this.values.days || 0 : NaN; } /** * Get the hours. * @type {number} */ }, { key: "hours", get: function get() { return this.isValid ? this.values.hours || 0 : NaN; } /** * Get the minutes. * @type {number} */ }, { key: "minutes", get: function get() { return this.isValid ? this.values.minutes || 0 : NaN; } /** * Get the seconds. * @return {number} */ }, { key: "seconds", get: function get() { return this.isValid ? this.values.seconds || 0 : NaN; } /** * Get the milliseconds. * @return {number} */ }, { key: "milliseconds", get: function get() { return this.isValid ? this.values.milliseconds || 0 : NaN; } /** * Returns whether the Duration is invalid. Invalid durations are returned by diff operations * on invalid DateTimes or Intervals. * @return {boolean} */ }, { key: "isValid", get: function get() { return this.invalid === null; } /** * Returns an error code if this Duration became invalid, or null if the Duration is valid * @return {string} */ }, { key: "invalidReason", get: function get() { return this.invalid ? this.invalid.reason : null; } /** * Returns an explanation of why this Duration became invalid, or null if the Duration is valid * @type {string} */ }, { key: "invalidExplanation", get: function get() { return this.invalid ? this.invalid.explanation : null; } }]); return Duration; }(); function friendlyDuration(durationish) { if (isNumber(durationish)) { return Duration.fromMillis(durationish); } else if (Duration.isDuration(durationish)) { return durationish; } else if (typeof durationish === "object") { return Duration.fromObject(durationish); } else { throw new InvalidArgumentError("Unknown duration argument " + durationish + " of type " + typeof durationish); } } var INVALID$1 = "Invalid Interval"; // checks if the start is equal to or before the end function validateStartEnd(start, end) { if (!start || !start.isValid) { return Interval.invalid("missing or invalid start"); } else if (!end || !end.isValid) { return Interval.invalid("missing or invalid end"); } else if (end < start) { return Interval.invalid("end before start", "The end of an interval must be after its start, but you had start=" + start.toISO() + " and end=" + end.toISO()); } else { return null; } } /** * An Interval object represents a half-open interval of time, where each endpoint is a {@link DateTime}. Conceptually, it's a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them. * * Here is a brief overview of the most commonly used methods and getters in Interval: * * * **Creation** To create an Interval, use {@link Interval.fromDateTimes}, {@link Interval.after}, {@link Interval.before}, or {@link Interval.fromISO}. * * **Accessors** Use {@link Interval#start} and {@link Interval#end} to get the start and end. * * **Interrogation** To analyze the Interval, use {@link Interval#count}, {@link Interval#length}, {@link Interval#hasSame}, {@link Interval#contains}, {@link Interval#isAfter}, or {@link Interval#isBefore}. * * **Transformation** To create other Intervals out of this one, use {@link Interval#set}, {@link Interval#splitAt}, {@link Interval#splitBy}, {@link Interval#divideEqually}, {@link Interval#merge}, {@link Interval#xor}, {@link Interval#union}, {@link Interval#intersection}, or {@link Interval#difference}. * * **Comparison** To compare this Interval to another one, use {@link Interval#equals}, {@link Interval#overlaps}, {@link Interval#abutsStart}, {@link Interval#abutsEnd}, {@link Interval#engulfs} * * **Output** To convert the Interval into other representations, see {@link Interval#toString}, {@link Interval#toISO}, {@link Interval#toISODate}, {@link Interval#toISOTime}, {@link Interval#toFormat}, and {@link Interval#toDuration}. */ var Interval = /*#__PURE__*/function () { /** * @private */ function Interval(config) { /** * @access private */ this.s = config.start; /** * @access private */ this.e = config.end; /** * @access private */ this.invalid = config.invalid || null; /** * @access private */ this.isLuxonInterval = true; } /** * Create an invalid Interval. * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information * @return {Interval} */ Interval.invalid = function invalid(reason, explanation) { if (explanation === void 0) { explanation = null; } if (!reason) { throw new InvalidArgumentError("need to specify a reason the Interval is invalid"); } var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); if (Settings.throwOnInvalid) { throw new InvalidIntervalError(invalid); } else { return new Interval({ invalid: invalid }); } } /** * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end. * @param {DateTime|Date|Object} start * @param {DateTime|Date|Object} end * @return {Interval} */ ; Interval.fromDateTimes = function fromDateTimes(start, end) { var builtStart = friendlyDateTime(start), builtEnd = friendlyDateTime(end); var validateError = validateStartEnd(builtStart, builtEnd); if (validateError == null) { return new Interval({ start: builtStart, end: builtEnd }); } else { return validateError; } } /** * Create an Interval from a start DateTime and a Duration to extend to. * @param {DateTime|Date|Object} start * @param {Duration|Object|number} duration - the length of the Interval. * @return {Interval} */ ; Interval.after = function after(start, duration) { var dur = friendlyDuration(duration), dt = friendlyDateTime(start); return Interval.fromDateTimes(dt, dt.plus(dur)); } /** * Create an Interval from an end DateTime and a Duration to extend backwards to. * @param {DateTime|Date|Object} end * @param {Duration|Object|number} duration - the length of the Interval. * @return {Interval} */ ; Interval.before = function before(end, duration) { var dur = friendlyDuration(duration), dt = friendlyDateTime(end); return Interval.fromDateTimes(dt.minus(dur), dt); } /** * Create an Interval from an ISO 8601 string. * Accepts `/`, `/`, and `/` formats. * @param {string} text - the ISO string to parse * @param {Object} [opts] - options to pass {@link DateTime.fromISO} and optionally {@link Duration.fromISO} * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals * @return {Interval} */ ; Interval.fromISO = function fromISO(text, opts) { var _split = (text || "").split("/", 2), s = _split[0], e = _split[1]; if (s && e) { var start, startIsValid; try { start = DateTime.fromISO(s, opts); startIsValid = start.isValid; } catch (e) { startIsValid = false; } var end, endIsValid; try { end = DateTime.fromISO(e, opts); endIsValid = end.isValid; } catch (e) { endIsValid = false; } if (startIsValid && endIsValid) { return Interval.fromDateTimes(start, end); } if (startIsValid) { var dur = Duration.fromISO(e, opts); if (dur.isValid) { return Interval.after(start, dur); } } else if (endIsValid) { var _dur = Duration.fromISO(s, opts); if (_dur.isValid) { return Interval.before(end, _dur); } } } return Interval.invalid("unparsable", "the input \"" + text + "\" can't be parsed as ISO 8601"); } /** * Check if an object is an Interval. Works across context boundaries * @param {object} o * @return {boolean} */ ; Interval.isInterval = function isInterval(o) { return o && o.isLuxonInterval || false; } /** * Returns the start of the Interval * @type {DateTime} */ ; var _proto = Interval.prototype; /** * Returns the length of the Interval in the specified unit. * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in. * @return {number} */ _proto.length = function length(unit) { if (unit === void 0) { unit = "milliseconds"; } return this.isValid ? this.toDuration.apply(this, [unit]).get(unit) : NaN; } /** * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part. * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day' * asks 'what dates are included in this interval?', not 'how many days long is this interval?' * @param {string} [unit='milliseconds'] - the unit of time to count. * @return {number} */ ; _proto.count = function count(unit) { if (unit === void 0) { unit = "milliseconds"; } if (!this.isValid) return NaN; var start = this.start.startOf(unit), end = this.end.startOf(unit); return Math.floor(end.diff(start, unit).get(unit)) + 1; } /** * Returns whether this Interval's start and end are both in the same unit of time * @param {string} unit - the unit of time to check sameness on * @return {boolean} */ ; _proto.hasSame = function hasSame(unit) { return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false; } /** * Return whether this Interval has the same start and end DateTimes. * @return {boolean} */ ; _proto.isEmpty = function isEmpty() { return this.s.valueOf() === this.e.valueOf(); } /** * Return whether this Interval's start is after the specified DateTime. * @param {DateTime} dateTime * @return {boolean} */ ; _proto.isAfter = function isAfter(dateTime) { if (!this.isValid) return false; return this.s > dateTime; } /** * Return whether this Interval's end is before the specified DateTime. * @param {DateTime} dateTime * @return {boolean} */ ; _proto.isBefore = function isBefore(dateTime) { if (!this.isValid) return false; return this.e <= dateTime; } /** * Return whether this Interval contains the specified DateTime. * @param {DateTime} dateTime * @return {boolean} */ ; _proto.contains = function contains(dateTime) { if (!this.isValid) return false; return this.s <= dateTime && this.e > dateTime; } /** * "Sets" the start and/or end dates. Returns a newly-constructed Interval. * @param {Object} values - the values to set * @param {DateTime} values.start - the starting DateTime * @param {DateTime} values.end - the ending DateTime * @return {Interval} */ ; _proto.set = function set(_temp) { var _ref = _temp === void 0 ? {} : _temp, start = _ref.start, end = _ref.end; if (!this.isValid) return this; return Interval.fromDateTimes(start || this.s, end || this.e); } /** * Split this Interval at each of the specified DateTimes * @param {...DateTime} dateTimes - the unit of time to count. * @return {Array} */ ; _proto.splitAt = function splitAt() { var _this = this; if (!this.isValid) return []; for (var _len = arguments.length, dateTimes = new Array(_len), _key = 0; _key < _len; _key++) { dateTimes[_key] = arguments[_key]; } var sorted = dateTimes.map(friendlyDateTime).filter(function (d) { return _this.contains(d); }).sort(), results = []; var s = this.s, i = 0; while (s < this.e) { var added = sorted[i] || this.e, next = +added > +this.e ? this.e : added; results.push(Interval.fromDateTimes(s, next)); s = next; i += 1; } return results; } /** * Split this Interval into smaller Intervals, each of the specified length. * Left over time is grouped into a smaller interval * @param {Duration|Object|number} duration - The length of each resulting interval. * @return {Array} */ ; _proto.splitBy = function splitBy(duration) { var dur = friendlyDuration(duration); if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) { return []; } var s = this.s, idx = 1, next; var results = []; while (s < this.e) { var added = this.start.plus(dur.mapUnits(function (x) { return x * idx; })); next = +added > +this.e ? this.e : added; results.push(Interval.fromDateTimes(s, next)); s = next; idx += 1; } return results; } /** * Split this Interval into the specified number of smaller intervals. * @param {number} numberOfParts - The number of Intervals to divide the Interval into. * @return {Array} */ ; _proto.divideEqually = function divideEqually(numberOfParts) { if (!this.isValid) return []; return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts); } /** * Return whether this Interval overlaps with the specified Interval * @param {Interval} other * @return {boolean} */ ; _proto.overlaps = function overlaps(other) { return this.e > other.s && this.s < other.e; } /** * Return whether this Interval's end is adjacent to the specified Interval's start. * @param {Interval} other * @return {boolean} */ ; _proto.abutsStart = function abutsStart(other) { if (!this.isValid) return false; return +this.e === +other.s; } /** * Return whether this Interval's start is adjacent to the specified Interval's end. * @param {Interval} other * @return {boolean} */ ; _proto.abutsEnd = function abutsEnd(other) { if (!this.isValid) return false; return +other.e === +this.s; } /** * Return whether this Interval engulfs the start and end of the specified Interval. * @param {Interval} other * @return {boolean} */ ; _proto.engulfs = function engulfs(other) { if (!this.isValid) return false; return this.s <= other.s && this.e >= other.e; } /** * Return whether this Interval has the same start and end as the specified Interval. * @param {Interval} other * @return {boolean} */ ; _proto.equals = function equals(other) { if (!this.isValid || !other.isValid) { return false; } return this.s.equals(other.s) && this.e.equals(other.e); } /** * Return an Interval representing the intersection of this Interval and the specified Interval. * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals. * Returns null if the intersection is empty, meaning, the intervals don't intersect. * @param {Interval} other * @return {Interval} */ ; _proto.intersection = function intersection(other) { if (!this.isValid) return this; var s = this.s > other.s ? this.s : other.s, e = this.e < other.e ? this.e : other.e; if (s >= e) { return null; } else { return Interval.fromDateTimes(s, e); } } /** * Return an Interval representing the union of this Interval and the specified Interval. * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals. * @param {Interval} other * @return {Interval} */ ; _proto.union = function union(other) { if (!this.isValid) return this; var s = this.s < other.s ? this.s : other.s, e = this.e > other.e ? this.e : other.e; return Interval.fromDateTimes(s, e); } /** * Merge an array of Intervals into a equivalent minimal set of Intervals. * Combines overlapping and adjacent Intervals. * @param {Array} intervals * @return {Array} */ ; Interval.merge = function merge(intervals) { var _intervals$sort$reduc = intervals.sort(function (a, b) { return a.s - b.s; }).reduce(function (_ref2, item) { var sofar = _ref2[0], current = _ref2[1]; if (!current) { return [sofar, item]; } else if (current.overlaps(item) || current.abutsStart(item)) { return [sofar, current.union(item)]; } else { return [sofar.concat([current]), item]; } }, [[], null]), found = _intervals$sort$reduc[0], final = _intervals$sort$reduc[1]; if (final) { found.push(final); } return found; } /** * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals. * @param {Array} intervals * @return {Array} */ ; Interval.xor = function xor(intervals) { var _Array$prototype; var start = null, currentCount = 0; var results = [], ends = intervals.map(function (i) { return [{ time: i.s, type: "s" }, { time: i.e, type: "e" }]; }), flattened = (_Array$prototype = Array.prototype).concat.apply(_Array$prototype, ends), arr = flattened.sort(function (a, b) { return a.time - b.time; }); for (var _iterator = _createForOfIteratorHelperLoose(arr), _step; !(_step = _iterator()).done;) { var i = _step.value; currentCount += i.type === "s" ? 1 : -1; if (currentCount === 1) { start = i.time; } else { if (start && +start !== +i.time) { results.push(Interval.fromDateTimes(start, i.time)); } start = null; } } return Interval.merge(results); } /** * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals. * @param {...Interval} intervals * @return {Array} */ ; _proto.difference = function difference() { var _this2 = this; for (var _len2 = arguments.length, intervals = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { intervals[_key2] = arguments[_key2]; } return Interval.xor([this].concat(intervals)).map(function (i) { return _this2.intersection(i); }).filter(function (i) { return i && !i.isEmpty(); }); } /** * Returns a string representation of this Interval appropriate for debugging. * @return {string} */ ; _proto.toString = function toString() { if (!this.isValid) return INVALID$1; return "[" + this.s.toISO() + " \u2013 " + this.e.toISO() + ")"; } /** * Returns an ISO 8601-compliant string representation of this Interval. * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals * @param {Object} opts - The same options as {@link DateTime#toISO} * @return {string} */ ; _proto.toISO = function toISO(opts) { if (!this.isValid) return INVALID$1; return this.s.toISO(opts) + "/" + this.e.toISO(opts); } /** * Returns an ISO 8601-compliant string representation of date of this Interval. * The time components are ignored. * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals * @return {string} */ ; _proto.toISODate = function toISODate() { if (!this.isValid) return INVALID$1; return this.s.toISODate() + "/" + this.e.toISODate(); } /** * Returns an ISO 8601-compliant string representation of time of this Interval. * The date components are ignored. * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals * @param {Object} opts - The same options as {@link DateTime.toISO} * @return {string} */ ; _proto.toISOTime = function toISOTime(opts) { if (!this.isValid) return INVALID$1; return this.s.toISOTime(opts) + "/" + this.e.toISOTime(opts); } /** * Returns a string representation of this Interval formatted according to the specified format string. * @param {string} dateFormat - the format string. This string formats the start and end time. See {@link DateTime.toFormat} for details. * @param {Object} opts - options * @param {string} [opts.separator = ' – '] - a separator to place between the start and end representations * @return {string} */ ; _proto.toFormat = function toFormat(dateFormat, _temp2) { var _ref3 = _temp2 === void 0 ? {} : _temp2, _ref3$separator = _ref3.separator, separator = _ref3$separator === void 0 ? " – " : _ref3$separator; if (!this.isValid) return INVALID$1; return "" + this.s.toFormat(dateFormat) + separator + this.e.toFormat(dateFormat); } /** * Return a Duration representing the time spanned by this interval. * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration. * @param {Object} opts - options that affect the creation of the Duration * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 } * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 } * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 } * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 } * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 } * @return {Duration} */ ; _proto.toDuration = function toDuration(unit, opts) { if (!this.isValid) { return Duration.invalid(this.invalidReason); } return this.e.diff(this.s, unit, opts); } /** * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes * @param {function} mapFn * @return {Interval} * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC()) * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 })) */ ; _proto.mapEndpoints = function mapEndpoints(mapFn) { return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e)); }; _createClass(Interval, [{ key: "start", get: function get() { return this.isValid ? this.s : null; } /** * Returns the end of the Interval * @type {DateTime} */ }, { key: "end", get: function get() { return this.isValid ? this.e : null; } /** * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'. * @type {boolean} */ }, { key: "isValid", get: function get() { return this.invalidReason === null; } /** * Returns an error code if this Interval is invalid, or null if the Interval is valid * @type {string} */ }, { key: "invalidReason", get: function get() { return this.invalid ? this.invalid.reason : null; } /** * Returns an explanation of why this Interval became invalid, or null if the Interval is valid * @type {string} */ }, { key: "invalidExplanation", get: function get() { return this.invalid ? this.invalid.explanation : null; } }]); return Interval; }(); /** * The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment. */ var Info$1 = /*#__PURE__*/function () { function Info() {} /** * Return whether the specified zone contains a DST. * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone. * @return {boolean} */ Info.hasDST = function hasDST(zone) { if (zone === void 0) { zone = Settings.defaultZone; } var proto = DateTime.now().setZone(zone).set({ month: 12 }); return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset; } /** * Return whether the specified zone is a valid IANA specifier. * @param {string} zone - Zone to check * @return {boolean} */ ; Info.isValidIANAZone = function isValidIANAZone(zone) { return IANAZone.isValidSpecifier(zone) && IANAZone.isValidZone(zone); } /** * Converts the input into a {@link Zone} instance. * * * If `input` is already a Zone instance, it is returned unchanged. * * If `input` is a string containing a valid time zone name, a Zone instance * with that name is returned. * * If `input` is a string that doesn't refer to a known time zone, a Zone * instance with {@link Zone.isValid} == false is returned. * * If `input is a number, a Zone instance with the specified fixed offset * in minutes is returned. * * If `input` is `null` or `undefined`, the default zone is returned. * @param {string|Zone|number} [input] - the value to be converted * @return {Zone} */ ; Info.normalizeZone = function normalizeZone$1(input) { return normalizeZone(input, Settings.defaultZone); } /** * Return an array of standalone month names. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @param {string} [opts.locObj=null] - an existing locale object to use * @param {string} [opts.outputCalendar='gregory'] - the calendar * @example Info.months()[0] //=> 'January' * @example Info.months('short')[0] //=> 'Jan' * @example Info.months('numeric')[0] //=> '1' * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.' * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١' * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I' * @return {Array} */ ; Info.months = function months(length, _temp) { if (length === void 0) { length = "long"; } var _ref = _temp === void 0 ? {} : _temp, _ref$locale = _ref.locale, locale = _ref$locale === void 0 ? null : _ref$locale, _ref$numberingSystem = _ref.numberingSystem, numberingSystem = _ref$numberingSystem === void 0 ? null : _ref$numberingSystem, _ref$locObj = _ref.locObj, locObj = _ref$locObj === void 0 ? null : _ref$locObj, _ref$outputCalendar = _ref.outputCalendar, outputCalendar = _ref$outputCalendar === void 0 ? "gregory" : _ref$outputCalendar; return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length); } /** * Return an array of format month names. * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that * changes the string. * See {@link Info#months} * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @param {string} [opts.locObj=null] - an existing locale object to use * @param {string} [opts.outputCalendar='gregory'] - the calendar * @return {Array} */ ; Info.monthsFormat = function monthsFormat(length, _temp2) { if (length === void 0) { length = "long"; } var _ref2 = _temp2 === void 0 ? {} : _temp2, _ref2$locale = _ref2.locale, locale = _ref2$locale === void 0 ? null : _ref2$locale, _ref2$numberingSystem = _ref2.numberingSystem, numberingSystem = _ref2$numberingSystem === void 0 ? null : _ref2$numberingSystem, _ref2$locObj = _ref2.locObj, locObj = _ref2$locObj === void 0 ? null : _ref2$locObj, _ref2$outputCalendar = _ref2.outputCalendar, outputCalendar = _ref2$outputCalendar === void 0 ? "gregory" : _ref2$outputCalendar; return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true); } /** * Return an array of standalone week names. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long". * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @param {string} [opts.locObj=null] - an existing locale object to use * @example Info.weekdays()[0] //=> 'Monday' * @example Info.weekdays('short')[0] //=> 'Mon' * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.' * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين' * @return {Array} */ ; Info.weekdays = function weekdays(length, _temp3) { if (length === void 0) { length = "long"; } var _ref3 = _temp3 === void 0 ? {} : _temp3, _ref3$locale = _ref3.locale, locale = _ref3$locale === void 0 ? null : _ref3$locale, _ref3$numberingSystem = _ref3.numberingSystem, numberingSystem = _ref3$numberingSystem === void 0 ? null : _ref3$numberingSystem, _ref3$locObj = _ref3.locObj, locObj = _ref3$locObj === void 0 ? null : _ref3$locObj; return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length); } /** * Return an array of format week names. * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that * changes the string. * See {@link Info#weekdays} * @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long". * @param {Object} opts - options * @param {string} [opts.locale=null] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @param {string} [opts.locObj=null] - an existing locale object to use * @return {Array} */ ; Info.weekdaysFormat = function weekdaysFormat(length, _temp4) { if (length === void 0) { length = "long"; } var _ref4 = _temp4 === void 0 ? {} : _temp4, _ref4$locale = _ref4.locale, locale = _ref4$locale === void 0 ? null : _ref4$locale, _ref4$numberingSystem = _ref4.numberingSystem, numberingSystem = _ref4$numberingSystem === void 0 ? null : _ref4$numberingSystem, _ref4$locObj = _ref4.locObj, locObj = _ref4$locObj === void 0 ? null : _ref4$locObj; return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true); } /** * Return an array of meridiems. * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @example Info.meridiems() //=> [ 'AM', 'PM' ] * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ] * @return {Array} */ ; Info.meridiems = function meridiems(_temp5) { var _ref5 = _temp5 === void 0 ? {} : _temp5, _ref5$locale = _ref5.locale, locale = _ref5$locale === void 0 ? null : _ref5$locale; return Locale.create(locale).meridiems(); } /** * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian. * @param {string} [length='short'] - the length of the era representation, such as "short" or "long". * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @example Info.eras() //=> [ 'BC', 'AD' ] * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ] * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ] * @return {Array} */ ; Info.eras = function eras(length, _temp6) { if (length === void 0) { length = "short"; } var _ref6 = _temp6 === void 0 ? {} : _temp6, _ref6$locale = _ref6.locale, locale = _ref6$locale === void 0 ? null : _ref6$locale; return Locale.create(locale, null, "gregory").eras(length); } /** * Return the set of available features in this environment. * Some features of Luxon are not available in all environments. For example, on older browsers, timezone support is not available. Use this function to figure out if that's the case. * Keys: * * `relative`: whether this environment supports relative time formatting * @example Info.features() //=> { intl: true, intlTokens: false, zones: true, relative: false } * @return {Object} */ ; Info.features = function features() { return { relative: hasRelative() }; }; return Info; }(); function dayDiff(earlier, later) { var utcDayStart = function utcDayStart(dt) { return dt.toUTC(0, { keepLocalTime: true }).startOf("day").valueOf(); }, ms = utcDayStart(later) - utcDayStart(earlier); return Math.floor(Duration.fromMillis(ms).as("days")); } function highOrderDiffs(cursor, later, units) { var differs = [["years", function (a, b) { return b.year - a.year; }], ["quarters", function (a, b) { return b.quarter - a.quarter; }], ["months", function (a, b) { return b.month - a.month + (b.year - a.year) * 12; }], ["weeks", function (a, b) { var days = dayDiff(a, b); return (days - days % 7) / 7; }], ["days", dayDiff]]; var results = {}; var lowestOrder, highWater; for (var _i = 0, _differs = differs; _i < _differs.length; _i++) { var _differs$_i = _differs[_i], unit = _differs$_i[0], differ = _differs$_i[1]; if (units.indexOf(unit) >= 0) { var _cursor$plus; lowestOrder = unit; var delta = differ(cursor, later); highWater = cursor.plus((_cursor$plus = {}, _cursor$plus[unit] = delta, _cursor$plus)); if (highWater > later) { var _cursor$plus2; cursor = cursor.plus((_cursor$plus2 = {}, _cursor$plus2[unit] = delta - 1, _cursor$plus2)); delta -= 1; } else { cursor = highWater; } results[unit] = delta; } } return [cursor, results, highWater, lowestOrder]; } function _diff (earlier, later, units, opts) { var _highOrderDiffs = highOrderDiffs(earlier, later, units), cursor = _highOrderDiffs[0], results = _highOrderDiffs[1], highWater = _highOrderDiffs[2], lowestOrder = _highOrderDiffs[3]; var remainingMillis = later - cursor; var lowerOrderUnits = units.filter(function (u) { return ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0; }); if (lowerOrderUnits.length === 0) { if (highWater < later) { var _cursor$plus3; highWater = cursor.plus((_cursor$plus3 = {}, _cursor$plus3[lowestOrder] = 1, _cursor$plus3)); } if (highWater !== cursor) { results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor); } } var duration = Duration.fromObject(results, opts); if (lowerOrderUnits.length > 0) { var _Duration$fromMillis; return (_Duration$fromMillis = Duration.fromMillis(remainingMillis, opts)).shiftTo.apply(_Duration$fromMillis, lowerOrderUnits).plus(duration); } else { return duration; } } var numberingSystems = { arab: "[\u0660-\u0669]", arabext: "[\u06F0-\u06F9]", bali: "[\u1B50-\u1B59]", beng: "[\u09E6-\u09EF]", deva: "[\u0966-\u096F]", fullwide: "[\uFF10-\uFF19]", gujr: "[\u0AE6-\u0AEF]", hanidec: "[〇|一|二|三|四|五|六|七|八|九]", khmr: "[\u17E0-\u17E9]", knda: "[\u0CE6-\u0CEF]", laoo: "[\u0ED0-\u0ED9]", limb: "[\u1946-\u194F]", mlym: "[\u0D66-\u0D6F]", mong: "[\u1810-\u1819]", mymr: "[\u1040-\u1049]", orya: "[\u0B66-\u0B6F]", tamldec: "[\u0BE6-\u0BEF]", telu: "[\u0C66-\u0C6F]", thai: "[\u0E50-\u0E59]", tibt: "[\u0F20-\u0F29]", latn: "\\d" }; var numberingSystemsUTF16 = { arab: [1632, 1641], arabext: [1776, 1785], bali: [6992, 7001], beng: [2534, 2543], deva: [2406, 2415], fullwide: [65296, 65303], gujr: [2790, 2799], khmr: [6112, 6121], knda: [3302, 3311], laoo: [3792, 3801], limb: [6470, 6479], mlym: [3430, 3439], mong: [6160, 6169], mymr: [4160, 4169], orya: [2918, 2927], tamldec: [3046, 3055], telu: [3174, 3183], thai: [3664, 3673], tibt: [3872, 3881] }; var hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split(""); function parseDigits(str) { var value = parseInt(str, 10); if (isNaN(value)) { value = ""; for (var i = 0; i < str.length; i++) { var code = str.charCodeAt(i); if (str[i].search(numberingSystems.hanidec) !== -1) { value += hanidecChars.indexOf(str[i]); } else { for (var key in numberingSystemsUTF16) { var _numberingSystemsUTF = numberingSystemsUTF16[key], min = _numberingSystemsUTF[0], max = _numberingSystemsUTF[1]; if (code >= min && code <= max) { value += code - min; } } } } return parseInt(value, 10); } else { return value; } } function digitRegex(_ref, append) { var numberingSystem = _ref.numberingSystem; if (append === void 0) { append = ""; } return new RegExp("" + numberingSystems[numberingSystem || "latn"] + append); } var MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support"; function intUnit(regex, post) { if (post === void 0) { post = function post(i) { return i; }; } return { regex: regex, deser: function deser(_ref) { var s = _ref[0]; return post(parseDigits(s)); } }; } var NBSP = String.fromCharCode(160); var spaceOrNBSP = "( |" + NBSP + ")"; var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g"); function fixListRegex(s) { // make dots optional and also make them literal // make space and non breakable space characters interchangeable return s.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP); } function stripInsensitivities(s) { return s.replace(/\./g, "") // ignore dots that were made optional .replace(spaceOrNBSPRegExp, " ") // interchange space and nbsp .toLowerCase(); } function oneOf(strings, startIndex) { if (strings === null) { return null; } else { return { regex: RegExp(strings.map(fixListRegex).join("|")), deser: function deser(_ref2) { var s = _ref2[0]; return strings.findIndex(function (i) { return stripInsensitivities(s) === stripInsensitivities(i); }) + startIndex; } }; } } function offset(regex, groups) { return { regex: regex, deser: function deser(_ref3) { var h = _ref3[1], m = _ref3[2]; return signedOffset(h, m); }, groups: groups }; } function simple(regex) { return { regex: regex, deser: function deser(_ref4) { var s = _ref4[0]; return s; } }; } function escapeToken(value) { return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); } function unitForToken(token, loc) { var one = digitRegex(loc), two = digitRegex(loc, "{2}"), three = digitRegex(loc, "{3}"), four = digitRegex(loc, "{4}"), six = digitRegex(loc, "{6}"), oneOrTwo = digitRegex(loc, "{1,2}"), oneToThree = digitRegex(loc, "{1,3}"), oneToSix = digitRegex(loc, "{1,6}"), oneToNine = digitRegex(loc, "{1,9}"), twoToFour = digitRegex(loc, "{2,4}"), fourToSix = digitRegex(loc, "{4,6}"), literal = function literal(t) { return { regex: RegExp(escapeToken(t.val)), deser: function deser(_ref5) { var s = _ref5[0]; return s; }, literal: true }; }, unitate = function unitate(t) { if (token.literal) { return literal(t); } switch (t.val) { // era case "G": return oneOf(loc.eras("short", false), 0); case "GG": return oneOf(loc.eras("long", false), 0); // years case "y": return intUnit(oneToSix); case "yy": return intUnit(twoToFour, untruncateYear); case "yyyy": return intUnit(four); case "yyyyy": return intUnit(fourToSix); case "yyyyyy": return intUnit(six); // months case "M": return intUnit(oneOrTwo); case "MM": return intUnit(two); case "MMM": return oneOf(loc.months("short", true, false), 1); case "MMMM": return oneOf(loc.months("long", true, false), 1); case "L": return intUnit(oneOrTwo); case "LL": return intUnit(two); case "LLL": return oneOf(loc.months("short", false, false), 1); case "LLLL": return oneOf(loc.months("long", false, false), 1); // dates case "d": return intUnit(oneOrTwo); case "dd": return intUnit(two); // ordinals case "o": return intUnit(oneToThree); case "ooo": return intUnit(three); // time case "HH": return intUnit(two); case "H": return intUnit(oneOrTwo); case "hh": return intUnit(two); case "h": return intUnit(oneOrTwo); case "mm": return intUnit(two); case "m": return intUnit(oneOrTwo); case "q": return intUnit(oneOrTwo); case "qq": return intUnit(two); case "s": return intUnit(oneOrTwo); case "ss": return intUnit(two); case "S": return intUnit(oneToThree); case "SSS": return intUnit(three); case "u": return simple(oneToNine); // meridiem case "a": return oneOf(loc.meridiems(), 0); // weekYear (k) case "kkkk": return intUnit(four); case "kk": return intUnit(twoToFour, untruncateYear); // weekNumber (W) case "W": return intUnit(oneOrTwo); case "WW": return intUnit(two); // weekdays case "E": case "c": return intUnit(one); case "EEE": return oneOf(loc.weekdays("short", false, false), 1); case "EEEE": return oneOf(loc.weekdays("long", false, false), 1); case "ccc": return oneOf(loc.weekdays("short", true, false), 1); case "cccc": return oneOf(loc.weekdays("long", true, false), 1); // offset/zone case "Z": case "ZZ": return offset(new RegExp("([+-]" + oneOrTwo.source + ")(?::(" + two.source + "))?"), 2); case "ZZZ": return offset(new RegExp("([+-]" + oneOrTwo.source + ")(" + two.source + ")?"), 2); // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing // because we don't have any way to figure out what they are case "z": return simple(/[a-z_+-/]{1,256}?/i); default: return literal(t); } }; var unit = unitate(token) || { invalidReason: MISSING_FTP }; unit.token = token; return unit; } var partTypeStyleToTokenVal = { year: { "2-digit": "yy", numeric: "yyyyy" }, month: { numeric: "M", "2-digit": "MM", short: "MMM", long: "MMMM" }, day: { numeric: "d", "2-digit": "dd" }, weekday: { short: "EEE", long: "EEEE" }, dayperiod: "a", dayPeriod: "a", hour: { numeric: "h", "2-digit": "hh" }, minute: { numeric: "m", "2-digit": "mm" }, second: { numeric: "s", "2-digit": "ss" } }; function tokenForPart(part, locale, formatOpts) { var type = part.type, value = part.value; if (type === "literal") { return { literal: true, val: value }; } var style = formatOpts[type]; var val = partTypeStyleToTokenVal[type]; if (typeof val === "object") { val = val[style]; } if (val) { return { literal: false, val: val }; } return undefined; } function buildRegex(units) { var re = units.map(function (u) { return u.regex; }).reduce(function (f, r) { return f + "(" + r.source + ")"; }, ""); return ["^" + re + "$", units]; } function match(input, regex, handlers) { var matches = input.match(regex); if (matches) { var all = {}; var matchIndex = 1; for (var i in handlers) { if (hasOwnProperty$3(handlers, i)) { var h = handlers[i], groups = h.groups ? h.groups + 1 : 1; if (!h.literal && h.token) { all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups)); } matchIndex += groups; } } return [matches, all]; } else { return [matches, {}]; } } function dateTimeFromMatches(matches) { var toField = function toField(token) { switch (token) { case "S": return "millisecond"; case "s": return "second"; case "m": return "minute"; case "h": case "H": return "hour"; case "d": return "day"; case "o": return "ordinal"; case "L": case "M": return "month"; case "y": return "year"; case "E": case "c": return "weekday"; case "W": return "weekNumber"; case "k": return "weekYear"; case "q": return "quarter"; default: return null; } }; var zone; if (!isUndefined$1(matches.Z)) { zone = new FixedOffsetZone(matches.Z); } else if (!isUndefined$1(matches.z)) { zone = IANAZone.create(matches.z); } else { zone = null; } if (!isUndefined$1(matches.q)) { matches.M = (matches.q - 1) * 3 + 1; } if (!isUndefined$1(matches.h)) { if (matches.h < 12 && matches.a === 1) { matches.h += 12; } else if (matches.h === 12 && matches.a === 0) { matches.h = 0; } } if (matches.G === 0 && matches.y) { matches.y = -matches.y; } if (!isUndefined$1(matches.u)) { matches.S = parseMillis(matches.u); } var vals = Object.keys(matches).reduce(function (r, k) { var f = toField(k); if (f) { r[f] = matches[k]; } return r; }, {}); return [vals, zone]; } var dummyDateTimeCache = null; function getDummyDateTime() { if (!dummyDateTimeCache) { dummyDateTimeCache = DateTime.fromMillis(1555555555555); } return dummyDateTimeCache; } function maybeExpandMacroToken(token, locale) { if (token.literal) { return token; } var formatOpts = Formatter$1.macroTokenToFormatOpts(token.val); if (!formatOpts) { return token; } var formatter = Formatter$1.create(locale, formatOpts); var parts = formatter.formatDateTimeParts(getDummyDateTime()); var tokens = parts.map(function (p) { return tokenForPart(p, locale, formatOpts); }); if (tokens.includes(undefined)) { return token; } return tokens; } function expandMacroTokens(tokens, locale) { var _Array$prototype; return (_Array$prototype = Array.prototype).concat.apply(_Array$prototype, tokens.map(function (t) { return maybeExpandMacroToken(t, locale); })); } /** * @private */ function explainFromTokens(locale, input, format) { var tokens = expandMacroTokens(Formatter$1.parseFormat(format), locale), units = tokens.map(function (t) { return unitForToken(t, locale); }), disqualifyingUnit = units.find(function (t) { return t.invalidReason; }); if (disqualifyingUnit) { return { input: input, tokens: tokens, invalidReason: disqualifyingUnit.invalidReason }; } else { var _buildRegex = buildRegex(units), regexString = _buildRegex[0], handlers = _buildRegex[1], regex = RegExp(regexString, "i"), _match = match(input, regex, handlers), rawMatches = _match[0], matches = _match[1], _ref6 = matches ? dateTimeFromMatches(matches) : [null, null], result = _ref6[0], zone = _ref6[1]; if (hasOwnProperty$3(matches, "a") && hasOwnProperty$3(matches, "H")) { throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format"); } return { input: input, tokens: tokens, regex: regex, rawMatches: rawMatches, matches: matches, result: result, zone: zone }; } } function parseFromTokens(locale, input, format) { var _explainFromTokens = explainFromTokens(locale, input, format), result = _explainFromTokens.result, zone = _explainFromTokens.zone, invalidReason = _explainFromTokens.invalidReason; return [result, zone, invalidReason]; } var nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]; function unitOutOfRange(unit, value) { return new Invalid("unit out of range", "you specified " + value + " (of type " + typeof value + ") as a " + unit + ", which is invalid"); } function dayOfWeek(year, month, day) { var js = new Date(Date.UTC(year, month - 1, day)).getUTCDay(); return js === 0 ? 7 : js; } function computeOrdinal(year, month, day) { return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1]; } function uncomputeOrdinal(year, ordinal) { var table = isLeapYear(year) ? leapLadder : nonLeapLadder, month0 = table.findIndex(function (i) { return i < ordinal; }), day = ordinal - table[month0]; return { month: month0 + 1, day: day }; } /** * @private */ function gregorianToWeek(gregObj) { var year = gregObj.year, month = gregObj.month, day = gregObj.day, ordinal = computeOrdinal(year, month, day), weekday = dayOfWeek(year, month, day); var weekNumber = Math.floor((ordinal - weekday + 10) / 7), weekYear; if (weekNumber < 1) { weekYear = year - 1; weekNumber = weeksInWeekYear(weekYear); } else if (weekNumber > weeksInWeekYear(year)) { weekYear = year + 1; weekNumber = 1; } else { weekYear = year; } return _extends({ weekYear: weekYear, weekNumber: weekNumber, weekday: weekday }, timeObject(gregObj)); } function weekToGregorian(weekData) { var weekYear = weekData.weekYear, weekNumber = weekData.weekNumber, weekday = weekData.weekday, weekdayOfJan4 = dayOfWeek(weekYear, 1, 4), yearInDays = daysInYear(weekYear); var ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 3, year; if (ordinal < 1) { year = weekYear - 1; ordinal += daysInYear(year); } else if (ordinal > yearInDays) { year = weekYear + 1; ordinal -= daysInYear(weekYear); } else { year = weekYear; } var _uncomputeOrdinal = uncomputeOrdinal(year, ordinal), month = _uncomputeOrdinal.month, day = _uncomputeOrdinal.day; return _extends({ year: year, month: month, day: day }, timeObject(weekData)); } function gregorianToOrdinal(gregData) { var year = gregData.year, month = gregData.month, day = gregData.day; var ordinal = computeOrdinal(year, month, day); return _extends({ year: year, ordinal: ordinal }, timeObject(gregData)); } function ordinalToGregorian(ordinalData) { var year = ordinalData.year, ordinal = ordinalData.ordinal; var _uncomputeOrdinal2 = uncomputeOrdinal(year, ordinal), month = _uncomputeOrdinal2.month, day = _uncomputeOrdinal2.day; return _extends({ year: year, month: month, day: day }, timeObject(ordinalData)); } function hasInvalidWeekData(obj) { var validYear = isInteger(obj.weekYear), validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear)), validWeekday = integerBetween(obj.weekday, 1, 7); if (!validYear) { return unitOutOfRange("weekYear", obj.weekYear); } else if (!validWeek) { return unitOutOfRange("week", obj.week); } else if (!validWeekday) { return unitOutOfRange("weekday", obj.weekday); } else return false; } function hasInvalidOrdinalData(obj) { var validYear = isInteger(obj.year), validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year)); if (!validYear) { return unitOutOfRange("year", obj.year); } else if (!validOrdinal) { return unitOutOfRange("ordinal", obj.ordinal); } else return false; } function hasInvalidGregorianData(obj) { var validYear = isInteger(obj.year), validMonth = integerBetween(obj.month, 1, 12), validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month)); if (!validYear) { return unitOutOfRange("year", obj.year); } else if (!validMonth) { return unitOutOfRange("month", obj.month); } else if (!validDay) { return unitOutOfRange("day", obj.day); } else return false; } function hasInvalidTimeData(obj) { var hour = obj.hour, minute = obj.minute, second = obj.second, millisecond = obj.millisecond; var validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0, validMinute = integerBetween(minute, 0, 59), validSecond = integerBetween(second, 0, 59), validMillisecond = integerBetween(millisecond, 0, 999); if (!validHour) { return unitOutOfRange("hour", hour); } else if (!validMinute) { return unitOutOfRange("minute", minute); } else if (!validSecond) { return unitOutOfRange("second", second); } else if (!validMillisecond) { return unitOutOfRange("millisecond", millisecond); } else return false; } var INVALID = "Invalid DateTime"; var MAX_DATE = 8.64e15; function unsupportedZone(zone) { return new Invalid("unsupported zone", "the zone \"" + zone.name + "\" is not supported"); } // we cache week data on the DT object and this intermediates the cache function possiblyCachedWeekData(dt) { if (dt.weekData === null) { dt.weekData = gregorianToWeek(dt.c); } return dt.weekData; } // clone really means, "make a new object with these modifications". all "setters" really use this // to create a new object while only changing some of the properties function clone(inst, alts) { var current = { ts: inst.ts, zone: inst.zone, c: inst.c, o: inst.o, loc: inst.loc, invalid: inst.invalid }; return new DateTime(_extends({}, current, alts, { old: current })); } // find the right offset a given local time. The o input is our guess, which determines which // offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST) function fixOffset(localTS, o, tz) { // Our UTC time is just a guess because our offset is just a guess var utcGuess = localTS - o * 60 * 1000; // Test whether the zone matches the offset for this ts var o2 = tz.offset(utcGuess); // If so, offset didn't change and we're done if (o === o2) { return [utcGuess, o]; } // If not, change the ts by the difference in the offset utcGuess -= (o2 - o) * 60 * 1000; // If that gives us the local time we want, we're done var o3 = tz.offset(utcGuess); if (o2 === o3) { return [utcGuess, o2]; } // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)]; } // convert an epoch timestamp into a calendar object with the given offset function tsToObj(ts, offset) { ts += offset * 60 * 1000; var d = new Date(ts); return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, day: d.getUTCDate(), hour: d.getUTCHours(), minute: d.getUTCMinutes(), second: d.getUTCSeconds(), millisecond: d.getUTCMilliseconds() }; } // convert a calendar object to a epoch timestamp function objToTS(obj, offset, zone) { return fixOffset(objToLocalTS(obj), offset, zone); } // create a new DT instance by adding a duration, adjusting for DSTs function adjustTime(inst, dur) { var oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c = _extends({}, inst.c, { year: year, month: month, day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7 }), millisToAdd = Duration.fromObject({ years: dur.years - Math.trunc(dur.years), quarters: dur.quarters - Math.trunc(dur.quarters), months: dur.months - Math.trunc(dur.months), weeks: dur.weeks - Math.trunc(dur.weeks), days: dur.days - Math.trunc(dur.days), hours: dur.hours, minutes: dur.minutes, seconds: dur.seconds, milliseconds: dur.milliseconds }).as("milliseconds"), localTS = objToLocalTS(c); var _fixOffset = fixOffset(localTS, oPre, inst.zone), ts = _fixOffset[0], o = _fixOffset[1]; if (millisToAdd !== 0) { ts += millisToAdd; // that could have changed the offset by going over a DST, but we want to keep the ts the same o = inst.zone.offset(ts); } return { ts: ts, o: o }; } // helper useful in turning the results of parsing into real dates // by handling the zone options function parseDataToDateTime(parsed, parsedZone, opts, format, text) { var setZone = opts.setZone, zone = opts.zone; if (parsed && Object.keys(parsed).length !== 0) { var interpretationZone = parsedZone || zone, inst = DateTime.fromObject(parsed, _extends({}, opts, { zone: interpretationZone })); return setZone ? inst : inst.setZone(zone); } else { return DateTime.invalid(new Invalid("unparsable", "the input \"" + text + "\" can't be parsed as " + format)); } } // if you want to output a technical format (e.g. RFC 2822), this helper // helps handle the details function toTechFormat(dt, format, allowZ) { if (allowZ === void 0) { allowZ = true; } return dt.isValid ? Formatter$1.create(Locale.create("en-US"), { allowZ: allowZ, forceSimple: true }).formatDateTimeFromString(dt, format) : null; } // technical time formats (e.g. the time part of ISO 8601), take some options // and this commonizes their handling function toTechTimeFormat(dt, _ref) { var _ref$suppressSeconds = _ref.suppressSeconds, suppressSeconds = _ref$suppressSeconds === void 0 ? false : _ref$suppressSeconds, _ref$suppressMillisec = _ref.suppressMilliseconds, suppressMilliseconds = _ref$suppressMillisec === void 0 ? false : _ref$suppressMillisec, includeOffset = _ref.includeOffset, _ref$includePrefix = _ref.includePrefix, includePrefix = _ref$includePrefix === void 0 ? false : _ref$includePrefix, _ref$includeZone = _ref.includeZone, includeZone = _ref$includeZone === void 0 ? false : _ref$includeZone, _ref$spaceZone = _ref.spaceZone, spaceZone = _ref$spaceZone === void 0 ? false : _ref$spaceZone, _ref$format = _ref.format, format = _ref$format === void 0 ? "extended" : _ref$format; var fmt = format === "basic" ? "HHmm" : "HH:mm"; if (!suppressSeconds || dt.second !== 0 || dt.millisecond !== 0) { fmt += format === "basic" ? "ss" : ":ss"; if (!suppressMilliseconds || dt.millisecond !== 0) { fmt += ".SSS"; } } if ((includeZone || includeOffset) && spaceZone) { fmt += " "; } if (includeZone) { fmt += "z"; } else if (includeOffset) { fmt += format === "basic" ? "ZZZ" : "ZZ"; } var str = toTechFormat(dt, fmt); if (includePrefix) { str = "T" + str; } return str; } // defaults for unspecified units in the supported calendars var defaultUnitValues = { month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }, defaultWeekUnitValues = { weekNumber: 1, weekday: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }, defaultOrdinalUnitValues = { ordinal: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }; // Units in the supported calendars, sorted by bigness var orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"], orderedWeekUnits = ["weekYear", "weekNumber", "weekday", "hour", "minute", "second", "millisecond"], orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; // standardize case and plurality in units function normalizeUnit(unit) { var normalized = { year: "year", years: "year", month: "month", months: "month", day: "day", days: "day", hour: "hour", hours: "hour", minute: "minute", minutes: "minute", quarter: "quarter", quarters: "quarter", second: "second", seconds: "second", millisecond: "millisecond", milliseconds: "millisecond", weekday: "weekday", weekdays: "weekday", weeknumber: "weekNumber", weeksnumber: "weekNumber", weeknumbers: "weekNumber", weekyear: "weekYear", weekyears: "weekYear", ordinal: "ordinal" }[unit.toLowerCase()]; if (!normalized) throw new InvalidUnitError(unit); return normalized; } // this is a dumbed down version of fromObject() that runs about 60% faster // but doesn't do any validation, makes a bunch of assumptions about what units // are present, and so on. // this is a dumbed down version of fromObject() that runs about 60% faster // but doesn't do any validation, makes a bunch of assumptions about what units // are present, and so on. function quickDT(obj, opts) { var zone = normalizeZone(opts.zone, Settings.defaultZone), loc = Locale.fromObject(opts), tsNow = Settings.now(); var ts, o; // assume we have the higher-order units if (!isUndefined$1(obj.year)) { for (var _iterator = _createForOfIteratorHelperLoose(orderedUnits), _step; !(_step = _iterator()).done;) { var u = _step.value; if (isUndefined$1(obj[u])) { obj[u] = defaultUnitValues[u]; } } var invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj); if (invalid) { return DateTime.invalid(invalid); } var offsetProvis = zone.offset(tsNow); var _objToTS = objToTS(obj, offsetProvis, zone); ts = _objToTS[0]; o = _objToTS[1]; } else { ts = tsNow; } return new DateTime({ ts: ts, zone: zone, loc: loc, o: o }); } function diffRelative(start, end, opts) { var round = isUndefined$1(opts.round) ? true : opts.round, format = function format(c, unit) { c = roundTo$1(c, round || opts.calendary ? 0 : 2, true); var formatter = end.loc.clone(opts).relFormatter(opts); return formatter.format(c, unit); }, differ = function differ(unit) { if (opts.calendary) { if (!end.hasSame(start, unit)) { return end.startOf(unit).diff(start.startOf(unit), unit).get(unit); } else return 0; } else { return end.diff(start, unit).get(unit); } }; if (opts.unit) { return format(differ(opts.unit), opts.unit); } for (var _iterator2 = _createForOfIteratorHelperLoose(opts.units), _step2; !(_step2 = _iterator2()).done;) { var unit = _step2.value; var count = differ(unit); if (Math.abs(count) >= 1) { return format(count, unit); } } return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]); } function lastOpts(argList) { var opts = {}, args; if (argList.length > 0 && typeof argList[argList.length - 1] === "object") { opts = argList[argList.length - 1]; args = Array.from(argList).slice(0, argList.length - 1); } else { args = Array.from(argList); } return [opts, args]; } /** * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them. * * A DateTime comprises of: * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch. * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone). * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`. * * Here is a brief overview of the most commonly used functionality it provides: * * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link DateTime.local}, {@link DateTime.utc}, and (most flexibly) {@link DateTime.fromObject}. To create one from a standard string format, use {@link DateTime.fromISO}, {@link DateTime.fromHTTP}, and {@link DateTime.fromRFC2822}. To create one from a custom string format, use {@link DateTime.fromFormat}. To create one from a native JS date, use {@link DateTime.fromJSDate}. * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link DateTime#toObject}), use the {@link DateTime#year}, {@link DateTime#month}, * {@link DateTime#day}, {@link DateTime#hour}, {@link DateTime#minute}, {@link DateTime#second}, {@link DateTime#millisecond} accessors. * * **Week calendar**: For ISO week calendar attributes, see the {@link DateTime#weekYear}, {@link DateTime#weekNumber}, and {@link DateTime#weekday} accessors. * * **Configuration** See the {@link DateTime#locale} and {@link DateTime#numberingSystem} accessors. * * **Transformation**: To transform the DateTime into other DateTimes, use {@link DateTime#set}, {@link DateTime#reconfigure}, {@link DateTime#setZone}, {@link DateTime#setLocale}, {@link DateTime.plus}, {@link DateTime#minus}, {@link DateTime#endOf}, {@link DateTime#startOf}, {@link DateTime#toUTC}, and {@link DateTime#toLocal}. * * **Output**: To convert the DateTime to other representations, use the {@link DateTime#toRelative}, {@link DateTime#toRelativeCalendar}, {@link DateTime#toJSON}, {@link DateTime#toISO}, {@link DateTime#toHTTP}, {@link DateTime#toObject}, {@link DateTime#toRFC2822}, {@link DateTime#toString}, {@link DateTime#toLocaleString}, {@link DateTime#toFormat}, {@link DateTime#toMillis} and {@link DateTime#toJSDate}. * * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation. */ var DateTime = /*#__PURE__*/function () { /** * @access private */ function DateTime(config) { var zone = config.zone || Settings.defaultZone; var invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null); /** * @access private */ this.ts = isUndefined$1(config.ts) ? Settings.now() : config.ts; var c = null, o = null; if (!invalid) { var unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); if (unchanged) { var _ref2 = [config.old.c, config.old.o]; c = _ref2[0]; o = _ref2[1]; } else { var ot = zone.offset(this.ts); c = tsToObj(this.ts, ot); invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null; c = invalid ? null : c; o = invalid ? null : ot; } } /** * @access private */ this._zone = zone; /** * @access private */ this.loc = config.loc || Locale.create(); /** * @access private */ this.invalid = invalid; /** * @access private */ this.weekData = null; /** * @access private */ this.c = c; /** * @access private */ this.o = o; /** * @access private */ this.isLuxonDateTime = true; } // CONSTRUCT /** * Create a DateTime for the current instant, in the system's time zone. * * Use Settings to override these default values if needed. * @example DateTime.now().toISO() //~> now in the ISO format * @return {DateTime} */ DateTime.now = function now() { return new DateTime({}); } /** * Create a local DateTime * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used * @param {number} [month=1] - The month, 1-indexed * @param {number} [day=1] - The day of the month, 1-indexed * @param {number} [hour=0] - The hour of the day, in 24-hour time * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59 * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59 * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999 * @example DateTime.local() //~> now * @example DateTime.local({ zone: "America/New_York" }) //~> now, in US east coast time * @example DateTime.local(2017) //~> 2017-01-01T00:00:00 * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00 * @example DateTime.local(2017, 3, 12, { locale: "fr" }) //~> 2017-03-12T00:00:00, with a French locale * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00 * @example DateTime.local(2017, 3, 12, 5, { zone: "utc" }) //~> 2017-03-12T05:00:00, in UTC * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00 * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10 * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765 * @return {DateTime} */ ; DateTime.local = function local() { var _lastOpts = lastOpts(arguments), opts = _lastOpts[0], args = _lastOpts[1], year = args[0], month = args[1], day = args[2], hour = args[3], minute = args[4], second = args[5], millisecond = args[6]; return quickDT({ year: year, month: month, day: day, hour: hour, minute: minute, second: second, millisecond: millisecond }, opts); } /** * Create a DateTime in UTC * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used * @param {number} [month=1] - The month, 1-indexed * @param {number} [day=1] - The day of the month * @param {number} [hour=0] - The hour of the day, in 24-hour time * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59 * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59 * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999 * @param {Object} options - configuration options for the DateTime * @param {string} [options.locale] - a locale to set on the resulting DateTime instance * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance * @example DateTime.utc() //~> now * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: "fr" }) //~> 2017-03-12T05:45:00Z with a French locale * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: "fr" }) //~> 2017-03-12T05:45:10.765Z with a French locale * @return {DateTime} */ ; DateTime.utc = function utc() { var _lastOpts2 = lastOpts(arguments), opts = _lastOpts2[0], args = _lastOpts2[1], year = args[0], month = args[1], day = args[2], hour = args[3], minute = args[4], second = args[5], millisecond = args[6]; opts.zone = FixedOffsetZone.utcInstance; return quickDT({ year: year, month: month, day: day, hour: hour, minute: minute, second: second, millisecond: millisecond }, opts); } /** * Create a DateTime from a JavaScript Date object. Uses the default zone. * @param {Date} date - a JavaScript Date object * @param {Object} options - configuration options for the DateTime * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into * @return {DateTime} */ ; DateTime.fromJSDate = function fromJSDate(date, options) { if (options === void 0) { options = {}; } var ts = isDate(date) ? date.valueOf() : NaN; if (Number.isNaN(ts)) { return DateTime.invalid("invalid input"); } var zoneToUse = normalizeZone(options.zone, Settings.defaultZone); if (!zoneToUse.isValid) { return DateTime.invalid(unsupportedZone(zoneToUse)); } return new DateTime({ ts: ts, zone: zoneToUse, loc: Locale.fromObject(options) }); } /** * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone. * @param {number} milliseconds - a number of milliseconds since 1970 UTC * @param {Object} options - configuration options for the DateTime * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into * @param {string} [options.locale] - a locale to set on the resulting DateTime instance * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance * @return {DateTime} */ ; DateTime.fromMillis = function fromMillis(milliseconds, options) { if (options === void 0) { options = {}; } if (!isNumber(milliseconds)) { throw new InvalidArgumentError("fromMillis requires a numerical input, but received a " + typeof milliseconds + " with value " + milliseconds); } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) { // this isn't perfect because because we can still end up out of range because of additional shifting, but it's a start return DateTime.invalid("Timestamp out of range"); } else { return new DateTime({ ts: milliseconds, zone: normalizeZone(options.zone, Settings.defaultZone), loc: Locale.fromObject(options) }); } } /** * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone. * @param {number} seconds - a number of seconds since 1970 UTC * @param {Object} options - configuration options for the DateTime * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into * @param {string} [options.locale] - a locale to set on the resulting DateTime instance * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance * @return {DateTime} */ ; DateTime.fromSeconds = function fromSeconds(seconds, options) { if (options === void 0) { options = {}; } if (!isNumber(seconds)) { throw new InvalidArgumentError("fromSeconds requires a numerical input"); } else { return new DateTime({ ts: seconds * 1000, zone: normalizeZone(options.zone, Settings.defaultZone), loc: Locale.fromObject(options) }); } } /** * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults. * @param {Object} obj - the object to create the DateTime from * @param {number} obj.year - a year, such as 1987 * @param {number} obj.month - a month, 1-12 * @param {number} obj.day - a day of the month, 1-31, depending on the month * @param {number} obj.ordinal - day of the year, 1-365 or 366 * @param {number} obj.weekYear - an ISO week year * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday * @param {number} obj.hour - hour of the day, 0-23 * @param {number} obj.minute - minute of the hour, 0-59 * @param {number} obj.second - second of the minute, 0-59 * @param {number} obj.millisecond - millisecond of the second, 0-999 * @param {Object} opts - options for creating this DateTime * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone() * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25' * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01' * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06 * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }), * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' }) * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' }) * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13' * @return {DateTime} */ ; DateTime.fromObject = function fromObject(obj, opts) { if (opts === void 0) { opts = {}; } obj = obj || {}; var zoneToUse = normalizeZone(opts.zone, Settings.defaultZone); if (!zoneToUse.isValid) { return DateTime.invalid(unsupportedZone(zoneToUse)); } var tsNow = Settings.now(), offsetProvis = zoneToUse.offset(tsNow), normalized = normalizeObject(obj, normalizeUnit), containsOrdinal = !isUndefined$1(normalized.ordinal), containsGregorYear = !isUndefined$1(normalized.year), containsGregorMD = !isUndefined$1(normalized.month) || !isUndefined$1(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber, loc = Locale.fromObject(opts); // cases: // just a weekday -> this week's instance of that weekday, no worries // (gregorian data or ordinal) + (weekYear or weekNumber) -> error // (gregorian month or day) + ordinal -> error // otherwise just use weeks or ordinals or gregorian, depending on what's specified if ((containsGregor || containsOrdinal) && definiteWeekDef) { throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals"); } if (containsGregorMD && containsOrdinal) { throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); } var useWeekData = definiteWeekDef || normalized.weekday && !containsGregor; // configure ourselves to deal with gregorian dates or week stuff var units, defaultValues, objNow = tsToObj(tsNow, offsetProvis); if (useWeekData) { units = orderedWeekUnits; defaultValues = defaultWeekUnitValues; objNow = gregorianToWeek(objNow); } else if (containsOrdinal) { units = orderedOrdinalUnits; defaultValues = defaultOrdinalUnitValues; objNow = gregorianToOrdinal(objNow); } else { units = orderedUnits; defaultValues = defaultUnitValues; } // set default values for missing stuff var foundFirst = false; for (var _iterator3 = _createForOfIteratorHelperLoose(units), _step3; !(_step3 = _iterator3()).done;) { var u = _step3.value; var v = normalized[u]; if (!isUndefined$1(v)) { foundFirst = true; } else if (foundFirst) { normalized[u] = defaultValues[u]; } else { normalized[u] = objNow[u]; } } // make sure the values we have are in range var higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid = higherOrderInvalid || hasInvalidTimeData(normalized); if (invalid) { return DateTime.invalid(invalid); } // compute the actual time var gregorian = useWeekData ? weekToGregorian(normalized) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, _objToTS2 = objToTS(gregorian, offsetProvis, zoneToUse), tsFinal = _objToTS2[0], offsetFinal = _objToTS2[1], inst = new DateTime({ ts: tsFinal, zone: zoneToUse, o: offsetFinal, loc: loc }); // gregorian data + weekday serves only to validate if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) { return DateTime.invalid("mismatched weekday", "you can't specify both a weekday of " + normalized.weekday + " and a date of " + inst.toISO()); } return inst; } /** * Create a DateTime from an ISO 8601 string * @param {string} text - the ISO string * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance * @example DateTime.fromISO('2016-05-25T09:08:34.123') * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00') * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true}) * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'}) * @example DateTime.fromISO('2016-W05-4') * @return {DateTime} */ ; DateTime.fromISO = function fromISO(text, opts) { if (opts === void 0) { opts = {}; } var _parseISODate = parseISODate(text), vals = _parseISODate[0], parsedZone = _parseISODate[1]; return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text); } /** * Create a DateTime from an RFC 2822 string * @param {string} text - the RFC 2822 string * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT') * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600') * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z') * @return {DateTime} */ ; DateTime.fromRFC2822 = function fromRFC2822(text, opts) { if (opts === void 0) { opts = {}; } var _parseRFC2822Date = parseRFC2822Date(text), vals = _parseRFC2822Date[0], parsedZone = _parseRFC2822Date[1]; return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text); } /** * Create a DateTime from an HTTP header date * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 * @param {string} text - the HTTP header date * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods. * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT') * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT') * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994') * @return {DateTime} */ ; DateTime.fromHTTP = function fromHTTP(text, opts) { if (opts === void 0) { opts = {}; } var _parseHTTPDate = parseHTTPDate(text), vals = _parseHTTPDate[0], parsedZone = _parseHTTPDate[1]; return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts); } /** * Create a DateTime from an input string and format string. * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens). * @param {string} text - the string to parse * @param {string} fmt - the format the string is expected to be in (see the link below for the formats) * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @return {DateTime} */ ; DateTime.fromFormat = function fromFormat(text, fmt, opts) { if (opts === void 0) { opts = {}; } if (isUndefined$1(text) || isUndefined$1(fmt)) { throw new InvalidArgumentError("fromFormat requires an input string and a format"); } var _opts = opts, _opts$locale = _opts.locale, locale = _opts$locale === void 0 ? null : _opts$locale, _opts$numberingSystem = _opts.numberingSystem, numberingSystem = _opts$numberingSystem === void 0 ? null : _opts$numberingSystem, localeToUse = Locale.fromOpts({ locale: locale, numberingSystem: numberingSystem, defaultToEN: true }), _parseFromTokens = parseFromTokens(localeToUse, text, fmt), vals = _parseFromTokens[0], parsedZone = _parseFromTokens[1], invalid = _parseFromTokens[2]; if (invalid) { return DateTime.invalid(invalid); } else { return parseDataToDateTime(vals, parsedZone, opts, "format " + fmt, text); } } /** * @deprecated use fromFormat instead */ ; DateTime.fromString = function fromString(text, fmt, opts) { if (opts === void 0) { opts = {}; } return DateTime.fromFormat(text, fmt, opts); } /** * Create a DateTime from a SQL date, time, or datetime * Defaults to en-US if no locale has been specified, regardless of the system's locale * @param {string} text - the string to parse * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @example DateTime.fromSQL('2017-05-15') * @example DateTime.fromSQL('2017-05-15 09:12:34') * @example DateTime.fromSQL('2017-05-15 09:12:34.342') * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00') * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles') * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true }) * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' }) * @example DateTime.fromSQL('09:12:34.342') * @return {DateTime} */ ; DateTime.fromSQL = function fromSQL(text, opts) { if (opts === void 0) { opts = {}; } var _parseSQL = parseSQL(text), vals = _parseSQL[0], parsedZone = _parseSQL[1]; return parseDataToDateTime(vals, parsedZone, opts, "SQL", text); } /** * Create an invalid DateTime. * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information * @return {DateTime} */ ; DateTime.invalid = function invalid(reason, explanation) { if (explanation === void 0) { explanation = null; } if (!reason) { throw new InvalidArgumentError("need to specify a reason the DateTime is invalid"); } var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); if (Settings.throwOnInvalid) { throw new InvalidDateTimeError(invalid); } else { return new DateTime({ invalid: invalid }); } } /** * Check if an object is a DateTime. Works across context boundaries * @param {object} o * @return {boolean} */ ; DateTime.isDateTime = function isDateTime(o) { return o && o.isLuxonDateTime || false; } // INFO /** * Get the value of unit. * @param {string} unit - a unit such as 'minute' or 'day' * @example DateTime.local(2017, 7, 4).get('month'); //=> 7 * @example DateTime.local(2017, 7, 4).get('day'); //=> 4 * @return {number} */ ; var _proto = DateTime.prototype; _proto.get = function get(unit) { return this[unit]; } /** * Returns whether the DateTime is valid. Invalid DateTimes occur when: * * The DateTime was created from invalid calendar information, such as the 13th month or February 30 * * The DateTime was created by an operation on another invalid date * @type {boolean} */ ; /** * Returns the resolved Intl options for this DateTime. * This is useful in understanding the behavior of formatting methods * @param {Object} opts - the same options as toLocaleString * @return {Object} */ _proto.resolvedLocaleOptions = function resolvedLocaleOptions(opts) { if (opts === void 0) { opts = {}; } var _Formatter$create$res = Formatter$1.create(this.loc.clone(opts), opts).resolvedOptions(this), locale = _Formatter$create$res.locale, numberingSystem = _Formatter$create$res.numberingSystem, calendar = _Formatter$create$res.calendar; return { locale: locale, numberingSystem: numberingSystem, outputCalendar: calendar }; } // TRANSFORM /** * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime. * * Equivalent to {@link DateTime.setZone}('utc') * @param {number} [offset=0] - optionally, an offset from UTC in minutes * @param {Object} [opts={}] - options to pass to `setZone()` * @return {DateTime} */ ; _proto.toUTC = function toUTC(offset, opts) { if (offset === void 0) { offset = 0; } if (opts === void 0) { opts = {}; } return this.setZone(FixedOffsetZone.instance(offset), opts); } /** * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime. * * Equivalent to `setZone('local')` * @return {DateTime} */ ; _proto.toLocal = function toLocal() { return this.setZone(Settings.defaultZone); } /** * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime. * * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime.plus}. You may wish to use {@link DateTime.toLocal} and {@link DateTime.toUTC} which provide simple convenience wrappers for commonly used zones. * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime.Zone} class. * @param {Object} opts - options * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this. * @return {DateTime} */ ; _proto.setZone = function setZone(zone, _temp) { var _ref3 = _temp === void 0 ? {} : _temp, _ref3$keepLocalTime = _ref3.keepLocalTime, keepLocalTime = _ref3$keepLocalTime === void 0 ? false : _ref3$keepLocalTime, _ref3$keepCalendarTim = _ref3.keepCalendarTime, keepCalendarTime = _ref3$keepCalendarTim === void 0 ? false : _ref3$keepCalendarTim; zone = normalizeZone(zone, Settings.defaultZone); if (zone.equals(this.zone)) { return this; } else if (!zone.isValid) { return DateTime.invalid(unsupportedZone(zone)); } else { var newTS = this.ts; if (keepLocalTime || keepCalendarTime) { var offsetGuess = zone.offset(this.ts); var asObj = this.toObject(); var _objToTS3 = objToTS(asObj, offsetGuess, zone); newTS = _objToTS3[0]; } return clone(this, { ts: newTS, zone: zone }); } } /** * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime. * @param {Object} properties - the properties to set * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' }) * @return {DateTime} */ ; _proto.reconfigure = function reconfigure(_temp2) { var _ref4 = _temp2 === void 0 ? {} : _temp2, locale = _ref4.locale, numberingSystem = _ref4.numberingSystem, outputCalendar = _ref4.outputCalendar; var loc = this.loc.clone({ locale: locale, numberingSystem: numberingSystem, outputCalendar: outputCalendar }); return clone(this, { loc: loc }); } /** * "Set" the locale. Returns a newly-constructed DateTime. * Just a convenient alias for reconfigure({ locale }) * @example DateTime.local(2017, 5, 25).setLocale('en-GB') * @return {DateTime} */ ; _proto.setLocale = function setLocale(locale) { return this.reconfigure({ locale: locale }); } /** * "Set" the values of specified units. Returns a newly-constructed DateTime. * You can only set units with this method; for "setting" metadata, see {@link DateTime.reconfigure} and {@link DateTime.setZone}. * @param {Object} values - a mapping of units to numbers * @example dt.set({ year: 2017 }) * @example dt.set({ hour: 8, minute: 30 }) * @example dt.set({ weekday: 5 }) * @example dt.set({ year: 2005, ordinal: 234 }) * @return {DateTime} */ ; _proto.set = function set(values) { if (!this.isValid) return this; var normalized = normalizeObject(values, normalizeUnit), settingWeekStuff = !isUndefined$1(normalized.weekYear) || !isUndefined$1(normalized.weekNumber) || !isUndefined$1(normalized.weekday), containsOrdinal = !isUndefined$1(normalized.ordinal), containsGregorYear = !isUndefined$1(normalized.year), containsGregorMD = !isUndefined$1(normalized.month) || !isUndefined$1(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber; if ((containsGregor || containsOrdinal) && definiteWeekDef) { throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals"); } if (containsGregorMD && containsOrdinal) { throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); } var mixed; if (settingWeekStuff) { mixed = weekToGregorian(_extends({}, gregorianToWeek(this.c), normalized)); } else if (!isUndefined$1(normalized.ordinal)) { mixed = ordinalToGregorian(_extends({}, gregorianToOrdinal(this.c), normalized)); } else { mixed = _extends({}, this.toObject(), normalized); // if we didn't set the day but we ended up on an overflow date, // use the last day of the right month if (isUndefined$1(normalized.day)) { mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day); } } var _objToTS4 = objToTS(mixed, this.o, this.zone), ts = _objToTS4[0], o = _objToTS4[1]; return clone(this, { ts: ts, o: o }); } /** * Add a period of time to this DateTime and return the resulting DateTime * * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between. * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() * @example DateTime.now().plus(123) //~> in 123 milliseconds * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min * @return {DateTime} */ ; _proto.plus = function plus(duration) { if (!this.isValid) return this; var dur = friendlyDuration(duration); return clone(this, adjustTime(this, dur)); } /** * Subtract a period of time to this DateTime and return the resulting DateTime * See {@link DateTime.plus} * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() @return {DateTime} */ ; _proto.minus = function minus(duration) { if (!this.isValid) return this; var dur = friendlyDuration(duration).negate(); return clone(this, adjustTime(this, dur)); } /** * "Set" this DateTime to the beginning of a unit of time. * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01' * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01' * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00' * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00' * @return {DateTime} */ ; _proto.startOf = function startOf(unit) { if (!this.isValid) return this; var o = {}, normalizedUnit = Duration.normalizeUnit(unit); switch (normalizedUnit) { case "years": o.month = 1; // falls through case "quarters": case "months": o.day = 1; // falls through case "weeks": case "days": o.hour = 0; // falls through case "hours": o.minute = 0; // falls through case "minutes": o.second = 0; // falls through case "seconds": o.millisecond = 0; break; // no default, invalid units throw in normalizeUnit() } if (normalizedUnit === "weeks") { o.weekday = 1; } if (normalizedUnit === "quarters") { var q = Math.ceil(this.month / 3); o.month = (q - 1) * 3 + 1; } return this.set(o); } /** * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00' * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00' * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00' * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00' * @return {DateTime} */ ; _proto.endOf = function endOf(unit) { var _this$plus; return this.isValid ? this.plus((_this$plus = {}, _this$plus[unit] = 1, _this$plus)).startOf(unit).minus(1) : this; } // OUTPUT /** * Returns a string representation of this DateTime formatted according to the specified format string. * **You may not want this.** See {@link DateTime.toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens). * Defaults to en-US if no locale has been specified, regardless of the system's locale. * @param {string} fmt - the format string * @param {Object} opts - opts to override the configuration options on this DateTime * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22' * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22' * @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22' * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes' * @return {string} */ ; _proto.toFormat = function toFormat(fmt, opts) { if (opts === void 0) { opts = {}; } return this.isValid ? Formatter$1.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID; } /** * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`. * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation * of the DateTime in the assigned locale. * Defaults to the system's locale if no locale has been specified * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options * @param {Object} opts - opts to override the configuration options on this DateTime * @example DateTime.now().toLocaleString(); //=> 4/20/2017 * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017' * @example DateTime.now().toLocaleString({ locale: 'en-gb' }); //=> '20/04/2017' * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017' * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM' * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM' * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20' * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM' * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32' * @return {string} */ ; _proto.toLocaleString = function toLocaleString(formatOpts, opts) { if (formatOpts === void 0) { formatOpts = DATE_SHORT; } if (opts === void 0) { opts = {}; } return this.isValid ? Formatter$1.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID; } /** * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output. * Defaults to the system's locale if no locale has been specified * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`. * @example DateTime.now().toLocaleParts(); //=> [ * //=> { type: 'day', value: '25' }, * //=> { type: 'literal', value: '/' }, * //=> { type: 'month', value: '05' }, * //=> { type: 'literal', value: '/' }, * //=> { type: 'year', value: '1982' } * //=> ] */ ; _proto.toLocaleParts = function toLocaleParts(opts) { if (opts === void 0) { opts = {}; } return this.isValid ? Formatter$1.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : []; } /** * Returns an ISO 8601-compliant string representation of this DateTime * @param {Object} opts - options * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @param {string} [opts.format='extended'] - choose between the basic and extended format * @example DateTime.utc(1982, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z' * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00' * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335' * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400' * @return {string} */ ; _proto.toISO = function toISO(opts) { if (opts === void 0) { opts = {}; } if (!this.isValid) { return null; } return this.toISODate(opts) + "T" + this.toISOTime(opts); } /** * Returns an ISO 8601-compliant string representation of this DateTime's date component * @param {Object} opts - options * @param {string} [opts.format='extended'] - choose between the basic and extended format * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25' * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525' * @return {string} */ ; _proto.toISODate = function toISODate(_temp3) { var _ref5 = _temp3 === void 0 ? {} : _temp3, _ref5$format = _ref5.format, format = _ref5$format === void 0 ? "extended" : _ref5$format; var fmt = format === "basic" ? "yyyyMMdd" : "yyyy-MM-dd"; if (this.year > 9999) { fmt = "+" + fmt; } return toTechFormat(this, fmt); } /** * Returns an ISO 8601-compliant string representation of this DateTime's week date * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2' * @return {string} */ ; _proto.toISOWeekDate = function toISOWeekDate() { return toTechFormat(this, "kkkk-'W'WW-c"); } /** * Returns an ISO 8601-compliant string representation of this DateTime's time component * @param {Object} opts - options * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @param {boolean} [opts.includePrefix=false] - include the `T` prefix * @param {string} [opts.format='extended'] - choose between the basic and extended format * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z' * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z' * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z' * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z' * @return {string} */ ; _proto.toISOTime = function toISOTime(_temp4) { var _ref6 = _temp4 === void 0 ? {} : _temp4, _ref6$suppressMillise = _ref6.suppressMilliseconds, suppressMilliseconds = _ref6$suppressMillise === void 0 ? false : _ref6$suppressMillise, _ref6$suppressSeconds = _ref6.suppressSeconds, suppressSeconds = _ref6$suppressSeconds === void 0 ? false : _ref6$suppressSeconds, _ref6$includeOffset = _ref6.includeOffset, includeOffset = _ref6$includeOffset === void 0 ? true : _ref6$includeOffset, _ref6$includePrefix = _ref6.includePrefix, includePrefix = _ref6$includePrefix === void 0 ? false : _ref6$includePrefix, _ref6$format = _ref6.format, format = _ref6$format === void 0 ? "extended" : _ref6$format; return toTechTimeFormat(this, { suppressSeconds: suppressSeconds, suppressMilliseconds: suppressMilliseconds, includeOffset: includeOffset, includePrefix: includePrefix, format: format }); } /** * Returns an RFC 2822-compatible string representation of this DateTime, always in UTC * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000' * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400' * @return {string} */ ; _proto.toRFC2822 = function toRFC2822() { return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false); } /** * Returns a string representation of this DateTime appropriate for use in HTTP headers. * Specifically, the string conforms to RFC 1123. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT' * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT' * @return {string} */ ; _proto.toHTTP = function toHTTP() { return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'"); } /** * Returns a string representation of this DateTime appropriate for use in SQL Date * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13' * @return {string} */ ; _proto.toSQLDate = function toSQLDate() { return toTechFormat(this, "yyyy-MM-dd"); } /** * Returns a string representation of this DateTime appropriate for use in SQL Time * @param {Object} opts - options * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @example DateTime.utc().toSQL() //=> '05:15:16.345' * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00' * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345' * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York' * @return {string} */ ; _proto.toSQLTime = function toSQLTime(_temp5) { var _ref7 = _temp5 === void 0 ? {} : _temp5, _ref7$includeOffset = _ref7.includeOffset, includeOffset = _ref7$includeOffset === void 0 ? true : _ref7$includeOffset, _ref7$includeZone = _ref7.includeZone, includeZone = _ref7$includeZone === void 0 ? false : _ref7$includeZone; return toTechTimeFormat(this, { includeOffset: includeOffset, includeZone: includeZone, spaceZone: true }); } /** * Returns a string representation of this DateTime appropriate for use in SQL DateTime * @param {Object} opts - options * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z' * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00' * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000' * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York' * @return {string} */ ; _proto.toSQL = function toSQL(opts) { if (opts === void 0) { opts = {}; } if (!this.isValid) { return null; } return this.toSQLDate() + " " + this.toSQLTime(opts); } /** * Returns a string representation of this DateTime appropriate for debugging * @return {string} */ ; _proto.toString = function toString() { return this.isValid ? this.toISO() : INVALID; } /** * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime.toMillis} * @return {number} */ ; _proto.valueOf = function valueOf() { return this.toMillis(); } /** * Returns the epoch milliseconds of this DateTime. * @return {number} */ ; _proto.toMillis = function toMillis() { return this.isValid ? this.ts : NaN; } /** * Returns the epoch seconds of this DateTime. * @return {number} */ ; _proto.toSeconds = function toSeconds() { return this.isValid ? this.ts / 1000 : NaN; } /** * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON. * @return {string} */ ; _proto.toJSON = function toJSON() { return this.toISO(); } /** * Returns a BSON serializable equivalent to this DateTime. * @return {Date} */ ; _proto.toBSON = function toBSON() { return this.toJSDate(); } /** * Returns a JavaScript object with this DateTime's year, month, day, and so on. * @param opts - options for generating the object * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 } * @return {Object} */ ; _proto.toObject = function toObject(opts) { if (opts === void 0) { opts = {}; } if (!this.isValid) return {}; var base = _extends({}, this.c); if (opts.includeConfig) { base.outputCalendar = this.outputCalendar; base.numberingSystem = this.loc.numberingSystem; base.locale = this.loc.locale; } return base; } /** * Returns a JavaScript Date equivalent to this DateTime. * @return {Date} */ ; _proto.toJSDate = function toJSDate() { return new Date(this.isValid ? this.ts : NaN); } // COMPARE /** * Return the difference between two DateTimes as a Duration. * @param {DateTime} otherDateTime - the DateTime to compare this one to * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration. * @param {Object} opts - options that affect the creation of the Duration * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @example * var i1 = DateTime.fromISO('1982-05-25T09:45'), * i2 = DateTime.fromISO('1983-10-14T10:30'); * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 } * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 } * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 } * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 } * @return {Duration} */ ; _proto.diff = function diff(otherDateTime, unit, opts) { if (unit === void 0) { unit = "milliseconds"; } if (opts === void 0) { opts = {}; } if (!this.isValid || !otherDateTime.isValid) { return Duration.invalid("created by diffing an invalid DateTime"); } var durOpts = _extends({ locale: this.locale, numberingSystem: this.numberingSystem }, opts); var units = maybeArray(unit).map(Duration.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = _diff(earlier, later, units, durOpts); return otherIsLater ? diffed.negate() : diffed; } /** * Return the difference between this DateTime and right now. * See {@link DateTime.diff} * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration * @param {Object} opts - options that affect the creation of the Duration * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @return {Duration} */ ; _proto.diffNow = function diffNow(unit, opts) { if (unit === void 0) { unit = "milliseconds"; } if (opts === void 0) { opts = {}; } return this.diff(DateTime.now(), unit, opts); } /** * Return an Interval spanning between this DateTime and another DateTime * @param {DateTime} otherDateTime - the other end point of the Interval * @return {Interval} */ ; _proto.until = function until(otherDateTime) { return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this; } /** * Return whether this DateTime is in the same unit of time as another DateTime. * Higher-order units must also be identical for this function to return `true`. * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime.setZone} to convert one of the dates if needed. * @param {DateTime} otherDateTime - the other DateTime * @param {string} unit - the unit of time to check sameness on * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day * @return {boolean} */ ; _proto.hasSame = function hasSame(otherDateTime, unit) { if (!this.isValid) return false; var inputMs = otherDateTime.valueOf(); var otherZoneDateTime = this.setZone(otherDateTime.zone, { keepLocalTime: true }); return otherZoneDateTime.startOf(unit) <= inputMs && inputMs <= otherZoneDateTime.endOf(unit); } /** * Equality check * Two DateTimes are equal iff they represent the same millisecond, have the same zone and location, and are both valid. * To compare just the millisecond values, use `+dt1 === +dt2`. * @param {DateTime} other - the other DateTime * @return {boolean} */ ; _proto.equals = function equals(other) { return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc); } /** * Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your * platform supports Intl.RelativeTimeFormat. Rounds down by default. * @param {Object} options - options that affect the output * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now. * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow" * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds" * @param {boolean} [options.round=true] - whether to round the numbers in the output. * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding. * @param {string} options.locale - override the locale of this DateTime * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this * @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day" * @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día" * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures" * @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago" * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago" * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago" */ ; _proto.toRelative = function toRelative(options) { if (options === void 0) { options = {}; } if (!this.isValid) return null; var base = options.base || DateTime.fromObject({}, { zone: this.zone }), padding = options.padding ? this < base ? -options.padding : options.padding : 0; var units = ["years", "months", "days", "hours", "minutes", "seconds"]; var unit = options.unit; if (Array.isArray(options.unit)) { units = options.unit; unit = undefined; } return diffRelative(base, this.plus(padding), _extends({}, options, { numeric: "always", units: units, unit: unit })); } /** * Returns a string representation of this date relative to today, such as "yesterday" or "next month". * Only internationalizes on platforms that supports Intl.RelativeTimeFormat. * @param {Object} options - options that affect the output * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now. * @param {string} options.locale - override the locale of this DateTime * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days" * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow" * @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana" * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain" * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago" */ ; _proto.toRelativeCalendar = function toRelativeCalendar(options) { if (options === void 0) { options = {}; } if (!this.isValid) return null; return diffRelative(options.base || DateTime.fromObject({}, { zone: this.zone }), this, _extends({}, options, { numeric: "auto", units: ["years", "months", "days"], calendary: true })); } /** * Return the min of several date times * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum * @return {DateTime} the min DateTime, or undefined if called with no argument */ ; DateTime.min = function min() { for (var _len = arguments.length, dateTimes = new Array(_len), _key = 0; _key < _len; _key++) { dateTimes[_key] = arguments[_key]; } if (!dateTimes.every(DateTime.isDateTime)) { throw new InvalidArgumentError("min requires all arguments be DateTimes"); } return bestBy(dateTimes, function (i) { return i.valueOf(); }, Math.min); } /** * Return the max of several date times * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum * @return {DateTime} the max DateTime, or undefined if called with no argument */ ; DateTime.max = function max() { for (var _len2 = arguments.length, dateTimes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { dateTimes[_key2] = arguments[_key2]; } if (!dateTimes.every(DateTime.isDateTime)) { throw new InvalidArgumentError("max requires all arguments be DateTimes"); } return bestBy(dateTimes, function (i) { return i.valueOf(); }, Math.max); } // MISC /** * Explain how a string would be parsed by fromFormat() * @param {string} text - the string to parse * @param {string} fmt - the format the string is expected to be in (see description) * @param {Object} options - options taken by fromFormat() * @return {Object} */ ; DateTime.fromFormatExplain = function fromFormatExplain(text, fmt, options) { if (options === void 0) { options = {}; } var _options = options, _options$locale = _options.locale, locale = _options$locale === void 0 ? null : _options$locale, _options$numberingSys = _options.numberingSystem, numberingSystem = _options$numberingSys === void 0 ? null : _options$numberingSys, localeToUse = Locale.fromOpts({ locale: locale, numberingSystem: numberingSystem, defaultToEN: true }); return explainFromTokens(localeToUse, text, fmt); } /** * @deprecated use fromFormatExplain instead */ ; DateTime.fromStringExplain = function fromStringExplain(text, fmt, options) { if (options === void 0) { options = {}; } return DateTime.fromFormatExplain(text, fmt, options); } // FORMAT PRESETS /** * {@link DateTime.toLocaleString} format like 10/14/1983 * @type {Object} */ ; _createClass(DateTime, [{ key: "isValid", get: function get() { return this.invalid === null; } /** * Returns an error code if this DateTime is invalid, or null if the DateTime is valid * @type {string} */ }, { key: "invalidReason", get: function get() { return this.invalid ? this.invalid.reason : null; } /** * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid * @type {string} */ }, { key: "invalidExplanation", get: function get() { return this.invalid ? this.invalid.explanation : null; } /** * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime * * @type {string} */ }, { key: "locale", get: function get() { return this.isValid ? this.loc.locale : null; } /** * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime * * @type {string} */ }, { key: "numberingSystem", get: function get() { return this.isValid ? this.loc.numberingSystem : null; } /** * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime * * @type {string} */ }, { key: "outputCalendar", get: function get() { return this.isValid ? this.loc.outputCalendar : null; } /** * Get the time zone associated with this DateTime. * @type {Zone} */ }, { key: "zone", get: function get() { return this._zone; } /** * Get the name of the time zone. * @type {string} */ }, { key: "zoneName", get: function get() { return this.isValid ? this.zone.name : null; } /** * Get the year * @example DateTime.local(2017, 5, 25).year //=> 2017 * @type {number} */ }, { key: "year", get: function get() { return this.isValid ? this.c.year : NaN; } /** * Get the quarter * @example DateTime.local(2017, 5, 25).quarter //=> 2 * @type {number} */ }, { key: "quarter", get: function get() { return this.isValid ? Math.ceil(this.c.month / 3) : NaN; } /** * Get the month (1-12). * @example DateTime.local(2017, 5, 25).month //=> 5 * @type {number} */ }, { key: "month", get: function get() { return this.isValid ? this.c.month : NaN; } /** * Get the day of the month (1-30ish). * @example DateTime.local(2017, 5, 25).day //=> 25 * @type {number} */ }, { key: "day", get: function get() { return this.isValid ? this.c.day : NaN; } /** * Get the hour of the day (0-23). * @example DateTime.local(2017, 5, 25, 9).hour //=> 9 * @type {number} */ }, { key: "hour", get: function get() { return this.isValid ? this.c.hour : NaN; } /** * Get the minute of the hour (0-59). * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30 * @type {number} */ }, { key: "minute", get: function get() { return this.isValid ? this.c.minute : NaN; } /** * Get the second of the minute (0-59). * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52 * @type {number} */ }, { key: "second", get: function get() { return this.isValid ? this.c.second : NaN; } /** * Get the millisecond of the second (0-999). * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654 * @type {number} */ }, { key: "millisecond", get: function get() { return this.isValid ? this.c.millisecond : NaN; } /** * Get the week year * @see https://en.wikipedia.org/wiki/ISO_week_date * @example DateTime.local(2014, 12, 31).weekYear //=> 2015 * @type {number} */ }, { key: "weekYear", get: function get() { return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN; } /** * Get the week number of the week year (1-52ish). * @see https://en.wikipedia.org/wiki/ISO_week_date * @example DateTime.local(2017, 5, 25).weekNumber //=> 21 * @type {number} */ }, { key: "weekNumber", get: function get() { return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN; } /** * Get the day of the week. * 1 is Monday and 7 is Sunday * @see https://en.wikipedia.org/wiki/ISO_week_date * @example DateTime.local(2014, 11, 31).weekday //=> 4 * @type {number} */ }, { key: "weekday", get: function get() { return this.isValid ? possiblyCachedWeekData(this).weekday : NaN; } /** * Get the ordinal (meaning the day of the year) * @example DateTime.local(2017, 5, 25).ordinal //=> 145 * @type {number|DateTime} */ }, { key: "ordinal", get: function get() { return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN; } /** * Get the human readable short month name, such as 'Oct'. * Defaults to the system's locale if no locale has been specified * @example DateTime.local(2017, 10, 30).monthShort //=> Oct * @type {string} */ }, { key: "monthShort", get: function get() { return this.isValid ? Info$1.months("short", { locObj: this.loc })[this.month - 1] : null; } /** * Get the human readable long month name, such as 'October'. * Defaults to the system's locale if no locale has been specified * @example DateTime.local(2017, 10, 30).monthLong //=> October * @type {string} */ }, { key: "monthLong", get: function get() { return this.isValid ? Info$1.months("long", { locObj: this.loc })[this.month - 1] : null; } /** * Get the human readable short weekday, such as 'Mon'. * Defaults to the system's locale if no locale has been specified * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon * @type {string} */ }, { key: "weekdayShort", get: function get() { return this.isValid ? Info$1.weekdays("short", { locObj: this.loc })[this.weekday - 1] : null; } /** * Get the human readable long weekday, such as 'Monday'. * Defaults to the system's locale if no locale has been specified * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday * @type {string} */ }, { key: "weekdayLong", get: function get() { return this.isValid ? Info$1.weekdays("long", { locObj: this.loc })[this.weekday - 1] : null; } /** * Get the UTC offset of this DateTime in minutes * @example DateTime.now().offset //=> -240 * @example DateTime.utc().offset //=> 0 * @type {number} */ }, { key: "offset", get: function get() { return this.isValid ? +this.o : NaN; } /** * Get the short human name for the zone's current offset, for example "EST" or "EDT". * Defaults to the system's locale if no locale has been specified * @type {string} */ }, { key: "offsetNameShort", get: function get() { if (this.isValid) { return this.zone.offsetName(this.ts, { format: "short", locale: this.locale }); } else { return null; } } /** * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time". * Defaults to the system's locale if no locale has been specified * @type {string} */ }, { key: "offsetNameLong", get: function get() { if (this.isValid) { return this.zone.offsetName(this.ts, { format: "long", locale: this.locale }); } else { return null; } } /** * Get whether this zone's offset ever changes, as in a DST. * @type {boolean} */ }, { key: "isOffsetFixed", get: function get() { return this.isValid ? this.zone.isUniversal : null; } /** * Get whether the DateTime is in a DST. * @type {boolean} */ }, { key: "isInDST", get: function get() { if (this.isOffsetFixed) { return false; } else { return this.offset > this.set({ month: 1 }).offset || this.offset > this.set({ month: 5 }).offset; } } /** * Returns true if this DateTime is in a leap year, false otherwise * @example DateTime.local(2016).isInLeapYear //=> true * @example DateTime.local(2013).isInLeapYear //=> false * @type {boolean} */ }, { key: "isInLeapYear", get: function get() { return isLeapYear(this.year); } /** * Returns the number of days in this DateTime's month * @example DateTime.local(2016, 2).daysInMonth //=> 29 * @example DateTime.local(2016, 3).daysInMonth //=> 31 * @type {number} */ }, { key: "daysInMonth", get: function get() { return daysInMonth(this.year, this.month); } /** * Returns the number of days in this DateTime's year * @example DateTime.local(2016).daysInYear //=> 366 * @example DateTime.local(2013).daysInYear //=> 365 * @type {number} */ }, { key: "daysInYear", get: function get() { return this.isValid ? daysInYear(this.year) : NaN; } /** * Returns the number of weeks in this DateTime's year * @see https://en.wikipedia.org/wiki/ISO_week_date * @example DateTime.local(2004).weeksInWeekYear //=> 53 * @example DateTime.local(2013).weeksInWeekYear //=> 52 * @type {number} */ }, { key: "weeksInWeekYear", get: function get() { return this.isValid ? weeksInWeekYear(this.weekYear) : NaN; } }], [{ key: "DATE_SHORT", get: function get() { return DATE_SHORT; } /** * {@link DateTime.toLocaleString} format like 'Oct 14, 1983' * @type {Object} */ }, { key: "DATE_MED", get: function get() { return DATE_MED; } /** * {@link DateTime.toLocaleString} format like 'Fri, Oct 14, 1983' * @type {Object} */ }, { key: "DATE_MED_WITH_WEEKDAY", get: function get() { return DATE_MED_WITH_WEEKDAY; } /** * {@link DateTime.toLocaleString} format like 'October 14, 1983' * @type {Object} */ }, { key: "DATE_FULL", get: function get() { return DATE_FULL; } /** * {@link DateTime.toLocaleString} format like 'Tuesday, October 14, 1983' * @type {Object} */ }, { key: "DATE_HUGE", get: function get() { return DATE_HUGE; } /** * {@link DateTime.toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "TIME_SIMPLE", get: function get() { return TIME_SIMPLE; } /** * {@link DateTime.toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "TIME_WITH_SECONDS", get: function get() { return TIME_WITH_SECONDS; } /** * {@link DateTime.toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "TIME_WITH_SHORT_OFFSET", get: function get() { return TIME_WITH_SHORT_OFFSET; } /** * {@link DateTime.toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "TIME_WITH_LONG_OFFSET", get: function get() { return TIME_WITH_LONG_OFFSET; } /** * {@link DateTime.toLocaleString} format like '09:30', always 24-hour. * @type {Object} */ }, { key: "TIME_24_SIMPLE", get: function get() { return TIME_24_SIMPLE; } /** * {@link DateTime.toLocaleString} format like '09:30:23', always 24-hour. * @type {Object} */ }, { key: "TIME_24_WITH_SECONDS", get: function get() { return TIME_24_WITH_SECONDS; } /** * {@link DateTime.toLocaleString} format like '09:30:23 EDT', always 24-hour. * @type {Object} */ }, { key: "TIME_24_WITH_SHORT_OFFSET", get: function get() { return TIME_24_WITH_SHORT_OFFSET; } /** * {@link DateTime.toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour. * @type {Object} */ }, { key: "TIME_24_WITH_LONG_OFFSET", get: function get() { return TIME_24_WITH_LONG_OFFSET; } /** * {@link DateTime.toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_SHORT", get: function get() { return DATETIME_SHORT; } /** * {@link DateTime.toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_SHORT_WITH_SECONDS", get: function get() { return DATETIME_SHORT_WITH_SECONDS; } /** * {@link DateTime.toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_MED", get: function get() { return DATETIME_MED; } /** * {@link DateTime.toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_MED_WITH_SECONDS", get: function get() { return DATETIME_MED_WITH_SECONDS; } /** * {@link DateTime.toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_MED_WITH_WEEKDAY", get: function get() { return DATETIME_MED_WITH_WEEKDAY; } /** * {@link DateTime.toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_FULL", get: function get() { return DATETIME_FULL; } /** * {@link DateTime.toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_FULL_WITH_SECONDS", get: function get() { return DATETIME_FULL_WITH_SECONDS; } /** * {@link DateTime.toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_HUGE", get: function get() { return DATETIME_HUGE; } /** * {@link DateTime.toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is. * @type {Object} */ }, { key: "DATETIME_HUGE_WITH_SECONDS", get: function get() { return DATETIME_HUGE_WITH_SECONDS; } }]); return DateTime; }(); function friendlyDateTime(dateTimeish) { if (DateTime.isDateTime(dateTimeish)) { return dateTimeish; } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) { return DateTime.fromJSDate(dateTimeish); } else if (dateTimeish && typeof dateTimeish === "object") { return DateTime.fromObject(dateTimeish); } else { throw new InvalidArgumentError("Unknown datetime argument: " + dateTimeish + ", of type " + typeof dateTimeish); } } var VERSION = "2.0.2"; var DateTime_1 = luxon.DateTime = DateTime; var Duration_1 = luxon.Duration = Duration; luxon.FixedOffsetZone = FixedOffsetZone; luxon.IANAZone = IANAZone; luxon.Info = Info$1; luxon.Interval = Interval; luxon.InvalidZone = InvalidZone; luxon.Settings = Settings; luxon.SystemZone = SystemZone; luxon.VERSION = VERSION; luxon.Zone = Zone; const UserInfoContext = React$2.createContext({ loggedIn: false, email: null, modMode: false, projectId: null, userId: null, activated: false, readOnly: true, emailVerifyCanceled: null, emailVerified: null, twoFactorActive: false, deleteAfter: null, }); const UserInfoProvider = ({ children }) => { const { data: wireUserInfo } = trpc.login.loggedIn.useQuery(undefined, { refetchInterval: false, refetchOnReconnect: false, refetchOnWindowFocus: false, refetchIntervalInBackground: false, suspense: true, notifyOnChangeProps: ["data", "error"], }); // convert delete-after from string to date object let userInfo; if (wireUserInfo && wireUserInfo.loggedIn) { userInfo = { ...wireUserInfo, deleteAfter: wireUserInfo.deleteAfter ? DateTime_1.fromISO(wireUserInfo.deleteAfter) : null, }; } else if (wireUserInfo) { userInfo = wireUserInfo; } const updateContext = index_browserExports.useUnleashContext() ; /** * refresh if we log out or the active project/user changes. * this helps prevent stale requests from going out, helping prevent * unintended behavior for users and keeping things Fresh. * we don't reload on `logged out -> logged in` b/c on the subdomain this * defaults to logged out and we would just reload every time. */ const previousUserInfo = usePrevious(userInfo); reactExports.useEffect(() => { // type check to logged in if (userInfo?.loggedIn === true) { if (previousUserInfo?.loggedIn) { if ( userInfo.projectId !== previousUserInfo.projectId || userInfo.userId !== previousUserInfo.userId ) { // we're someone else! refresh window.location.reload(); } } } else { if (previousUserInfo?.loggedIn) { // we logged out! refresh window.location.reload(); } } }, [ previousUserInfo, previousUserInfo?.loggedIn, userInfo?.loggedIn, userInfo?.projectId, userInfo?.userId, ]); reactExports.useEffect(() => { reactExports.startTransition(() => { void updateContext({ userId: userInfo?.loggedIn ? userInfo.userId.toString() ?? undefined : undefined, }); }); }, [updateContext, userInfo, userInfo?.loggedIn]); return ( // we're using `suspense: true` in the fetcher so userInfo will never // actually be undefined. // we can only get away with this b/c we're pre-fetching in the server! React$2.createElement(UserInfoContext.Provider, { value: userInfo,} , children ) ); }; const useUserInfo = () => reactExports.useContext(UserInfoContext); const useRequiresLogin = () => { const userInfo = useUserInfo(); const location = useLocation(); if (!userInfo.loggedIn) { throw new RequiresLoginError("Requires login", location.pathname); } }; // ensure the broken attachment icon actually gets its hash icon in /static/ const App = ({ children, }) => { const siteConfig = loadJSONFromID( ClientStateID$1.SITE_CONFIG ); const initialI18nStore = loadJSONFromID( ClientStateID$1.INITIAL_I18N_STORE ); const initialLanguage = loadJSONFromID( ClientStateID$1.INITIAL_LANGUAGE ); const flashes = loadJSONFromID( ClientStateID$1.FLASHES ); const rollbarConfig = loadJSONFromID( ClientStateID$1.ROLLBAR_CONFIG ); const unleashBootstrap = loadJSONFromID( ClientStateID$1.UNLEASH_BOOTSTRAP ); const mutableStore = loadJSONFromID( ClientStateID$1.INITIAL_MUTABLE_STORE ); const unleashConfig = { appName: siteConfig.UNLEASH_APP_NAME, url: sitemap.public.unleashProxy().toString(), clientKey: siteConfig.UNLEASH_CLIENT_KEY, bootstrap: unleashBootstrap, disableRefresh: true, }; const dehyrdatedState = loadJSONFromID(ClientStateID$1.TRPC_DEHYRDATED_STATE); useSSR$1(initialI18nStore, initialLanguage); const [queryClient] = reactExports.useState(() => new QueryClient()); const [trpcClient] = reactExports.useState(() => trpc.createClient({ links: [ httpBatchLink({ url: sitemap.public.apiV1.trpc().toString(), maxURLLength: 2083, fetch(url, options) { return fetch(url, { ...options, credentials: "include", }); }, }), ], }) ); return ( React$2.createElement(React$2.StrictMode, null , React$2.createElement(trpc.Provider, { client: trpcClient, queryClient: queryClient,} , React$2.createElement(QueryClientProvider, { client: queryClient,} , React$2.createElement(Hydrate, { state: dehyrdatedState,} , React$2.createElement(HelmetProvider, null , React$2.createElement(RollbarProvider, { config: rollbarConfig,} , React$2.createElement(FlagsProvider, { config: unleashConfig,} , React$2.createElement(UserInfoProvider, null , React$2.createElement(FlashesProvider.Provider, { value: flashes,} , React$2.createElement(SiteConfigProvider.Provider, { value: siteConfig,} , React$2.createElement(ReqMutableStoreProvider, { store: mutableStore,} , children ) ) ) ) ) ) ) ) ) ) ) ); }; var createPlugin$2 = {}; var createPlugin$1 = {}; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "default", { enumerable: true, get: function() { return _default; } }); function createPlugin(plugin, config) { return { handler: plugin, config }; } createPlugin.withOptions = function(pluginFunction, configFunction = ()=>({})) { const optionsFunction = function(options) { return { __options: options, handler: pluginFunction(options), config: configFunction(options) }; }; optionsFunction.__isOptionsFunction = true; // Expose plugin dependencies so that `object-hash` returns a different // value if anything here changes, to ensure a rebuild is triggered. optionsFunction.__pluginFunction = pluginFunction; optionsFunction.__configFunction = configFunction; return optionsFunction; }; const _default = createPlugin; } (createPlugin$1)); (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "default", { enumerable: true, get: function() { return _default; } }); const _createPlugin = /*#__PURE__*/ _interop_require_default(createPlugin$1); function _interop_require_default(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const _default = _createPlugin.default; } (createPlugin$2)); let createPlugin = createPlugin$2; var plugin$3 = (createPlugin.__esModule ? createPlugin : { default: createPlugin }).default; var colors$2 = {}; var log$1 = {}; var picocolors_browser = {exports: {}}; var x$5=String; var create$1=function() {return {isColorSupported:false,reset:x$5,bold:x$5,dim:x$5,italic:x$5,underline:x$5,inverse:x$5,hidden:x$5,strikethrough:x$5,black:x$5,red:x$5,green:x$5,yellow:x$5,blue:x$5,magenta:x$5,cyan:x$5,white:x$5,gray:x$5,bgBlack:x$5,bgRed:x$5,bgGreen:x$5,bgYellow:x$5,bgBlue:x$5,bgMagenta:x$5,bgCyan:x$5,bgWhite:x$5}}; picocolors_browser.exports=create$1(); picocolors_browser.exports.createColors = create$1; var picocolors_browserExports = picocolors_browser.exports; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); function _export(target, all) { for(var name in all)Object.defineProperty(target, name, { enumerable: true, get: all[name] }); } _export(exports, { dim: function() { return dim; }, default: function() { return _default; } }); const _picocolors = /*#__PURE__*/ _interop_require_default(picocolors_browserExports); function _interop_require_default(obj) { return obj && obj.__esModule ? obj : { default: obj }; } let alreadyShown = new Set(); function log(type, messages, key) { if (typeof process !== "undefined" && process.env.JEST_WORKER_ID) return; if (key && alreadyShown.has(key)) return; if (key) alreadyShown.add(key); console.warn(""); messages.forEach((message)=>console.warn(type, "-", message)); } function dim(input) { return _picocolors.default.dim(input); } const _default = { info (key, messages) { log(_picocolors.default.bold(_picocolors.default.cyan("info")), ...Array.isArray(key) ? [ key ] : [ messages, key ]); }, warn (key, messages) { log(_picocolors.default.bold(_picocolors.default.yellow("warn")), ...Array.isArray(key) ? [ key ] : [ messages, key ]); }, risk (key, messages) { log(_picocolors.default.bold(_picocolors.default.magenta("risk")), ...Array.isArray(key) ? [ key ] : [ messages, key ]); } }; } (log$1)); (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "default", { enumerable: true, get: function() { return _default; } }); const _log = /*#__PURE__*/ _interop_require_default(log$1); function _interop_require_default(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function warn({ version , from , to }) { _log.default.warn(`${from}-color-renamed`, [ `As of Tailwind CSS ${version}, \`${from}\` has been renamed to \`${to}\`.`, "Update your configuration file to silence this warning." ]); } const _default = { inherit: "inherit", current: "currentColor", transparent: "transparent", black: "#000", white: "#fff", slate: { 50: "#f8fafc", 100: "#f1f5f9", 200: "#e2e8f0", 300: "#cbd5e1", 400: "#94a3b8", 500: "#64748b", 600: "#475569", 700: "#334155", 800: "#1e293b", 900: "#0f172a", 950: "#020617" }, gray: { 50: "#f9fafb", 100: "#f3f4f6", 200: "#e5e7eb", 300: "#d1d5db", 400: "#9ca3af", 500: "#6b7280", 600: "#4b5563", 700: "#374151", 800: "#1f2937", 900: "#111827", 950: "#030712" }, zinc: { 50: "#fafafa", 100: "#f4f4f5", 200: "#e4e4e7", 300: "#d4d4d8", 400: "#a1a1aa", 500: "#71717a", 600: "#52525b", 700: "#3f3f46", 800: "#27272a", 900: "#18181b", 950: "#09090b" }, neutral: { 50: "#fafafa", 100: "#f5f5f5", 200: "#e5e5e5", 300: "#d4d4d4", 400: "#a3a3a3", 500: "#737373", 600: "#525252", 700: "#404040", 800: "#262626", 900: "#171717", 950: "#0a0a0a" }, stone: { 50: "#fafaf9", 100: "#f5f5f4", 200: "#e7e5e4", 300: "#d6d3d1", 400: "#a8a29e", 500: "#78716c", 600: "#57534e", 700: "#44403c", 800: "#292524", 900: "#1c1917", 950: "#0c0a09" }, red: { 50: "#fef2f2", 100: "#fee2e2", 200: "#fecaca", 300: "#fca5a5", 400: "#f87171", 500: "#ef4444", 600: "#dc2626", 700: "#b91c1c", 800: "#991b1b", 900: "#7f1d1d", 950: "#450a0a" }, orange: { 50: "#fff7ed", 100: "#ffedd5", 200: "#fed7aa", 300: "#fdba74", 400: "#fb923c", 500: "#f97316", 600: "#ea580c", 700: "#c2410c", 800: "#9a3412", 900: "#7c2d12", 950: "#431407" }, amber: { 50: "#fffbeb", 100: "#fef3c7", 200: "#fde68a", 300: "#fcd34d", 400: "#fbbf24", 500: "#f59e0b", 600: "#d97706", 700: "#b45309", 800: "#92400e", 900: "#78350f", 950: "#451a03" }, yellow: { 50: "#fefce8", 100: "#fef9c3", 200: "#fef08a", 300: "#fde047", 400: "#facc15", 500: "#eab308", 600: "#ca8a04", 700: "#a16207", 800: "#854d0e", 900: "#713f12", 950: "#422006" }, lime: { 50: "#f7fee7", 100: "#ecfccb", 200: "#d9f99d", 300: "#bef264", 400: "#a3e635", 500: "#84cc16", 600: "#65a30d", 700: "#4d7c0f", 800: "#3f6212", 900: "#365314", 950: "#1a2e05" }, green: { 50: "#f0fdf4", 100: "#dcfce7", 200: "#bbf7d0", 300: "#86efac", 400: "#4ade80", 500: "#22c55e", 600: "#16a34a", 700: "#15803d", 800: "#166534", 900: "#14532d", 950: "#052e16" }, emerald: { 50: "#ecfdf5", 100: "#d1fae5", 200: "#a7f3d0", 300: "#6ee7b7", 400: "#34d399", 500: "#10b981", 600: "#059669", 700: "#047857", 800: "#065f46", 900: "#064e3b", 950: "#022c22" }, teal: { 50: "#f0fdfa", 100: "#ccfbf1", 200: "#99f6e4", 300: "#5eead4", 400: "#2dd4bf", 500: "#14b8a6", 600: "#0d9488", 700: "#0f766e", 800: "#115e59", 900: "#134e4a", 950: "#042f2e" }, cyan: { 50: "#ecfeff", 100: "#cffafe", 200: "#a5f3fc", 300: "#67e8f9", 400: "#22d3ee", 500: "#06b6d4", 600: "#0891b2", 700: "#0e7490", 800: "#155e75", 900: "#164e63", 950: "#083344" }, sky: { 50: "#f0f9ff", 100: "#e0f2fe", 200: "#bae6fd", 300: "#7dd3fc", 400: "#38bdf8", 500: "#0ea5e9", 600: "#0284c7", 700: "#0369a1", 800: "#075985", 900: "#0c4a6e", 950: "#082f49" }, blue: { 50: "#eff6ff", 100: "#dbeafe", 200: "#bfdbfe", 300: "#93c5fd", 400: "#60a5fa", 500: "#3b82f6", 600: "#2563eb", 700: "#1d4ed8", 800: "#1e40af", 900: "#1e3a8a", 950: "#172554" }, indigo: { 50: "#eef2ff", 100: "#e0e7ff", 200: "#c7d2fe", 300: "#a5b4fc", 400: "#818cf8", 500: "#6366f1", 600: "#4f46e5", 700: "#4338ca", 800: "#3730a3", 900: "#312e81", 950: "#1e1b4b" }, violet: { 50: "#f5f3ff", 100: "#ede9fe", 200: "#ddd6fe", 300: "#c4b5fd", 400: "#a78bfa", 500: "#8b5cf6", 600: "#7c3aed", 700: "#6d28d9", 800: "#5b21b6", 900: "#4c1d95", 950: "#2e1065" }, purple: { 50: "#faf5ff", 100: "#f3e8ff", 200: "#e9d5ff", 300: "#d8b4fe", 400: "#c084fc", 500: "#a855f7", 600: "#9333ea", 700: "#7e22ce", 800: "#6b21a8", 900: "#581c87", 950: "#3b0764" }, fuchsia: { 50: "#fdf4ff", 100: "#fae8ff", 200: "#f5d0fe", 300: "#f0abfc", 400: "#e879f9", 500: "#d946ef", 600: "#c026d3", 700: "#a21caf", 800: "#86198f", 900: "#701a75", 950: "#4a044e" }, pink: { 50: "#fdf2f8", 100: "#fce7f3", 200: "#fbcfe8", 300: "#f9a8d4", 400: "#f472b6", 500: "#ec4899", 600: "#db2777", 700: "#be185d", 800: "#9d174d", 900: "#831843", 950: "#500724" }, rose: { 50: "#fff1f2", 100: "#ffe4e6", 200: "#fecdd3", 300: "#fda4af", 400: "#fb7185", 500: "#f43f5e", 600: "#e11d48", 700: "#be123c", 800: "#9f1239", 900: "#881337", 950: "#4c0519" }, get lightBlue () { warn({ version: "v2.2", from: "lightBlue", to: "sky" }); return this.sky; }, get warmGray () { warn({ version: "v3.0", from: "warmGray", to: "stone" }); return this.stone; }, get trueGray () { warn({ version: "v3.0", from: "trueGray", to: "neutral" }); return this.neutral; }, get coolGray () { warn({ version: "v3.0", from: "coolGray", to: "gray" }); return this.gray; }, get blueGray () { warn({ version: "v3.0", from: "blueGray", to: "slate" }); return this.slate; } }; } (colors$2)); let colors$1 = colors$2; (colors$1.__esModule ? colors$1 : { default: colors$1 }).default; var defaultTheme$2 = {}; var cloneDeep = {}; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "cloneDeep", { enumerable: true, get: function() { return cloneDeep; } }); function cloneDeep(value) { if (Array.isArray(value)) { return value.map((child)=>cloneDeep(child)); } if (typeof value === "object" && value !== null) { return Object.fromEntries(Object.entries(value).map(([k, v])=>[ k, cloneDeep(v) ])); } return value; } } (cloneDeep)); var config_full = { content: [], presets: [], darkMode: 'media', // or 'class' theme: { accentColor: ({ theme }) => ({ ...theme('colors'), auto: 'auto', }), animation: { none: 'none', spin: 'spin 1s linear infinite', ping: 'ping 1s cubic-bezier(0, 0, 0.2, 1) infinite', pulse: 'pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite', bounce: 'bounce 1s infinite', }, aria: { busy: 'busy="true"', checked: 'checked="true"', disabled: 'disabled="true"', expanded: 'expanded="true"', hidden: 'hidden="true"', pressed: 'pressed="true"', readonly: 'readonly="true"', required: 'required="true"', selected: 'selected="true"', }, aspectRatio: { auto: 'auto', square: '1 / 1', video: '16 / 9', }, backdropBlur: ({ theme }) => theme('blur'), backdropBrightness: ({ theme }) => theme('brightness'), backdropContrast: ({ theme }) => theme('contrast'), backdropGrayscale: ({ theme }) => theme('grayscale'), backdropHueRotate: ({ theme }) => theme('hueRotate'), backdropInvert: ({ theme }) => theme('invert'), backdropOpacity: ({ theme }) => theme('opacity'), backdropSaturate: ({ theme }) => theme('saturate'), backdropSepia: ({ theme }) => theme('sepia'), backgroundColor: ({ theme }) => theme('colors'), backgroundImage: { none: 'none', 'gradient-to-t': 'linear-gradient(to top, var(--tw-gradient-stops))', 'gradient-to-tr': 'linear-gradient(to top right, var(--tw-gradient-stops))', 'gradient-to-r': 'linear-gradient(to right, var(--tw-gradient-stops))', 'gradient-to-br': 'linear-gradient(to bottom right, var(--tw-gradient-stops))', 'gradient-to-b': 'linear-gradient(to bottom, var(--tw-gradient-stops))', 'gradient-to-bl': 'linear-gradient(to bottom left, var(--tw-gradient-stops))', 'gradient-to-l': 'linear-gradient(to left, var(--tw-gradient-stops))', 'gradient-to-tl': 'linear-gradient(to top left, var(--tw-gradient-stops))', }, backgroundOpacity: ({ theme }) => theme('opacity'), backgroundPosition: { bottom: 'bottom', center: 'center', left: 'left', 'left-bottom': 'left bottom', 'left-top': 'left top', right: 'right', 'right-bottom': 'right bottom', 'right-top': 'right top', top: 'top', }, backgroundSize: { auto: 'auto', cover: 'cover', contain: 'contain', }, blur: { 0: '0', none: '0', sm: '4px', DEFAULT: '8px', md: '12px', lg: '16px', xl: '24px', '2xl': '40px', '3xl': '64px', }, borderColor: ({ theme }) => ({ ...theme('colors'), DEFAULT: theme('colors.gray.200', 'currentColor'), }), borderOpacity: ({ theme }) => theme('opacity'), borderRadius: { none: '0px', sm: '0.125rem', DEFAULT: '0.25rem', md: '0.375rem', lg: '0.5rem', xl: '0.75rem', '2xl': '1rem', '3xl': '1.5rem', full: '9999px', }, borderSpacing: ({ theme }) => ({ ...theme('spacing'), }), borderWidth: { DEFAULT: '1px', 0: '0px', 2: '2px', 4: '4px', 8: '8px', }, boxShadow: { sm: '0 1px 2px 0 rgb(0 0 0 / 0.05)', DEFAULT: '0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)', md: '0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)', lg: '0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)', xl: '0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)', '2xl': '0 25px 50px -12px rgb(0 0 0 / 0.25)', inner: 'inset 0 2px 4px 0 rgb(0 0 0 / 0.05)', none: 'none', }, boxShadowColor: ({ theme }) => theme('colors'), brightness: { 0: '0', 50: '.5', 75: '.75', 90: '.9', 95: '.95', 100: '1', 105: '1.05', 110: '1.1', 125: '1.25', 150: '1.5', 200: '2', }, caretColor: ({ theme }) => theme('colors'), colors: ({ colors }) => ({ inherit: colors.inherit, current: colors.current, transparent: colors.transparent, black: colors.black, white: colors.white, slate: colors.slate, gray: colors.gray, zinc: colors.zinc, neutral: colors.neutral, stone: colors.stone, red: colors.red, orange: colors.orange, amber: colors.amber, yellow: colors.yellow, lime: colors.lime, green: colors.green, emerald: colors.emerald, teal: colors.teal, cyan: colors.cyan, sky: colors.sky, blue: colors.blue, indigo: colors.indigo, violet: colors.violet, purple: colors.purple, fuchsia: colors.fuchsia, pink: colors.pink, rose: colors.rose, }), columns: { auto: 'auto', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '10', 11: '11', 12: '12', '3xs': '16rem', '2xs': '18rem', xs: '20rem', sm: '24rem', md: '28rem', lg: '32rem', xl: '36rem', '2xl': '42rem', '3xl': '48rem', '4xl': '56rem', '5xl': '64rem', '6xl': '72rem', '7xl': '80rem', }, container: {}, content: { none: 'none', }, contrast: { 0: '0', 50: '.5', 75: '.75', 100: '1', 125: '1.25', 150: '1.5', 200: '2', }, cursor: { auto: 'auto', default: 'default', pointer: 'pointer', wait: 'wait', text: 'text', move: 'move', help: 'help', 'not-allowed': 'not-allowed', none: 'none', 'context-menu': 'context-menu', progress: 'progress', cell: 'cell', crosshair: 'crosshair', 'vertical-text': 'vertical-text', alias: 'alias', copy: 'copy', 'no-drop': 'no-drop', grab: 'grab', grabbing: 'grabbing', 'all-scroll': 'all-scroll', 'col-resize': 'col-resize', 'row-resize': 'row-resize', 'n-resize': 'n-resize', 'e-resize': 'e-resize', 's-resize': 's-resize', 'w-resize': 'w-resize', 'ne-resize': 'ne-resize', 'nw-resize': 'nw-resize', 'se-resize': 'se-resize', 'sw-resize': 'sw-resize', 'ew-resize': 'ew-resize', 'ns-resize': 'ns-resize', 'nesw-resize': 'nesw-resize', 'nwse-resize': 'nwse-resize', 'zoom-in': 'zoom-in', 'zoom-out': 'zoom-out', }, divideColor: ({ theme }) => theme('borderColor'), divideOpacity: ({ theme }) => theme('borderOpacity'), divideWidth: ({ theme }) => theme('borderWidth'), dropShadow: { sm: '0 1px 1px rgb(0 0 0 / 0.05)', DEFAULT: ['0 1px 2px rgb(0 0 0 / 0.1)', '0 1px 1px rgb(0 0 0 / 0.06)'], md: ['0 4px 3px rgb(0 0 0 / 0.07)', '0 2px 2px rgb(0 0 0 / 0.06)'], lg: ['0 10px 8px rgb(0 0 0 / 0.04)', '0 4px 3px rgb(0 0 0 / 0.1)'], xl: ['0 20px 13px rgb(0 0 0 / 0.03)', '0 8px 5px rgb(0 0 0 / 0.08)'], '2xl': '0 25px 25px rgb(0 0 0 / 0.15)', none: '0 0 #0000', }, fill: ({ theme }) => ({ none: 'none', ...theme('colors'), }), flex: { 1: '1 1 0%', auto: '1 1 auto', initial: '0 1 auto', none: 'none', }, flexBasis: ({ theme }) => ({ auto: 'auto', ...theme('spacing'), '1/2': '50%', '1/3': '33.333333%', '2/3': '66.666667%', '1/4': '25%', '2/4': '50%', '3/4': '75%', '1/5': '20%', '2/5': '40%', '3/5': '60%', '4/5': '80%', '1/6': '16.666667%', '2/6': '33.333333%', '3/6': '50%', '4/6': '66.666667%', '5/6': '83.333333%', '1/12': '8.333333%', '2/12': '16.666667%', '3/12': '25%', '4/12': '33.333333%', '5/12': '41.666667%', '6/12': '50%', '7/12': '58.333333%', '8/12': '66.666667%', '9/12': '75%', '10/12': '83.333333%', '11/12': '91.666667%', full: '100%', }), flexGrow: { 0: '0', DEFAULT: '1', }, flexShrink: { 0: '0', DEFAULT: '1', }, fontFamily: { sans: [ 'ui-sans-serif', 'system-ui', 'sans-serif', '"Apple Color Emoji"', '"Segoe UI Emoji"', '"Segoe UI Symbol"', '"Noto Color Emoji"', ], serif: ['ui-serif', 'Georgia', 'Cambria', '"Times New Roman"', 'Times', 'serif'], mono: [ 'ui-monospace', 'SFMono-Regular', 'Menlo', 'Monaco', 'Consolas', '"Liberation Mono"', '"Courier New"', 'monospace', ], }, fontSize: { xs: ['0.75rem', { lineHeight: '1rem' }], sm: ['0.875rem', { lineHeight: '1.25rem' }], base: ['1rem', { lineHeight: '1.5rem' }], lg: ['1.125rem', { lineHeight: '1.75rem' }], xl: ['1.25rem', { lineHeight: '1.75rem' }], '2xl': ['1.5rem', { lineHeight: '2rem' }], '3xl': ['1.875rem', { lineHeight: '2.25rem' }], '4xl': ['2.25rem', { lineHeight: '2.5rem' }], '5xl': ['3rem', { lineHeight: '1' }], '6xl': ['3.75rem', { lineHeight: '1' }], '7xl': ['4.5rem', { lineHeight: '1' }], '8xl': ['6rem', { lineHeight: '1' }], '9xl': ['8rem', { lineHeight: '1' }], }, fontWeight: { thin: '100', extralight: '200', light: '300', normal: '400', medium: '500', semibold: '600', bold: '700', extrabold: '800', black: '900', }, gap: ({ theme }) => theme('spacing'), gradientColorStops: ({ theme }) => theme('colors'), gradientColorStopPositions: { '0%': '0%', '5%': '5%', '10%': '10%', '15%': '15%', '20%': '20%', '25%': '25%', '30%': '30%', '35%': '35%', '40%': '40%', '45%': '45%', '50%': '50%', '55%': '55%', '60%': '60%', '65%': '65%', '70%': '70%', '75%': '75%', '80%': '80%', '85%': '85%', '90%': '90%', '95%': '95%', '100%': '100%', }, grayscale: { 0: '0', DEFAULT: '100%', }, gridAutoColumns: { auto: 'auto', min: 'min-content', max: 'max-content', fr: 'minmax(0, 1fr)', }, gridAutoRows: { auto: 'auto', min: 'min-content', max: 'max-content', fr: 'minmax(0, 1fr)', }, gridColumn: { auto: 'auto', 'span-1': 'span 1 / span 1', 'span-2': 'span 2 / span 2', 'span-3': 'span 3 / span 3', 'span-4': 'span 4 / span 4', 'span-5': 'span 5 / span 5', 'span-6': 'span 6 / span 6', 'span-7': 'span 7 / span 7', 'span-8': 'span 8 / span 8', 'span-9': 'span 9 / span 9', 'span-10': 'span 10 / span 10', 'span-11': 'span 11 / span 11', 'span-12': 'span 12 / span 12', 'span-full': '1 / -1', }, gridColumnEnd: { auto: 'auto', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '10', 11: '11', 12: '12', 13: '13', }, gridColumnStart: { auto: 'auto', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '10', 11: '11', 12: '12', 13: '13', }, gridRow: { auto: 'auto', 'span-1': 'span 1 / span 1', 'span-2': 'span 2 / span 2', 'span-3': 'span 3 / span 3', 'span-4': 'span 4 / span 4', 'span-5': 'span 5 / span 5', 'span-6': 'span 6 / span 6', 'span-7': 'span 7 / span 7', 'span-8': 'span 8 / span 8', 'span-9': 'span 9 / span 9', 'span-10': 'span 10 / span 10', 'span-11': 'span 11 / span 11', 'span-12': 'span 12 / span 12', 'span-full': '1 / -1', }, gridRowEnd: { auto: 'auto', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '10', 11: '11', 12: '12', 13: '13', }, gridRowStart: { auto: 'auto', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '10', 11: '11', 12: '12', 13: '13', }, gridTemplateColumns: { none: 'none', subgrid: 'subgrid', 1: 'repeat(1, minmax(0, 1fr))', 2: 'repeat(2, minmax(0, 1fr))', 3: 'repeat(3, minmax(0, 1fr))', 4: 'repeat(4, minmax(0, 1fr))', 5: 'repeat(5, minmax(0, 1fr))', 6: 'repeat(6, minmax(0, 1fr))', 7: 'repeat(7, minmax(0, 1fr))', 8: 'repeat(8, minmax(0, 1fr))', 9: 'repeat(9, minmax(0, 1fr))', 10: 'repeat(10, minmax(0, 1fr))', 11: 'repeat(11, minmax(0, 1fr))', 12: 'repeat(12, minmax(0, 1fr))', }, gridTemplateRows: { none: 'none', subgrid: 'subgrid', 1: 'repeat(1, minmax(0, 1fr))', 2: 'repeat(2, minmax(0, 1fr))', 3: 'repeat(3, minmax(0, 1fr))', 4: 'repeat(4, minmax(0, 1fr))', 5: 'repeat(5, minmax(0, 1fr))', 6: 'repeat(6, minmax(0, 1fr))', 7: 'repeat(7, minmax(0, 1fr))', 8: 'repeat(8, minmax(0, 1fr))', 9: 'repeat(9, minmax(0, 1fr))', 10: 'repeat(10, minmax(0, 1fr))', 11: 'repeat(11, minmax(0, 1fr))', 12: 'repeat(12, minmax(0, 1fr))', }, height: ({ theme }) => ({ auto: 'auto', ...theme('spacing'), '1/2': '50%', '1/3': '33.333333%', '2/3': '66.666667%', '1/4': '25%', '2/4': '50%', '3/4': '75%', '1/5': '20%', '2/5': '40%', '3/5': '60%', '4/5': '80%', '1/6': '16.666667%', '2/6': '33.333333%', '3/6': '50%', '4/6': '66.666667%', '5/6': '83.333333%', full: '100%', screen: '100vh', svh: '100svh', lvh: '100lvh', dvh: '100dvh', min: 'min-content', max: 'max-content', fit: 'fit-content', }), hueRotate: { 0: '0deg', 15: '15deg', 30: '30deg', 60: '60deg', 90: '90deg', 180: '180deg', }, inset: ({ theme }) => ({ auto: 'auto', ...theme('spacing'), '1/2': '50%', '1/3': '33.333333%', '2/3': '66.666667%', '1/4': '25%', '2/4': '50%', '3/4': '75%', full: '100%', }), invert: { 0: '0', DEFAULT: '100%', }, keyframes: { spin: { to: { transform: 'rotate(360deg)', }, }, ping: { '75%, 100%': { transform: 'scale(2)', opacity: '0', }, }, pulse: { '50%': { opacity: '.5', }, }, bounce: { '0%, 100%': { transform: 'translateY(-25%)', animationTimingFunction: 'cubic-bezier(0.8,0,1,1)', }, '50%': { transform: 'none', animationTimingFunction: 'cubic-bezier(0,0,0.2,1)', }, }, }, letterSpacing: { tighter: '-0.05em', tight: '-0.025em', normal: '0em', wide: '0.025em', wider: '0.05em', widest: '0.1em', }, lineHeight: { none: '1', tight: '1.25', snug: '1.375', normal: '1.5', relaxed: '1.625', loose: '2', 3: '.75rem', 4: '1rem', 5: '1.25rem', 6: '1.5rem', 7: '1.75rem', 8: '2rem', 9: '2.25rem', 10: '2.5rem', }, listStyleType: { none: 'none', disc: 'disc', decimal: 'decimal', }, listStyleImage: { none: 'none', }, margin: ({ theme }) => ({ auto: 'auto', ...theme('spacing'), }), lineClamp: { 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', }, maxHeight: ({ theme }) => ({ ...theme('spacing'), none: 'none', full: '100%', screen: '100vh', svh: '100svh', lvh: '100lvh', dvh: '100dvh', min: 'min-content', max: 'max-content', fit: 'fit-content', }), maxWidth: ({ theme, breakpoints }) => ({ ...theme('spacing'), none: 'none', xs: '20rem', sm: '24rem', md: '28rem', lg: '32rem', xl: '36rem', '2xl': '42rem', '3xl': '48rem', '4xl': '56rem', '5xl': '64rem', '6xl': '72rem', '7xl': '80rem', full: '100%', min: 'min-content', max: 'max-content', fit: 'fit-content', prose: '65ch', ...breakpoints(theme('screens')), }), minHeight: ({ theme }) => ({ ...theme('spacing'), full: '100%', screen: '100vh', svh: '100svh', lvh: '100lvh', dvh: '100dvh', min: 'min-content', max: 'max-content', fit: 'fit-content', }), minWidth: ({ theme }) => ({ ...theme('spacing'), full: '100%', min: 'min-content', max: 'max-content', fit: 'fit-content', }), objectPosition: { bottom: 'bottom', center: 'center', left: 'left', 'left-bottom': 'left bottom', 'left-top': 'left top', right: 'right', 'right-bottom': 'right bottom', 'right-top': 'right top', top: 'top', }, opacity: { 0: '0', 5: '0.05', 10: '0.1', 15: '0.15', 20: '0.2', 25: '0.25', 30: '0.3', 35: '0.35', 40: '0.4', 45: '0.45', 50: '0.5', 55: '0.55', 60: '0.6', 65: '0.65', 70: '0.7', 75: '0.75', 80: '0.8', 85: '0.85', 90: '0.9', 95: '0.95', 100: '1', }, order: { first: '-9999', last: '9999', none: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '10', 11: '11', 12: '12', }, outlineColor: ({ theme }) => theme('colors'), outlineOffset: { 0: '0px', 1: '1px', 2: '2px', 4: '4px', 8: '8px', }, outlineWidth: { 0: '0px', 1: '1px', 2: '2px', 4: '4px', 8: '8px', }, padding: ({ theme }) => theme('spacing'), placeholderColor: ({ theme }) => theme('colors'), placeholderOpacity: ({ theme }) => theme('opacity'), ringColor: ({ theme }) => ({ DEFAULT: theme('colors.blue.500', '#3b82f6'), ...theme('colors'), }), ringOffsetColor: ({ theme }) => theme('colors'), ringOffsetWidth: { 0: '0px', 1: '1px', 2: '2px', 4: '4px', 8: '8px', }, ringOpacity: ({ theme }) => ({ DEFAULT: '0.5', ...theme('opacity'), }), ringWidth: { DEFAULT: '3px', 0: '0px', 1: '1px', 2: '2px', 4: '4px', 8: '8px', }, rotate: { 0: '0deg', 1: '1deg', 2: '2deg', 3: '3deg', 6: '6deg', 12: '12deg', 45: '45deg', 90: '90deg', 180: '180deg', }, saturate: { 0: '0', 50: '.5', 100: '1', 150: '1.5', 200: '2', }, scale: { 0: '0', 50: '.5', 75: '.75', 90: '.9', 95: '.95', 100: '1', 105: '1.05', 110: '1.1', 125: '1.25', 150: '1.5', }, screens: { sm: '640px', md: '768px', lg: '1024px', xl: '1280px', '2xl': '1536px', }, scrollMargin: ({ theme }) => ({ ...theme('spacing'), }), scrollPadding: ({ theme }) => theme('spacing'), sepia: { 0: '0', DEFAULT: '100%', }, skew: { 0: '0deg', 1: '1deg', 2: '2deg', 3: '3deg', 6: '6deg', 12: '12deg', }, space: ({ theme }) => ({ ...theme('spacing'), }), spacing: { px: '1px', 0: '0px', 0.5: '0.125rem', 1: '0.25rem', 1.5: '0.375rem', 2: '0.5rem', 2.5: '0.625rem', 3: '0.75rem', 3.5: '0.875rem', 4: '1rem', 5: '1.25rem', 6: '1.5rem', 7: '1.75rem', 8: '2rem', 9: '2.25rem', 10: '2.5rem', 11: '2.75rem', 12: '3rem', 14: '3.5rem', 16: '4rem', 20: '5rem', 24: '6rem', 28: '7rem', 32: '8rem', 36: '9rem', 40: '10rem', 44: '11rem', 48: '12rem', 52: '13rem', 56: '14rem', 60: '15rem', 64: '16rem', 72: '18rem', 80: '20rem', 96: '24rem', }, stroke: ({ theme }) => ({ none: 'none', ...theme('colors'), }), strokeWidth: { 0: '0', 1: '1', 2: '2', }, supports: {}, data: {}, textColor: ({ theme }) => theme('colors'), textDecorationColor: ({ theme }) => theme('colors'), textDecorationThickness: { auto: 'auto', 'from-font': 'from-font', 0: '0px', 1: '1px', 2: '2px', 4: '4px', 8: '8px', }, textIndent: ({ theme }) => ({ ...theme('spacing'), }), textOpacity: ({ theme }) => theme('opacity'), textUnderlineOffset: { auto: 'auto', 0: '0px', 1: '1px', 2: '2px', 4: '4px', 8: '8px', }, transformOrigin: { center: 'center', top: 'top', 'top-right': 'top right', right: 'right', 'bottom-right': 'bottom right', bottom: 'bottom', 'bottom-left': 'bottom left', left: 'left', 'top-left': 'top left', }, transitionDelay: { 0: '0s', 75: '75ms', 100: '100ms', 150: '150ms', 200: '200ms', 300: '300ms', 500: '500ms', 700: '700ms', 1000: '1000ms', }, transitionDuration: { DEFAULT: '150ms', 0: '0s', 75: '75ms', 100: '100ms', 150: '150ms', 200: '200ms', 300: '300ms', 500: '500ms', 700: '700ms', 1000: '1000ms', }, transitionProperty: { none: 'none', all: 'all', DEFAULT: 'color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter', colors: 'color, background-color, border-color, text-decoration-color, fill, stroke', opacity: 'opacity', shadow: 'box-shadow', transform: 'transform', }, transitionTimingFunction: { DEFAULT: 'cubic-bezier(0.4, 0, 0.2, 1)', linear: 'linear', in: 'cubic-bezier(0.4, 0, 1, 1)', out: 'cubic-bezier(0, 0, 0.2, 1)', 'in-out': 'cubic-bezier(0.4, 0, 0.2, 1)', }, translate: ({ theme }) => ({ ...theme('spacing'), '1/2': '50%', '1/3': '33.333333%', '2/3': '66.666667%', '1/4': '25%', '2/4': '50%', '3/4': '75%', full: '100%', }), size: ({ theme }) => ({ auto: 'auto', ...theme('spacing'), '1/2': '50%', '1/3': '33.333333%', '2/3': '66.666667%', '1/4': '25%', '2/4': '50%', '3/4': '75%', '1/5': '20%', '2/5': '40%', '3/5': '60%', '4/5': '80%', '1/6': '16.666667%', '2/6': '33.333333%', '3/6': '50%', '4/6': '66.666667%', '5/6': '83.333333%', '1/12': '8.333333%', '2/12': '16.666667%', '3/12': '25%', '4/12': '33.333333%', '5/12': '41.666667%', '6/12': '50%', '7/12': '58.333333%', '8/12': '66.666667%', '9/12': '75%', '10/12': '83.333333%', '11/12': '91.666667%', full: '100%', min: 'min-content', max: 'max-content', fit: 'fit-content', }), width: ({ theme }) => ({ auto: 'auto', ...theme('spacing'), '1/2': '50%', '1/3': '33.333333%', '2/3': '66.666667%', '1/4': '25%', '2/4': '50%', '3/4': '75%', '1/5': '20%', '2/5': '40%', '3/5': '60%', '4/5': '80%', '1/6': '16.666667%', '2/6': '33.333333%', '3/6': '50%', '4/6': '66.666667%', '5/6': '83.333333%', '1/12': '8.333333%', '2/12': '16.666667%', '3/12': '25%', '4/12': '33.333333%', '5/12': '41.666667%', '6/12': '50%', '7/12': '58.333333%', '8/12': '66.666667%', '9/12': '75%', '10/12': '83.333333%', '11/12': '91.666667%', full: '100%', screen: '100vw', svw: '100svw', lvw: '100lvw', dvw: '100dvw', min: 'min-content', max: 'max-content', fit: 'fit-content', }), willChange: { auto: 'auto', scroll: 'scroll-position', contents: 'contents', transform: 'transform', }, zIndex: { auto: 'auto', 0: '0', 10: '10', 20: '20', 30: '30', 40: '40', 50: '50', }, }, plugins: [], }; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "default", { enumerable: true, get: function() { return _default; } }); const _cloneDeep = cloneDeep; const _configfull = /*#__PURE__*/ _interop_require_default(config_full); function _interop_require_default(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const _default = (0, _cloneDeep.cloneDeep)(_configfull.default.theme); } (defaultTheme$2)); let defaultTheme$1 = defaultTheme$2; var defaultTheme_1 = (defaultTheme$1.__esModule ? defaultTheme$1 : { default: defaultTheme$1 }).default; var require$$4 = /*@__PURE__*/getAugmentedNamespace(nothing); var prefixNegativeModifiers$2 = {}; var lodash = {exports: {}}; /** * @license * Lodash * Copyright OpenJS Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ lodash.exports; (function (module, exports) { (function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined$1; /** Used as the semantic version number. */ var VERSION = '4.17.21'; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Error message constants. */ var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', FUNC_ERROR_TEXT = 'Expected a function', INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used as default options for `_.truncate`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /** Used to indicate the type of lazy iteratees. */ var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', domExcTag = '[object DOMException]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]', weakSetTag = '[object WeakSet]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); /** Used to match leading whitespace. */ var reTrimStart = /^\s+/; /** Used to match a single whitespace character. */ var reWhitespace = /\s/; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** Used to match words composed of alphanumeric characters. */ var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; /** * Used to validate the `validate` option in `_.template` variable. * * Forbids characters which could potentially change the meaning of the function argument definition: * - "()," (modification of function parameters) * - "=" (default value) * - "[]{}" (destructuring of function parameters) * - "/" (beginning of a comment) * - whitespace */ var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Used to match * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to match Latin Unicode letters (excluding mathematical operators). */ var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsPunctuationRange = '\\u2000-\\u206f', rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; /** Used to compose unicode capture groups. */ var rsApos = "['\u2019]", rsAstral = '[' + rsAstralRange + ']', rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match apostrophes. */ var reApos = RegExp(rsApos, 'g'); /** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). */ var reComboMark = RegExp(rsCombo, 'g'); /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to match complex or compound words. */ var reUnicodeWord = RegExp([ rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, rsUpper + '+' + rsOptContrUpper, rsOrdUpper, rsOrdLower, rsDigits, rsEmoji ].join('|'), 'g'); /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** Used to detect strings that need a more robust regexp to match words. */ var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; /** Used to assign default `context` object properties. */ var contextProps = [ 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' ]; /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** Used to map Latin Unicode letters to basic Latin letters. */ var deburredLetters = { // Latin-1 Supplement block. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss', // Latin Extended-A block. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', '\u0134': 'J', '\u0135': 'j', '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', '\u0163': 't', '\u0165': 't', '\u0167': 't', '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', '\u0174': 'W', '\u0175': 'w', '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', '\u0132': 'IJ', '\u0133': 'ij', '\u0152': 'Oe', '\u0153': 'oe', '\u0149': "'n", '\u017f': 's' }; /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; /** Used to map HTML entities to characters. */ var htmlUnescapes = { '&': '&', '<': '<', '>': '>', '"': '"', ''': "'" }; /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Built-in method references without a dependency on `root`. */ var freeParseFloat = parseFloat, freeParseInt = parseInt; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { // Use `util.types` for Node.js 10+. var types = freeModule && freeModule.require && freeModule.require('util').types; if (types) { return types; } // Legacy `process.binding('util')` for Node.js < 10. return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /*--------------------------------------------------------------------------*/ /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } /** * A specialized version of `baseAggregator` for arrays. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * A specialized version of `_.forEachRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEachRight(array, iteratee) { var length = array == null ? 0 : array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; } /** * A specialized version of `_.every` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. */ function arrayEvery(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * A specialized version of `_.reduceRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the last element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * Gets the size of an ASCII `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ var asciiSize = baseProperty('length'); /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } /** * Splits an ASCII `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function asciiWords(string) { return string.match(reAsciiWord) || []; } /** * The base implementation of methods like `_.findKey` and `_.findLastKey`, * without support for iteratee shorthands, which iterates over `collection` * using `eachFunc`. * * @private * @param {Array|Object} collection The collection to inspect. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFindKey(collection, predicate, eachFunc) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = key; return false; } }); return result; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } /** * This function is like `baseIndexOf` except that it accepts a comparator. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @param {Function} comparator The comparator invoked per element. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index; } } return -1; } /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } /** * The base implementation of `_.mean` and `_.meanBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the mean. */ function baseMean(array, iteratee) { var length = array == null ? 0 : array.length; return length ? (baseSum(array, iteratee) / length) : NAN; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined$1 : object[key]; }; } /** * The base implementation of `_.propertyOf` without support for deep paths. * * @private * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. */ function basePropertyOf(object) { return function(key) { return object == null ? undefined$1 : object[key]; }; } /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined$1) { result = result === undefined$1 ? current : (result + current); } } return result; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array * of key-value pairs for `object` corresponding to the property names of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the key-value pairs. */ function baseToPairs(object, props) { return arrayMap(props, function(key) { return [key, object[key]]; }); } /** * The base implementation of `_.trim`. * * @private * @param {string} string The string to trim. * @returns {string} Returns the trimmed string. */ function baseTrim(string) { return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') : string; } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } /** * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A * letters to basic Latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ var deburrLetter = basePropertyOf(deburredLetters); /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ var escapeHtmlChar = basePropertyOf(htmlEscapes); /** * Used by `_.template` to escape characters for inclusion in compiled string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(chr) { return '\\' + stringEscapes[chr]; } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined$1 : object[key]; } /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } /** * Checks if `string` contains a word composed of Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a word is found, else `false`. */ function hasUnicodeWord(string) { return reHasUnicodeWord.test(string); } /** * Converts `iterator` to an array. * * @private * @param {Object} iterator The iterator to convert. * @returns {Array} Returns the converted array. */ function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { result.push(data.value); } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** * Converts `set` to its value-value pairs. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the value-value pairs. */ function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = [value, value]; }); return result; } /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * A specialized version of `_.lastIndexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictLastIndexOf(array, value, fromIndex) { var index = fromIndex + 1; while (index--) { if (array[index] === value) { return index; } } return index; } /** * Gets the number of symbols in `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the string size. */ function stringSize(string) { return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); } /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace * character of `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the index of the last non-whitespace character. */ function trimmedEndIndex(string) { var index = string.length; while (index-- && reWhitespace.test(string.charAt(index))) {} return index; } /** * Used by `_.unescape` to convert HTML entities to characters. * * @private * @param {string} chr The matched character to unescape. * @returns {string} Returns the unescaped character. */ var unescapeHtmlChar = basePropertyOf(htmlUnescapes); /** * Gets the size of a Unicode `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ function unicodeSize(string) { var result = reUnicode.lastIndex = 0; while (reUnicode.test(string)) { ++result; } return result; } /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } /** * Splits a Unicode `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function unicodeWords(string) { return string.match(reUnicodeWord) || []; } /*--------------------------------------------------------------------------*/ /** * Create a new pristine `lodash` function using the `context` object. * * @static * @memberOf _ * @since 1.1.0 * @category Util * @param {Object} [context=root] The context object. * @returns {Function} Returns a new `lodash` function. * @example * * _.mixin({ 'foo': _.constant('foo') }); * * var lodash = _.runInContext(); * lodash.mixin({ 'bar': lodash.constant('bar') }); * * _.isFunction(_.foo); * // => true * _.isFunction(_.bar); * // => false * * lodash.isFunction(lodash.foo); * // => false * lodash.isFunction(lodash.bar); * // => true * * // Create a suped-up `defer` in Node.js. * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; */ var runInContext = (function runInContext(context) { context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); /** Built-in constructor references. */ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = context['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to generate unique IDs. */ var idCounter = 0; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = root._; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? context.Buffer : undefined$1, Symbol = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined$1, getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined$1, symIterator = Symbol ? Symbol.iterator : undefined$1, symToStringTag = Symbol ? Symbol.toStringTag : undefined$1; var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); /** Mocked built-ins. */ var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined$1, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; /* Built-in method references that are verified to be native. */ var DataView = getNative(context, 'DataView'), Map = getNative(context, 'Map'), Promise = getNative(context, 'Promise'), Set = getNative(context, 'Set'), WeakMap = getNative(context, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; /** Used to lookup unminified function names. */ var realNames = {}; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined$1, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined$1, symbolToString = symbolProto ? symbolProto.toString : undefined$1; /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined$1; return result; }; }()); /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined$1; } /** * By default, the template delimiters used by lodash are like those in * embedded Ruby (ERB) as well as ES2015 template strings. Change the * following template settings to use alternative delimiters. * * @static * @memberOf _ * @type {Object} */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type {RegExp} */ 'escape': reEscape, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type {RegExp} */ 'evaluate': reEvaluate, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type {RegExp} */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type {string} */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type {Object} */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type {Function} */ '_': lodash } }; // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; /*------------------------------------------------------------------------*/ /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } /** * Creates a clone of the lazy wrapper object. * * @private * @name clone * @memberOf LazyWrapper * @returns {Object} Returns the cloned `LazyWrapper` object. */ function lazyClone() { var result = new LazyWrapper(this.__wrapped__); result.__actions__ = copyArray(this.__actions__); result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = copyArray(this.__iteratees__); result.__takeCount__ = this.__takeCount__; result.__views__ = copyArray(this.__views__); return result; } /** * Reverses the direction of lazy iteration. * * @private * @name reverse * @memberOf LazyWrapper * @returns {Object} Returns the new reversed `LazyWrapper` object. */ function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); result.__dir__ = -1; result.__filtered__ = true; } else { result = this.clone(); result.__dir__ *= -1; } return result; } /** * Extracts the unwrapped value from its lazy wrapper. * * @private * @name value * @memberOf LazyWrapper * @returns {*} Returns the unwrapped value. */ function lazyValue() { var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : (start - 1), iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); if (!isArr || (!isRight && arrLength == length && takeCount == length)) { return baseWrapperValue(array, this.__actions__); } var result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer; } else { break outer; } } } result[resIndex++] = value; } return result; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; /*------------------------------------------------------------------------*/ /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined$1 : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined$1; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined$1) : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined$1) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /*------------------------------------------------------------------------*/ /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined$1 : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /*------------------------------------------------------------------------*/ /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /*------------------------------------------------------------------------*/ /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /*------------------------------------------------------------------------*/ /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /*------------------------------------------------------------------------*/ /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } /** * A specialized version of `_.sample` for arrays. * * @private * @param {Array} array The array to sample. * @returns {*} Returns the random element. */ function arraySample(array) { var length = array.length; return length ? array[baseRandom(0, length - 1)] : undefined$1; } /** * A specialized version of `_.sampleSize` for arrays. * * @private * @param {Array} array The array to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function arraySampleSize(array, n) { return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } /** * A specialized version of `_.shuffle` for arrays. * * @private * @param {Array} array The array to shuffle. * @returns {Array} Returns the new shuffled array. */ function arrayShuffle(array) { return shuffleSelf(copyArray(array)); } /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined$1 && !eq(object[key], value)) || (value === undefined$1 && !(key in object))) { baseAssignValue(object, key, value); } } /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined$1 && !(key in object))) { baseAssignValue(object, key, value); } } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * Aggregates elements of `collection` on `accumulator` with keys transformed * by `iteratee` and values set by `setter`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } /** * The base implementation of `_.at` without support for individual paths. * * @private * @param {Object} object The object to iterate over. * @param {string[]} paths The property paths to pick. * @returns {Array} Returns the picked elements. */ function baseAt(object, paths) { var index = -1, length = paths.length, result = Array(length), skip = object == null; while (++index < length) { result[index] = skip ? undefined$1 : get(object, paths[index]); } return result; } /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined$1) { number = number <= upper ? number : upper; } if (lower !== undefined$1) { number = number >= lower ? number : lower; } } return number; } /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined$1) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); } else if (isMap(value)) { value.forEach(function(subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); } var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined$1 : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } /** * The base implementation of `_.conforms` which doesn't clone `source`. * * @private * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. */ function baseConforms(source) { var props = keys(source); return function(object) { return baseConformsTo(object, source, props); }; } /** * The base implementation of `_.conformsTo` which accepts `props` to check. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. */ function baseConformsTo(object, source, props) { var length = props.length; if (object == null) { return !length; } object = Object(object); while (length--) { var key = props[length], predicate = source[key], value = object[key]; if ((value === undefined$1 && !(key in object)) || !predicate(value)) { return false; } } return true; } /** * The base implementation of `_.delay` and `_.defer` which accepts `args` * to provide to `func`. * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {Array} args The arguments to provide to `func`. * @returns {number|Object} Returns the timer id or timeout object. */ function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined$1, args); }, wait); } /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `_.forEachRight` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEachRight = createBaseEach(baseForOwnRight, true); /** * The base implementation of `_.every` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false` */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { result = !!predicate(value, index, collection); return result; }); return result; } /** * The base implementation of methods like `_.max` and `_.min` which accepts a * `comparator` to determine the extremum value. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The iteratee invoked per iteration. * @param {Function} comparator The comparator used to compare values. * @returns {*} Returns the extremum value. */ function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { var value = array[index], current = iteratee(value); if (current != null && (computed === undefined$1 ? (current === current && !isSymbol(current)) : comparator(current, computed) )) { var computed = current, result = value; } } return result; } /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined$1 || end > length) ? length : toInteger(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength(end); while (start < end) { array[start++] = value; } return array; } /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * This function is like `baseFor` except that it iterates over properties * in the opposite order. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseForRight = createBaseFor(true); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } /** * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwnRight(object, iteratee) { return object && baseForRight(object, iteratee, keys); } /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from `props`. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the function names. */ function baseFunctions(object, props) { return arrayFilter(props, function(key) { return isFunction(object[key]); }); } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined$1; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined$1 ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.gt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. */ function baseGt(value, other) { return value > other; } /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } /** * The base implementation of `_.inRange` which doesn't coerce arguments. * * @private * @param {number} number The number to check. * @param {number} start The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. */ function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end); } /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined$1; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } /** * The base implementation of `_.invoke` without support for individual * method arguments. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function baseInvoke(object, path, args) { path = castPath(path, object); object = parent(object, path); var func = object == null ? object : object[toKey(last(path))]; return func == null ? undefined$1 : apply(func, object, args); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ function baseIsArrayBuffer(value) { return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; } /** * The base implementation of `_.isDate` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ function baseIsDate(value) { return isObjectLike(value) && baseGetTag(value) == dateTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined$1 && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined$1 ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isRegExp` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ function baseIsRegExp(value) { return isObjectLike(value) && baseGetTag(value) == regexpTag; } /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag; } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } /** * The base implementation of `_.lt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. */ function baseLt(value, other) { return value < other; } /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined$1 && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { stack || (stack = new Stack); if (isObject(srcValue)) { baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) : undefined$1; if (newValue === undefined$1) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = safeGet(object, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined$1; var isCommon = newValue === undefined$1; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || isFunction(objValue)) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } /** * The base implementation of `_.nth` which doesn't coerce arguments. * * @private * @param {Array} array The array to query. * @param {number} n The index of the element to return. * @returns {*} Returns the nth element of `array`. */ function baseNth(array, n) { var length = array.length; if (!length) { return; } n += n < 0 ? length : 0; return isIndex(n, length) ? array[n] : undefined$1; } /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { if (iteratees.length) { iteratees = arrayMap(iteratees, function(iteratee) { if (isArray(iteratee)) { return function(value) { return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); } } return iteratee; }); } else { iteratees = [identity]; } var index = -1; iteratees = arrayMap(iteratees, baseUnary(getIteratee())); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return basePickBy(object, paths, function(value, path) { return hasIn(object, path); }); } /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, castPath(path, object), value); } } return result; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } /** * The base implementation of `_.pullAllBy` without support for iteratee * shorthands. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. */ function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (array === values) { values = copyArray(values); } if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)); } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1); } splice.call(array, fromIndex, 1); } } return array; } /** * The base implementation of `_.pullAt` without support for individual * indexes or capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1); } else { baseUnset(array, index); } } } return array; } /** * The base implementation of `_.random` without support for returning * floating-point numbers. * * @private * @param {number} lower The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the random number. */ function baseRandom(lower, upper) { return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } /** * The base implementation of `_.repeat` which doesn't coerce arguments. * * @private * @param {string} string The string to repeat. * @param {number} n The number of times to repeat the string. * @returns {string} Returns the repeated string. */ function baseRepeat(string, n) { var result = ''; if (!string || n < 1 || n > MAX_SAFE_INTEGER) { return result; } // Leverage the exponentiation by squaring algorithm for a faster repeat. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. do { if (n % 2) { result += string; } n = nativeFloor(n / 2); if (n) { string += string; } } while (n); return result; } /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } /** * The base implementation of `_.sample`. * * @private * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. */ function baseSample(collection) { return arraySample(values(collection)); } /** * The base implementation of `_.sampleSize` without param guards. * * @private * @param {Array|Object} collection The collection to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function baseSampleSize(collection, n) { var array = values(collection); return shuffleSelf(array, baseClamp(n, 0, array.length)); } /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (key === '__proto__' || key === 'constructor' || key === 'prototype') { return object; } if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined$1; if (newValue === undefined$1) { newValue = isObject(objValue) ? objValue : (isIndex(path[index + 1]) ? [] : {}); } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; /** * The base implementation of `_.shuffle`. * * @private * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. */ function baseShuffle(collection) { return shuffleSelf(values(collection)); } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.some` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } /** * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which * performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndex(array, value, retHighest) { var low = 0, high = array == null ? low : array.length; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (computed !== null && !isSymbol(computed) && (retHighest ? (computed <= value) : (computed < value))) { low = mid + 1; } else { high = mid; } } return high; } return baseSortedIndexBy(array, value, identity, retHighest); } /** * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` * which invokes `iteratee` for `value` and each element of `array` to compute * their sort ranking. The iteratee is invoked with one argument; (value). * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} iteratee The iteratee invoked per element. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndexBy(array, value, iteratee, retHighest) { var low = 0, high = array == null ? 0 : array.length; if (high === 0) { return 0; } value = iteratee(value); var valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined$1; while (low < high) { var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = computed !== undefined$1, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); if (valIsNaN) { var setLow = retHighest || othIsReflexive; } else if (valIsUndefined) { setLow = othIsReflexive && (retHighest || othIsDefined); } else if (valIsNull) { setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); } else if (valIsSymbol) { setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); } else if (othIsNull || othIsSymbol) { setLow = false; } else { setLow = retHighest ? (computed <= value) : (computed < value); } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } /** * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseSortedUniq(array, iteratee) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (!index || !eq(computed, seen)) { var seen = computed; result[resIndex++] = value === 0 ? 0 : value; } } return result; } /** * The base implementation of `_.toNumber` which doesn't ensure correct * conversions of binary, hexadecimal, or octal string values. * * @private * @param {*} value The value to process. * @returns {number} Returns the number. */ function baseToNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } return +value; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); return object == null || delete object[toKey(last(path))]; } /** * The base implementation of `_.update`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to update. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseUpdate(object, path, updater, customizer) { return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** * The base implementation of methods like `_.dropWhile` and `_.takeWhile` * without support for iteratee shorthands. * * @private * @param {Array} array The array to query. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [isDrop] Specify dropping elements instead of taking them. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the slice of `array`. */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** * The base implementation of `wrapperValue` which returns the result of * performing a sequence of actions on the unwrapped `value`, where each * successive action is supplied the return value of the previous. * * @private * @param {*} value The unwrapped value. * @param {Array} actions Actions to perform to resolve the unwrapped value. * @returns {*} Returns the resolved value. */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value(); } return arrayReduce(actions, function(result, action) { return action.func.apply(action.thisArg, arrayPush([result], action.args)); }, result); } /** * The base implementation of methods like `_.xor`, without support for * iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ function baseXor(arrays, iteratee, comparator) { var length = arrays.length; if (length < 2) { return length ? baseUniq(arrays[0]) : []; } var index = -1, result = Array(length); while (++index < length) { var array = arrays[index], othIndex = -1; while (++othIndex < length) { if (othIndex != index) { result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); } } } return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * * @private * @param {Array} props The property identifiers. * @param {Array} values The property values. * @param {Function} assignFunc The function to assign values. * @returns {Object} Returns the new object. */ function baseZipObject(props, values, assignFunc) { var index = -1, length = props.length, valsLength = values.length, result = {}; while (++index < length) { var value = index < valsLength ? values[index] : undefined$1; assignFunc(result, props[index], value); } return result; } /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } /** * A `baseRest` alias which can be replaced with `identity` by module * replacement plugins. * * @private * @type {Function} * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ var castRest = baseRest; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined$1 ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } /** * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * * @private * @param {number|Object} id The timer id or timeout object of the timer to clear. */ var clearTimeout = ctxClearTimeout || function(id) { return root.clearTimeout(id); }; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined$1, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined$1, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined$1; if (newValue === undefined$1) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } /** * Creates a function like `_.groupBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} [initializer] The accumulator object initializer. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee, 2), accumulator); }; } /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined$1, guard = length > 2 ? sources[2] : undefined$1; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined$1; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined$1 : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new case function. */ function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined$1; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); }; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined$1, args, holders, undefined$1, undefined$1, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = getIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined$1; }; } /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return flatRest(function(funcs) { var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse(); } while (index--) { var func = funcs[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (prereq && !wrapper && getFuncName(func) == 'wrapper') { var wrapper = new LodashWrapper([], true); } } index = wrapper ? index : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined$1; if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1 ) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments, value = args[0]; if (wrapper && args.length == 1 && isArray(value)) { return wrapper.plant(value).value(); } var index = 0, result = length ? funcs[index].apply(this, args) : value; while (++index < length) { result = funcs[index].call(this, result); } return result; }; }); } /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined$1 : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } /** * Creates a function that performs a mathematical operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @param {number} [defaultValue] The value used for `undefined` arguments. * @returns {Function} Returns the new mathematical operation function. */ function createMathOperation(operator, defaultValue) { return function(value, other) { var result; if (value === undefined$1 && other === undefined$1) { return defaultValue; } if (value !== undefined$1) { result = value; } if (other !== undefined$1) { if (result === undefined$1) { return other; } if (typeof value == 'string' || typeof other == 'string') { value = baseToString(value); other = baseToString(other); } else { value = baseToNumber(value); other = baseToNumber(other); } result = operator(value, other); } return result; }; } /** * Creates a function like `_.over`. * * @private * @param {Function} arrayFunc The function to iterate over iteratees. * @returns {Function} Returns the new over function. */ function createOver(arrayFunc) { return flatRest(function(iteratees) { iteratees = arrayMap(iteratees, baseUnary(getIteratee())); return baseRest(function(args) { var thisArg = this; return arrayFunc(iteratees, function(iteratee) { return apply(iteratee, thisArg, args); }); }); }); } /** * Creates the padding for `string` based on `length`. The `chars` string * is truncated if the number of characters exceeds `length`. * * @private * @param {number} length The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padding for `string`. */ function createPadding(length, chars) { chars = chars === undefined$1 ? ' ' : baseToString(chars); var charsLength = chars.length; if (charsLength < 2) { return charsLength ? baseRepeat(chars, length) : chars; } var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join('') : result.slice(0, length); } /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined$1; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined$1) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined$1 ? (start < end ? 1 : -1) : toFinite(step); return baseRange(start, end, step, fromRight); }; } /** * Creates a function that performs a relational operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @returns {Function} Returns the new relational operation function. */ function createRelationalOperation(operator) { return function(value, other) { if (!(typeof value == 'string' && typeof other == 'string')) { value = toNumber(value); other = toNumber(other); } return operator(value, other); }; } /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined$1, newHoldersRight = isCurry ? undefined$1 : holders, newPartials = isCurry ? partials : undefined$1, newPartialsRight = isCurry ? undefined$1 : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined$1, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } /** * Creates a function like `_.round`. * * @private * @param {string} methodName The name of the `Math` method to use when rounding. * @returns {Function} Returns the new round function. */ function createRound(methodName) { var func = Math[methodName]; return function(number, precision) { number = toNumber(number); precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); if (precision && nativeIsFinite(number)) { // Shift with exponential notation to avoid floating-point issues. // See [MDN](https://mdn.io/round#Examples) for more details. var pair = (toString(number) + 'e').split('e'), value = func(pair[0] + 'e' + (+pair[1] + precision)); pair = (toString(value) + 'e').split('e'); return +(pair[0] + 'e' + (+pair[1] - precision)); } return func(number); }; } /** * Creates a set object of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { return new Set(values); }; /** * Creates a `_.toPairs` or `_.toPairsIn` function. * * @private * @param {Function} keysFunc The function to get the keys of a given object. * @returns {Function} Returns the new pairs function. */ function createToPairs(keysFunc) { return function(object) { var tag = getTag(object); if (tag == mapTag) { return mapToArray(object); } if (tag == setTag) { return setToPairs(object); } return baseToPairs(object, keysFunc(object)); }; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined$1; } ary = ary === undefined$1 ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined$1 ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined$1; } var data = isBindKey ? undefined$1 : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined$1 ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined$1, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined$1 || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } /** * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source * objects into destination objects that are passed thru. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to merge. * @param {Object} object The parent object of `objValue`. * @param {Object} source The parent object of `srcValue`. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. * @returns {*} Returns the value to assign. */ function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, objValue); baseMerge(objValue, srcValue, undefined$1, customDefaultsMerge, stack); stack['delete'](srcValue); } return objValue; } /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject(value) ? undefined$1 : value; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Check that cyclic values are equal. var arrStacked = stack.get(array); var othStacked = stack.get(other); if (arrStacked && othStacked) { return arrStacked == other && othStacked == array; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined$1; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined$1) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Check that cyclic values are equal. var objStacked = stack.get(object); var othStacked = stack.get(other); if (objStacked && othStacked) { return objStacked == other && othStacked == object; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined$1 ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined$1, flatten), func + ''); } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; return object.placeholder; } /** * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, * this function returns the custom method, otherwise it returns `baseIteratee`. * If arguments are provided, the chosen function is invoked with them and * its result is returned. * * @private * @param {*} [value] The value to convert to an iteratee. * @param {number} [arity] The arity of the created iteratee. * @returns {Function} Returns the chosen function or its result. */ function getIteratee() { var result = lodash.iteratee || iteratee; result = result === iteratee ? baseIteratee : result; return arguments.length ? result(arguments[0], arguments[1]) : result; } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined$1; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined$1; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined$1, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} transforms The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return new Ctor; case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return new Ctor; case symbolTag: return cloneSymbol(object); } } /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `func` is capable of being masked. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `func` is maskable, else `false`. */ var isMaskable = coreJsData ? isFunction : stubFalse; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined$1 || (key in Object(object))); }; } /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined$1 ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined$1; } return array; } /** * Gets the value at `key`, unless `key` is "__proto__" or "constructor". * * @private * @param {Object} object The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function safeGet(object, key) { if (key === 'constructor' && typeof object[key] === 'function') { return; } if (key == '__proto__') { return; } return object[key]; } /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = shortOut(baseSetData); /** * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @returns {number|Object} Returns the timer id or timeout object. */ var setTimeout = ctxSetTimeout || function(func, wait) { return root.setTimeout(func, wait); }; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined$1, arguments); }; } /** * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * * @private * @param {Array} array The array to shuffle. * @param {number} [size=array.length] The size of `array`. * @returns {Array} Returns `array`. */ function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; size = size === undefined$1 ? length : size; while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value; } array.length = size; return array; } /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } /*------------------------------------------------------------------------*/ /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the new array of chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if ((guard ? isIterateeCall(array, size, guard) : size === undefined$1)) { size = 1; } else { size = nativeMax(toInteger(size), 0); } var length = array == null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = baseSlice(array, index, (index += size)); } return result; } /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } /** * Creates a new array concatenating `array` with any additional arrays * and/or values. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to concatenate. * @param {...*} [values] The values to concatenate. * @returns {Array} Returns the new concatenated array. * @example * * var array = [1]; * var other = _.concat(array, 2, [3], [[4]]); * * console.log(other); * // => [1, 2, 3, [4]] * * console.log(array); * // => [1] */ function concat() { var length = arguments.length; if (!length) { return []; } var args = Array(length - 1), array = arguments[0], index = length; while (index--) { args[index - 1] = arguments[index]; } return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); } /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); /** * This method is like `_.difference` except that it accepts `iteratee` which * is invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * **Note:** Unlike `_.pullAllBy`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2] * * // The `_.property` iteratee shorthand. * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var differenceBy = baseRest(function(array, values) { var iteratee = last(values); if (isArrayLikeObject(iteratee)) { iteratee = undefined$1; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.difference` except that it accepts `comparator` * which is invoked to compare elements of `array` to `values`. The order and * references of result values are determined by the first array. The comparator * is invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); * // => [{ 'x': 2, 'y': 1 }] */ var differenceWith = baseRest(function(array, values) { var comparator = last(values); if (isArrayLikeObject(comparator)) { comparator = undefined$1; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined$1, comparator) : []; }); /** * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ * @since 0.5.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.drop([1, 2, 3]); * // => [2, 3] * * _.drop([1, 2, 3], 2); * // => [3] * * _.drop([1, 2, 3], 5); * // => [] * * _.drop([1, 2, 3], 0); * // => [1, 2, 3] */ function drop(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined$1) ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRight([1, 2, 3]); * // => [1, 2] * * _.dropRight([1, 2, 3], 2); * // => [1] * * _.dropRight([1, 2, 3], 5); * // => [] * * _.dropRight([1, 2, 3], 0); * // => [1, 2, 3] */ function dropRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined$1) ? 1 : toInteger(n); n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` excluding elements dropped from the end. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.dropRightWhile(users, function(o) { return !o.active; }); * // => objects for ['barney'] * * // The `_.matches` iteratee shorthand. * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['barney', 'fred'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropRightWhile(users, ['active', false]); * // => objects for ['barney'] * * // The `_.property` iteratee shorthand. * _.dropRightWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; } /** * Creates a slice of `array` excluding elements dropped from the beginning. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.dropWhile(users, function(o) { return !o.active; }); * // => objects for ['pebbles'] * * // The `_.matches` iteratee shorthand. * _.dropWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['fred', 'pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropWhile(users, ['active', false]); * // => objects for ['pebbles'] * * // The `_.property` iteratee shorthand. * _.dropWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true) : []; } /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @since 3.2.0 * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8, 10], '*', 1, 3); * // => [4, '*', '*', 10] */ function fill(array, value, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { start = 0; end = length; } return baseFill(array, value, start, end); } /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, getIteratee(predicate, 3), index); } /** * This method is like `_.findIndex` except that it iterates over elements * of `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); * // => 2 * * // The `_.matches` iteratee shorthand. * _.findLastIndex(users, { 'user': 'barney', 'active': true }); * // => 0 * * // The `_.matchesProperty` iteratee shorthand. * _.findLastIndex(users, ['active', false]); * // => 2 * * // The `_.property` iteratee shorthand. * _.findLastIndex(users, 'active'); * // => 0 */ function findLastIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length - 1; if (fromIndex !== undefined$1) { index = toInteger(fromIndex); index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return baseFindIndex(array, getIteratee(predicate, 3), index, true); } /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } /** * Recursively flattens `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, [3, [4]], 5]]); * // => [1, 2, 3, 4, 5] */ function flattenDeep(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, INFINITY) : []; } /** * Recursively flatten `array` up to `depth` times. * * @static * @memberOf _ * @since 4.4.0 * @category Array * @param {Array} array The array to flatten. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * var array = [1, [2, [3, [4]], 5]]; * * _.flattenDepth(array, 1); * // => [1, 2, [3, [4]], 5] * * _.flattenDepth(array, 2); * // => [1, 2, 3, [4], 5] */ function flattenDepth(array, depth) { var length = array == null ? 0 : array.length; if (!length) { return []; } depth = depth === undefined$1 ? 1 : toInteger(depth); return baseFlatten(array, depth); } /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['a', 1], ['b', 2]]); * // => { 'a': 1, 'b': 2 } */ function fromPairs(pairs) { var index = -1, length = pairs == null ? 0 : pairs.length, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1]; } return result; } /** * Gets the first element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @alias first * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.head([1, 2, 3]); * // => 1 * * _.head([]); * // => undefined */ function head(array) { return (array && array.length) ? array[0] : undefined$1; } /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } /** * Gets all but the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] */ function initial(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 0, -1) : []; } /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); /** * This method is like `_.intersection` except that it accepts `iteratee` * which is invoked for each element of each `arrays` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [2.1] * * // The `_.property` iteratee shorthand. * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }] */ var intersectionBy = baseRest(function(arrays) { var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (iteratee === last(mapped)) { iteratee = undefined$1; } else { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.intersection` except that it accepts `comparator` * which is invoked to compare elements of `arrays`. The order and references * of result values are determined by the first array. The comparator is * invoked with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.intersectionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }] */ var intersectionWith = baseRest(function(arrays) { var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); comparator = typeof comparator == 'function' ? comparator : undefined$1; if (comparator) { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, undefined$1, comparator) : []; }); /** * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to convert. * @param {string} [separator=','] The element separator. * @returns {string} Returns the joined string. * @example * * _.join(['a', 'b', 'c'], '~'); * // => 'a~b~c' */ function join(array, separator) { return array == null ? '' : nativeJoin.call(array, separator); } /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined$1; } /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // Search from the `fromIndex`. * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length; if (fromIndex !== undefined$1) { index = toInteger(fromIndex); index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true); } /** * Gets the element at index `n` of `array`. If `n` is negative, the nth * element from the end is returned. * * @static * @memberOf _ * @since 4.11.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=0] The index of the element to return. * @returns {*} Returns the nth element of `array`. * @example * * var array = ['a', 'b', 'c', 'd']; * * _.nth(array, 1); * // => 'b' * * _.nth(array, -2); * // => 'c'; */ function nth(array, n) { return (array && array.length) ? baseNth(array, toInteger(n)) : undefined$1; } /** * Removes all given values from `array` using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` * to remove elements from an array by predicate. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pull(array, 'a', 'c'); * console.log(array); * // => ['b', 'b'] */ var pull = baseRest(pullAll); /** * This method is like `_.pull` except that it accepts an array of values to remove. * * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pullAll(array, ['a', 'c']); * console.log(array); * // => ['b', 'b'] */ function pullAll(array, values) { return (array && array.length && values && values.length) ? basePullAll(array, values) : array; } /** * This method is like `_.pullAll` except that it accepts `iteratee` which is * invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The iteratee is invoked with one argument: (value). * * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); * console.log(array); * // => [{ 'x': 2 }] */ function pullAllBy(array, values, iteratee) { return (array && array.length && values && values.length) ? basePullAll(array, values, getIteratee(iteratee, 2)) : array; } /** * This method is like `_.pullAll` except that it accepts `comparator` which * is invoked to compare elements of `array` to `values`. The comparator is * invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * * @static * @memberOf _ * @since 4.6.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); * console.log(array); * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ function pullAllWith(array, values, comparator) { return (array && array.length && values && values.length) ? basePullAll(array, values, undefined$1, comparator) : array; } /** * Removes elements from `array` corresponding to `indexes` and returns an * array of removed elements. * * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to modify. * @param {...(number|number[])} [indexes] The indexes of elements to remove. * @returns {Array} Returns the new array of removed elements. * @example * * var array = ['a', 'b', 'c', 'd']; * var pulled = _.pullAt(array, [1, 3]); * * console.log(array); * // => ['a', 'c'] * * console.log(pulled); * // => ['b', 'd'] */ var pullAt = flatRest(function(array, indexes) { var length = array == null ? 0 : array.length, result = baseAt(array, indexes); basePullAt(array, arrayMap(indexes, function(index) { return isIndex(index, length) ? +index : index; }).sort(compareAscending)); return result; }); /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` * to pull elements from an array by value. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = getIteratee(predicate, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Reverses `array` so that the first element becomes the last, the second * element becomes the second to last, and so on. * * **Note:** This method mutates `array` and is based on * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.reverse(array); * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function reverse(array) { return array == null ? array : nativeReverse.call(array); } /** * Creates a slice of `array` from `start` up to, but not including, `end`. * * **Note:** This method is used instead of * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are * returned. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function slice(array, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } else { start = start == null ? 0 : toInteger(start); end = end === undefined$1 ? length : toInteger(end); } return baseSlice(array, start, end); } /** * Uses a binary search to determine the lowest index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 */ function sortedIndex(array, value) { return baseSortedIndex(array, value); } /** * This method is like `_.sortedIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 0 * * // The `_.property` iteratee shorthand. * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); * // => 0 */ function sortedIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } /** * This method is like `_.indexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedIndexOf([4, 5, 5, 5, 6], 5); * // => 1 */ function sortedIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value); if (index < length && eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 5, 5, 5, 6], 5); * // => 4 */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 1 * * // The `_.property` iteratee shorthand. * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); * // => 1 */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); } /** * This method is like `_.lastIndexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); * // => 3 */ function sortedLastIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value, true) - 1; if (eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.uniq` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniq([1, 1, 2]); * // => [1, 2] */ function sortedUniq(array) { return (array && array.length) ? baseSortedUniq(array) : []; } /** * This method is like `_.uniqBy` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); * // => [1.1, 2.3] */ function sortedUniqBy(array, iteratee) { return (array && array.length) ? baseSortedUniq(array, getIteratee(iteratee, 2)) : []; } /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.tail([1, 2, 3]); * // => [2, 3] */ function tail(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 1, length) : []; } /** * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.take([1, 2, 3]); * // => [1] * * _.take([1, 2, 3], 2); * // => [1, 2] * * _.take([1, 2, 3], 5); * // => [1, 2, 3] * * _.take([1, 2, 3], 0); * // => [] */ function take(array, n, guard) { if (!(array && array.length)) { return []; } n = (guard || n === undefined$1) ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRight([1, 2, 3]); * // => [3] * * _.takeRight([1, 2, 3], 2); * // => [2, 3] * * _.takeRight([1, 2, 3], 5); * // => [1, 2, 3] * * _.takeRight([1, 2, 3], 0); * // => [] */ function takeRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined$1) ? 1 : toInteger(n); n = length - n; return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with elements taken from the end. Elements are * taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.takeRightWhile(users, function(o) { return !o.active; }); * // => objects for ['fred', 'pebbles'] * * // The `_.matches` iteratee shorthand. * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeRightWhile(users, ['active', false]); * // => objects for ['fred', 'pebbles'] * * // The `_.property` iteratee shorthand. * _.takeRightWhile(users, 'active'); * // => [] */ function takeRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; } /** * Creates a slice of `array` with elements taken from the beginning. Elements * are taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.takeWhile(users, function(o) { return !o.active; }); * // => objects for ['barney', 'fred'] * * // The `_.matches` iteratee shorthand. * _.takeWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeWhile(users, ['active', false]); * // => objects for ['barney', 'fred'] * * // The `_.property` iteratee shorthand. * _.takeWhile(users, 'active'); * // => [] */ function takeWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3)) : []; } /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2], [1, 2]); * // => [2, 1] */ var union = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); /** * This method is like `_.union` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which uniqueness is computed. Result values are chosen from the first * array in which the value occurs. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * _.unionBy([2.1], [1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ var unionBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined$1; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); }); /** * This method is like `_.union` except that it accepts `comparator` which * is invoked to compare elements of `arrays`. Result values are chosen from * the first array in which the value occurs. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.unionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var unionWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined$1; return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined$1, comparator); }); /** * Creates a duplicate-free version of an array, using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons, in which only the first occurrence of each element * is kept. The order of result values is determined by the order they occur * in the array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] */ function uniq(array) { return (array && array.length) ? baseUniq(array) : []; } /** * This method is like `_.uniq` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * uniqueness is computed. The order of result values is determined by the * order they occur in the array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniqBy(array, iteratee) { return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; } /** * This method is like `_.uniq` except that it accepts `comparator` which * is invoked to compare elements of `array`. The order of result values is * determined by the order they occur in the array.The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.uniqWith(objects, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ function uniqWith(array, comparator) { comparator = typeof comparator == 'function' ? comparator : undefined$1; return (array && array.length) ? baseUniq(array, undefined$1, comparator) : []; } /** * This method is like `_.zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-zip * configuration. * * @static * @memberOf _ * @since 1.2.0 * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] * * _.unzip(zipped); * // => [['a', 'b'], [1, 2], [true, false]] */ function unzip(array) { if (!(array && array.length)) { return []; } var length = 0; array = arrayFilter(array, function(group) { if (isArrayLikeObject(group)) { length = nativeMax(group.length, length); return true; } }); return baseTimes(length, function(index) { return arrayMap(array, baseProperty(index)); }); } /** * This method is like `_.unzip` except that it accepts `iteratee` to specify * how regrouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {Array} array The array of grouped elements to process. * @param {Function} [iteratee=_.identity] The function to combine * regrouped values. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip([1, 2], [10, 20], [100, 200]); * // => [[1, 10, 100], [2, 20, 200]] * * _.unzipWith(zipped, _.add); * // => [3, 30, 300] */ function unzipWith(array, iteratee) { if (!(array && array.length)) { return []; } var result = unzip(array); if (iteratee == null) { return result; } return arrayMap(result, function(group) { return apply(iteratee, undefined$1, group); }); } /** * Creates an array excluding all given values using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.xor * @example * * _.without([2, 1, 2, 3], 1, 2); * // => [3] */ var without = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @static * @memberOf _ * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.without * @example * * _.xor([2, 1], [2, 3]); * // => [1, 3] */ var xor = baseRest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); /** * This method is like `_.xor` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which by which they're compared. The order of result values is determined * by the order they occur in the arrays. The iteratee is invoked with one * argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2, 3.4] * * // The `_.property` iteratee shorthand. * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var xorBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined$1; } return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); }); /** * This method is like `_.xor` except that it accepts `comparator` which is * invoked to compare elements of `arrays`. The order of result values is * determined by the order they occur in the arrays. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.xorWith(objects, others, _.isEqual); * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var xorWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined$1; return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined$1, comparator); }); /** * Creates an array of grouped elements, the first of which contains the * first elements of the given arrays, the second of which contains the * second elements of the given arrays, and so on. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] */ var zip = baseRest(unzip); /** * This method is like `_.fromPairs` except that it accepts two arrays, * one of property identifiers and one of corresponding values. * * @static * @memberOf _ * @since 0.4.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObject(['a', 'b'], [1, 2]); * // => { 'a': 1, 'b': 2 } */ function zipObject(props, values) { return baseZipObject(props || [], values || [], assignValue); } /** * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ * @since 4.1.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ function zipObjectDeep(props, values) { return baseZipObject(props || [], values || [], baseSet); } /** * This method is like `_.zip` except that it accepts `iteratee` to specify * how grouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @param {Function} [iteratee=_.identity] The function to combine * grouped values. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { * return a + b + c; * }); * // => [111, 222] */ var zipWith = baseRest(function(arrays) { var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined$1; iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined$1; return unzipWith(arrays, iteratee); }); /*------------------------------------------------------------------------*/ /** * Creates a `lodash` wrapper instance that wraps `value` with explicit method * chain sequences enabled. The result of such sequences must be unwrapped * with `_#value`. * * @static * @memberOf _ * @since 1.3.0 * @category Seq * @param {*} value The value to wrap. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'pebbles', 'age': 1 } * ]; * * var youngest = _ * .chain(users) * .sortBy('age') * .map(function(o) { * return o.user + ' is ' + o.age; * }) * .head() * .value(); * // => 'pebbles is 1' */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } /** * This method invokes `interceptor` and returns `value`. The interceptor * is invoked with one argument; (value). The purpose of this method is to * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ * @since 0.1.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3]) * .tap(function(array) { * // Mutate input array. * array.pop(); * }) * .reverse() * .value(); * // => [2, 1] */ function tap(value, interceptor) { interceptor(value); return value; } /** * This method is like `_.tap` except that it returns the result of `interceptor`. * The purpose of this method is to "pass thru" values replacing intermediate * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns the result of `interceptor`. * @example * * _(' abc ') * .chain() * .trim() * .thru(function(value) { * return [value]; * }) * .value(); * // => ['abc'] */ function thru(value, interceptor) { return interceptor(value); } /** * This method is the wrapper version of `_.at`. * * @name at * @memberOf _ * @since 1.0.0 * @category Seq * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _(object).at(['a[0].b.c', 'a[1]']).value(); * // => [3, 4] */ var wrapperAt = flatRest(function(paths) { var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { return baseAt(object, paths); }; if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { return this.thru(interceptor); } value = value.slice(start, +start + (length ? 1 : 0)); value.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined$1 }); return new LodashWrapper(value, this.__chain__).thru(function(array) { if (length && !array.length) { array.push(undefined$1); } return array; }); }); /** * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * * @name chain * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // A sequence without explicit chaining. * _(users).head(); * // => { 'user': 'barney', 'age': 36 } * * // A sequence with explicit chaining. * _(users) * .chain() * .head() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this); } /** * Executes the chain sequence and returns the wrapped result. * * @name commit * @memberOf _ * @since 3.2.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapped = _(array).push(3); * * console.log(array); * // => [1, 2] * * wrapped = wrapped.commit(); * console.log(array); * // => [1, 2, 3] * * wrapped.last(); * // => 3 * * console.log(array); * // => [1, 2, 3] */ function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__); } /** * Gets the next value on a wrapped object following the * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * * @name next * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the next iterator value. * @example * * var wrapped = _([1, 2]); * * wrapped.next(); * // => { 'done': false, 'value': 1 } * * wrapped.next(); * // => { 'done': false, 'value': 2 } * * wrapped.next(); * // => { 'done': true, 'value': undefined } */ function wrapperNext() { if (this.__values__ === undefined$1) { this.__values__ = toArray(this.value()); } var done = this.__index__ >= this.__values__.length, value = done ? undefined$1 : this.__values__[this.__index__++]; return { 'done': done, 'value': value }; } /** * Enables the wrapper to be iterable. * * @name Symbol.iterator * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the wrapper object. * @example * * var wrapped = _([1, 2]); * * wrapped[Symbol.iterator]() === wrapped; * // => true * * Array.from(wrapped); * // => [1, 2] */ function wrapperToIterator() { return this; } /** * Creates a clone of the chain sequence planting `value` as the wrapped value. * * @name plant * @memberOf _ * @since 3.2.0 * @category Seq * @param {*} value The value to plant. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2]).map(square); * var other = wrapped.plant([3, 4]); * * other.value(); * // => [9, 16] * * wrapped.value(); * // => [1, 4] */ function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); clone.__index__ = 0; clone.__values__ = undefined$1; if (result) { previous.__wrapped__ = clone; } else { result = clone; } var previous = clone; parent = parent.__wrapped__; } previous.__wrapped__ = value; return result; } /** * This method is the wrapper version of `_.reverse`. * * **Note:** This method mutates the wrapped array. * * @name reverse * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2, 3]; * * _(array).reverse().value() * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { var wrapped = value; if (this.__actions__.length) { wrapped = new LazyWrapper(this); } wrapped = wrapped.reverse(); wrapped.__actions__.push({ 'func': thru, 'args': [reverse], 'thisArg': undefined$1 }); return new LodashWrapper(wrapped, this.__chain__); } return this.thru(reverse); } /** * Executes the chain sequence to resolve the unwrapped value. * * @name value * @memberOf _ * @since 0.1.0 * @alias toJSON, valueOf * @category Seq * @returns {*} Returns the resolved unwrapped value. * @example * * _([1, 2, 3]).value(); * // => [1, 2, 3] */ function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__); } /*------------------------------------------------------------------------*/ /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the number of times the key was returned by `iteratee`. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.5.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': 1, '6': 2 } * * // The `_.property` iteratee shorthand. * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { ++result[key]; } else { baseAssignValue(result, key, 1); } }); /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * Iteration is stopped once `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index|key, collection). * * **Note:** This method returns `true` for * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of * elements of empty collections. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.every(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.every(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.every(users, 'active'); * // => false */ function every(collection, predicate, guard) { var func = isArray(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined$1; } return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] * * // Combining several predicates using `_.overEvery` or `_.overSome`. * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); * // => objects for ['fred', 'barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); /** * This method is like `_.find` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=collection.length-1] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(n) { * return n % 2 == 1; * }); * // => 3 */ var findLast = createFind(findLastIndex); /** * Creates a flattened array of values by running each element in `collection` * thru `iteratee` and flattening the mapped results. The iteratee is invoked * with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [n, n]; * } * * _.flatMap([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDeep([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMapDeep(collection, iteratee) { return baseFlatten(map(collection, iteratee), INFINITY); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results up to `depth` times. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDepth([1, 2], duplicate, 2); * // => [[1, 1], [2, 2]] */ function flatMapDepth(collection, iteratee, depth) { depth = depth === undefined$1 ? 1 : toInteger(depth); return baseFlatten(map(collection, iteratee), depth); } /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.forEach` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @alias eachRight * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEach * @example * * _.forEachRight([1, 2], function(value) { * console.log(value); * }); * // => Logs `2` then `1`. */ function forEachRight(collection, iteratee) { var func = isArray(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee, 3)); } /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The order of grouped values * is determined by the order they occur in `collection`. The corresponding * value of each key is an array of elements responsible for generating the * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': [4.2], '6': [6.1, 6.3] } * * // The `_.property` iteratee shorthand. * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { baseAssignValue(result, key, [value]); } }); /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } /** * Invokes the method at `path` of each element in `collection`, returning * an array of the results of each invoked method. Any additional arguments * are provided to each invoked method. If `path` is a function, it's invoked * for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|string} path The path of the method to invoke or * the function invoked per iteration. * @param {...*} [args] The arguments to invoke each method with. * @returns {Array} Returns the array of results. * @example * * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invokeMap([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ var invokeMap = baseRest(function(collection, path, args) { var index = -1, isFunc = typeof path == 'function', result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value) { result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); }); return result; }); /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the last element responsible for generating the key. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * var array = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.keyBy(array, function(o) { * return String.fromCharCode(o.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.keyBy(array, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } */ var keyBy = createAggregator(function(result, value, key) { baseAssignValue(result, key, value); }); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined$1 : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } /** * Creates an array of elements split into two groups, the first of which * contains elements `predicate` returns truthy for, the second of which * contains elements `predicate` returns falsey for. The predicate is * invoked with one argument: (value). * * @static * @memberOf _ * @since 3.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of grouped elements. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true }, * { 'user': 'pebbles', 'age': 1, 'active': false } * ]; * * _.partition(users, function(o) { return o.active; }); * // => objects for [['fred'], ['barney', 'pebbles']] * * // The `_.matches` iteratee shorthand. * _.partition(users, { 'age': 1, 'active': false }); * // => objects for [['pebbles'], ['barney', 'fred']] * * // The `_.matchesProperty` iteratee shorthand. * _.partition(users, ['active', false]); * // => objects for [['barney', 'pebbles'], ['fred']] * * // The `_.property` iteratee shorthand. * _.partition(users, 'active'); * // => objects for [['fred'], ['barney', 'pebbles']] */ var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value); }, function() { return [[], []]; }); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); } /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduce * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * * _.reduceRight(array, function(flattened, other) { * return flattened.concat(other); * }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } /** * The opposite of `_.filter`; this method returns the elements of `collection` * that `predicate` does **not** return truthy for. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.filter * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true } * ]; * * _.reject(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.reject(users, { 'age': 40, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.reject(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.reject(users, 'active'); * // => objects for ['barney'] */ function reject(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, negate(getIteratee(predicate, 3))); } /** * Gets a random element from `collection`. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. * @example * * _.sample([1, 2, 3, 4]); * // => 2 */ function sample(collection) { var func = isArray(collection) ? arraySample : baseSample; return func(collection); } /** * Gets `n` random elements at unique keys from `collection` up to the * size of `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @param {number} [n=1] The number of elements to sample. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the random elements. * @example * * _.sampleSize([1, 2, 3], 2); * // => [3, 1] * * _.sampleSize([1, 2, 3], 4); * // => [2, 3, 1] */ function sampleSize(collection, n, guard) { if ((guard ? isIterateeCall(collection, n, guard) : n === undefined$1)) { n = 1; } else { n = toInteger(n); } var func = isArray(collection) ? arraySampleSize : baseSampleSize; return func(collection, n); } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * _.shuffle([1, 2, 3, 4]); * // => [4, 1, 3, 2] */ function shuffle(collection) { var func = isArray(collection) ? arrayShuffle : baseShuffle; return func(collection); } /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the collection size. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { if (collection == null) { return 0; } if (isArrayLike(collection)) { return isString(collection) ? stringSize(collection) : collection.length; } var tag = getTag(collection); if (tag == mapTag || tag == setTag) { return collection.size; } return baseKeys(collection).length; } /** * Checks if `predicate` returns truthy for **any** element of `collection`. * Iteration is stopped once `predicate` returns truthy. The predicate is * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.some(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.some(users, 'active'); * // => true */ function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined$1; } return func(collection, getIteratee(predicate, 3)); } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection thru each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to sort by. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 30 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, [function(o) { return o.user; }]); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] */ var sortBy = baseRest(function(collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return baseOrderBy(collection, baseFlatten(iteratees, 1), []); }); /*------------------------------------------------------------------------*/ /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = ctxNow || function() { return root.Date.now(); }; /*------------------------------------------------------------------------*/ /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => Logs 'done saving!' after the two async saves have completed. */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that invokes `func`, with up to `n` arguments, * ignoring any additional arguments. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { n = guard ? undefined$1 : n; n = (func && n == null) ? func.length : n; return createWrap(func, WRAP_ARY_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, n); } /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it's called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery(element).on('click', _.before(5, addContactToList)); * // => Allows adding up to 4 contacts to the list. */ function before(n, func) { var result; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = undefined$1; } return result; }; } /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); /** * Creates a function that invokes the method at `object[key]` with `partials` * prepended to the arguments it receives. * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. See * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ * @since 0.10.0 * @category Function * @param {Object} object The object to invoke the method on. * @param {string} key The key of the method. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'user': 'fred', * 'greet': function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * }; * * var bound = _.bindKey(object, 'greet', 'hi'); * bound('!'); * // => 'hi fred!' * * object.greet = function(greeting, punctuation) { * return greeting + 'ya ' + this.user + punctuation; * }; * * bound('!'); * // => 'hiya fred!' * * // Bound with placeholders. * var bound = _.bindKey(object, 'greet', _, '!'); * bound('hi'); * // => 'hiya fred!' */ var bindKey = baseRest(function(object, key, partials) { var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bindKey)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(key, bitmask, object, partials, holders); }); /** * Creates a function that accepts arguments of `func` and either invokes * `func` returning its result, if at least `arity` number of arguments have * been provided, or returns a function that accepts the remaining `func` * arguments, and so on. The arity of `func` may be specified if `func.length` * is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 2.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(1)(_, 3)(2); * // => [1, 2, 3] */ function curry(func, arity, guard) { arity = guard ? undefined$1 : arity; var result = createWrap(func, WRAP_CURRY_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, undefined$1, arity); result.placeholder = curry.placeholder; return result; } /** * This method is like `_.curry` except that arguments are applied to `func` * in the manner of `_.partialRight` instead of `_.partial`. * * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curryRight(abc); * * curried(3)(2)(1); * // => [1, 2, 3] * * curried(2, 3)(1); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(3)(1, _)(2); * // => [1, 2, 3] */ function curryRight(func, arity, guard) { arity = guard ? undefined$1 : arity; var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, undefined$1, arity); result.placeholder = curryRight.placeholder; return result; } /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined$1; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined$1 || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined$1; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined$1; return result; } function cancel() { if (timerId !== undefined$1) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined$1; } function flush() { return timerId === undefined$1 ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined$1) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. clearTimeout(timerId); timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined$1) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } /** * Defers invoking the `func` until the current call stack has cleared. Any * additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to defer. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { * console.log(text); * }, 'deferred'); * // => Logs 'deferred' after one millisecond. */ var defer = baseRest(function(func, args) { return baseDelay(func, 1, args); }); /** * Invokes `func` after `wait` milliseconds. Any additional arguments are * provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { * console.log(text); * }, 1000, 'later'); * // => Logs 'later' after one second. */ var delay = baseRest(function(func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args); }); /** * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to flip arguments for. * @returns {Function} Returns the new flipped function. * @example * * var flipped = _.flip(function() { * return _.toArray(arguments); * }); * * flipped('a', 'b', 'c', 'd'); * // => ['d', 'c', 'b', 'a'] */ function flip(func) { return createWrap(func, WRAP_FLIP_FLAG); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; /** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new negated function. * @example * * function isEven(n) { * return n % 2 == 0; * } * * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); * // => [1, 3, 5] */ function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function() { var args = arguments; switch (args.length) { case 0: return !predicate.call(this); case 1: return !predicate.call(this, args[0]); case 2: return !predicate.call(this, args[0], args[1]); case 3: return !predicate.call(this, args[0], args[1], args[2]); } return !predicate.apply(this, args); }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first invocation. The `func` is * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // => `createApplication` is invoked once */ function once(func) { return before(2, func); } /** * Creates a function that invokes `func` with its arguments transformed. * * @static * @since 4.0.0 * @memberOf _ * @category Function * @param {Function} func The function to wrap. * @param {...(Function|Function[])} [transforms=[_.identity]] * The argument transforms. * @returns {Function} Returns the new function. * @example * * function doubled(n) { * return n * 2; * } * * function square(n) { * return n * n; * } * * var func = _.overArgs(function(x, y) { * return [x, y]; * }, [square, doubled]); * * func(9, 3); * // => [81, 6] * * func(10, 5); * // => [100, 10] */ var overArgs = castRest(function(func, transforms) { transforms = (transforms.length == 1 && isArray(transforms[0])) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); var funcsLength = transforms.length; return baseRest(function(args) { var index = -1, length = nativeMin(args.length, funcsLength); while (++index < length) { args[index] = transforms[index].call(this, args[index]); } return apply(func, this, args); }); }); /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, WRAP_PARTIAL_FLAG, undefined$1, partials, holders); }); /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined$1, partials, holders); }); /** * Creates a function that invokes `func` with arguments arranged according * to the specified `indexes` where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, [2, 0, 1]); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] */ var rearg = flatRest(function(func, indexes) { return createWrap(func, WRAP_REARG_FLAG, undefined$1, undefined$1, undefined$1, indexes); }); /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as * an array. * * **Note:** This method is based on the * [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.rest(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function rest(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start === undefined$1 ? start : toInteger(start); return baseRest(func, start); } /** * Creates a function that invokes `func` with the `this` binding of the * create function and an array of arguments much like * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). * * **Note:** This method is based on the * [spread operator](https://mdn.io/spread_operator). * * @static * @memberOf _ * @since 3.2.0 * @category Function * @param {Function} func The function to spread arguments over. * @param {number} [start=0] The start position of the spread. * @returns {Function} Returns the new function. * @example * * var say = _.spread(function(who, what) { * return who + ' says ' + what; * }); * * say(['fred', 'hello']); * // => 'fred says hello' * * var numbers = Promise.all([ * Promise.resolve(40), * Promise.resolve(36) * ]); * * numbers.then(_.spread(function(x, y) { * return x + y; * })); * // => a Promise of 76 */ function spread(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start == null ? 0 : nativeMax(toInteger(start), 0); return baseRest(function(args) { var array = args[start], otherArgs = castSlice(args, 0, start); if (array) { arrayPush(otherArgs, array); } return apply(func, this, otherArgs); }); } /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed `func` invocations and a `flush` method to * immediately invoke them. Provide `options` to indicate whether `func` * should be invoked on the leading and/or trailing edge of the `wait` * timeout. The `func` is invoked with the last arguments provided to the * throttled function. Subsequent calls to the throttled function return the * result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the throttled function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=true] * Specify invoking on the leading edge of the timeout. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // Avoid excessively updating the position while scrolling. * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); * jQuery(element).on('click', throttled); * * // Cancel the trailing throttled invocation. * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': wait, 'trailing': trailing }); } /** * Creates a function that accepts up to one argument, ignoring any * additional arguments. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.unary(parseInt)); * // => [6, 8, 10] */ function unary(func) { return ary(func, 1); } /** * Creates a function that provides `value` to `wrapper` as its first * argument. Any additional arguments provided to the function are appended * to those provided to the `wrapper`. The wrapper is invoked with the `this` * binding of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {*} value The value to wrap. * @param {Function} [wrapper=identity] The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '

' + func(text) + '

'; * }); * * p('fred, barney, & pebbles'); * // => '

fred, barney, & pebbles

' */ function wrap(value, wrapper) { return partial(castFunction(wrapper), value); } /*------------------------------------------------------------------------*/ /** * Casts `value` as an array if it's not one. * * @static * @memberOf _ * @since 4.4.0 * @category Lang * @param {*} value The value to inspect. * @returns {Array} Returns the cast array. * @example * * _.castArray(1); * // => [1] * * _.castArray({ 'a': 1 }); * // => [{ 'a': 1 }] * * _.castArray('abc'); * // => ['abc'] * * _.castArray(null); * // => [null] * * _.castArray(undefined); * // => [undefined] * * _.castArray(); * // => [] * * var array = [1, 2, 3]; * console.log(_.castArray(array) === array); * // => true */ function castArray() { if (!arguments.length) { return []; } var value = arguments[0]; return isArray(value) ? value : [value]; } /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined$1; return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); } /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); } /** * This method is like `_.cloneWith` except that it recursively clones `value`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to recursively clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the deep cloned value. * @see _.cloneWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * } * * var el = _.cloneDeepWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 20 */ function cloneDeepWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined$1; return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); } /** * Checks if `object` conforms to `source` by invoking the predicate * properties of `source` with the corresponding property values of `object`. * * **Note:** This method is equivalent to `_.conforms` when `source` is * partially applied. * * @static * @memberOf _ * @since 4.14.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); * // => true * * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); * // => false */ function conformsTo(object, source) { return source == null || baseConformsTo(object, source, keys(source)); } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is greater than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. * @see _.lt * @example * * _.gt(3, 1); * // => true * * _.gt(3, 3); * // => false * * _.gt(1, 3); * // => false */ var gt = createRelationalOperation(baseGt); /** * Checks if `value` is greater than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than or equal to * `other`, else `false`. * @see _.lte * @example * * _.gte(3, 1); * // => true * * _.gte(3, 3); * // => true * * _.gte(1, 3); * // => false */ var gte = createRelationalOperation(function(value, other) { return value >= other; }); /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is classified as an `ArrayBuffer` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. * @example * * _.isArrayBuffer(new ArrayBuffer(2)); * // => true * * _.isArrayBuffer(new Array(2)); * // => false */ var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && baseGetTag(value) == boolTag); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. * @example * * _.isDate(new Date); * // => true * * _.isDate('Mon April 23 2012'); * // => false */ var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; /** * Checks if `value` is likely a DOM element. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true * * _.isElement(''); * // => false */ function isElement(value) { return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); } /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * This method is like `_.isEqual` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with up to * six arguments: (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqualWith(array, other, customizer); * // => true */ function isEqualWith(value, other, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined$1; var result = customizer ? customizer(value, other) : undefined$1; return result === undefined$1 ? baseIsEqual(value, other, undefined$1, customizer) : !!result; } /** * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, * `SyntaxError`, `TypeError`, or `URIError` object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * * _.isError(new Error); * // => true * * _.isError(Error); * // => false */ function isError(value) { if (!isObjectLike(value)) { return false; } var tag = baseGetTag(value); return tag == errorTag || tag == domExcTag || (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); } /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is an integer. * * **Note:** This method is based on * [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * * _.isInteger(3); * // => true * * _.isInteger(Number.MIN_VALUE); * // => false * * _.isInteger(Infinity); * // => false * * _.isInteger('3'); * // => false */ function isInteger(value) { return typeof value == 'number' && value == toInteger(value); } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; /** * Performs a partial deep comparison between `object` and `source` to * determine if `object` contains equivalent property values. * * **Note:** This method is equivalent to `_.matches` when `source` is * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.isMatch(object, { 'b': 2 }); * // => true * * _.isMatch(object, { 'b': 1 }); * // => false */ function isMatch(object, source) { return object === source || baseIsMatch(object, source, getMatchData(source)); } /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with five * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ function isMatchWith(object, source, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined$1; return baseIsMatch(object, source, getMatchData(source), customizer); } /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } /** * Checks if `value` is a pristine native function. * * **Note:** This method can't reliably detect native functions in the presence * of the core-js package because core-js circumvents this kind of detection. * Despite multiple requests, the core-js maintainer has made it clear: any * attempt to fix the detection will be obstructed. As a result, we're left * with little choice but to throw an error. Unfortunately, this also affects * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), * which rely on core-js. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (isMaskable(value)) { throw new Error(CORE_ERROR_TEXT); } return baseIsNative(value); } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ function isNil(value) { return value == null; } /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && baseGetTag(value) == numberTag); } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 * double precision number which isn't the result of a rounded unsafe integer. * * **Note:** This method is based on * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. * @example * * _.isSafeInteger(3); * // => true * * _.isSafeInteger(Number.MIN_VALUE); * // => false * * _.isSafeInteger(Infinity); * // => false * * _.isSafeInteger('3'); * // => false */ function isSafeInteger(value) { return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined$1; } /** * Checks if `value` is classified as a `WeakMap` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. * @example * * _.isWeakMap(new WeakMap); * // => true * * _.isWeakMap(new Map); * // => false */ function isWeakMap(value) { return isObjectLike(value) && getTag(value) == weakMapTag; } /** * Checks if `value` is classified as a `WeakSet` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. * @example * * _.isWeakSet(new WeakSet); * // => true * * _.isWeakSet(new Set); * // => false */ function isWeakSet(value) { return isObjectLike(value) && baseGetTag(value) == weakSetTag; } /** * Checks if `value` is less than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. * @see _.gt * @example * * _.lt(1, 3); * // => true * * _.lt(3, 3); * // => false * * _.lt(3, 1); * // => false */ var lt = createRelationalOperation(baseLt); /** * Checks if `value` is less than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than or equal to * `other`, else `false`. * @see _.gte * @example * * _.lte(1, 3); * // => true * * _.lte(3, 3); * // => true * * _.lte(3, 1); * // => false */ var lte = createRelationalOperation(function(value, other) { return value <= other; }); /** * Converts `value` to an array. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Array} Returns the converted array. * @example * * _.toArray({ 'a': 1, 'b': 2 }); * // => [1, 2] * * _.toArray('abc'); * // => ['a', 'b', 'c'] * * _.toArray(1); * // => [] * * _.toArray(null); * // => [] */ function toArray(value) { if (!value) { return []; } if (isArrayLike(value)) { return isString(value) ? stringToArray(value) : copyArray(value); } if (symIterator && value[symIterator]) { return iteratorToArray(value[symIterator]()); } var tag = getTag(value), func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); return func(value); } /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toLength(3.2); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3.2'); * // => 3 */ function toLength(value) { return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = baseTrim(value); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } /** * Converts `value` to a safe integer. A safe integer can be compared and * represented correctly. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toSafeInteger(3.2); * // => 3 * * _.toSafeInteger(Number.MIN_VALUE); * // => 0 * * _.toSafeInteger(Infinity); * // => 9007199254740991 * * _.toSafeInteger('3.2'); * // => 3 */ function toSafeInteger(value) { return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : (value === 0 ? value : 0); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /*------------------------------------------------------------------------*/ /** * Assigns own enumerable string keyed properties of source objects to the * destination object. Source objects are applied from left to right. * Subsequent sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object` and is loosely based on * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ * @since 0.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assignIn * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assign({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3 } */ var assign = createAssigner(function(object, source) { if (isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return; } for (var key in source) { if (hasOwnProperty.call(source, key)) { assignValue(object, key, source[key]); } } }); /** * This method is like `_.assign` except that it iterates over own and * inherited source properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assign * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assignIn({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } */ var assignIn = createAssigner(function(object, source) { copyObject(source, keysIn(source), object); }); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); /** * This method is like `_.assign` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignInWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer); }); /** * Creates an array of values corresponding to `paths` of `object`. * * @static * @memberOf _ * @since 1.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Array} Returns the picked values. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _.at(object, ['a[0].b.c', 'a[1]']); * // => [3, 4] */ var at = flatRest(baseAt); /** * Creates an object that inherits from the `prototype` object. If a * `properties` object is given, its own enumerable string keyed properties * are assigned to the created object. * * @static * @memberOf _ * @since 2.3.0 * @category Object * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @returns {Object} Returns the new object. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * function Circle() { * Shape.call(this); * } * * Circle.prototype = _.create(Shape.prototype, { * 'constructor': Circle * }); * * var circle = new Circle; * circle instanceof Circle; * // => true * * circle instanceof Shape; * // => true */ function create(prototype, properties) { var result = baseCreate(prototype); return properties == null ? result : baseAssign(result, properties); } /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(object, sources) { object = Object(object); var index = -1; var length = sources.length; var guard = length > 2 ? sources[2] : undefined$1; if (guard && isIterateeCall(sources[0], sources[1], guard)) { length = 1; } while (++index < length) { var source = sources[index]; var props = keysIn(source); var propsIndex = -1; var propsLength = props.length; while (++propsIndex < propsLength) { var key = props[propsIndex]; var value = object[key]; if (value === undefined$1 || (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { object[key] = source[key]; } } } return object; }); /** * This method is like `_.defaults` except that it recursively assigns * default properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaults * @example * * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); * // => { 'a': { 'b': 2, 'c': 3 } } */ var defaultsDeep = baseRest(function(args) { args.push(undefined$1, customDefaultsMerge); return apply(mergeWith, undefined$1, args); }); /** * This method is like `_.find` except that it returns the key of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findKey(users, function(o) { return o.age < 40; }); * // => 'barney' (iteration order is not guaranteed) * * // The `_.matches` iteratee shorthand. * _.findKey(users, { 'age': 1, 'active': true }); * // => 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.findKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findKey(users, 'active'); * // => 'barney' */ function findKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); } /** * This method is like `_.findKey` except that it iterates over elements of * a collection in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findLastKey(users, function(o) { return o.age < 40; }); * // => returns 'pebbles' assuming `_.findKey` returns 'barney' * * // The `_.matches` iteratee shorthand. * _.findLastKey(users, { 'age': 36, 'active': true }); * // => 'barney' * * // The `_.matchesProperty` iteratee shorthand. * _.findLastKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findLastKey(users, 'active'); * // => 'pebbles' */ function findLastKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); } /** * Iterates over own and inherited enumerable string keyed properties of an * object and invokes `iteratee` for each property. The iteratee is invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forInRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). */ function forIn(object, iteratee) { return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn); } /** * This method is like `_.forIn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forIn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forInRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. */ function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn); } /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)); } /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. */ function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, getIteratee(iteratee, 3)); } /** * Creates an array of function property names from own enumerable properties * of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functionsIn * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functions(new Foo); * // => ['a', 'b'] */ function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)); } /** * Creates an array of function property names from own and inherited * enumerable properties of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functions * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functionsIn(new Foo); * // => ['a', 'b', 'c'] */ function functionsIn(object) { return object == null ? [] : baseFunctions(object, keysIn(object)); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined$1 : baseGet(object, path); return result === undefined$1 ? defaultValue : result; } /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } result[value] = key; }, constant(identity)); /** * This method is like `_.invert` except that the inverted object is generated * from the results of running each element of `object` thru `iteratee`. The * corresponding inverted value of each inverted key is an array of keys * responsible for generating the inverted value. The iteratee is invoked * with one argument: (value). * * @static * @memberOf _ * @since 4.1.0 * @category Object * @param {Object} object The object to invert. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invertBy(object); * // => { '1': ['a', 'c'], '2': ['b'] } * * _.invertBy(object, function(value) { * return 'group' + value; * }); * // => { 'group1': ['a', 'c'], 'group2': ['b'] } */ var invertBy = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } }, getIteratee); /** * Invokes the method at `path` of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. * @example * * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; * * _.invoke(object, 'a[0].b.c.slice', 1, 3); * // => [2, 3] */ var invoke = baseRest(baseInvoke); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, iteratee(value, key, object), value); }); return result; } /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); /** * This method is like `_.merge` except that it accepts `customizer` which * is invoked to produce the merged values of the destination and source * properties. If `customizer` returns `undefined`, merging is handled by the * method instead. The `customizer` is invoked with six arguments: * (objValue, srcValue, key, object, source, stack). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * if (_.isArray(objValue)) { * return objValue.concat(srcValue); * } * } * * var object = { 'a': [1], 'b': [2] }; * var other = { 'a': [3], 'b': [4] }; * * _.mergeWith(object, other, customizer); * // => { 'a': [1, 3], 'b': [2, 4] } */ var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer); }); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = arrayMap(paths, function(path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); copyObject(object, getAllKeysIn(object), result); if (isDeep) { result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); } var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); /** * The opposite of `_.pickBy`; this method creates an object composed of * the own and inherited enumerable string keyed properties of `object` that * `predicate` doesn't return truthy for. The predicate is invoked with two * arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ function omitBy(object, predicate) { return pickBy(object, negate(getIteratee(predicate))); } /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = flatRest(function(object, paths) { return object == null ? {} : basePick(object, paths); }); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap(getAllKeysIn(object), function(prop) { return [prop]; }); predicate = getIteratee(predicate); return basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } /** * This method is like `_.get` except that if the resolved value is a * function it's invoked with the `this` binding of its parent object and * its result is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to resolve. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * * _.result(object, 'a[0].b.c1'); * // => 3 * * _.result(object, 'a[0].b.c2'); * // => 4 * * _.result(object, 'a[0].b.c3', 'default'); * // => 'default' * * _.result(object, 'a[0].b.c3', _.constant('default')); * // => 'default' */ function result(object, path, defaultValue) { path = castPath(path, object); var index = -1, length = path.length; // Ensure the loop is entered when path is empty. if (!length) { length = 1; object = undefined$1; } while (++index < length) { var value = object == null ? undefined$1 : object[toKey(path[index])]; if (value === undefined$1) { index = length; value = defaultValue; } object = isFunction(value) ? value.call(object) : value; } return object; } /** * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, * it's created. Arrays are created for missing index properties while objects * are created for all other missing properties. Use `_.setWith` to customize * `path` creation. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.set(object, 'a[0].b.c', 4); * console.log(object.a[0].b.c); * // => 4 * * _.set(object, ['x', '0', 'y', 'z'], 5); * console.log(object.x[0].y.z); * // => 5 */ function set(object, path, value) { return object == null ? object : baseSet(object, path, value); } /** * This method is like `_.set` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.setWith(object, '[0][1]', 'a', Object); * // => { '0': { '1': 'a' } } */ function setWith(object, path, value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined$1; return object == null ? object : baseSet(object, path, value, customizer); } /** * Creates an array of own enumerable string keyed-value pairs for `object` * which can be consumed by `_.fromPairs`. If `object` is a map or set, its * entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entries * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairs(new Foo); * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ var toPairs = createToPairs(keys); /** * Creates an array of own and inherited enumerable string keyed-value pairs * for `object` which can be consumed by `_.fromPairs`. If `object` is a map * or set, its entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entriesIn * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairsIn(new Foo); * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) */ var toPairsIn = createToPairs(keysIn); /** * An alternative to `_.reduce`; this method transforms `object` to a new * `accumulator` object which is the result of running each of its own * enumerable string keyed properties thru `iteratee`, with each invocation * potentially mutating the `accumulator` object. If `accumulator` is not * provided, a new object with the same `[[Prototype]]` will be used. The * iteratee is invoked with four arguments: (accumulator, value, key, object). * Iteratee functions may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 1.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The custom accumulator value. * @returns {*} Returns the accumulated value. * @example * * _.transform([2, 3, 4], function(result, n) { * result.push(n *= n); * return n % 2 == 0; * }, []); * // => [4, 9] * * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } */ function transform(object, iteratee, accumulator) { var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); if (accumulator == null) { var Ctor = object && object.constructor; if (isArrLike) { accumulator = isArr ? new Ctor : []; } else if (isObject(object)) { accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; } else { accumulator = {}; } } (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; } /** * Removes the property at `path` of `object`. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. * @example * * var object = { 'a': [{ 'b': { 'c': 7 } }] }; * _.unset(object, 'a[0].b.c'); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; * * _.unset(object, ['a', '0', 'b', 'c']); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; */ function unset(object, path) { return object == null ? true : baseUnset(object, path); } /** * This method is like `_.set` except that accepts `updater` to produce the * value to set. Use `_.updateWith` to customize `path` creation. The `updater` * is invoked with one argument: (value). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.update(object, 'a[0].b.c', function(n) { return n * n; }); * console.log(object.a[0].b.c); * // => 9 * * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); * console.log(object.x[0].y.z); * // => 0 */ function update(object, path, updater) { return object == null ? object : baseUpdate(object, path, castFunction(updater)); } /** * This method is like `_.update` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.updateWith(object, '[0][1]', _.constant('a'), Object); * // => { '0': { '1': 'a' } } */ function updateWith(object, path, updater, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined$1; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); } /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : baseValues(object, keys(object)); } /** * Creates an array of the own and inherited enumerable string keyed property * values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.valuesIn(new Foo); * // => [1, 2, 3] (iteration order is not guaranteed) */ function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)); } /*------------------------------------------------------------------------*/ /** * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ * @since 4.0.0 * @category Number * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. * @example * * _.clamp(-10, -5, 5); * // => -5 * * _.clamp(10, -5, 5); * // => 5 */ function clamp(number, lower, upper) { if (upper === undefined$1) { upper = lower; lower = undefined$1; } if (upper !== undefined$1) { upper = toNumber(upper); upper = upper === upper ? upper : 0; } if (lower !== undefined$1) { lower = toNumber(lower); lower = lower === lower ? lower : 0; } return baseClamp(toNumber(number), lower, upper); } /** * Checks if `n` is between `start` and up to, but not including, `end`. If * `end` is not specified, it's set to `start` with `start` then set to `0`. * If `start` is greater than `end` the params are swapped to support * negative ranges. * * @static * @memberOf _ * @since 3.3.0 * @category Number * @param {number} number The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. * @see _.range, _.rangeRight * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false * * _.inRange(-3, -2, -6); * // => true */ function inRange(number, start, end) { start = toFinite(start); if (end === undefined$1) { end = start; start = 0; } else { end = toFinite(end); } number = toNumber(number); return baseInRange(number, start, end); } /** * Produces a random number between the inclusive `lower` and `upper` bounds. * If only one argument is provided a number between `0` and the given number * is returned. If `floating` is `true`, or either `lower` or `upper` are * floats, a floating-point number is returned instead of an integer. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @memberOf _ * @since 0.7.0 * @category Number * @param {number} [lower=0] The lower bound. * @param {number} [upper=1] The upper bound. * @param {boolean} [floating] Specify returning a floating-point number. * @returns {number} Returns the random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(lower, upper, floating) { if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { upper = floating = undefined$1; } if (floating === undefined$1) { if (typeof upper == 'boolean') { floating = upper; upper = undefined$1; } else if (typeof lower == 'boolean') { floating = lower; lower = undefined$1; } } if (lower === undefined$1 && upper === undefined$1) { lower = 0; upper = 1; } else { lower = toFinite(lower); if (upper === undefined$1) { upper = lower; lower = 0; } else { upper = toFinite(upper); } } if (lower > upper) { var temp = lower; lower = upper; upper = temp; } if (floating || lower % 1 || upper % 1) { var rand = nativeRandom(); return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); } return baseRandom(lower, upper); } /*------------------------------------------------------------------------*/ /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar--'); * // => 'fooBar' * * _.camelCase('__FOO_BAR__'); * // => 'fooBar' */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word); }); /** * Converts the first character of `string` to upper case and the remaining * to lower case. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('FRED'); * // => 'Fred' */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } /** * Deburrs `string` by converting * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) * letters to basic Latin letters and removing * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = toString(string); return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); } /** * Checks if `string` ends with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=string.length] The position to search up to. * @returns {boolean} Returns `true` if `string` ends with `target`, * else `false`. * @example * * _.endsWith('abc', 'c'); * // => true * * _.endsWith('abc', 'b'); * // => false * * _.endsWith('abc', 'b', 2); * // => true */ function endsWith(string, target, position) { string = toString(string); target = baseToString(target); var length = string.length; position = position === undefined$1 ? length : baseClamp(toInteger(position), 0, length); var end = position; position -= target.length; return position >= 0 && string.slice(position, end) == target; } /** * Converts the characters "&", "<", ">", '"', and "'" in `string` to their * corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional * characters use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't need escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. See * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * When working with HTML you should always * [quote attribute values](http://wonko.com/post/html-escaping) to reduce * XSS vectors. * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, & pebbles' */ function escape(string) { string = toString(string); return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } /** * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https://lodash\.com/\)' */ function escapeRegExp(string) { string = toString(string); return (string && reHasRegExpChar.test(string)) ? string.replace(reRegExpChar, '\\$&') : string; } /** * Converts `string` to * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__FOO_BAR__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); /** * Converts `string`, as space separated words, to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.lowerCase('--Foo-Bar--'); * // => 'foo bar' * * _.lowerCase('fooBar'); * // => 'foo bar' * * _.lowerCase('__FOO_BAR__'); * // => 'foo bar' */ var lowerCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toLowerCase(); }); /** * Converts the first character of `string` to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.lowerFirst('Fred'); * // => 'fred' * * _.lowerFirst('FRED'); * // => 'fRED' */ var lowerFirst = createCaseFirst('toLowerCase'); /** * Pads `string` on the left and right sides if it's shorter than `length`. * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.pad('abc', 8); * // => ' abc ' * * _.pad('abc', 8, '_-'); * // => '_-abc_-_' * * _.pad('abc', 3); * // => 'abc' */ function pad(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; if (!length || strLength >= length) { return string; } var mid = (length - strLength) / 2; return ( createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars) ); } /** * Pads `string` on the right side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padEnd('abc', 6); * // => 'abc ' * * _.padEnd('abc', 6, '_-'); * // => 'abc_-_' * * _.padEnd('abc', 3); * // => 'abc' */ function padEnd(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (string + createPadding(length - strLength, chars)) : string; } /** * Pads `string` on the left side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padStart('abc', 6); * // => ' abc' * * _.padStart('abc', 6, '_-'); * // => '_-_abc' * * _.padStart('abc', 3); * // => 'abc' */ function padStart(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (createPadding(length - strLength, chars) + string) : string; } /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a * hexadecimal, in which case a `radix` of `16` is used. * * **Note:** This method aligns with the * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. * * @static * @memberOf _ * @since 1.1.0 * @category String * @param {string} string The string to convert. * @param {number} [radix=10] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { if (guard || radix == null) { radix = 0; } else if (radix) { radix = +radix; } return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); } /** * Repeats the given string `n` times. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=1] The number of times to repeat the string. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n, guard) { if ((guard ? isIterateeCall(string, n, guard) : n === undefined$1)) { n = 1; } else { n = toInteger(n); } return baseRepeat(toString(string), n); } /** * Replaces matches for `pattern` in `string` with `replacement`. * * **Note:** This method is based on * [`String#replace`](https://mdn.io/String/replace). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to modify. * @param {RegExp|string} pattern The pattern to replace. * @param {Function|string} replacement The match replacement. * @returns {string} Returns the modified string. * @example * * _.replace('Hi Fred', 'Fred', 'Barney'); * // => 'Hi Barney' */ function replace() { var args = arguments, string = toString(args[0]); return args.length < 3 ? string : string.replace(args[1], args[2]); } /** * Converts `string` to * [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the snake cased string. * @example * * _.snakeCase('Foo Bar'); * // => 'foo_bar' * * _.snakeCase('fooBar'); * // => 'foo_bar' * * _.snakeCase('--FOO-BAR--'); * // => 'foo_bar' */ var snakeCase = createCompounder(function(result, word, index) { return result + (index ? '_' : '') + word.toLowerCase(); }); /** * Splits `string` by `separator`. * * **Note:** This method is based on * [`String#split`](https://mdn.io/String/split). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to split. * @param {RegExp|string} separator The separator pattern to split by. * @param {number} [limit] The length to truncate results to. * @returns {Array} Returns the string segments. * @example * * _.split('a-b-c', '-', 2); * // => ['a', 'b'] */ function split(string, separator, limit) { if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { separator = limit = undefined$1; } limit = limit === undefined$1 ? MAX_ARRAY_LENGTH : limit >>> 0; if (!limit) { return []; } string = toString(string); if (string && ( typeof separator == 'string' || (separator != null && !isRegExp(separator)) )) { separator = baseToString(separator); if (!separator && hasUnicode(string)) { return castSlice(stringToArray(string), 0, limit); } } return string.split(separator, limit); } /** * Converts `string` to * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * * @static * @memberOf _ * @since 3.1.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the start cased string. * @example * * _.startCase('--foo-bar--'); * // => 'Foo Bar' * * _.startCase('fooBar'); * // => 'Foo Bar' * * _.startCase('__FOO_BAR__'); * // => 'FOO BAR' */ var startCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + upperFirst(word); }); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } /** * Creates a compiled template function that can interpolate data properties * in "interpolate" delimiters, HTML-escape interpolated data properties in * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data * properties may be accessed as free variables in the template. If a setting * object is given, it takes precedence over `_.templateSettings` values. * * **Note:** In the development build `_.template` utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) * for easier debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The template string. * @param {Object} [options={}] The options object. * @param {RegExp} [options.escape=_.templateSettings.escape] * The HTML "escape" delimiter. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] * The "evaluate" delimiter. * @param {Object} [options.imports=_.templateSettings.imports] * An object to import into the template as free variables. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] * The "interpolate" delimiter. * @param {string} [options.sourceURL='lodash.templateSources[n]'] * The sourceURL of the compiled template. * @param {string} [options.variable='obj'] * The data object variable name. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the compiled template function. * @example * * // Use the "interpolate" delimiter to create a compiled template. * var compiled = _.template('hello <%= user %>!'); * compiled({ 'user': 'fred' }); * // => 'hello fred!' * * // Use the HTML "escape" delimiter to escape data property values. * var compiled = _.template('<%- value %>'); * compiled({ 'value': ' * ``` * * Elements by their ID are made available in browsers on the `window` object. * Using a prefix prevents this from being a problem. * @property {string} [footnoteLabel='Footnotes'] * Label to use for the footnotes section. * Affects screen reader users. * Change it if you’re authoring in a different language. * @property {string} [footnoteBackLabel='Back to content'] * Label to use from backreferences back to their footnote call. * Affects screen reader users. * Change it if you’re authoring in a different language. * @property {Handlers} [handlers] * Object mapping mdast nodes to functions handling them * @property {Array} [passThrough] * List of custom mdast node types to pass through (keep) in hast * @property {Handler} [unknownHandler] * Handler for all unknown nodes. * * @typedef {Record} Handlers * Map of node types to handlers * @typedef {HFunctionProps & HFunctionNoProps & HFields} H * Handle context */ const own$1 = {}.hasOwnProperty; /** * Factory to transform. * @param {MdastNode} tree mdast node * @param {Options} [options] Configuration * @returns {H} `h` function */ function factory(tree, options) { const settings = options || {}; const dangerous = settings.allowDangerousHtml || false; /** @type {Record} */ const footnoteById = {}; h.dangerous = dangerous; h.clobberPrefix = settings.clobberPrefix === undefined || settings.clobberPrefix === null ? 'user-content-' : settings.clobberPrefix; h.footnoteLabel = settings.footnoteLabel || 'Footnotes'; h.footnoteBackLabel = settings.footnoteBackLabel || 'Back to content'; h.definition = definitions(tree); h.footnoteById = footnoteById; /** @type {Array} */ h.footnoteOrder = []; /** @type {Record} */ h.footnoteCounts = {}; h.augment = augment; h.handlers = {...handlers, ...settings.handlers}; h.unknownHandler = settings.unknownHandler; h.passThrough = settings.passThrough; visit$2(tree, 'footnoteDefinition', (definition) => { const id = String(definition.identifier).toUpperCase(); // Mimick CM behavior of link definitions. // See: . if (!own$1.call(footnoteById, id)) { footnoteById[id] = definition; } }); // @ts-expect-error Hush, it’s fine! return h /** * Finalise the created `right`, a hast node, from `left`, an mdast node. * @param {(NodeWithData|PositionLike)?} left * @param {Content} right * @returns {Content} */ function augment(left, right) { // Handle `data.hName`, `data.hProperties, `data.hChildren`. if (left && 'data' in left && left.data) { /** @type {Data} */ const data = left.data; if (data.hName) { if (right.type !== 'element') { right = { type: 'element', tagName: '', properties: {}, children: [] }; } right.tagName = data.hName; } if (right.type === 'element' && data.hProperties) { right.properties = {...right.properties, ...data.hProperties}; } if ('children' in right && right.children && data.hChildren) { right.children = data.hChildren; } } if (left) { const ctx = 'type' in left ? left : {position: left}; if (!generated(ctx)) { right.position = {start: pointStart(ctx), end: pointEnd(ctx)}; } } return right } /** * Create an element for `node`. * * @type {HFunctionProps} */ function h(node, tagName, props, children) { if (Array.isArray(props)) { children = props; props = {}; } // @ts-expect-error augmenting an element yields an element. return augment(node, { type: 'element', tagName, properties: props || {}, children: children || [] }) } } /** * Transform `tree` (an mdast node) to a hast node. * * @param {MdastNode} tree mdast node * @param {Options} [options] Configuration * @returns {HastNode|null|undefined} hast node */ function toHast(tree, options) { const h = factory(tree, options); const node = one(h, tree, null); const foot = footer(h); if (foot) { // @ts-expect-error If there’s a footer, there were definitions, meaning block // content. // So assume `node` is a parent node. node.children.push(u('text', '\n'), foot); } return Array.isArray(node) ? {type: 'root', children: node} : node } /** * @typedef {import('hast').Root} HastRoot * @typedef {import('mdast').Root} MdastRoot * @typedef {import('mdast-util-to-hast').Options} Options * @typedef {import('unified').Processor} Processor * * @typedef {import('mdast-util-to-hast')} DoNotTouchAsThisImportIncludesRawInTree */ // Note: the `` overload doesn’t seem to work :'( /** * Plugin that turns markdown into HTML to support rehype. * * * If a destination processor is given, that processor runs with a new HTML * (hast) tree (bridge-mode). * As the given processor runs with a hast tree, and rehype plugins support * hast, that means rehype plugins can be used with the given processor. * The hast tree is discarded in the end. * It’s highly unlikely that you want to do this. * * The common case is to not pass a destination processor, in which case the * current processor continues running with a new HTML (hast) tree * (mutate-mode). * As the current processor continues with a hast tree, and rehype plugins * support hast, that means rehype plugins can be used after * `remark-rehype`. * It’s likely that this is what you want to do. * * @param destination * Optional unified processor. * @param options * Options passed to `mdast-util-to-hast`. */ const remarkRehype = /** @type {(import('unified').Plugin<[Processor, Options?]|[null|undefined, Options?]|[Options]|[], MdastRoot>)} */ ( function (destination, options) { return destination && 'run' in destination ? bridge(destination, options) : mutate(destination || options) } ); /** * Bridge-mode. * Runs the destination with the new hast tree. * * @type {import('unified').Plugin<[Processor, Options?], MdastRoot>} */ function bridge(destination, options) { return (node, file, next) => { destination.run(toHast(node, options), file, (error) => { next(error); }); } } /** * Mutate-mode. * Further plugins run on the hast tree. * * @type {import('unified').Plugin<[Options?]|void[], MdastRoot, HastRoot>} */ function mutate(options) { // @ts-expect-error: assume a corresponding node is returned by `toHast`. return (node) => toHast(node, options) } /** * Throw a given error. * * @param {Error|null|undefined} [error] * Maybe error. * @returns {asserts error is null|undefined} */ function bail(error) { if (error) { throw error } } /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh * @license MIT */ var isBuffer = function isBuffer (obj) { return obj != null && obj.constructor != null && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) }; var isBuffer$1 = /*@__PURE__*/getDefaultExportFromCjs(isBuffer); function isPlainObject$1(value) { if (Object.prototype.toString.call(value) !== '[object Object]') { return false; } const prototype = Object.getPrototypeOf(value); return prototype === null || prototype === Object.prototype; } /** * @typedef {(error?: Error|null|undefined, ...output: Array) => void} Callback * @typedef {(...input: Array) => any} Middleware * * @typedef {(...input: Array) => void} Run * Call all middleware. * @typedef {(fn: Middleware) => Pipeline} Use * Add `fn` (middleware) to the list. * @typedef {{run: Run, use: Use}} Pipeline * Middleware. */ /** * Create new middleware. * * @returns {Pipeline} */ function trough() { /** @type {Array} */ const fns = []; /** @type {Pipeline} */ const pipeline = {run, use}; return pipeline /** @type {Run} */ function run(...values) { let middlewareIndex = -1; /** @type {Callback} */ const callback = values.pop(); if (typeof callback !== 'function') { throw new TypeError('Expected function as last argument, not ' + callback) } next(null, ...values); /** * Run the next `fn`, or we’re done. * * @param {Error|null|undefined} error * @param {Array} output */ function next(error, ...output) { const fn = fns[++middlewareIndex]; let index = -1; if (error) { callback(error); return } // Copy non-nullish input into values. while (++index < values.length) { if (output[index] === null || output[index] === undefined) { output[index] = values[index]; } } // Save the newly created `output` for the next call. values = output; // Next or done. if (fn) { wrap(fn, next)(...output); } else { callback(null, ...output); } } } /** @type {Use} */ function use(middelware) { if (typeof middelware !== 'function') { throw new TypeError( 'Expected `middelware` to be a function, not ' + middelware ) } fns.push(middelware); return pipeline } } /** * Wrap `middleware`. * Can be sync or async; return a promise, receive a callback, or return new * values and errors. * * @param {Middleware} middleware * @param {Callback} callback */ function wrap(middleware, callback) { /** @type {boolean} */ let called; return wrapped /** * Call `middleware`. * @this {any} * @param {Array} parameters * @returns {void} */ function wrapped(...parameters) { const fnExpectsCallback = middleware.length > parameters.length; /** @type {any} */ let result; if (fnExpectsCallback) { parameters.push(done); } try { result = middleware.apply(this, parameters); } catch (error) { const exception = /** @type {Error} */ (error); // Well, this is quite the pickle. // `middleware` received a callback and called it synchronously, but that // threw an error. // The only thing left to do is to throw the thing instead. if (fnExpectsCallback && called) { throw exception } return done(exception) } if (!fnExpectsCallback) { if (result instanceof Promise) { result.then(then, done); } else if (result instanceof Error) { done(result); } else { then(result); } } } /** * Call `callback`, only once. * @type {Callback} */ function done(error, ...output) { if (!called) { called = true; callback(error, ...output); } } /** * Call `done` with one value. * * @param {any} [value] */ function then(value) { done(null, value); } } /** * @typedef {import('unist').Node} Node * @typedef {import('unist').Position} Position * @typedef {import('unist').Point} Point * @typedef {object & {type: string, position?: Position|undefined}} NodeLike */ class VFileMessage extends Error { /** * Create a message for `reason` at `place` from `origin`. * * When an error is passed in as `reason`, the `stack` is copied. * * @param {string|Error|VFileMessage} reason * Reason for message. * Uses the stack and message of the error if given. * @param {Node|NodeLike|Position|Point} [place] * Place at which the message occurred in a file. * @param {string} [origin] * Place in code the message originates from (example `'my-package:my-rule-name'`) */ constructor(reason, place, origin) { /** @type {[string|null, string|null]} */ const parts = [null, null]; /** @type {Position} */ let position = { // @ts-expect-error: we always follows the structure of `position`. start: {line: null, column: null}, // @ts-expect-error: " end: {line: null, column: null} }; super(); if (typeof place === 'string') { origin = place; place = undefined; } if (typeof origin === 'string') { const index = origin.indexOf(':'); if (index === -1) { parts[1] = origin; } else { parts[0] = origin.slice(0, index); parts[1] = origin.slice(index + 1); } } if (place) { // Node. if ('type' in place || 'position' in place) { if (place.position) { // @ts-expect-error: looks like a position. position = place.position; } } // Position. else if ('start' in place || 'end' in place) { // @ts-expect-error: looks like a position. position = place; } // Point. else if ('line' in place || 'column' in place) { position.start = place; } } // Fields from `Error` this.name = stringifyPosition(place) || '1:1'; /** @type {string} */ this.message = typeof reason === 'object' ? reason.message : reason; /** @type {string} */ this.stack = ''; if (typeof reason === 'object' && reason.stack) { this.stack = reason.stack; } /** * Reason for message. * * @type {string} */ this.reason = this.message; /* eslint-disable no-unused-expressions */ /** * Whether this is a fatal problem that marks an associated file as no * longer processable. * If `true`, marks associated file as no longer processable. * If `false`, necessitates a (potential) change. * The value can also be `null` or `undefined`, for things that might not * need changing. * * @type {boolean?} */ this.fatal; /** * Starting line of error. * * @type {number?} */ this.line = position.start.line; /** * Starting column of error. * * @type {number?} */ this.column = position.start.column; /** * Full range information, when available. * Has `start` and `end` fields, both set to an object with `line` and * `column`, set to `number?`. * * @type {Position?} */ this.position = position; /** * Namespace of warning (example: `'my-package'`). * * @type {string?} */ this.source = parts[0]; /** * Category of message (example: `'my-rule-name'`). * * @type {string?} */ this.ruleId = parts[1]; /** * Path of a file (used throughout the VFile ecosystem). * * @type {string?} */ this.file; // The following fields are “well known”. // Not standard. // Feel free to add other non-standard fields to your messages. /** * Specify the source value that’s being reported, which is deemed * incorrect. * * @type {string?} */ this.actual; /** * Suggest values that should be used instead of `actual`, one or more * values that are deemed as acceptable. * * @type {Array?} */ this.expected; /** * Link to documentation for the message. * * @type {string?} */ this.url; /** * Long form description of the message (supported by `vfile-reporter`). * * @type {string?} */ this.note; /* eslint-enable no-unused-expressions */ } } VFileMessage.prototype.file = ''; VFileMessage.prototype.name = ''; VFileMessage.prototype.reason = ''; VFileMessage.prototype.message = ''; VFileMessage.prototype.stack = ''; VFileMessage.prototype.fatal = null; VFileMessage.prototype.column = null; VFileMessage.prototype.line = null; VFileMessage.prototype.source = null; VFileMessage.prototype.ruleId = null; VFileMessage.prototype.position = null; // A derivative work based on: // . // Which is licensed: // // MIT License // // Copyright (c) 2013 James Halliday // // 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. // A derivative work based on: // // Parts of that are extracted from Node’s internal `path` module: // . // Which is licensed: // // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. const path = {basename, dirname, extname, join, sep: '/'}; /* eslint-disable max-depth, complexity */ /** * @param {string} path * @param {string} [ext] * @returns {string} */ function basename(path, ext) { if (ext !== undefined && typeof ext !== 'string') { throw new TypeError('"ext" argument must be a string') } assertPath$1(path); let start = 0; let end = -1; let index = path.length; /** @type {boolean|undefined} */ let seenNonSlash; if (ext === undefined || ext.length === 0 || ext.length > path.length) { while (index--) { if (path.charCodeAt(index) === 47 /* `/` */) { // If we reached a path separator that was not part of a set of path // separators at the end of the string, stop now. if (seenNonSlash) { start = index + 1; break } } else if (end < 0) { // We saw the first non-path separator, mark this as the end of our // path component. seenNonSlash = true; end = index + 1; } } return end < 0 ? '' : path.slice(start, end) } if (ext === path) { return '' } let firstNonSlashEnd = -1; let extIndex = ext.length - 1; while (index--) { if (path.charCodeAt(index) === 47 /* `/` */) { // If we reached a path separator that was not part of a set of path // separators at the end of the string, stop now. if (seenNonSlash) { start = index + 1; break } } else { if (firstNonSlashEnd < 0) { // We saw the first non-path separator, remember this index in case // we need it if the extension ends up not matching. seenNonSlash = true; firstNonSlashEnd = index + 1; } if (extIndex > -1) { // Try to match the explicit extension. if (path.charCodeAt(index) === ext.charCodeAt(extIndex--)) { if (extIndex < 0) { // We matched the extension, so mark this as the end of our path // component end = index; } } else { // Extension does not match, so our result is the entire path // component extIndex = -1; end = firstNonSlashEnd; } } } } if (start === end) { end = firstNonSlashEnd; } else if (end < 0) { end = path.length; } return path.slice(start, end) } /** * @param {string} path * @returns {string} */ function dirname(path) { assertPath$1(path); if (path.length === 0) { return '.' } let end = -1; let index = path.length; /** @type {boolean|undefined} */ let unmatchedSlash; // Prefix `--` is important to not run on `0`. while (--index) { if (path.charCodeAt(index) === 47 /* `/` */) { if (unmatchedSlash) { end = index; break } } else if (!unmatchedSlash) { // We saw the first non-path separator unmatchedSlash = true; } } return end < 0 ? path.charCodeAt(0) === 47 /* `/` */ ? '/' : '.' : end === 1 && path.charCodeAt(0) === 47 /* `/` */ ? '//' : path.slice(0, end) } /** * @param {string} path * @returns {string} */ function extname(path) { assertPath$1(path); let index = path.length; let end = -1; let startPart = 0; let startDot = -1; // Track the state of characters (if any) we see before our first dot and // after any path separator we find. let preDotState = 0; /** @type {boolean|undefined} */ let unmatchedSlash; while (index--) { const code = path.charCodeAt(index); if (code === 47 /* `/` */) { // If we reached a path separator that was not part of a set of path // separators at the end of the string, stop now. if (unmatchedSlash) { startPart = index + 1; break } continue } if (end < 0) { // We saw the first non-path separator, mark this as the end of our // extension. unmatchedSlash = true; end = index + 1; } if (code === 46 /* `.` */) { // If this is our first dot, mark it as the start of our extension. if (startDot < 0) { startDot = index; } else if (preDotState !== 1) { preDotState = 1; } } else if (startDot > -1) { // We saw a non-dot and non-path separator before our dot, so we should // have a good chance at having a non-empty extension. preDotState = -1; } } if ( startDot < 0 || end < 0 || // We saw a non-dot character immediately before the dot. preDotState === 0 || // The (right-most) trimmed path component is exactly `..`. (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) ) { return '' } return path.slice(startDot, end) } /** * @param {Array} segments * @returns {string} */ function join(...segments) { let index = -1; /** @type {string|undefined} */ let joined; while (++index < segments.length) { assertPath$1(segments[index]); if (segments[index]) { joined = joined === undefined ? segments[index] : joined + '/' + segments[index]; } } return joined === undefined ? '.' : normalize(joined) } /** * Note: `normalize` is not exposed as `path.normalize`, so some code is * manually removed from it. * * @param {string} path * @returns {string} */ function normalize(path) { assertPath$1(path); const absolute = path.charCodeAt(0) === 47; /* `/` */ // Normalize the path according to POSIX rules. let value = normalizeString(path, !absolute); if (value.length === 0 && !absolute) { value = '.'; } if (value.length > 0 && path.charCodeAt(path.length - 1) === 47 /* / */) { value += '/'; } return absolute ? '/' + value : value } /** * Resolve `.` and `..` elements in a path with directory names. * * @param {string} path * @param {boolean} allowAboveRoot * @returns {string} */ function normalizeString(path, allowAboveRoot) { let result = ''; let lastSegmentLength = 0; let lastSlash = -1; let dots = 0; let index = -1; /** @type {number|undefined} */ let code; /** @type {number} */ let lastSlashIndex; while (++index <= path.length) { if (index < path.length) { code = path.charCodeAt(index); } else if (code === 47 /* `/` */) { break } else { code = 47; /* `/` */ } if (code === 47 /* `/` */) { if (lastSlash === index - 1 || dots === 1) ; else if (lastSlash !== index - 1 && dots === 2) { if ( result.length < 2 || lastSegmentLength !== 2 || result.charCodeAt(result.length - 1) !== 46 /* `.` */ || result.charCodeAt(result.length - 2) !== 46 /* `.` */ ) { if (result.length > 2) { lastSlashIndex = result.lastIndexOf('/'); if (lastSlashIndex !== result.length - 1) { if (lastSlashIndex < 0) { result = ''; lastSegmentLength = 0; } else { result = result.slice(0, lastSlashIndex); lastSegmentLength = result.length - 1 - result.lastIndexOf('/'); } lastSlash = index; dots = 0; continue } } else if (result.length > 0) { result = ''; lastSegmentLength = 0; lastSlash = index; dots = 0; continue } } if (allowAboveRoot) { result = result.length > 0 ? result + '/..' : '..'; lastSegmentLength = 2; } } else { if (result.length > 0) { result += '/' + path.slice(lastSlash + 1, index); } else { result = path.slice(lastSlash + 1, index); } lastSegmentLength = index - lastSlash - 1; } lastSlash = index; dots = 0; } else if (code === 46 /* `.` */ && dots > -1) { dots++; } else { dots = -1; } } return result } /** * @param {string} path */ function assertPath$1(path) { if (typeof path !== 'string') { throw new TypeError( 'Path must be a string. Received ' + JSON.stringify(path) ) } } /* eslint-enable max-depth, complexity */ // Somewhat based on: // . // But I don’t think one tiny line of code can be copyrighted. 😅 const proc = {cwd}; function cwd() { return '/' } /** * @typedef URL * @property {string} hash * @property {string} host * @property {string} hostname * @property {string} href * @property {string} origin * @property {string} password * @property {string} pathname * @property {string} port * @property {string} protocol * @property {string} search * @property {any} searchParams * @property {string} username * @property {() => string} toString * @property {() => string} toJSON */ /** * @param {unknown} fileURLOrPath * @returns {fileURLOrPath is URL} */ // From: function isUrl(fileURLOrPath) { return ( fileURLOrPath !== null && typeof fileURLOrPath === 'object' && // @ts-expect-error: indexable. fileURLOrPath.href && // @ts-expect-error: indexable. fileURLOrPath.origin ) } /// // See: /** * @param {string|URL} path */ function urlToPath(path) { if (typeof path === 'string') { path = new URL(path); } else if (!isUrl(path)) { /** @type {NodeJS.ErrnoException} */ const error = new TypeError( 'The "path" argument must be of type string or an instance of URL. Received `' + path + '`' ); error.code = 'ERR_INVALID_ARG_TYPE'; throw error } if (path.protocol !== 'file:') { /** @type {NodeJS.ErrnoException} */ const error = new TypeError('The URL must be of scheme file'); error.code = 'ERR_INVALID_URL_SCHEME'; throw error } return getPathFromURLPosix(path) } /** * @param {URL} url */ function getPathFromURLPosix(url) { if (url.hostname !== '') { /** @type {NodeJS.ErrnoException} */ const error = new TypeError( 'File URL host must be "localhost" or empty on darwin' ); error.code = 'ERR_INVALID_FILE_URL_HOST'; throw error } const pathname = url.pathname; let index = -1; while (++index < pathname.length) { if ( pathname.charCodeAt(index) === 37 /* `%` */ && pathname.charCodeAt(index + 1) === 50 /* `2` */ ) { const third = pathname.charCodeAt(index + 2); if (third === 70 /* `F` */ || third === 102 /* `f` */) { /** @type {NodeJS.ErrnoException} */ const error = new TypeError( 'File URL path must not include encoded / characters' ); error.code = 'ERR_INVALID_FILE_URL_PATH'; throw error } } } return decodeURIComponent(pathname) } /** * @typedef {import('unist').Node} Node * @typedef {import('unist').Position} Position * @typedef {import('unist').Point} Point * @typedef {Record & {type: string, position?: Position|undefined}} NodeLike * @typedef {import('./minurl.shared.js').URL} URL * @typedef {import('..').VFileData} VFileData * @typedef {import('..').VFileValue} VFileValue * * @typedef {'ascii'|'utf8'|'utf-8'|'utf16le'|'ucs2'|'ucs-2'|'base64'|'base64url'|'latin1'|'binary'|'hex'} BufferEncoding * Encodings supported by the buffer class. * This is a copy of the typing from Node, copied to prevent Node globals from * being needed. * Copied from: * * @typedef {VFileValue|VFileOptions|VFile|URL} VFileCompatible * Things that can be passed to the constructor. * * @typedef VFileCoreOptions * @property {VFileValue} [value] * @property {string} [cwd] * @property {Array} [history] * @property {string|URL} [path] * @property {string} [basename] * @property {string} [stem] * @property {string} [extname] * @property {string} [dirname] * @property {VFileData} [data] * * @typedef Map * Raw source map, see: * . * @property {number} version * @property {Array} sources * @property {Array} names * @property {string|undefined} [sourceRoot] * @property {Array|undefined} [sourcesContent] * @property {string} mappings * @property {string} file * * @typedef {{[key: string]: unknown} & VFileCoreOptions} VFileOptions * Configuration: a bunch of keys that will be shallow copied over to the new * file. * * @typedef {Record} VFileReporterSettings * @typedef {(files: Array, options: T) => string} VFileReporter */ // Order of setting (least specific to most), we need this because otherwise // `{stem: 'a', path: '~/b.js'}` would throw, as a path is needed before a // stem can be set. const order = ['history', 'path', 'basename', 'stem', 'extname', 'dirname']; class VFile { /** * Create a new virtual file. * * If `options` is `string` or `Buffer`, treats it as `{value: options}`. * If `options` is a `VFile`, shallow copies its data over to the new file. * All other given fields are set on the newly created `VFile`. * * Path related properties are set in the following order (least specific to * most specific): `history`, `path`, `basename`, `stem`, `extname`, * `dirname`. * * It’s not possible to set either `dirname` or `extname` without setting * either `history`, `path`, `basename`, or `stem` as well. * * @param {VFileCompatible} [value] */ constructor(value) { /** @type {VFileOptions} */ let options; if (!value) { options = {}; } else if (typeof value === 'string' || isBuffer$1(value)) { // @ts-expect-error Looks like a buffer. options = {value}; } else if (isUrl(value)) { options = {path: value}; } else { // @ts-expect-error Looks like file or options. options = value; } /** * Place to store custom information. * It’s OK to store custom data directly on the file, moving it to `data` * gives a little more privacy. * @type {VFileData} */ this.data = {}; /** * List of messages associated with the file. * @type {Array} */ this.messages = []; /** * List of file paths the file moved between. * @type {Array} */ this.history = []; /** * Base of `path`. * Defaults to `process.cwd()` (`/` in browsers). * @type {string} */ this.cwd = proc.cwd(); /* eslint-disable no-unused-expressions */ /** * Raw value. * @type {VFileValue} */ this.value; // The below are non-standard, they are “well-known”. // As in, used in several tools. /** * Whether a file was saved to disk. * This is used by vfile reporters. * @type {boolean} */ this.stored; /** * Sometimes files have a non-string representation. * This can be stored in the `result` field. * One example is when turning markdown into React nodes. * This is used by unified to store non-string results. * @type {unknown} */ this.result; /** * Sometimes files have a source map associated with them. * This can be stored in the `map` field. * This should be a `RawSourceMap` type from the `source-map` module. * @type {Map|undefined} */ this.map; /* eslint-enable no-unused-expressions */ // Set path related properties in the correct order. let index = -1; while (++index < order.length) { const prop = order[index]; // Note: we specifically use `in` instead of `hasOwnProperty` to accept // `vfile`s too. if (prop in options && options[prop] !== undefined) { // @ts-expect-error: TS is confused by the different types for `history`. this[prop] = prop === 'history' ? [...options[prop]] : options[prop]; } } /** @type {string} */ let prop; // Set non-path related properties. for (prop in options) { // @ts-expect-error: fine to set other things. if (!order.includes(prop)) this[prop] = options[prop]; } } /** * Access full path (`~/index.min.js`). * * @returns {string} */ get path() { return this.history[this.history.length - 1] } /** * Set full path (`~/index.min.js`). * Cannot be nullified. * * @param {string|URL} path */ set path(path) { if (isUrl(path)) { path = urlToPath(path); } assertNonEmpty(path, 'path'); if (this.path !== path) { this.history.push(path); } } /** * Access parent path (`~`). */ get dirname() { return typeof this.path === 'string' ? path.dirname(this.path) : undefined } /** * Set parent path (`~`). * Cannot be set if there's no `path` yet. */ set dirname(dirname) { assertPath(this.basename, 'dirname'); this.path = path.join(dirname || '', this.basename); } /** * Access basename (including extname) (`index.min.js`). */ get basename() { return typeof this.path === 'string' ? path.basename(this.path) : undefined } /** * Set basename (`index.min.js`). * Cannot contain path separators. * Cannot be nullified either (use `file.path = file.dirname` instead). */ set basename(basename) { assertNonEmpty(basename, 'basename'); assertPart(basename, 'basename'); this.path = path.join(this.dirname || '', basename); } /** * Access extname (including dot) (`.js`). */ get extname() { return typeof this.path === 'string' ? path.extname(this.path) : undefined } /** * Set extname (including dot) (`.js`). * Cannot be set if there's no `path` yet and cannot contain path separators. */ set extname(extname) { assertPart(extname, 'extname'); assertPath(this.dirname, 'extname'); if (extname) { if (extname.charCodeAt(0) !== 46 /* `.` */) { throw new Error('`extname` must start with `.`') } if (extname.includes('.', 1)) { throw new Error('`extname` cannot contain multiple dots') } } this.path = path.join(this.dirname, this.stem + (extname || '')); } /** * Access stem (w/o extname) (`index.min`). */ get stem() { return typeof this.path === 'string' ? path.basename(this.path, this.extname) : undefined } /** * Set stem (w/o extname) (`index.min`). * Cannot be nullified, and cannot contain path separators. */ set stem(stem) { assertNonEmpty(stem, 'stem'); assertPart(stem, 'stem'); this.path = path.join(this.dirname || '', stem + (this.extname || '')); } /** * Serialize the file. * * @param {BufferEncoding} [encoding='utf8'] If `file.value` is a buffer, `encoding` is used to serialize buffers. * @returns {string} */ toString(encoding) { return (this.value || '').toString(encoding) } /** * Create a message and associates it w/ the file. * * @param {string|Error} reason Reason for message (`string` or `Error`). Uses the stack and message of the error if given. * @param {Node|NodeLike|Position|Point} [place] Place at which the message occurred in a file (`Node`, `Position`, or `Point`, optional). * @param {string} [origin] Place in code the message originates from (`string`, optional). * @returns {VFileMessage} */ message(reason, place, origin) { const message = new VFileMessage(reason, place, origin); if (this.path) { message.name = this.path + ':' + message.name; message.file = this.path; } message.fatal = false; this.messages.push(message); return message } /** * Info: create a message, associate it with the file, and mark the fatality * as `null`. * Calls `message()` internally. * * @param {string|Error} reason Reason for message (`string` or `Error`). Uses the stack and message of the error if given. * @param {Node|NodeLike|Position|Point} [place] Place at which the message occurred in a file (`Node`, `Position`, or `Point`, optional). * @param {string} [origin] Place in code the message originates from (`string`, optional). * @returns {VFileMessage} */ info(reason, place, origin) { const message = this.message(reason, place, origin); message.fatal = null; return message } /** * Fail: create a message, associate it with the file, mark the fatality as * `true`. * Note: fatal errors mean a file is no longer processable. * Calls `message()` internally. * * @param {string|Error} reason Reason for message (`string` or `Error`). Uses the stack and message of the error if given. * @param {Node|NodeLike|Position|Point} [place] Place at which the message occurred in a file (`Node`, `Position`, or `Point`, optional). * @param {string} [origin] Place in code the message originates from (`string`, optional). * @returns {never} */ fail(reason, place, origin) { const message = this.message(reason, place, origin); message.fatal = true; throw message } } /** * Assert that `part` is not a path (as in, does not contain `path.sep`). * * @param {string|undefined} part * @param {string} name * @returns {void} */ function assertPart(part, name) { if (part && part.includes(path.sep)) { throw new Error( '`' + name + '` cannot be a path: did not expect `' + path.sep + '`' ) } } /** * Assert that `part` is not empty. * * @param {string|undefined} part * @param {string} name * @returns {asserts part is string} */ function assertNonEmpty(part, name) { if (!part) { throw new Error('`' + name + '` cannot be empty') } } /** * Assert `path` exists. * * @param {string|undefined} path * @param {string} name * @returns {asserts path is string} */ function assertPath(path, name) { if (!path) { throw new Error('Setting `' + name + '` requires `path` to be set too') } } /** * @typedef {import('unist').Node} Node * @typedef {import('vfile').VFileCompatible} VFileCompatible * @typedef {import('vfile').VFileValue} VFileValue * @typedef {import('..').Processor} Processor * @typedef {import('..').Plugin} Plugin * @typedef {import('..').Preset} Preset * @typedef {import('..').Pluggable} Pluggable * @typedef {import('..').PluggableList} PluggableList * @typedef {import('..').Transformer} Transformer * @typedef {import('..').Parser} Parser * @typedef {import('..').Compiler} Compiler * @typedef {import('..').RunCallback} RunCallback * @typedef {import('..').ProcessCallback} ProcessCallback * * @typedef Context * @property {Node} tree * @property {VFile} file */ // Expose a frozen processor. const unified = base().freeze(); const own = {}.hasOwnProperty; // Function to create the first processor. /** * @returns {Processor} */ function base() { const transformers = trough(); /** @type {Processor['attachers']} */ const attachers = []; /** @type {Record} */ let namespace = {}; /** @type {boolean|undefined} */ let frozen; let freezeIndex = -1; // Data management. // @ts-expect-error: overloads are handled. processor.data = data; processor.Parser = undefined; processor.Compiler = undefined; // Lock. processor.freeze = freeze; // Plugins. processor.attachers = attachers; // @ts-expect-error: overloads are handled. processor.use = use; // API. processor.parse = parse; processor.stringify = stringify; // @ts-expect-error: overloads are handled. processor.run = run; processor.runSync = runSync; // @ts-expect-error: overloads are handled. processor.process = process; processor.processSync = processSync; // Expose. return processor // Create a new processor based on the processor in the current scope. /** @type {Processor} */ function processor() { const destination = base(); let index = -1; while (++index < attachers.length) { destination.use(...attachers[index]); } destination.data(extend$1(true, {}, namespace)); return destination } /** * @param {string|Record} [key] * @param {unknown} [value] * @returns {unknown} */ function data(key, value) { if (typeof key === 'string') { // Set `key`. if (arguments.length === 2) { assertUnfrozen('data', frozen); namespace[key] = value; return processor } // Get `key`. return (own.call(namespace, key) && namespace[key]) || null } // Set space. if (key) { assertUnfrozen('data', frozen); namespace = key; return processor } // Get space. return namespace } /** @type {Processor['freeze']} */ function freeze() { if (frozen) { return processor } while (++freezeIndex < attachers.length) { const [attacher, ...options] = attachers[freezeIndex]; if (options[0] === false) { continue } if (options[0] === true) { options[0] = undefined; } /** @type {Transformer|void} */ const transformer = attacher.call(processor, ...options); if (typeof transformer === 'function') { transformers.use(transformer); } } frozen = true; freezeIndex = Number.POSITIVE_INFINITY; return processor } /** * @param {Pluggable|null|undefined} [value] * @param {...unknown} options * @returns {Processor} */ function use(value, ...options) { /** @type {Record|undefined} */ let settings; assertUnfrozen('use', frozen); if (value === null || value === undefined) ; else if (typeof value === 'function') { addPlugin(value, ...options); } else if (typeof value === 'object') { if (Array.isArray(value)) { addList(value); } else { addPreset(value); } } else { throw new TypeError('Expected usable value, not `' + value + '`') } if (settings) { namespace.settings = Object.assign(namespace.settings || {}, settings); } return processor /** * @param {import('..').Pluggable} value * @returns {void} */ function add(value) { if (typeof value === 'function') { addPlugin(value); } else if (typeof value === 'object') { if (Array.isArray(value)) { const [plugin, ...options] = value; addPlugin(plugin, ...options); } else { addPreset(value); } } else { throw new TypeError('Expected usable value, not `' + value + '`') } } /** * @param {Preset} result * @returns {void} */ function addPreset(result) { addList(result.plugins); if (result.settings) { settings = Object.assign(settings || {}, result.settings); } } /** * @param {PluggableList|null|undefined} [plugins] * @returns {void} */ function addList(plugins) { let index = -1; if (plugins === null || plugins === undefined) ; else if (Array.isArray(plugins)) { while (++index < plugins.length) { const thing = plugins[index]; add(thing); } } else { throw new TypeError('Expected a list of plugins, not `' + plugins + '`') } } /** * @param {Plugin} plugin * @param {...unknown} [value] * @returns {void} */ function addPlugin(plugin, value) { let index = -1; /** @type {Processor['attachers'][number]|undefined} */ let entry; while (++index < attachers.length) { if (attachers[index][0] === plugin) { entry = attachers[index]; break } } if (entry) { if (isPlainObject$1(entry[1]) && isPlainObject$1(value)) { value = extend$1(true, entry[1], value); } entry[1] = value; } else { // @ts-expect-error: fine. attachers.push([...arguments]); } } } /** @type {Processor['parse']} */ function parse(doc) { processor.freeze(); const file = vfile(doc); const Parser = processor.Parser; assertParser('parse', Parser); if (newable(Parser, 'parse')) { // @ts-expect-error: `newable` checks this. return new Parser(String(file), file).parse() } // @ts-expect-error: `newable` checks this. return Parser(String(file), file) // eslint-disable-line new-cap } /** @type {Processor['stringify']} */ function stringify(node, doc) { processor.freeze(); const file = vfile(doc); const Compiler = processor.Compiler; assertCompiler('stringify', Compiler); assertNode(node); if (newable(Compiler, 'compile')) { // @ts-expect-error: `newable` checks this. return new Compiler(node, file).compile() } // @ts-expect-error: `newable` checks this. return Compiler(node, file) // eslint-disable-line new-cap } /** * @param {Node} node * @param {VFileCompatible|RunCallback} [doc] * @param {RunCallback} [callback] * @returns {Promise|void} */ function run(node, doc, callback) { assertNode(node); processor.freeze(); if (!callback && typeof doc === 'function') { callback = doc; doc = undefined; } if (!callback) { return new Promise(executor) } executor(null, callback); /** * @param {null|((node: Node) => void)} resolve * @param {(error: Error) => void} reject * @returns {void} */ function executor(resolve, reject) { // @ts-expect-error: `doc` can’t be a callback anymore, we checked. transformers.run(node, vfile(doc), done); /** * @param {Error|null} error * @param {Node} tree * @param {VFile} file * @returns {void} */ function done(error, tree, file) { tree = tree || node; if (error) { reject(error); } else if (resolve) { resolve(tree); } else { // @ts-expect-error: `callback` is defined if `resolve` is not. callback(null, tree, file); } } } } /** @type {Processor['runSync']} */ function runSync(node, file) { /** @type {Node|undefined} */ let result; /** @type {boolean|undefined} */ let complete; processor.run(node, file, done); assertDone('runSync', 'run', complete); // @ts-expect-error: we either bailed on an error or have a tree. return result /** * @param {Error|null} [error] * @param {Node} [tree] * @returns {void} */ function done(error, tree) { bail(error); result = tree; complete = true; } } /** * @param {VFileCompatible} doc * @param {ProcessCallback} [callback] * @returns {Promise|undefined} */ function process(doc, callback) { processor.freeze(); assertParser('process', processor.Parser); assertCompiler('process', processor.Compiler); if (!callback) { return new Promise(executor) } executor(null, callback); /** * @param {null|((file: VFile) => void)} resolve * @param {(error?: Error|null|undefined) => void} reject * @returns {void} */ function executor(resolve, reject) { const file = vfile(doc); processor.run(processor.parse(file), file, (error, tree, file) => { if (error || !tree || !file) { done(error); } else { /** @type {unknown} */ const result = processor.stringify(tree, file); if (result === undefined || result === null) ; else if (looksLikeAVFileValue(result)) { file.value = result; } else { file.result = result; } done(error, file); } }); /** * @param {Error|null|undefined} [error] * @param {VFile|undefined} [file] * @returns {void} */ function done(error, file) { if (error || !file) { reject(error); } else if (resolve) { resolve(file); } else { // @ts-expect-error: `callback` is defined if `resolve` is not. callback(null, file); } } } } /** @type {Processor['processSync']} */ function processSync(doc) { /** @type {boolean|undefined} */ let complete; processor.freeze(); assertParser('processSync', processor.Parser); assertCompiler('processSync', processor.Compiler); const file = vfile(doc); processor.process(file, done); assertDone('processSync', 'process', complete); return file /** * @param {Error|null|undefined} [error] * @returns {void} */ function done(error) { complete = true; bail(error); } } } /** * Check if `value` is a constructor. * * @param {unknown} value * @param {string} name * @returns {boolean} */ function newable(value, name) { return ( typeof value === 'function' && // Prototypes do exist. // type-coverage:ignore-next-line value.prototype && // A function with keys in its prototype is probably a constructor. // Classes’ prototype methods are not enumerable, so we check if some value // exists in the prototype. // type-coverage:ignore-next-line (keys(value.prototype) || name in value.prototype) ) } /** * Check if `value` is an object with keys. * * @param {Record} value * @returns {boolean} */ function keys(value) { /** @type {string} */ let key; for (key in value) { if (own.call(value, key)) { return true } } return false } /** * Assert a parser is available. * * @param {string} name * @param {unknown} value * @returns {asserts value is Parser} */ function assertParser(name, value) { if (typeof value !== 'function') { throw new TypeError('Cannot `' + name + '` without `Parser`') } } /** * Assert a compiler is available. * * @param {string} name * @param {unknown} value * @returns {asserts value is Compiler} */ function assertCompiler(name, value) { if (typeof value !== 'function') { throw new TypeError('Cannot `' + name + '` without `Compiler`') } } /** * Assert the processor is not frozen. * * @param {string} name * @param {unknown} frozen * @returns {asserts frozen is false} */ function assertUnfrozen(name, frozen) { if (frozen) { throw new Error( 'Cannot call `' + name + '` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.' ) } } /** * Assert `node` is a unist node. * * @param {unknown} node * @returns {asserts node is Node} */ function assertNode(node) { // `isPlainObj` unfortunately uses `any` instead of `unknown`. // type-coverage:ignore-next-line if (!isPlainObject$1(node) || typeof node.type !== 'string') { throw new TypeError('Expected node, got `' + node + '`') // Fine. } } /** * Assert that `complete` is `true`. * * @param {string} name * @param {string} asyncName * @param {unknown} complete * @returns {asserts complete is true} */ function assertDone(name, asyncName, complete) { if (!complete) { throw new Error( '`' + name + '` finished async. Use `' + asyncName + '` instead' ) } } /** * @param {VFileCompatible} [value] * @returns {VFile} */ function vfile(value) { return looksLikeAVFile(value) ? value : new VFile(value) } /** * @param {VFileCompatible} [value] * @returns {value is VFile} */ function looksLikeAVFile(value) { return Boolean( value && typeof value === 'object' && 'message' in value && 'messages' in value ) } /** * @param {unknown} [value] * @returns {value is VFileValue} */ function looksLikeAVFileValue(value) { return typeof value === 'string' || isBuffer$1(value) } var thinkbug = "4fd0f5fb276c23f89e61.png"; var dist$1 = {}; Object.defineProperty(dist$1, '__esModule', { value: true }); function _interopDefault$1 (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var React = reactExports; var React__default = _interopDefault$1(React); var RenderIfVisible = function (_a) { var _b = _a.initialVisible, initialVisible = _b === void 0 ? false : _b, _c = _a.defaultHeight, defaultHeight = _c === void 0 ? 300 : _c, _d = _a.visibleOffset, visibleOffset = _d === void 0 ? 1000 : _d, _e = _a.stayRendered, stayRendered = _e === void 0 ? false : _e, _f = _a.root, root = _f === void 0 ? null : _f, _g = _a.rootElement, rootElement = _g === void 0 ? 'div' : _g, _h = _a.rootElementClass, rootElementClass = _h === void 0 ? '' : _h, _j = _a.placeholderElement, placeholderElement = _j === void 0 ? 'div' : _j, _k = _a.placeholderElementClass, placeholderElementClass = _k === void 0 ? '' : _k, children = _a.children; var _l = React.useState(initialVisible), isVisible = _l[0], setIsVisible = _l[1]; var _m = React.useState(false), wasVisible = _m[0], setWasVisible = _m[1]; var placeholderHeight = React.useRef(defaultHeight); var intersectionRef = React.useRef(null); var placeholderStyle = { height: placeholderHeight.current }; var rootClasses = React.useMemo(function () { return "renderIfVisible " + rootElementClass; }, [rootElementClass]); var placeholderClasses = React.useMemo(function () { return "renderIfVisible-placeholder " + placeholderElementClass; }, [placeholderElementClass]); // Set visibility with intersection observer React.useEffect(function () { if (intersectionRef.current) { var observer_1 = new IntersectionObserver(function (entries) { if (typeof window !== undefined && window.requestIdleCallback) { window.requestIdleCallback(function () { return setIsVisible(entries[0].isIntersecting); }, { timeout: 600, }); } else { setIsVisible(entries[0].isIntersecting); } }, { root: root, rootMargin: visibleOffset + "px 0px " + visibleOffset + "px 0px" }); observer_1.observe(intersectionRef.current); return function () { if (intersectionRef.current) { observer_1.unobserve(intersectionRef.current); } }; } return function () { }; }, [intersectionRef]); // Set true height for placeholder element after render. React.useEffect(function () { if (intersectionRef.current && isVisible) { placeholderHeight.current = intersectionRef.current.offsetHeight; setWasVisible(true); } }, [isVisible, intersectionRef]); return React__default.createElement(rootElement, { children: isVisible || (stayRendered && wasVisible) ? (React__default.createElement(React__default.Fragment, null, children)) : (React__default.createElement(placeholderElement, { className: placeholderClasses, style: placeholderStyle, })), ref: intersectionRef, className: rootClasses, }); }; var _default = dist$1.default = RenderIfVisible; const IframelyEmbed = React$2.memo( (props) => { const siteConfig = useSiteConfig(); reactExports.useEffect(() => { window.iframely && window.iframely.load(); }); const { data, status } = useQuery( ["iframely", props.url], ({ queryKey }) => fetch( `https://cdn.iframe.ly/api/iframely?url=${encodeURIComponent( queryKey[1] )}&key=${siteConfig.IFRAMELY_KEY}&iframe=1&omit_script=1` ).then((res) => res.json()), { staleTime: Infinity, // never refetch keepPreviousData: true, // but just in case we do, keep using the old data retry: false, // pretty much all error states are an issue with the URL or our account. no reason to retry } ); let embedBody = undefined; // prioritize states where we have data so that we don't accidentally swap // to `loading...` on refetch if (data && data.error) { embedBody = ( React$2.createElement('div', { className: tw`co-embed co-loading not-prose flex flex-row gap-8 py-8 pl-8`,} , React$2.createElement('img', { className: "max-w-[106px] object-contain" , src: serverPathFromImport(thinkbug), alt: "",} ) , React$2.createElement('div', { className: "self-center", 'data-testid': "iframely-error",} , React$2.createElement('p', { className: "font-league text-2xl font-semibold" ,}, "hmm..." ) , React$2.createElement('p', { className: "font-atkinson text-2xl" ,}, "something went wrong with this preview." ) , React$2.createElement('p', { className: "font-atkinson text-2xl" ,}, "here's why: " , data.error ) ) ) ); } else if (data && data.html) { embedBody = ( // only render the iframely player if it's visible onscreen // because we can't take its children out of the tab order; set // initial visibility to true to minimize glitches for elements // above the fold in a read-more post when the read more is // closed React$2.createElement(_default, { initialVisible: true,} , React$2.createElement('div', { dangerouslySetInnerHTML: { __html: data.html },} ) ) ); } else if (status === "loading") { // display `loading...` immediately instead of waiting for the request to // actually start embedBody = ( React$2.createElement('div', { className: tw`co-embed co-loading not-prose flex flex-row gap-8 py-8 pl-8`,} /* TODO: add throbber */ , React$2.createElement('div', { className: "h-[102px] w-[106px]" ,}, " ") , React$2.createElement('div', { className: "self-center",} , React$2.createElement('p', { className: "font-atkinson text-2xl" ,}, "loading...") ) ) ); } return ( React$2.createElement('div', { className: tw`co-embed`,} , embedBody , React$2.createElement('div', { className: tw`co-ui-text mt-0 p-3 text-right`,} , React$2.createElement('a', { href: props.url, target: "_blank", rel: "noopener nofollow" ,} , props.url ) ) ) ); } ); IframelyEmbed.displayName = "IframelyEmbed"; const Mention = ({ handle, }) => { return ( React$2.createElement('a', { 'data-testid': "mention", href: sitemap.public.project .mainAppProfile({ projectHandle: handle, }) .toString(), className: "!font-bold !no-underline hover:!underline" ,} , "@" , handle ) ); }; /** * Default props included because Mention is used outside of typescript and we * need an easy way to see when it's fucked instead of just crashing */ Mention.defaultProps = { handle: "ERROR" , }; // Adapted from https://github.com/twitter/twitter-text function regexSupplant( regex, map, flags = "" ) { if (typeof regex !== "string") { if (regex.global && flags.indexOf("g") < 0) { flags += "g"; } if (regex.ignoreCase && flags.indexOf("i") < 0) { flags += "i"; } if (regex.multiline && flags.indexOf("m") < 0) { flags += "m"; } regex = regex.source; } return new RegExp( regex.replace(/#\{(\w+)\}/g, function (match, name) { let newRegex = map[name] || ""; if (typeof newRegex !== "string") { newRegex = newRegex.source; } return newRegex; }), flags ); } const latinAccentChars = /\xC0-\xD6\xD8-\xF6\xF8-\xFF\u0100-\u024F\u0253\u0254\u0256\u0257\u0259\u025B\u0263\u0268\u026F\u0272\u0289\u028B\u02BB\u0300-\u036F\u1E00-\u1EFF/; const atSigns = /[@@]/; const validMentionPrecedingChars = /(?:^|[^a-zA-Z0-9_!#$%&*@@\\/]|(?:^|[^a-zA-Z0-9_+~.-\\/]))/; const validMention = regexSupplant( "(#{validMentionPrecedingChars})" + // $1: Preceding character "(#{atSigns})" + // $2: At mark "([a-zA-Z0-9-]{3,})", // $3: handle { validMentionPrecedingChars, atSigns }, "g" ); const endMentionMatch = regexSupplant( /^(?:#{atSigns}|[#{latinAccentChars}]|:\/\/)/, { atSigns, latinAccentChars } ); function extractMentions(text) { if (!text.match(atSigns)) { return []; } const possibleNames = []; text.replace( validMention, function ( match, before, atSign, handle, offset, chunk ) { const after = chunk.slice(offset + match.length); if (!after.match(endMentionMatch)) { const startPosition = offset + before.length; const endPosition = startPosition + handle.length + 1; possibleNames.push({ handle, indices: [startPosition, endPosition], }); } return ""; } ); return possibleNames; } const processMatches = ( regex, callback ) => (hast) => { // we only want to check on text nodes for this visit$2(hast, "text", (node, index, parent) => { // there is no such thing as a text node without a parent. // but if there is we want nothing to do with it. if (parent === null || index === null) return; const matches = node.value.match(regex); // if this text has mentions, process them if (matches) { const splits = node.value.split(regex); if (splits.length - 1 !== matches.length) { // something isn't how it should be. bail. return; } return callback(matches, splits, node, index, parent); } }); }; const convertMentions = (hast) => { // we only want to check on text nodes for this visit$2(hast, "text", (node, index, parent) => { // there is no such thing as a text node without a parent. // but if there is we want nothing to do with it. if (parent === null || index === null) return; const text = node.value; const names = extractMentions(text); // if this text has mentions, consider processing them if (names.length) { // if we have an `a` in our parent tree, we don't want to process // the mention so that links still work. let hasAnchorParent = false; visitParents$2(parent, { type: "text" }, (newNode, ancestors) => { // since we have to traverse for all text nodes on the parent, // we will pretty often get text nodes that _aren't_ the one // we're trying to operate on. check to make sure they match. if (!_$5.isEqual(node, newNode)) return CONTINUE$2; // flag if we've got an anchro parent hasAnchorParent = !!ancestors.find((el) => is$2(el, { type: "element", tagName: "a" }) ); // if we do, we don't need to check everything else so bail out. if (hasAnchorParent) return EXIT$2; }); if (hasAnchorParent) return CONTINUE$2; const els = []; let currentStart = 0; names.forEach((token, idx, names) => { const [startPosition, endPosition] = token.indices; els.push({ type: "text", value: text.slice(currentStart, startPosition), }); els.push({ type: "element", tagName: "Mention", properties: { handle: token.handle, }, children: [ { type: "text", value: `@${token.handle}`, }, ], }); currentStart = endPosition; if (idx === names.length - 1) { // if we're last we need to grab the rest of the string els.push({ type: "text", value: text.slice(currentStart), }); } }); parent.children.splice(index, 1, ...els); // skip over all the new elements we just created return [SKIP$2, index + els.length]; } }); }; const cleanUpFootnotes = (hast) => { visit$2(hast, "element", (node, index, parent) => { if (parent === null || index === null) return; // remove the link from the superscript number if ( node.tagName === "a" && (node.properties?.id )?.includes("fnref") ) { parent.children.splice(index, 1, ...node.children); return [SKIP$2, index]; } // remove the little arrow at the bottom if ( node.tagName === "a" && (node.properties?.href )?.includes("fnref") ) { parent.children.splice(index, 1); return [SKIP$2, index]; } // replace the invisible label with a hr if ( node.tagName === "h2" && (node.properties?.id )?.includes("footnote-label") ) { const hrEl = { tagName: "hr", type: "element", children: [], properties: { "aria-label": "Footnotes", style: "margin-bottom: -0.5rem;", }, }; parent.children.splice(index, 1, hrEl); } }); }; const copyImgAltToTitle = (hast) => { visit$2(hast, { type: "element", tagName: "img" }, (node) => { if (node.properties?.alt) { node.properties.title = node.properties.alt; } }); }; const makeIframelyEmbeds = (hast) => { visit$2(hast, { type: "element", tagName: "a" }, (node, index, parent) => { if (parent === null || index === null) return; // GFM autolink literals have the following two properties: // - they have exactly one child, and it's a text child; if (node.children.length != 1 || node.children[0].type != "text") return; // - the starting offset of the text child matches the starting offset // of the node (angle-bracket autolinks and explicit links differ by 1 // char) if ( !node.position || !node.children[0].position || node.children[0].position.start.offset != node.position.start.offset ) return; // additionally, GFM autolink literals in their own paragraph are the // only child of their parent node. if (parent.children.length != 1) return; // change the type of the parent to a div because you can't nest a div // inside a paragraph if (parent.type === "element") parent.tagName = "div"; parent.children.splice(index, 1, { type: "element", tagName: "IframelyEmbed", properties: { url: node.properties?.href, }, children: [], }); return true; }); }; const compileHastAST = function () { const compiler = (node) => { return JSON.stringify(node); }; Object.assign(this, { Compiler: compiler }); }; const parseHastAST = function () { const parser = (astString) => { const ast = JSON.parse(astString) ; return ast; }; Object.assign(this, { Parser: parser }); }; const EMOJI_REGEX = /:[a-zA-Z\d-_]+:/gims; function importAll(r) { return r.keys().map((key) => { const name = path$3.basename(key, path$3.extname(key)); return { id: name, name, skins: [ { src: sitemap.public.static .staticAsset({ path: r(key) }) .toString(), }, ], keywords: [], }; }); } const customEmoji = // require.context is webpack runtime specific and thus not available under jest typeof process !== "undefined" && process.env?.RUN_MODE === "test" ? [] : importAll( require.context("../images/emoji", false, /\.(png|jpe?g|svg)$/) ); const cohostPlusCustomEmoji = // require.context is webpack runtime specific and thus not available under jest typeof process !== "undefined" && process.env?.RUN_MODE === "test" ? [] : importAll( require.context( "../images/plus-emoji", false, /\.(png|jpe?g|svg)$/ ) ); const indexableCustomEmoji = new Map( customEmoji.reduce((collector, emoji) => { return [...collector, [emoji.name, emoji]]; }, []) ); const indexableCohostPlusCustomEmoji = new Map( cohostPlusCustomEmoji.reduce( (collector, emoji) => { return [...collector, [emoji.name, emoji]]; }, [] ) ); const parseEmoji = (options) => { const compiler = processMatches( EMOJI_REGEX, (matches, splits, node, index, parent) => { const els = splits.reduce( (collector, curr, index) => { const currNode = { type: "text", value: curr, }; const pending = [...collector, currNode]; if (index < matches.length) { const emojiName = matches[index].slice( 1, matches[index].length - 1 ); let emoji = indexableCustomEmoji.get(emojiName); if (!emoji && options.cohostPlus) { emoji = indexableCohostPlusCustomEmoji.get(emojiName); } if (emoji) { pending.push({ type: "element", tagName: "CustomEmoji", properties: { name: emoji.name, url: emoji.skins[0].src, }, children: [], } ); } else { pending.push({ type: "text", value: matches[index], }); } } return pending; }, [] ); parent.children.splice(index, 1, ...els); // skip over all the new elements we just created return [SKIP$2, index + els.length]; } ); return compiler; }; var emoji = /*#__PURE__*/Object.freeze({ __proto__: null, cohostPlusCustomEmoji: cohostPlusCustomEmoji, customEmoji: customEmoji, indexableCohostPlusCustomEmoji: indexableCohostPlusCustomEmoji, indexableCustomEmoji: indexableCustomEmoji, parseEmoji: parseEmoji }); const MAX_GFM_LINES = 256; /* esm.sh - esbuild bundle(css-tree@2.3.1) es2022 production */ var rs=Object.create;var tr=Object.defineProperty;var ns=Object.getOwnPropertyDescriptor;var os=Object.getOwnPropertyNames;var is$1=Object.getPrototypeOf,as=Object.prototype.hasOwnProperty;var Oe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),b=(e,t)=>{for(var r in t)tr(e,r,{get:t[r],enumerable:!0});},ss=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of os(t))!as.call(e,o)&&o!==r&&tr(e,o,{get:()=>t[o],enumerable:!(n=ns(t,o))||n.enumerable});return e};var ls=(e,t,r)=>(r=e!=null?rs(is$1(e)):{},ss(tr(r,"default",{value:e,enumerable:!0}),e));var Jo=Oe(ur=>{var Zo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");ur.encode=function(e){if(0<=e&&e{var ei=Jo(),pr=5,ti=1<>1;return t?-r:r}hr.encode=function(t){var r="",n,o=ks(t);do n=o&ri,o>>>=pr,o>0&&(n|=ni),r+=ei.encode(n);while(o>0);return r};hr.decode=function(t,r,n){var o=t.length,i=0,s=0,u,c;do{if(r>=o)throw new Error("Expected more digits in base 64 VLQ value.");if(c=ei.decode(t.charCodeAt(r++)),c===-1)throw new Error("Invalid base64 digit: "+t.charAt(r-1));u=!!(c&ni),c&=ri,i=i+(c<{function vs(e,t,r){if(t in e)return e[t];if(arguments.length===3)return r;throw new Error('"'+t+'" is a required argument.')}V.getArg=vs;var ii=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,Ss=/^data:.+\,.+$/;function nt(e){var t=e.match(ii);return t?{scheme:t[1],auth:t[2],host:t[3],port:t[4],path:t[5]}:null}V.urlParse=nt;function Ue(e){var t="";return e.scheme&&(t+=e.scheme+":"),t+="//",e.auth&&(t+=e.auth+"@"),e.host&&(t+=e.host),e.port&&(t+=":"+e.port),e.path&&(t+=e.path),t}V.urlGenerate=Ue;var Cs=32;function As(e){var t=[];return function(r){for(var n=0;nCs&&t.pop(),i}}var mr=As(function(t){var r=t,n=nt(t);if(n){if(!n.path)return t;r=n.path;}for(var o=V.isAbsolute(r),i=[],s=0,u=0;;)if(s=u,u=r.indexOf("/",s),u===-1){i.push(r.slice(s));break}else for(i.push(r.slice(s,u));u=0;u--)c=i[u],c==="."?i.splice(u,1):c===".."?a++:a>0&&(c===""?(i.splice(u+1,a),a=0):(i.splice(u,2),a--));return r=i.join("/"),r===""&&(r=o?"/":"."),n?(n.path=r,Ue(n)):r});V.normalize=mr;function ai(e,t){e===""&&(e="."),t===""&&(t=".");var r=nt(t),n=nt(e);if(n&&(e=n.path||"/"),r&&!r.scheme)return n&&(r.scheme=n.scheme),Ue(r);if(r||t.match(Ss))return t;if(n&&!n.host&&!n.path)return n.host=t,Ue(n);var o=t.charAt(0)==="/"?t:mr(e.replace(/\/+$/,"")+"/"+t);return n?(n.path=o,Ue(n)):o}V.join=ai;V.isAbsolute=function(e){return e.charAt(0)==="/"||ii.test(e)};function Ts(e,t){e===""&&(e="."),e=e.replace(/\/$/,"");for(var r=0;t.indexOf(e+"/")!==0;){var n=e.lastIndexOf("/");if(n<0||(e=e.slice(0,n),e.match(/^([^\/]+:\/)?\/*$/)))return t;++r;}return Array(r+1).join("../")+t.substr(e.length+1)}V.relative=Ts;var si=function(){var e=Object.create(null);return !("__proto__"in e)}();function li(e){return e}function Es(e){return ci(e)?"$"+e:e}V.toSetString=si?li:Es;function Ls(e){return ci(e)?e.slice(1):e}V.fromSetString=si?li:Ls;function ci(e){if(!e)return !1;var t=e.length;if(t<9||e.charCodeAt(t-1)!==95||e.charCodeAt(t-2)!==95||e.charCodeAt(t-3)!==111||e.charCodeAt(t-4)!==116||e.charCodeAt(t-5)!==111||e.charCodeAt(t-6)!==114||e.charCodeAt(t-7)!==112||e.charCodeAt(t-8)!==95||e.charCodeAt(t-9)!==95)return !1;for(var r=t-10;r>=0;r--)if(e.charCodeAt(r)!==36)return !1;return !0}function Ps(e,t,r){var n=be(e.source,t.source);return n!==0||(n=e.originalLine-t.originalLine,n!==0)||(n=e.originalColumn-t.originalColumn,n!==0||r)||(n=e.generatedColumn-t.generatedColumn,n!==0)||(n=e.generatedLine-t.generatedLine,n!==0)?n:be(e.name,t.name)}V.compareByOriginalPositions=Ps;function Is(e,t,r){var n;return n=e.originalLine-t.originalLine,n!==0||(n=e.originalColumn-t.originalColumn,n!==0||r)||(n=e.generatedColumn-t.generatedColumn,n!==0)||(n=e.generatedLine-t.generatedLine,n!==0)?n:be(e.name,t.name)}V.compareByOriginalPositionsNoSource=Is;function Ds(e,t,r){var n=e.generatedLine-t.generatedLine;return n!==0||(n=e.generatedColumn-t.generatedColumn,n!==0||r)||(n=be(e.source,t.source),n!==0)||(n=e.originalLine-t.originalLine,n!==0)||(n=e.originalColumn-t.originalColumn,n!==0)?n:be(e.name,t.name)}V.compareByGeneratedPositionsDeflated=Ds;function Os(e,t,r){var n=e.generatedColumn-t.generatedColumn;return n!==0||r||(n=be(e.source,t.source),n!==0)||(n=e.originalLine-t.originalLine,n!==0)||(n=e.originalColumn-t.originalColumn,n!==0)?n:be(e.name,t.name)}V.compareByGeneratedPositionsDeflatedNoLine=Os;function be(e,t){return e===t?0:e===null?1:t===null?-1:e>t?1:-1}function Ns(e,t){var r=e.generatedLine-t.generatedLine;return r!==0||(r=e.generatedColumn-t.generatedColumn,r!==0)||(r=be(e.source,t.source),r!==0)||(r=e.originalLine-t.originalLine,r!==0)||(r=e.originalColumn-t.originalColumn,r!==0)?r:be(e.name,t.name)}V.compareByGeneratedPositionsInflated=Ns;function zs(e){return JSON.parse(e.replace(/^\)]}'[^\n]*\n/,""))}V.parseSourceMapInput=zs;function Ms(e,t,r){if(t=t||"",e&&(e[e.length-1]!=="/"&&t[0]!=="/"&&(e+="/"),t=e+t),r){var n=nt(r);if(!n)throw new Error("sourceMapURL could not be parsed");if(n.path){var o=n.path.lastIndexOf("/");o>=0&&(n.path=n.path.substring(0,o+1));}t=ai(Ue(n),t);}return mr(t)}V.computeSourceURL=Ms;});var pi=Oe(ui=>{var fr=Et(),dr=Object.prototype.hasOwnProperty,Le=typeof Map<"u";function xe(){this._array=[],this._set=Le?new Map:Object.create(null);}xe.fromArray=function(t,r){for(var n=new xe,o=0,i=t.length;o=0)return r}else {var n=fr.toSetString(t);if(dr.call(this._set,n))return this._set[n]}throw new Error('"'+t+'" is not in the set.')};xe.prototype.at=function(t){if(t>=0&&t{var hi=Et();function Rs(e,t){var r=e.generatedLine,n=t.generatedLine,o=e.generatedColumn,i=t.generatedColumn;return n>r||n==r&&i>=o||hi.compareByGeneratedPositionsInflated(e,t)<=0}function Lt(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0};}Lt.prototype.unsortedForEach=function(t,r){this._array.forEach(t,r);};Lt.prototype.add=function(t){Rs(this._last,t)?(this._last=t,this._array.push(t)):(this._sorted=!1,this._array.push(t));};Lt.prototype.toArray=function(){return this._sorted||(this._array.sort(hi.compareByGeneratedPositionsInflated),this._sorted=!0),this._array};mi.MappingList=Lt;});var gi=Oe(di=>{var ot=oi(),U=Et(),Pt=pi().ArraySet,Fs=fi().MappingList;function oe(e){e||(e={}),this._file=U.getArg(e,"file",null),this._sourceRoot=U.getArg(e,"sourceRoot",null),this._skipValidation=U.getArg(e,"skipValidation",!1),this._ignoreInvalidMapping=U.getArg(e,"ignoreInvalidMapping",!1),this._sources=new Pt,this._names=new Pt,this._mappings=new Fs,this._sourcesContents=null;}oe.prototype._version=3;oe.fromSourceMap=function(t,r){var n=t.sourceRoot,o=new oe(Object.assign(r||{},{file:t.file,sourceRoot:n}));return t.eachMapping(function(i){var s={generated:{line:i.generatedLine,column:i.generatedColumn}};i.source!=null&&(s.source=i.source,n!=null&&(s.source=U.relative(n,s.source)),s.original={line:i.originalLine,column:i.originalColumn},i.name!=null&&(s.name=i.name)),o.addMapping(s);}),t.sources.forEach(function(i){var s=i;n!==null&&(s=U.relative(n,i)),o._sources.has(s)||o._sources.add(s);var u=t.sourceContentFor(i);u!=null&&o.setSourceContent(i,u);}),o};oe.prototype.addMapping=function(t){var r=U.getArg(t,"generated"),n=U.getArg(t,"original",null),o=U.getArg(t,"source",null),i=U.getArg(t,"name",null);!this._skipValidation&&this._validateMapping(r,n,o,i)===!1||(o!=null&&(o=String(o),this._sources.has(o)||this._sources.add(o)),i!=null&&(i=String(i),this._names.has(i)||this._names.add(i)),this._mappings.add({generatedLine:r.line,generatedColumn:r.column,originalLine:n!=null&&n.line,originalColumn:n!=null&&n.column,source:o,name:i}));};oe.prototype.setSourceContent=function(t,r){var n=t;this._sourceRoot!=null&&(n=U.relative(this._sourceRoot,n)),r!=null?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[U.toSetString(n)]=r):this._sourcesContents&&(delete this._sourcesContents[U.toSetString(n)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null));};oe.prototype.applySourceMap=function(t,r,n){var o=r;if(r==null){if(t.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);o=t.file;}var i=this._sourceRoot;i!=null&&(o=U.relative(i,o));var s=new Pt,u=new Pt;this._mappings.unsortedForEach(function(c){if(c.source===o&&c.originalLine!=null){var a=t.originalPositionFor({line:c.originalLine,column:c.originalColumn});a.source!=null&&(c.source=a.source,n!=null&&(c.source=U.join(n,c.source)),i!=null&&(c.source=U.relative(i,c.source)),c.originalLine=a.line,c.originalColumn=a.column,a.name!=null&&(c.name=a.name));}var l=c.source;l!=null&&!s.has(l)&&s.add(l);var p=c.name;p!=null&&!u.has(p)&&u.add(p);},this),this._sources=s,this._names=u,t.sources.forEach(function(c){var a=t.sourceContentFor(c);a!=null&&(n!=null&&(c=U.join(n,c)),i!=null&&(c=U.relative(i,c)),this.setSourceContent(c,a));},this);};oe.prototype._validateMapping=function(t,r,n,o){if(r&&typeof r.line!="number"&&typeof r.column!="number"){var i="original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.";if(this._ignoreInvalidMapping)return typeof console<"u"&&console.warn&&console.warn(i),!1;throw new Error(i)}if(!(t&&"line"in t&&"column"in t&&t.line>0&&t.column>=0&&!r&&!n&&!o)){if(t&&"line"in t&&"column"in t&&r&&"line"in r&&"column"in r&&t.line>0&&t.column>=0&&r.line>0&&r.column>=0&&n)return;var i="Invalid mapping: "+JSON.stringify({generated:t,source:n,original:r,name:o});if(this._ignoreInvalidMapping)return typeof console<"u"&&console.warn&&console.warn(i),!1;throw new Error(i)}};oe.prototype._serializeMappings=function(){for(var t=0,r=1,n=0,o=0,i=0,s=0,u="",c,a,l,p,m=this._mappings.toArray(),f=0,P=m.length;f0){if(!U.compareByGeneratedPositionsInflated(a,m[f-1]))continue;c+=",";}c+=ot.encode(a.generatedColumn-t),t=a.generatedColumn,a.source!=null&&(p=this._sources.indexOf(a.source),c+=ot.encode(p-s),s=p,c+=ot.encode(a.originalLine-1-o),o=a.originalLine-1,c+=ot.encode(a.originalColumn-n),n=a.originalColumn,a.name!=null&&(l=this._names.indexOf(a.name),c+=ot.encode(l-i),i=l)),u+=c;}return u};oe.prototype._generateSourcesContent=function(t,r){return t.map(function(n){if(!this._sourcesContents)return null;r!=null&&(n=U.relative(r,n));var o=U.toSetString(n);return Object.prototype.hasOwnProperty.call(this._sourcesContents,o)?this._sourcesContents[o]:null},this)};oe.prototype.toJSON=function(){var t={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(t.file=this._file),this._sourceRoot!=null&&(t.sourceRoot=this._sourceRoot),this._sourcesContents&&(t.sourcesContent=this._generateSourcesContent(t.sources,t.sourceRoot)),t};oe.prototype.toString=function(){return JSON.stringify(this.toJSON())};di.SourceMapGenerator=oe;});var $e={};b($e,{AtKeyword:()=>I,BadString:()=>Ae,BadUrl:()=>H,CDC:()=>j,CDO:()=>ue,Colon:()=>D,Comma:()=>Y,Comment:()=>E,Delim:()=>g,Dimension:()=>y,EOF:()=>Xe,Function:()=>x,Hash:()=>v,Ident:()=>h,LeftCurlyBracket:()=>z,LeftParenthesis:()=>T,LeftSquareBracket:()=>_,Number:()=>d,Percentage:()=>A,RightCurlyBracket:()=>W,RightParenthesis:()=>w,RightSquareBracket:()=>G,Semicolon:()=>B,String:()=>q,Url:()=>R,WhiteSpace:()=>k});var Xe=0,h=1,x=2,I=3,v=4,q=5,Ae=6,R=7,H=8,g=9,d=10,A=11,y=12,k=13,ue=14,j=15,D=16,B=17,Y=18,_=19,G=20,T=21,w=22,z=23,W=24,E=25;function F(e){return e>=48&&e<=57}function ee(e){return F(e)||e>=65&&e<=70||e>=97&&e<=102}function yt(e){return e>=65&&e<=90}function cs(e){return e>=97&&e<=122}function us(e){return yt(e)||cs(e)}function ps(e){return e>=128}function xt(e){return us(e)||ps(e)||e===95}function Ne(e){return xt(e)||F(e)||e===45}function hs(e){return e>=0&&e<=8||e===11||e>=14&&e<=31||e===127}function Ze(e){return e===10||e===13||e===12}function pe(e){return Ze(e)||e===32||e===9}function X(e,t){return !(e!==92||Ze(t)||t===0)}function ze(e,t,r){return e===45?xt(t)||t===45||X(t,r):xt(e)?!0:e===92?X(e,t):!1}function kt(e,t,r){return e===43||e===45?F(t)?2:t===46&&F(r)?3:0:e===46?F(t)?2:0:F(e)?1:0}function wt(e){return e===65279||e===65534?1:0}var rr=new Array(128),ms=128,Je=130,nr=131,vt=132,or=133;for(let e=0;ee.length)return !1;for(let o=t;o=0&&pe(e.charCodeAt(t));t--);return t+1}function et(e,t){for(;t=55296&&t<=57343||t>1114111)&&(t=65533),String.fromCodePoint(t)}var Fe=["EOF-token","ident-token","function-token","at-keyword-token","hash-token","string-token","bad-string-token","url-token","bad-url-token","delim-token","number-token","percentage-token","dimension-token","whitespace-token","CDO-token","CDC-token","colon-token","semicolon-token","comma-token","[-token","]-token","(-token",")-token","{-token","}-token"];function Be(e=null,t){return e===null||e.length0?wt(t.charCodeAt(0)):0,o=Be(e.lines,r),i=Be(e.columns,r),s=e.startLine,u=e.startColumn;for(let c=n;c{}){t=String(t||"");let n=t.length,o=Be(this.offsetAndType,t.length+1),i=Be(this.balance,t.length+1),s=0,u=0,c=0,a=-1;for(this.offsetAndType=null,this.balance=null,r(t,(l,p,m)=>{switch(l){default:i[s]=n;break;case u:{let f=c≠for(c=i[f],u=c>>we,i[s]=f,i[f++]=s;f>we:0}lookupOffset(t){return t+=this.tokenIndex,t0?t>we,this.tokenEnd=r&ne):(this.tokenIndex=this.tokenCount,this.next());}next(){let t=this.tokenIndex+1;t>we,this.tokenEnd=t&ne):(this.eof=!0,this.tokenIndex=this.tokenCount,this.tokenType=0,this.tokenStart=this.tokenEnd=this.source.length);}skipSC(){for(;this.tokenType===13||this.tokenType===25;)this.next();}skipUntilBalanced(t,r){let n=t,o,i;e:for(;n0?this.offsetAndType[n-1]&ne:this.firstCharOffset,r(this.source.charCodeAt(i))){case 1:break e;case 2:n++;break e;default:this.balance[o]===n&&(n=o);}}this.skip(n-this.tokenIndex);}forEachToken(t){for(let r=0,n=this.firstCharOffset;r>we;n=s,t(u,o,s,r);}}dump(){let t=new Array(this.tokenCount);return this.forEachToken((r,n,o,i)=>{t[i]={idx:i,type:Fe[r],chunk:this.source.substring(n,o),balance:this.balance[i]};}),t}};function ve(e,t){function r(p){return p=e.length){aString(l+f+1).padStart(c)+" |"+m).join(` `)}let i=e.split(/\r\n?|\n|\f/),s=Math.max(1,t-n)-1,u=Math.min(t+n,i.length+1),c=Math.max(4,String(u).length)+1,a=0;r+=(Yo.length-1)*(i[t-1].substr(0,r-1).match(/\t/g)||[]).length,r>ar&&(a=r-Ho+3,r=Ho-2);for(let l=s;l<=u;l++)l>=0&&l0&&i[l].length>a?"\u2026":"")+i[l].substr(a,ar-2)+(i[l].length>a+ar-1?"\u2026":""));return [o(s,t),new Array(r+c+2).join("-")+"^",o(t,u)].filter(Boolean).join(` `)}function sr(e,t,r,n,o){return Object.assign(Ee("SyntaxError",e),{source:t,offset:r,line:n,column:o,sourceFragment(s){return Go({source:t,line:n,column:o},isNaN(s)?0:s)},get formattedMessage(){return `Parse error: ${e} `+Go({source:t,line:n,column:o},2)}})}function Vo(e){let t=this.createList(),r=!1,n={recognizer:e};for(;!this.eof;){switch(this.tokenType){case 25:this.next();continue;case 13:r=!0,this.next();continue}let o=e.getNode.call(this,n);if(o===void 0)break;r&&(e.onWhiteSpace&&e.onWhiteSpace.call(this,o,t,n),r=!1),t.push(o);}return r&&e.onWhiteSpace&&e.onWhiteSpace.call(this,null,t,n),t}var Ko=()=>{},gs=33,bs=35,lr=59,Qo=123,Xo=0;function xs(e){return function(){return this[e]()}}function cr(e){let t=Object.create(null);for(let r in e){let n=e[r],o=n.parse||n;o&&(t[r]=o);}return t}function ys(e){let t={context:Object.create(null),scope:Object.assign(Object.create(null),e.scope),atrule:cr(e.atrule),pseudo:cr(e.pseudo),node:cr(e.node)};for(let r in e.parseContext)switch(typeof e.parseContext[r]){case"function":t.context[r]=e.parseContext[r];break;case"string":t.context[r]=xs(e.parseContext[r]);break}return {config:t,...t,...t.node}}function $o(e){let t="",r="",n=!1,o=Ko,i=!1,s=new Tt,u=Object.assign(new rt,ys(e||{}),{parseAtrulePrelude:!0,parseRulePrelude:!0,parseValue:!0,parseCustomProperty:!1,readSequence:Vo,consumeUntilBalanceEnd:()=>0,consumeUntilLeftCurlyBracket(a){return a===Qo?1:0},consumeUntilLeftCurlyBracketOrSemicolon(a){return a===Qo||a===lr?1:0},consumeUntilExclamationMarkOrSemicolon(a){return a===gs||a===lr?1:0},consumeUntilSemicolonIncluded(a){return a===lr?2:0},createList(){return new $},createSingleNodeList(a){return new $().appendData(a)},getFirstListNode(a){return a&&a.first},getLastListNode(a){return a&&a.last},parseWithFallback(a,l){let p=this.tokenIndex;try{return a.call(this)}catch(m){if(i)throw m;let f=l.call(this,p);return i=!0,o(m,f),i=!1,f}},lookupNonWSType(a){let l;do if(l=this.lookupType(a++),l!==13)return l;while(l!==Xo);return Xo},charCodeAt(a){return a>=0&&af.toUpperCase()),p=`${/[[\](){}]/.test(l)?`"${l}"`:l} is expected`,m=this.tokenStart;switch(a){case 1:this.tokenType===2||this.tokenType===7?(m=this.tokenEnd-1,p="Identifier is expected but function found"):p="Identifier is expected";break;case 4:this.isDelim(bs)&&(this.next(),m++,p="Name is expected");break;case 11:this.tokenType===10&&(m=this.tokenEnd,p="Percent sign is expected");break}this.error(p,m);}this.next();},eatIdent(a){(this.tokenType!==1||this.lookupValue(0,a)===!1)&&this.error(`Identifier "${a}" is expected`),this.next();},eatDelim(a){this.isDelim(a)||this.error(`Delim "${String.fromCharCode(a)}" is expected`),this.next();},getLocation(a,l){return n?s.getLocationRange(a,l,r):null},getLocationFromList(a){if(n){let l=this.getFirstListNode(a),p=this.getLastListNode(a);return s.getLocationRange(l!==null?l.loc.start.offset-s.startOffset:this.tokenStart,p!==null?p.loc.end.offset-s.startOffset:this.tokenStart,r)}return null},error(a,l){let p=typeof l<"u"&&l",n=!!l.positions,o=typeof l.onParseError=="function"?l.onParseError:Ko,i=!1,u.parseAtrulePrelude="parseAtrulePrelude"in l?!!l.parseAtrulePrelude:!0,u.parseRulePrelude="parseRulePrelude"in l?!!l.parseRulePrelude:!0,u.parseValue="parseValue"in l?!!l.parseValue:!0,u.parseCustomProperty="parseCustomProperty"in l?!!l.parseCustomProperty:!1;let{context:p="default",onComment:m}=l;if(!(p in u.context))throw new Error("Unknown context `"+p+"`");typeof m=="function"&&u.forEachToken((P,te,Q)=>{if(P===25){let S=u.getLocation(te,Q),M=ge(t,Q-2,Q,"*/")?t.slice(te+2,Q-2):t.slice(te+2,Q);m(M,S);}});let f=u.context[p].call(u,l);return u.eof||u.error(),f},{SyntaxError:sr,config:u.config})}var xi=ls(gi()),bi=new Set(["Atrule","Selector","Declaration"]);function yi(e){let t=new xi.SourceMapGenerator,r={line:1,column:0},n={line:0,column:0},o={line:1,column:0},i={generated:o},s=1,u=0,c=!1,a=e.node;e.node=function(m){if(m.loc&&m.loc.start&&bi.has(m.type)){let f=m.loc.start.line,P=m.loc.start.column-1;(n.line!==f||n.column!==P)&&(n.line=f,n.column=P,r.line=s,r.column=u,c&&(c=!1,(r.line!==o.line||r.column!==o.column)&&t.addMapping(i)),c=!0,t.addMapping({source:m.loc.source,original:n,generated:r}));}a.call(this,m),c&&bi.has(m.type)&&(o.line=s,o.column=u);};let l=e.emit;e.emit=function(m,f,P){for(let te=0;tebr,spec:()=>js});var Bs=43,_s=45,gr=(e,t)=>{if(e===9&&(e=t),typeof e=="string"){let r=e.charCodeAt(0);return r>127?32768:r<<8}return e},ki=[[1,1],[1,2],[1,7],[1,8],[1,"-"],[1,10],[1,11],[1,12],[1,15],[1,21],[3,1],[3,2],[3,7],[3,8],[3,"-"],[3,10],[3,11],[3,12],[3,15],[4,1],[4,2],[4,7],[4,8],[4,"-"],[4,10],[4,11],[4,12],[4,15],[12,1],[12,2],[12,7],[12,8],[12,"-"],[12,10],[12,11],[12,12],[12,15],["#",1],["#",2],["#",7],["#",8],["#","-"],["#",10],["#",11],["#",12],["#",15],["-",1],["-",2],["-",7],["-",8],["-","-"],["-",10],["-",11],["-",12],["-",15],[10,1],[10,2],[10,7],[10,8],[10,10],[10,11],[10,12],[10,"%"],[10,15],["@",1],["@",2],["@",7],["@",8],["@","-"],["@",15],[".",10],[".",11],[".",12],["+",10],["+",11],["+",12],["/","*"]],Us=ki.concat([[1,4],[12,4],[4,4],[3,21],[3,5],[3,16],[11,11],[11,12],[11,2],[11,"-"],[22,1],[22,2],[22,11],[22,12],[22,4],[22,"-"]]);function wi(e){let t=new Set(e.map(([r,n])=>gr(r)<<16|gr(n)));return function(r,n,o){let i=gr(n,o),s=o.charCodeAt(0);return (s===_s&&n!==1&&n!==2&&n!==15||s===Bs?t.has(r<<16|s<<8):t.has(r<<16|i))&&this.emit(" ",13,!0),i}}var js=wi(ki),br=wi(Us);var qs=92;function Ws(e,t){if(typeof t=="function"){let r=null;e.children.forEach(n=>{r!==null&&t.call(this,r),this.node(n),r=n;});return}e.children.forEach(this.node,this);}function Hs(e){ve(e,(t,r,n)=>{this.token(t,e.slice(r,n));});}function vi(e){let t=new Map;for(let r in e.node){let n=e.node[r];typeof(n.generate||n)=="function"&&t.set(r,n.generate||n);}return function(r,n){let o="",i=0,s={node(c){if(t.has(c.type))t.get(c.type).call(u,c);else throw new Error("Unknown node type: "+c.type)},tokenBefore:br,token(c,a){i=this.tokenBefore(i,c,a),this.emit(a,c,!1),c===9&&a.charCodeAt(0)===qs&&this.emit(` `,13,!0);},emit(c){o+=c;},result(){return o}};n&&(typeof n.decorator=="function"&&(s=n.decorator(s)),n.sourceMap&&(s=yi(s)),n.mode in It&&(s.tokenBefore=It[n.mode]));let u={node:c=>s.node(c),children:Ws,token:(c,a)=>s.token(c,a),tokenize:Hs};return s.node(r),s.result()}}function Si(e){return {fromPlainObject(t){return e(t,{enter(r){r.children&&!(r.children instanceof $)&&(r.children=new $().fromArray(r.children));}}),t},toPlainObject(t){return e(t,{leave(r){r.children&&r.children instanceof $&&(r.children=r.children.toArray());}}),t}}}var{hasOwnProperty:xr}=Object.prototype,it=function(){};function Ci(e){return typeof e=="function"?e:it}function Ai(e,t){return function(r,n,o){r.type===t&&e.call(this,r,n,o);}}function Ys(e,t){let r=t.structure,n=[];for(let o in r){if(xr.call(r,o)===!1)continue;let i=r[o],s={name:o,type:!1,nullable:!1};Array.isArray(i)||(i=[i]);for(let u of i)u===null?s.nullable=!0:typeof u=="string"?s.type="node":Array.isArray(u)&&(s.type="list");s.type&&n.push(s);}return n.length?{context:t.walkContext,fields:n}:null}function Gs(e){let t={};for(let r in e.node)if(xr.call(e.node,r)){let n=e.node[r];if(!n.structure)throw new Error("Missed `structure` field in `"+r+"` node type definition");t[r]=Ys(r,n);}return t}function Ti(e,t){let r=e.fields.slice(),n=e.context,o=typeof n=="string";return t&&r.reverse(),function(i,s,u,c){let a;o&&(a=s[n],s[n]=i);for(let l of r){let p=i[l.name];if(!l.nullable||p){if(l.type==="list"){if(t?p.reduceRight(c,!1):p.reduce(c,!1))return !0}else if(u(p))return !0}}o&&(s[n]=a);}}function Ei({StyleSheet:e,Atrule:t,Rule:r,Block:n,DeclarationList:o}){return {Atrule:{StyleSheet:e,Atrule:t,Rule:r,Block:n},Rule:{StyleSheet:e,Atrule:t,Rule:r,Block:n},Declaration:{StyleSheet:e,Atrule:t,Rule:r,Block:n,DeclarationList:o}}}function Li(e){let t=Gs(e),r={},n={},o=Symbol("break-walk"),i=Symbol("skip-node");for(let a in t)xr.call(t,a)&&t[a]!==null&&(r[a]=Ti(t[a],!1),n[a]=Ti(t[a],!0));let s=Ei(r),u=Ei(n),c=function(a,l){function p(S,M,ke){let N=m.call(Q,S,M,ke);return N===o?!0:N===i?!1:!!(P.hasOwnProperty(S.type)&&P[S.type](S,Q,p,te)||f.call(Q,S,M,ke)===o)}let m=it,f=it,P=r,te=(S,M,ke,N)=>S||p(M,ke,N),Q={break:o,skip:i,root:a,stylesheet:null,atrule:null,atrulePrelude:null,rule:null,selector:null,block:null,declaration:null,function:null};if(typeof l=="function")m=l;else if(l&&(m=Ci(l.enter),f=Ci(l.leave),l.reverse&&(P=n),l.visit)){if(s.hasOwnProperty(l.visit))P=l.reverse?u[l.visit]:s[l.visit];else if(!t.hasOwnProperty(l.visit))throw new Error("Bad value `"+l.visit+"` for `visit` option (should be: "+Object.keys(t).sort().join(", ")+")");m=Ai(m,l.visit),f=Ai(f,l.visit);}if(m===it&&f===it)throw new Error("Neither `enter` nor `leave` walker handler is set or both aren't a function");p(a);};return c.break=o,c.skip=i,c.find=function(a,l){let p=null;return c(a,function(m,f,P){if(l.call(this,m,f,P))return p=m,o}),p},c.findLast=function(a,l){let p=null;return c(a,{reverse:!0,enter(m,f,P){if(l.call(this,m,f,P))return p=m,o}}),p},c.findAll=function(a,l){let p=[];return c(a,function(m,f,P){l.call(this,m,f,P)&&p.push(m);}),p},c}function Vs(e){return e}function Ks(e){let{min:t,max:r,comma:n}=e;return t===0&&r===0?n?"#?":"*":t===0&&r===1?"?":t===1&&r===0?n?"#":"+":t===1&&r===1?"":(n?"#":"")+(t===r?"{"+t+"}":"{"+t+","+(r!==0?r:"")+"}")}function Qs(e){switch(e.type){case"Range":return " ["+(e.min===null?"-\u221E":e.min)+","+(e.max===null?"\u221E":e.max)+"]";default:throw new Error("Unknown node type `"+e.type+"`")}}function Xs(e,t,r,n){let o=e.combinator===" "||n?e.combinator:" "+e.combinator+" ",i=e.terms.map(s=>yr(s,t,r,n)).join(o);return e.explicit||r?(n||i[0]===","?"[":"[ ")+i+(n?"]":" ]"):i}function yr(e,t,r,n){let o;switch(e.type){case"Group":o=Xs(e,t,r,n)+(e.disallowEmpty?"!":"");break;case"Multiplier":return yr(e.term,t,r,n)+t(Ks(e),e);case"Type":o="<"+e.name+(e.opts?t(Qs(e.opts),e.opts):"")+">";break;case"Property":o="<'"+e.name+"'>";break;case"Keyword":o=e.name;break;case"AtKeyword":o="@"+e.name;break;case"Function":o=e.name+"(";break;case"String":case"Token":o=e.value;break;case"Comma":o=",";break;default:throw new Error("Unknown node type `"+e.type+"`")}return t(o,e)}function Pe(e,t){let r=Vs,n=!1,o=!1;return typeof t=="function"?r=t:t&&(n=!!t.forceBraces,o=!!t.compact,typeof t.decorate=="function"&&(r=t.decorate)),yr(e,r,n,o)}var Pi={offset:0,line:1,column:1};function $s(e,t){let r=e.tokens,n=e.longestMatch,o=n1?(l=Dt(i||t,"end")||at(Pi,a),p=at(l)):(l=Dt(i,"start")||at(Dt(t,"start")||Pi,a.slice(0,s)),p=Dt(i,"end")||at(l,a.substr(s,u))),{css:a,mismatchOffset:s,mismatchLength:u,start:l,end:p}}function Dt(e,t){let r=e&&e.loc&&e.loc[t];return r?"line"in r?at(r):r:null}function at({offset:e,line:t,column:r},n){let o={offset:e,line:t,column:r};if(n){let i=n.split(/\n|\r\n?|\f/);o.offset+=n.length,o.line+=i.length-1,o.column=i.length===1?o.column+n.length:i.pop().length+1;}return o}var je=function(e,t){let r=Ee("SyntaxReferenceError",e+(t?" `"+t+"`":""));return r.reference=t,r},Ii=function(e,t,r,n){let o=Ee("SyntaxMatchError",e),{css:i,mismatchOffset:s,mismatchLength:u,start:c,end:a}=$s(n,r);return o.rawMessage=e,o.syntax=t?Pe(t):"",o.css=i,o.mismatchOffset=s,o.mismatchLength=u,o.message=e+` syntax: `+o.syntax+` value: `+(i||"")+` --------`+new Array(o.mismatchOffset+1).join("-")+"^",Object.assign(o,c),o.loc={source:r&&r.loc&&r.loc.source||"",start:c,end:a},o};var Ot=new Map,qe=new Map,Nt=45,zt=Zs,kr=Js;function Mt(e,t){return t=t||0,e.length-t>=2&&e.charCodeAt(t)===Nt&&e.charCodeAt(t+1)===Nt}function wr(e,t){if(t=t||0,e.length-t>=3&&e.charCodeAt(t)===Nt&&e.charCodeAt(t+1)!==Nt){let r=e.indexOf("-",t+2);if(r!==-1)return e.substring(t,r+1)}return ""}function Zs(e){if(Ot.has(e))return Ot.get(e);let t=e.toLowerCase(),r=Ot.get(t);if(r===void 0){let n=Mt(t,0),o=n?"":wr(t,0);r=Object.freeze({basename:t.substr(o.length),name:t,prefix:o,vendor:o,custom:n});}return Ot.set(e,r),r}function Js(e){if(qe.has(e))return qe.get(e);let t=e,r=e[0];r==="/"?r=e[1]==="/"?"//":"/":r!=="_"&&r!=="*"&&r!=="$"&&r!=="#"&&r!=="+"&&r!=="&"&&(r="");let n=Mt(t,r.length);if(!n&&(t=t.toLowerCase(),qe.has(t))){let u=qe.get(t);return qe.set(e,u),u}let o=n?"":wr(t,r.length),i=t.substr(0,r.length+o.length),s=Object.freeze({basename:t.substr(i.length),name:t.substr(r.length),hack:r,vendor:o,prefix:i,custom:n});return qe.set(e,s),s}var Rt=["initial","inherit","unset","revert","revert-layer"];var lt=43,he=45,vr=110,We=!0,tl=!1;function Cr(e,t){return e!==null&&e.type===9&&e.value.charCodeAt(0)===t}function st(e,t,r){for(;e!==null&&(e.type===13||e.type===25);)e=r(++t);return t}function Se(e,t,r,n){if(!e)return 0;let o=e.value.charCodeAt(t);if(o===lt||o===he){if(r)return 0;t++;}for(;t6)return 0}return n}function Ft(e,t,r){if(!e)return 0;for(;Tr(r(t),Oi);){if(++e>6)return 0;t++;}return t}function Er(e,t){let r=0;if(e===null||e.type!==1||!de(e.value,0,nl)||(e=t(++r),e===null))return 0;if(Tr(e,rl))return e=t(++r),e===null?0:e.type===1?Ft(ct(e,0,!0),++r,t):Tr(e,Oi)?Ft(1,++r,t):0;if(e.type===10){let n=ct(e,1,!0);return n===0?0:(e=t(++r),e===null?r:e.type===12||e.type===10?!ol(e,Di)||!ct(e,1,!1)?0:r+1:Ft(n,r,t))}return e.type===12?Ft(ct(e,1,!0),++r,t):0}var il=["calc(","-moz-calc(","-webkit-calc("],Lr=new Map([[2,22],[21,22],[19,20],[23,24]]);function le(e,t){return te.max&&typeof e.max!="string")return !0}return !1}function al(e,t){let r=0,n=[],o=0;e:do{switch(e.type){case 24:case 22:case 20:if(e.type!==r)break e;if(r=n.pop(),n.length===0){o++;break e}break;case 2:case 21:case 19:case 23:n.push(r),r=Lr.get(e.type);break}o++;}while(e=t(o));return o}function ie(e){return function(t,r,n){return t===null?0:t.type===2&&zi(t.value,il)?al(t,r):e(t,r,n)}}function O(e){return function(t){return t===null||t.type!==e?0:1}}function sl(e){if(e===null||e.type!==1)return 0;let t=e.value.toLowerCase();return zi(t,Rt)||Ni(t,"default")?0:1}function ll(e){return e===null||e.type!==1||le(e.value,0)!==45||le(e.value,1)!==45?0:1}function cl(e){if(e===null||e.type!==4)return 0;let t=e.value.length;if(t!==4&&t!==5&&t!==7&&t!==9)return 0;for(let r=1;rkl,decibel:()=>Al,flex:()=>Cl,frequency:()=>vl,length:()=>yl,resolution:()=>Sl,semitones:()=>Tl,time:()=>wl});var yl=["cm","mm","q","in","pt","pc","px","em","rem","ex","rex","cap","rcap","ch","rch","ic","ric","lh","rlh","vw","svw","lvw","dvw","vh","svh","lvh","dvh","vi","svi","lvi","dvi","vb","svb","lvb","dvb","vmin","svmin","lvmin","dvmin","vmax","svmax","lvmax","dvmax","cqw","cqh","cqi","cqb","cqmin","cqmax"],kl=["deg","grad","rad","turn"],wl=["s","ms"],vl=["hz","khz"],Sl=["dpi","dpcm","dppx","x"],Cl=["fr"],Al=["db"],Tl=["st"];var $i={};b($i,{SyntaxError:()=>Ut,generate:()=>Pe,parse:()=>Ge,walk:()=>Vt});function Ut(e,t,r){return Object.assign(Ee("SyntaxError",e),{input:t,offset:r,rawMessage:e,message:e+` `+t+` --`+new Array((r||t.length)+1).join("-")+"^"})}var El=9,Ll=10,Pl=12,Il=13,Dl=32,jt=class{constructor(t){this.str=t,this.pos=0;}charCodeAt(t){return t/[a-zA-Z0-9\-]/.test(String.fromCharCode(t))?1:0),Wi={" ":1,"&&":2,"||":3,"|":4};function Ht(e){return e.substringToPos(e.findWsEnd(e.pos))}function He(e){let t=e.pos;for(;t=128||ut[r]===0)break}return e.pos===t&&e.error("Expect a keyword"),e.substringToPos(t)}function Yt(e){let t=e.pos;for(;t57)break}return e.pos===t&&e.error("Expect a number"),e.substringToPos(t)}function _l(e){let t=e.str.indexOf("'",e.pos+1);return t===-1&&(e.pos=e.str.length,e.error("Expect an apostrophe")),e.substringToPos(t+1)}function Hi(e){let t=null,r=null;return e.eat(Wt),t=Yt(e),e.charCode()===Nr?(e.pos++,e.charCode()!==ji&&(r=Yt(e))):r=t,e.eat(ji),{min:Number(t),max:r?Number(r):0}}function Ul(e){let t=null,r=!1;switch(e.charCode()){case Vi:e.pos++,t={min:0,max:0};break;case Or:e.pos++,t={min:1,max:0};break;case Ir:e.pos++,t={min:0,max:1};break;case Dr:e.pos++,r=!0,e.charCode()===Wt?t=Hi(e):e.charCode()===Ir?(e.pos++,t={min:0,max:0}):t={min:1,max:0};break;case Wt:t=Hi(e);break;default:return null}return {type:"Multiplier",comma:r,min:t.min,max:t.max,term:null}}function Ye(e,t){let r=Ul(e);return r!==null?(r.term=t,e.charCode()===Dr&&e.charCodeAt(e.pos-1)===Or?Ye(e,r):r):t}function Pr(e){let t=e.peek();return t===""?null:{type:"Token",value:t}}function jl(e){let t;return e.eat(zr),e.eat(qt),t=He(e),e.eat(qt),e.eat(Ki),Ye(e,{type:"Property",name:t})}function ql(e){let t=null,r=null,n=1;return e.eat(Gt),e.charCode()===_i&&(e.peek(),n=-1),n==-1&&e.charCode()===qi?e.peek():(t=n*Number(Yt(e)),ut[e.charCode()]!==0&&(t+=He(e))),Ht(e),e.eat(Nr),Ht(e),e.charCode()===qi?e.peek():(n=1,e.charCode()===_i&&(e.peek(),n=-1),r=n*Number(Yt(e)),ut[e.charCode()]!==0&&(r+=He(e))),e.eat(Mr),{type:"Range",min:t,max:r}}function Wl(e){let t,r=null;return e.eat(zr),t=He(e),e.charCode()===Gi&&e.nextCharCode()===Fl&&(e.pos+=2,t+="()"),e.charCodeAt(e.findWsEnd(e.pos))===Gt&&(Ht(e),r=ql(e)),e.eat(Ki),Ye(e,{type:"Type",name:t,opts:r})}function Hl(e){let t=He(e);return e.charCode()===Gi?(e.pos++,{type:"Function",name:t}):Ye(e,{type:"Keyword",name:t})}function Yl(e,t){function r(o,i){return {type:"Group",terms:o,combinator:i,disallowEmpty:!1,explicit:!1}}let n;for(t=Object.keys(t).sort((o,i)=>Wi[o]-Wi[i]);t.length>0;){n=t.shift();let o=0,i=0;for(;o1&&(e.splice(i,o-i,r(e.slice(i,o),n)),o=i+1),i=-1));}i!==-1&&t.length&&e.splice(i,o-i,r(e.slice(i,o),n));}return n}function Qi(e){let t=[],r={},n,o=null,i=e.pos;for(;n=Vl(e);)n.type!=="Spaces"&&(n.type==="Combinator"?((o===null||o.type==="Combinator")&&(e.pos=i,e.error("Unexpected combinator")),r[n.value]=!0):o!==null&&o.type!=="Combinator"&&(r[" "]=!0,t.push({type:"Combinator",value:" "})),t.push(n),o=n,i=e.pos);return o!==null&&o.type==="Combinator"&&(e.pos-=i,e.error("Unexpected combinator")),{type:"Group",terms:t,combinator:Yl(t,r)||" ",disallowEmpty:!1,explicit:!1}}function Gl(e){let t;return e.eat(Gt),t=Qi(e),e.eat(Mr),t.explicit=!0,e.charCode()===Yi&&(e.pos++,t.disallowEmpty=!0),t}function Vl(e){let t=e.charCode();if(t<128&&ut[t]===1)return Hl(e);switch(t){case Mr:break;case Gt:return Ye(e,Gl(e));case zr:return e.nextCharCode()===qt?jl(e):Wl(e);case Ui:return {type:"Combinator",value:e.substringToPos(e.pos+(e.nextCharCode()===Ui?2:1))};case Bi:return e.pos++,e.eat(Bi),{type:"Combinator",value:"&&"};case Nr:return e.pos++,{type:"Comma"};case qt:return Ye(e,{type:"String",value:_l(e)});case Rl:case Ol:case Nl:case Ml:case zl:return {type:"Spaces",value:Ht(e)};case Bl:return t=e.nextCharCode(),t<128&&ut[t]===1?(e.pos++,{type:"AtKeyword",name:He(e)}):Pr(e);case Vi:case Or:case Ir:case Dr:case Yi:break;case Wt:if(t=e.nextCharCode(),t<48||t>57)return Pr(e);break;default:return Pr(e)}}function Ge(e){let t=new jt(e),r=Qi(t);return t.pos!==e.length&&t.error("Unexpected input"),r.terms.length===1&&r.terms[0].type==="Group"?r.terms[0]:r}var pt=function(){};function Xi(e){return typeof e=="function"?e:pt}function Vt(e,t,r){function n(s){switch(o.call(r,s),s.type){case"Group":s.terms.forEach(n);break;case"Multiplier":n(s.term);break;case"Type":case"Property":case"Keyword":case"AtKeyword":case"Function":case"String":case"Token":case"Comma":break;default:throw new Error("Unknown type: "+s.type)}i.call(r,s);}let o=pt,i=pt;if(typeof t=="function"?o=t:t&&(o=Xi(t.enter),i=Xi(t.leave)),o===pt&&i===pt)throw new Error("Neither `enter` nor `leave` walker handler is set or both aren't a function");n(e);}var Kl={decorator(e){let t=[],r=null;return {...e,node(n){let o=r;r=n,e.node.call(this,n),r=o;},emit(n,o,i){t.push({type:o,value:n,node:i?null:r});},result(){return t}}}};function Ql(e){let t=[];return ve(e,(r,n,o)=>t.push({type:r,value:e.slice(n,o),node:null})),t}function Zi(e,t){return typeof e=="string"?Ql(e):t.generate(e,Kl)}var C={type:"Match"},L={type:"Mismatch"},Kt={type:"DisallowEmpty"},Xl=40,$l=41;function Z(e,t,r){return t===C&&r===L||e===C&&t===C&&r===C?e:(e.type==="If"&&e.else===L&&t===C&&(t=e.then,e=e.match),{type:"If",match:e,then:t,else:r})}function ea(e){return e.length>2&&e.charCodeAt(e.length-2)===Xl&&e.charCodeAt(e.length-1)===$l}function Ji(e){return e.type==="Keyword"||e.type==="AtKeyword"||e.type==="Function"||e.type==="Type"&&ea(e.name)}function Rr(e,t,r){switch(e){case" ":{let n=C;for(let o=t.length-1;o>=0;o--){let i=t[o];n=Z(i,n,L);}return n}case"|":{let n=L,o=null;for(let i=t.length-1;i>=0;i--){let s=t[i];if(Ji(s)&&(o===null&&i>0&&Ji(t[i-1])&&(o=Object.create(null),n=Z({type:"Enum",map:o},C,n)),o!==null)){let u=(ea(s.name)?s.name.slice(0,-1):s.name).toLowerCase();if(!(u in o)){o[u]=s;continue}}o=null,n=Z(s,C,n);}return n}case"&&":{if(t.length>5)return {type:"MatchOnce",terms:t,all:!0};let n=L;for(let o=t.length-1;o>=0;o--){let i=t[o],s;t.length>1?s=Rr(e,t.filter(function(u){return u!==i}),!1):s=C,n=Z(i,s,n);}return n}case"||":{if(t.length>5)return {type:"MatchOnce",terms:t,all:!1};let n=r?C:L;for(let o=t.length-1;o>=0;o--){let i=t[o],s;t.length>1?s=Rr(e,t.filter(function(u){return u!==i}),!0):s=C,n=Z(i,s,n);}return n}}}function Zl(e){let t=C,r=Fr(e.term);if(e.max===0)r=Z(r,Kt,L),t=Z(r,null,L),t.then=Z(C,C,t),e.comma&&(t.then.else=Z({type:"Comma",syntax:e},t,L));else for(let n=e.min||1;n<=e.max;n++)e.comma&&t!==C&&(t=Z({type:"Comma",syntax:e},t,L)),t=Z(r,Z(C,C,t),L);if(e.min===0)t=Z(C,C,t);else for(let n=0;n=65&&o<=90&&(o=o|32),o!==n)return !1}return !0}function ic(e){return e.type!==9?!1:e.value!=="?"}function oa(e){return e===null?!0:e.type===18||e.type===2||e.type===21||e.type===19||e.type===23||ic(e)}function ia(e){return e===null?!0:e.type===22||e.type===20||e.type===24||e.type===9&&e.value==="/"}function ac(e,t,r){function n(){do M++,S=Mke&&(ke=M);}function a(){p={syntax:t.syntax,opts:t.syntax.opts||p!==null&&p.opts||null,prev:p},N={type:_r,syntax:t.syntax,token:N.token,prev:N};}function l(){N.type===_r?N=N.prev:N={type:aa,syntax:p.syntax,token:N.token,prev:N},p=p.prev;}let p=null,m=null,f=null,P=null,te=0,Q=null,S=null,M=-1,ke=0,N={type:Jl,syntax:null,token:null,prev:null};for(n();Q===null&&++tef.tokenIndex)&&(f=P,P=!1);else if(f===null){Q=tc;break}t=f.nextState,m=f.thenStack,p=f.syntaxStack,N=f.matchStack,M=f.tokenIndex,S=MM){for(;M":"<'"+t.name+"'>"));if(P!==!1&&S!==null&&t.type==="Type"&&(t.name==="custom-ident"&&S.type===1||t.name==="length"&&S.value==="0")){P===null&&(P=i(t,f)),t=L;break}a(),t=J.match;break}case"Keyword":{let K=t.name;if(S!==null){let J=S.value;if(J.indexOf("\\")!==-1&&(J=J.replace(/\\[09].*$/,"")),Br(J,K)){c(),t=C;break}}t=L;break}case"AtKeyword":case"Function":if(S!==null&&Br(S.value,t.name)){c(),t=C;break}t=L;break;case"Token":if(S!==null&&S.value===t.value){c(),t=C;break}t=L;break;case"Comma":S!==null&&S.type===18?oa(N.token)?t=L:(c(),t=ia(S)?L:C):t=oa(N.token)||ia(S)?C:L;break;case"String":let ae="",fe=M;for(;fesa,isKeyword:()=>cc,isProperty:()=>lc,isType:()=>sc});function sa(e){function t(o){return o===null?!1:o.type==="Type"||o.type==="Property"||o.type==="Keyword"}function r(o){if(Array.isArray(o.match)){for(let i=0;ir.type==="Type"&&r.name===t)}function lc(e,t){return jr(this,e,r=>r.type==="Property"&&r.name===t)}function cc(e){return jr(this,e,t=>t.type==="Keyword")}function jr(e,t,r){let n=sa.call(e,t);return n===null?!1:n.some(r)}function la(e){return "node"in e?e.node:la(e.match[0])}function ca(e){return "node"in e?e.node:ca(e.match[e.match.length-1])}function Wr(e,t,r,n,o){function i(u){if(u.syntax!==null&&u.syntax.type===n&&u.syntax.name===o){let c=la(u),a=ca(u);e.syntax.walk(t,function(l,p,m){if(l===c){let f=new $;do{if(f.appendData(p.data),p.data===a)break;p=p.next;}while(p!==null);s.push({parent:m,nodes:f});}});}Array.isArray(u.match)&&u.match.forEach(i);}let s=[];return r.matched!==null&&i(r.matched),s}var{hasOwnProperty:ht}=Object.prototype;function Hr(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e&&e>=0}function ua(e){return !!e&&Hr(e.offset)&&Hr(e.line)&&Hr(e.column)}function uc(e,t){return function(n,o){if(!n||n.constructor!==Object)return o(n,"Type of node should be an Object");for(let i in n){let s=!0;if(ht.call(n,i)!==!1){if(i==="type")n.type!==e&&o(n,"Wrong node type `"+n.type+"`, expected `"+e+"`");else if(i==="loc"){if(n.loc===null)continue;if(n.loc&&n.loc.constructor===Object)if(typeof n.loc.source!="string")i+=".source";else if(!ua(n.loc.start))i+=".start";else if(!ua(n.loc.end))i+=".end";else continue;s=!1;}else if(t.hasOwnProperty(i)){s=!1;for(let u=0;!s&&u");else if(Array.isArray(a))s.push("List");else throw new Error("Wrong value `"+a+"` in `"+e+"."+i+"` structure definition")}o[i]=s.join(" | ");}return {docs:o,check:uc(e,n)}}function pa(e){let t={};if(e.node){for(let r in e.node)if(ht.call(e.node,r)){let n=e.node[r];if(n.structure)t[r]=pc(r,n);else throw new Error("Missed `structure` field in `"+r+"` node type definition")}}return t}var hc=Qt(Rt.join(" | "));function Yr(e,t,r){let n={};for(let o in e)e[o].syntax&&(n[o]=r?e[o].syntax:Pe(e[o].syntax,{compact:t}));return n}function mc(e,t,r){let n={};for(let[o,i]of Object.entries(e))n[o]={prelude:i.prelude&&(r?i.prelude.syntax:Pe(i.prelude.syntax,{compact:t})),descriptors:i.descriptors&&Yr(i.descriptors,t,r)};return n}function fc(e){for(let t=0;t(n[o]=this.createDescriptor(r.descriptors[o],"AtruleDescriptor",o,t),n),Object.create(null)):null});}addProperty_(t,r){r&&(this.properties[t]=this.createDescriptor(r,"Property",t));}addType_(t,r){r&&(this.types[t]=this.createDescriptor(r,"Type",t));}checkAtruleName(t){if(!this.getAtrule(t))return new je("Unknown at-rule","@"+t)}checkAtrulePrelude(t,r){let n=this.checkAtruleName(t);if(n)return n;let o=this.getAtrule(t);if(!o.prelude&&r)return new SyntaxError("At-rule `@"+t+"` should not contain a prelude");if(o.prelude&&!r&&!Ve(this,o.prelude,"",!1).matched)return new SyntaxError("At-rule `@"+t+"` should contain a prelude")}checkAtruleDescriptorName(t,r){let n=this.checkAtruleName(t);if(n)return n;let o=this.getAtrule(t),i=zt(r);if(!o.descriptors)return new SyntaxError("At-rule `@"+t+"` has no known descriptors");if(!o.descriptors[i.name]&&!o.descriptors[i.basename])return new je("Unknown at-rule descriptor",r)}checkPropertyName(t){if(!this.getProperty(t))return new je("Unknown property",t)}matchAtrulePrelude(t,r){let n=this.checkAtrulePrelude(t,r);if(n)return ce(null,n);let o=this.getAtrule(t);return o.prelude?Ve(this,o.prelude,r||"",!1):ce(null,null)}matchAtruleDescriptor(t,r,n){let o=this.checkAtruleDescriptorName(t,r);if(o)return ce(null,o);let i=this.getAtrule(t),s=zt(r);return Ve(this,i.descriptors[s.name]||i.descriptors[s.basename],n,!1)}matchDeclaration(t){return t.type!=="Declaration"?ce(null,new Error("Not a Declaration node")):this.matchProperty(t.property,t.value)}matchProperty(t,r){if(kr(t).custom)return ce(null,new Error("Lexer matching doesn't applicable for custom properties"));let n=this.checkPropertyName(t);return n?ce(null,n):Ve(this,this.getProperty(t),r,!0)}matchType(t,r){let n=this.getType(t);return n?Ve(this,n,r,!1):ce(null,new je("Unknown type",t))}match(t,r){return typeof t!="string"&&(!t||!t.type)?ce(null,new je("Bad syntax")):((typeof t=="string"||!t.match)&&(t=this.createDescriptor(t,"Type","anonymous")),Ve(this,t,r,!1))}findValueFragments(t,r,n,o){return Wr(this,r,this.matchProperty(t,r),n,o)}findDeclarationValueFragments(t,r,n){return Wr(this,t.value,this.matchDeclaration(t),r,n)}findAllFragments(t,r,n){let o=[];return this.syntax.walk(t,{visit:"Declaration",enter:i=>{o.push.apply(o,this.findDeclarationValueFragments(i,r,n));}}),o}getAtrule(t,r=!0){let n=zt(t);return (n.vendor&&r?this.atrules[n.name]||this.atrules[n.basename]:this.atrules[n.name])||null}getAtrulePrelude(t,r=!0){let n=this.getAtrule(t,r);return n&&n.prelude||null}getAtruleDescriptor(t,r){return this.atrules.hasOwnProperty(t)&&this.atrules.declarators&&this.atrules[t].declarators[r]||null}getProperty(t,r=!0){let n=kr(t);return (n.vendor&&r?this.properties[n.name]||this.properties[n.basename]:this.properties[n.name])||null}getType(t){return hasOwnProperty.call(this.types,t)?this.types[t]:null}validate(){function t(o,i,s,u){if(s.has(i))return s.get(i);s.set(i,!1),u.syntax!==null&&Vt(u.syntax,function(c){if(c.type!=="Type"&&c.type!=="Property")return;let a=c.type==="Type"?o.types:o.properties,l=c.type==="Type"?r:n;(!hasOwnProperty.call(a,c.name)||t(o,c.name,l,a[c.name]))&&s.set(i,!0);},this);}let r=new Map,n=new Map;for(let o in this.types)t(this,o,r,this.types[o]);for(let o in this.properties)t(this,o,n,this.properties[o]);return r=[...r.keys()].filter(o=>r.get(o)),n=[...n.keys()].filter(o=>n.get(o)),r.length||n.length?{types:r,properties:n}:null}dump(t,r){return {generic:this.generic,units:this.units,types:Yr(this.types,!r,t),properties:Yr(this.properties,!r,t),atrules:mc(this.atrules,!r,t)}}toString(){return JSON.stringify(this.dump())}};function Gr(e,t){return typeof t=="string"&&/^\s*\|/.test(t)?typeof e=="string"?e+t:t.replace(/^\s*\|\s*/,""):t||null}function ha(e,t){let r=Object.create(null);for(let[n,o]of Object.entries(e))if(o){r[n]={};for(let i of Object.keys(o))t.includes(i)&&(r[n][i]=o[i]);}return r}function mt(e,t){let r={...e};for(let[n,o]of Object.entries(t))switch(n){case"generic":r[n]=!!o;break;case"units":r[n]={...e[n]};for(let[i,s]of Object.entries(o))r[n][i]=Array.isArray(s)?s:[];break;case"atrules":r[n]={...e[n]};for(let[i,s]of Object.entries(o)){let u=r[n][i]||{},c=r[n][i]={prelude:u.prelude||null,descriptors:{...u.descriptors}};if(s){c.prelude=s.prelude?Gr(c.prelude,s.prelude):c.prelude||null;for(let[a,l]of Object.entries(s.descriptors||{}))c.descriptors[a]=l?Gr(c.descriptors[a],l):null;Object.keys(c.descriptors).length||(c.descriptors=null);}}break;case"types":case"properties":r[n]={...e[n]};for(let[i,s]of Object.entries(o))r[n][i]=Gr(r[n][i],s);break;case"scope":r[n]={...e[n]};for(let[i,s]of Object.entries(o))r[n][i]={...r[n][i],...s};break;case"parseContext":r[n]={...e[n],...o};break;case"atrule":case"pseudo":r[n]={...e[n],...ha(o,["parse"])};break;case"node":r[n]={...e[n],...ha(o,["name","structure","parse","generate","walkContext"])};break}return r}function ma(e){let t=$o(e),r=Li(e),n=vi(e),{fromPlainObject:o,toPlainObject:i}=Si(r),s={lexer:null,createLexer:u=>new Ke(u,s,s.lexer.structure),tokenize:ve,parse:t,generate:n,walk:r,find:r.find,findLast:r.findLast,findAll:r.findAll,fromPlainObject:o,toPlainObject:i,fork(u){let c=mt({},e);return ma(typeof u=="function"?u(c,Object.assign):mt(c,u))}};return s.lexer=new Ke({generic:!0,units:e.units,types:e.types,atrules:e.atrules,properties:e.properties,node:e.node},s),s}var Vr=e=>ma(mt({},e));var fa={generic:!0,units:{angle:["deg","grad","rad","turn"],decibel:["db"],flex:["fr"],frequency:["hz","khz"],length:["cm","mm","q","in","pt","pc","px","em","rem","ex","rex","cap","rcap","ch","rch","ic","ric","lh","rlh","vw","svw","lvw","dvw","vh","svh","lvh","dvh","vi","svi","lvi","dvi","vb","svb","lvb","dvb","vmin","svmin","lvmin","dvmin","vmax","svmax","lvmax","dvmax","cqw","cqh","cqi","cqb","cqmin","cqmax"],resolution:["dpi","dpcm","dppx","x"],semitones:["st"],time:["s","ms"]},types:{"abs()":"abs( )","absolute-size":"xx-small|x-small|small|medium|large|x-large|xx-large|xxx-large","acos()":"acos( )","alpha-value":"|","angle-percentage":"|","angular-color-hint":"","angular-color-stop":"&&?","angular-color-stop-list":"[ [, ]?]# , ","animateable-feature":"scroll-position|contents|","asin()":"asin( )","atan()":"atan( )","atan2()":"atan2( , )",attachment:"scroll|fixed|local","attr()":"attr( ? [, ]? )","attr-matcher":"['~'|'|'|'^'|'$'|'*']? '='","attr-modifier":"i|s","attribute-selector":"'[' ']'|'[' [|] ? ']'","auto-repeat":"repeat( [auto-fill|auto-fit] , [? ]+ ? )","auto-track-list":"[? [|]]* ? [? [|]]* ?",axis:"block|inline|vertical|horizontal","baseline-position":"[first|last]? baseline","basic-shape":"||||","bg-image":"none|","bg-layer":"|| [/ ]?||||||||","bg-position":"[[left|center|right|top|bottom|]|[left|center|right|] [top|center|bottom|]|[center|[left|right] ?]&&[center|[top|bottom] ?]]","bg-size":"[|auto]{1,2}|cover|contain","blur()":"blur( )","blend-mode":"normal|multiply|screen|overlay|darken|lighten|color-dodge|color-burn|hard-light|soft-light|difference|exclusion|hue|saturation|color|luminosity",box:"border-box|padding-box|content-box","brightness()":"brightness( )","calc()":"calc( )","calc-sum":" [['+'|'-'] ]*","calc-product":" ['*' |'/' ]*","calc-value":"||||( )","calc-constant":"e|pi|infinity|-infinity|NaN","cf-final-image":"|","cf-mixing-image":"?&&","circle()":"circle( []? [at ]? )","clamp()":"clamp( #{3} )","class-selector":"'.' ","clip-source":"",color:"|||||||||currentcolor|","color-stop":"|","color-stop-angle":"{1,2}","color-stop-length":"{1,2}","color-stop-list":"[ [, ]?]# , ",combinator:"'>'|'+'|'~'|['||']","common-lig-values":"[common-ligatures|no-common-ligatures]","compat-auto":"searchfield|textarea|push-button|slider-horizontal|checkbox|radio|square-button|menulist|listbox|meter|progress-bar|button","composite-style":"clear|copy|source-over|source-in|source-out|source-atop|destination-over|destination-in|destination-out|destination-atop|xor","compositing-operator":"add|subtract|intersect|exclude","compound-selector":"[? * [ *]*]!","compound-selector-list":"#","complex-selector":" [? ]*","complex-selector-list":"#","conic-gradient()":"conic-gradient( [from ]? [at ]? , )","contextual-alt-values":"[contextual|no-contextual]","content-distribution":"space-between|space-around|space-evenly|stretch","content-list":"[|contents||||||]+","content-position":"center|start|end|flex-start|flex-end","content-replacement":"","contrast()":"contrast( [] )","cos()":"cos( )",counter:"|","counter()":"counter( , ? )","counter-name":"","counter-style":"|symbols( )","counter-style-name":"","counters()":"counters( , , ? )","cross-fade()":"cross-fade( , ? )","cubic-bezier-timing-function":"ease|ease-in|ease-out|ease-in-out|cubic-bezier( , , , )","deprecated-system-color":"ActiveBorder|ActiveCaption|AppWorkspace|Background|ButtonFace|ButtonHighlight|ButtonShadow|ButtonText|CaptionText|GrayText|Highlight|HighlightText|InactiveBorder|InactiveCaption|InactiveCaptionText|InfoBackground|InfoText|Menu|MenuText|Scrollbar|ThreeDDarkShadow|ThreeDFace|ThreeDHighlight|ThreeDLightShadow|ThreeDShadow|Window|WindowFrame|WindowText","discretionary-lig-values":"[discretionary-ligatures|no-discretionary-ligatures]","display-box":"contents|none","display-inside":"flow|flow-root|table|flex|grid|ruby","display-internal":"table-row-group|table-header-group|table-footer-group|table-row|table-cell|table-column-group|table-column|table-caption|ruby-base|ruby-text|ruby-base-container|ruby-text-container","display-legacy":"inline-block|inline-list-item|inline-table|inline-flex|inline-grid","display-listitem":"?&&[flow|flow-root]?&&list-item","display-outside":"block|inline|run-in","drop-shadow()":"drop-shadow( {2,3} ? )","east-asian-variant-values":"[jis78|jis83|jis90|jis04|simplified|traditional]","east-asian-width-values":"[full-width|proportional-width]","element()":"element( , [first|start|last|first-except]? )|element( )","ellipse()":"ellipse( [{2}]? [at ]? )","ending-shape":"circle|ellipse","env()":"env( , ? )","exp()":"exp( )","explicit-track-list":"[? ]+ ?","family-name":"|+","feature-tag-value":" [|on|off]?","feature-type":"@stylistic|@historical-forms|@styleset|@character-variant|@swash|@ornaments|@annotation","feature-value-block":" '{' '}'","feature-value-block-list":"+","feature-value-declaration":" : + ;","feature-value-declaration-list":"","feature-value-name":"","fill-rule":"nonzero|evenodd","filter-function":"|||||||||","filter-function-list":"[|]+","final-bg-layer":"<'background-color'>|||| [/ ]?||||||||","fixed-breadth":"","fixed-repeat":"repeat( [] , [? ]+ ? )","fixed-size":"|minmax( , )|minmax( , )","font-stretch-absolute":"normal|ultra-condensed|extra-condensed|condensed|semi-condensed|semi-expanded|expanded|extra-expanded|ultra-expanded|","font-variant-css21":"[normal|small-caps]","font-weight-absolute":"normal|bold|","frequency-percentage":"|","general-enclosed":"[ )]|( )","generic-family":"serif|sans-serif|cursive|fantasy|monospace|-apple-system","generic-name":"serif|sans-serif|cursive|fantasy|monospace","geometry-box":"|fill-box|stroke-box|view-box",gradient:"||||||<-legacy-gradient>","grayscale()":"grayscale( )","grid-line":"auto||[&&?]|[span&&[||]]","historical-lig-values":"[historical-ligatures|no-historical-ligatures]","hsl()":"hsl( [/ ]? )|hsl( , , , ? )","hsla()":"hsla( [/ ]? )|hsla( , , , ? )",hue:"|","hue-rotate()":"hue-rotate( )","hwb()":"hwb( [|none] [|none] [|none] [/ [|none]]? )","hypot()":"hypot( # )",image:"||||||","image()":"image( ? [? , ?]! )","image-set()":"image-set( # )","image-set-option":"[|] [||type( )]","image-src":"|","image-tags":"ltr|rtl","inflexible-breadth":"|min-content|max-content|auto","inset()":"inset( {1,4} [round <'border-radius'>]? )","invert()":"invert( )","keyframes-name":"|","keyframe-block":"# { }","keyframe-block-list":"+","keyframe-selector":"from|to|","lab()":"lab( [||none] [||none] [||none] [/ [|none]]? )","layer()":"layer( )","layer-name":" ['.' ]*","lch()":"lch( [||none] [||none] [|none] [/ [|none]]? )","leader()":"leader( )","leader-type":"dotted|solid|space|","length-percentage":"|","line-names":"'[' * ']'","line-name-list":"[|]+","line-style":"none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset","line-width":"|thin|medium|thick","linear-color-hint":"","linear-color-stop":" ?","linear-gradient()":"linear-gradient( [|to ]? , )","log()":"log( , ? )","mask-layer":"|| [/ ]?||||||[|no-clip]||||","mask-position":"[|left|center|right] [|top|center|bottom]?","mask-reference":"none||","mask-source":"","masking-mode":"alpha|luminance|match-source","matrix()":"matrix( #{6} )","matrix3d()":"matrix3d( #{16} )","max()":"max( # )","media-and":" [and ]+","media-condition":"|||","media-condition-without-or":"||","media-feature":"( [||] )","media-in-parens":"( )||","media-not":"not ","media-or":" [or ]+","media-query":"|[not|only]? [and ]?","media-query-list":"#","media-type":"","mf-boolean":"","mf-name":"","mf-plain":" : ","mf-range":" ['<'|'>']? '='? | ['<'|'>']? '='? | '<' '='? '<' '='? | '>' '='? '>' '='? ","mf-value":"|||","min()":"min( # )","minmax()":"minmax( [|min-content|max-content|auto] , [||min-content|max-content|auto] )","mod()":"mod( , )","name-repeat":"repeat( [|auto-fill] , + )","named-color":"transparent|aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkgrey|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkslategrey|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dimgrey|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|grey|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgray|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightslategrey|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|rebeccapurple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|slategrey|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|violet|wheat|white|whitesmoke|yellow|yellowgreen|<-non-standard-color>","namespace-prefix":"","ns-prefix":"[|'*']? '|'","number-percentage":"|","numeric-figure-values":"[lining-nums|oldstyle-nums]","numeric-fraction-values":"[diagonal-fractions|stacked-fractions]","numeric-spacing-values":"[proportional-nums|tabular-nums]",nth:"|even|odd","opacity()":"opacity( [] )","overflow-position":"unsafe|safe","outline-radius":"|","page-body":"? [; ]?| ","page-margin-box":" '{' '}'","page-margin-box-type":"@top-left-corner|@top-left|@top-center|@top-right|@top-right-corner|@bottom-left-corner|@bottom-left|@bottom-center|@bottom-right|@bottom-right-corner|@left-top|@left-middle|@left-bottom|@right-top|@right-middle|@right-bottom","page-selector-list":"[#]?","page-selector":"+| *","page-size":"A5|A4|A3|B5|B4|JIS-B5|JIS-B4|letter|legal|ledger","path()":"path( [ ,]? )","paint()":"paint( , ? )","perspective()":"perspective( [|none] )","polygon()":"polygon( ? , [ ]# )",position:"[[left|center|right]||[top|center|bottom]|[left|center|right|] [top|center|bottom|]?|[[left|right] ]&&[[top|bottom] ]]","pow()":"pow( , )","pseudo-class-selector":"':' |':' ')'","pseudo-element-selector":"':' ","pseudo-page":": [left|right|first|blank]",quote:"open-quote|close-quote|no-open-quote|no-close-quote","radial-gradient()":"radial-gradient( [||]? [at ]? , )",ratio:" [/ ]?","relative-selector":"? ","relative-selector-list":"#","relative-size":"larger|smaller","rem()":"rem( , )","repeat-style":"repeat-x|repeat-y|[repeat|space|round|no-repeat]{1,2}","repeating-conic-gradient()":"repeating-conic-gradient( [from ]? [at ]? , )","repeating-linear-gradient()":"repeating-linear-gradient( [|to ]? , )","repeating-radial-gradient()":"repeating-radial-gradient( [||]? [at ]? , )","reversed-counter-name":"reversed( )","rgb()":"rgb( {3} [/ ]? )|rgb( {3} [/ ]? )|rgb( #{3} , ? )|rgb( #{3} , ? )","rgba()":"rgba( {3} [/ ]? )|rgba( {3} [/ ]? )|rgba( #{3} , ? )|rgba( #{3} , ? )","rotate()":"rotate( [|] )","rotate3d()":"rotate3d( , , , [|] )","rotateX()":"rotateX( [|] )","rotateY()":"rotateY( [|] )","rotateZ()":"rotateZ( [|] )","round()":"round( ? , , )","rounding-strategy":"nearest|up|down|to-zero","saturate()":"saturate( )","scale()":"scale( [|]#{1,2} )","scale3d()":"scale3d( [|]#{3} )","scaleX()":"scaleX( [|] )","scaleY()":"scaleY( [|] )","scaleZ()":"scaleZ( [|] )",scroller:"root|nearest","self-position":"center|start|end|self-start|self-end|flex-start|flex-end","shape-radius":"|closest-side|farthest-side","sign()":"sign( )","skew()":"skew( [|] , [|]? )","skewX()":"skewX( [|] )","skewY()":"skewY( [|] )","sepia()":"sepia( )",shadow:"inset?&&{2,4}&&?","shadow-t":"[{2,3}&&?]",shape:"rect( , , , )|rect( )","shape-box":"|margin-box","side-or-corner":"[left|right]||[top|bottom]","sin()":"sin( )","single-animation":"