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 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 react$1 = {exports: {}}; var react_production_min = {}; var l$d=Symbol.for("react.element"),n$c=Symbol.for("react.portal"),p$e=Symbol.for("react.fragment"),q$a=Symbol.for("react.strict_mode"),r$b=Symbol.for("react.profiler"),t$e=Symbol.for("react.provider"),u$e=Symbol.for("react.context"),v$a=Symbol.for("react.forward_ref"),w$9=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$7={isMounted:function(){return !1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C$5=Object.assign,D$a={};function E$8(a,b,e){this.props=a;this.context=b;this.refs=D$a;this.updater=e||B$7;}E$8.prototype.isReactComponent={}; E$8.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$8.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate");};function F$b(){}F$b.prototype=E$8.prototype;function G$6(a,b,e){this.props=a;this.context=b;this.refs=D$a;this.updater=e||B$7;}var H$b=G$6.prototype=new F$b; H$b.constructor=G$6;C$5(H$b,E$8.prototype);H$b.isPureReactComponent=!0;var I$9=Array.isArray,J$5=Object.prototype.hasOwnProperty,K$4={current:null},L$7={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$7.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1>>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$d(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;cb}return !1}function q$9(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$7={}; "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){z$7[a]=new q$9(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$7[b]=new q$9(b,1,!1,a[1],null,!1,!1);});["contentEditable","draggable","spellCheck","value"].forEach(function(a){z$7[a]=new q$9(a,2,!1,a.toLowerCase(),null,!1,!1);}); ["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){z$7[a]=new q$9(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$7[a]=new q$9(a,3,!1,a.toLowerCase(),null,!1,!1);}); ["checked","multiple","muted","selected"].forEach(function(a){z$7[a]=new q$9(a,3,!0,a,null,!1,!1);});["capture","download"].forEach(function(a){z$7[a]=new q$9(a,4,!1,a,null,!1,!1);});["cols","rows","size","span"].forEach(function(a){z$7[a]=new q$9(a,6,!1,a,null,!1,!1);});["rowSpan","start"].forEach(function(a){z$7[a]=new q$9(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$7[b]=new q$9(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$7[b]=new q$9(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$7[b]=new q$9(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1);});["tabIndex","crossOrigin"].forEach(function(a){z$7[a]=new q$9(a,1,!1,a.toLowerCase(),null,!1,!1);}); z$7.xlinkHref=new q$9("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){z$7[a]=new q$9(a,1,!1,a.toLowerCase(),null,!0,!0);}); function ra$3(a,b,c,d){var e=z$7.hasOwnProperty(b)?z$7[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$8({},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$8({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$d(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p$d(60));if("object"!==typeof b.dangerouslySetInnerHTML||!("__html"in b.dangerouslySetInnerHTML))throw Error(p$d(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(p$d(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$d(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$3(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$3=!1;function ee$3(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$2(a,b){if(de$3)return "compositionend"===a||!Wd&&be$3(a,b)?(a=id$1(),hd=gd=fd=null,de$3=!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$4(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$5(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$5(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$5(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$a(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$5(Qf);G$5(I$8);}function Vf(a,b,c){if(I$8.current!==Pf)throw Error(p$d(168));H$a(I$8,b);H$a(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$d(108,Pa$3(a)||"Unknown",e));return A$8({},c,d)} function Xf(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Pf;Rf=I$8.current;H$a(I$8,a);H$a(Qf,Qf.current);return !0}function Yf(a,b,c){var d=a.stateNode;if(!d)throw Error(p$d(169));c?(a=Wf(a,b,Rf),d.__reactInternalMemoizedMergedChildContext=a,G$5(Qf),G$5(I$8),H$a(I$8,a)):G$5(Qf);H$a(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$7;try{var c=Zf;for(E$7=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$5&&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$5&&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$5&&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$5&&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$d(174));return a}function yh$1(a,b){H$a(wh$1,b);H$a(vh$1,a);H$a(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$5(uh$1);H$a(uh$1,b);}function zh$1(){G$5(uh$1);G$5(vh$1);G$5(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$a(vh$1,a),H$a(uh$1,c));}function Bh$1(a){vh$1.current===a&&(G$5(uh$1),G$5(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$7=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$3&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$5){if(void 0===c)throw Error(p$d(407));c=c();}else {c=b();if(null===J$4)throw Error(p$d(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$5){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$a("cancel",a);F$a("close",a);e=d;break;case "iframe":case "object":case "embed":F$a("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$5)return V$5(b),null}else 2*D$9()-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$9(),b.sibling=null,c=P$6.current,H$a(P$6,d?c&1|2:c&1),b;V$5(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$5(b),b.subtreeFlags&6&&(b.flags|=8192)):V$5(b),null;case 24:return null;case 25:return null}throw Error(p$d(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$5&&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$a(ej,Vi$1),Vi$1|=c;else if(0!==(c&1073741824))b.memoizedState={baseLanes:0,cachePool:null},d=null!==f?f.baseLanes:c,H$a(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$a(ej,Vi$1),Vi$1|=a,null;else null!==f?(d=f.baseLanes|c,b.memoizedState=null): d=c,H$a(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$5&&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$a(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$d(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$d(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$d(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$5=!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$a(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$d(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$a(gg,d._currentValue);d._currentValue=e;break;case 13:d=b.memoizedState;if(null!==d){if(null!==d.dehydrated)return H$a(P$6,P$6.current&1),b.flags|=128,null;if(0!==(c&b.child.childLanes))return mj(a,b,c);H$a(P$6,P$6.current&1);a=Zi$1(a,b,c);return null!==a?a.sibling:null}H$a(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$a(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$5(Qf),G$5(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$5(P$6);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p$d(340));gh$1();}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return G$5(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$5(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$d(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$d(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$d(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$d(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$9()-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$3&6))throw Error(p$d(331));var e=K$3;K$3|=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$9()-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$d(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$5&&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$5&&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$d(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$d(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$d(423));b=jj(a,b,d,c,e);break a}else if(d!==e){e=Error(p$d(424));b=jj(a,b,d,c,e);break a}else for(Yg=Ff(b.stateNode.containerInfo.firstChild),Xg=b,N$5=!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$a(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$d(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$d(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$d(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 { 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$4() { 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$3(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$3(a) && isPlainObject$3(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$3(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$4); } 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$4)), Promise.resolve())); } } // CLASS 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$4).catch(noop$4) : 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$4).catch(noop$4); } 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$4); if (!(options != null && options.throwOnError)) { promise = promise.catch(noop$4); } 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$4).catch(noop$4); } 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$4).catch(noop$4); } 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$9(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k$7="function"===typeof Object.is?Object.is:h$9,l$c=e$8.useState,m$6=e$8.useEffect,n$b=e$8.useLayoutEffect,p$c=e$8.useDebugValue;function q$8(a,b){var d=b(),f=l$c({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n$b(function(){c.value=d;c.getSnapshot=b;r$a(c)&&g({inst:c});},[a,d,b]);m$6(function(){r$a(c)&&g({inst:c});return a(function(){r$a(c)&&g({inst:c});})},[a]);p$c(d);return d} function r$a(a){var b=a.getSnapshot;a=a.value;try{var d=b();return !k$7(a,d)}catch(f){return !0}}function t$d(a,b){return b()}var u$d="undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement?t$d:q$8;useSyncExternalStoreShim_production_min.useSyncExternalStore=void 0!==e$8.useSyncExternalStore?e$8.useSyncExternalStore:u$d; { 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(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$3); }, [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$3() {} // - `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 ArrowLeftOnRectangleIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15M12 9l-3 3m0 0l3 3m-3-3h12.75" })); } reactExports.forwardRef(ArrowLeftOnRectangleIcon); function LifebuoyIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M16.712 4.33a9.027 9.027 0 011.652 1.306c.51.51.944 1.064 1.306 1.652M16.712 4.33l-3.448 4.138m3.448-4.138a9.014 9.014 0 00-9.424 0M19.67 7.288l-4.138 3.448m4.138-3.448a9.014 9.014 0 010 9.424m-4.138-5.976a3.736 3.736 0 00-.88-1.388 3.737 3.737 0 00-1.388-.88m2.268 2.268a3.765 3.765 0 010 2.528m-2.268-4.796a3.765 3.765 0 00-2.528 0m4.796 4.796c-.181.506-.475.982-.88 1.388a3.736 3.736 0 01-1.388.88m2.268-2.268l4.138 3.448m0 0a9.027 9.027 0 01-1.306 1.652c-.51.51-1.064.944-1.652 1.306m0 0l-3.448-4.138m3.448 4.138a9.014 9.014 0 01-9.424 0m5.976-4.138a3.765 3.765 0 01-2.528 0m0 0a3.736 3.736 0 01-1.388-.88 3.737 3.737 0 01-.88-1.388m2.268 2.268L7.288 19.67m0 0a9.024 9.024 0 01-1.652-1.306 9.027 9.027 0 01-1.306-1.652m0 0l4.138-3.448M4.33 16.712a9.014 9.014 0 010-9.424m4.138 5.976a3.765 3.765 0 010-2.528m0 0c.181-.506.475-.982.88-1.388a3.736 3.736 0 011.388-.88m-2.268 2.268L4.33 7.288m6.406 1.18L7.288 4.33m0 0a9.024 9.024 0 00-1.652 1.306A9.025 9.025 0 004.33 7.288" })); } reactExports.forwardRef(LifebuoyIcon$1); function ArrowPathIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99" })); } const ForwardRef$I = reactExports.forwardRef(ArrowPathIcon$1); function LightBulbIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 18v-5.25m0 0a6.01 6.01 0 001.5-.189m-1.5.189a6.01 6.01 0 01-1.5-.189m3.75 7.478a12.06 12.06 0 01-4.5 0m3.75 2.383a14.406 14.406 0 01-3 0M14.25 18v-.192c0-.983.658-1.823 1.508-2.316a7.5 7.5 0 10-7.517 0c.85.493 1.509 1.333 1.509 2.316V18" })); } const ForwardRef$H = reactExports.forwardRef(LightBulbIcon); function ArrowRightOnRectangleIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15m3 0l3-3m0 0l-3-3m3 3H9" })); } const ForwardRef$G = reactExports.forwardRef(ArrowRightOnRectangleIcon); function LockClosedIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z" })); } const ForwardRef$F = reactExports.forwardRef(LockClosedIcon$1); function ArrowUpTrayIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" })); } const ForwardRef$E = reactExports.forwardRef(ArrowUpTrayIcon$1); function LockOpenIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M13.5 10.5V6.75a4.5 4.5 0 119 0v3.75M3.75 21.75h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H3.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z" })); } const ForwardRef$D = reactExports.forwardRef(LockOpenIcon); function BellIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0" })); } reactExports.forwardRef(BellIcon$1); function MagnifyingGlassIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" })); } const ForwardRef$C = reactExports.forwardRef(MagnifyingGlassIcon$1); function ChatBubbleOvalLeftEllipsisIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M8.625 12a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H8.25m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H12m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0h-.375M21 12c0 4.556-4.03 8.25-9 8.25a9.764 9.764 0 01-2.555-.337A5.972 5.972 0 015.41 20.97a5.969 5.969 0 01-.474-.065 4.48 4.48 0 00.978-2.025c.09-.457-.133-.901-.467-1.226C3.93 16.178 3 14.189 3 12c0-4.556 4.03-8.25 9-8.25s9 3.694 9 8.25z" })); } const ForwardRef$B = reactExports.forwardRef(ChatBubbleOvalLeftEllipsisIcon$1); function NewspaperIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 7.5h1.5m-1.5 3h1.5m-7.5 3h7.5m-7.5 3h7.5m3-9h3.375c.621 0 1.125.504 1.125 1.125V18a2.25 2.25 0 01-2.25 2.25M16.5 7.5V18a2.25 2.25 0 002.25 2.25M16.5 7.5V4.875c0-.621-.504-1.125-1.125-1.125H4.125C3.504 3.75 3 4.254 3 4.875V18a2.25 2.25 0 002.25 2.25h13.5M6 7.5h3v3H6v-3z" })); } reactExports.forwardRef(NewspaperIcon$1); function CheckCircleIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" })); } const ForwardRef$A = reactExports.forwardRef(CheckCircleIcon$1); function NoSymbolIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" })); } const ForwardRef$z = reactExports.forwardRef(NoSymbolIcon); function CheckIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M4.5 12.75l6 6 9-13.5" })); } reactExports.forwardRef(CheckIcon$1); function PaintBrushIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M9.53 16.122a3 3 0 00-5.78 1.128 2.25 2.25 0 01-2.4 2.245 4.5 4.5 0 008.4-2.245c0-.399-.078-.78-.22-1.128zm0 0a15.998 15.998 0 003.388-1.62m-5.043-.025a15.994 15.994 0 011.622-3.395m3.42 3.42a15.995 15.995 0 004.764-4.648l3.876-5.814a1.151 1.151 0 00-1.597-1.597L14.146 6.32a15.996 15.996 0 00-4.649 4.763m3.42 3.42a6.776 6.776 0 00-3.42-3.42" })); } reactExports.forwardRef(PaintBrushIcon$1); function ChevronDoubleLeftIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M18.75 19.5l-7.5-7.5 7.5-7.5m-6 15L5.25 12l7.5-7.5" })); } reactExports.forwardRef(ChevronDoubleLeftIcon); function PaperClipIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M18.375 12.739l-7.693 7.693a4.5 4.5 0 01-6.364-6.364l10.94-10.94A3 3 0 1119.5 7.372L8.552 18.32m.009-.01l-.01.01m5.699-9.941l-7.81 7.81a1.5 1.5 0 002.112 2.13" })); } reactExports.forwardRef(PaperClipIcon); function ChevronDownIcon$2({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M19.5 8.25l-7.5 7.5-7.5-7.5" })); } reactExports.forwardRef(ChevronDownIcon$2); function PauseCircleIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M14.25 9v6m-4.5 0V9M21 12a9 9 0 11-18 0 9 9 0 0118 0z" })); } const ForwardRef$y = reactExports.forwardRef(PauseCircleIcon); function ChevronLeftIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M15.75 19.5L8.25 12l7.5-7.5" })); } reactExports.forwardRef(ChevronLeftIcon$1); function PencilIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L6.832 19.82a4.5 4.5 0 01-1.897 1.13l-2.685.8.8-2.685a4.5 4.5 0 011.13-1.897L16.863 4.487zm0 0L19.5 7.125" })); } reactExports.forwardRef(PencilIcon); function ChevronRightIcon$2({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M8.25 4.5l7.5 7.5-7.5 7.5" })); } const ForwardRef$x = reactExports.forwardRef(ChevronRightIcon$2); function PencilSquareIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10" })); } const ForwardRef$w = reactExports.forwardRef(PencilSquareIcon); function CloudArrowDownIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 9.75v6.75m0 0l-3-3m3 3l3-3m-8.25 6a4.5 4.5 0 01-1.41-8.775 5.25 5.25 0 0110.233-2.33 3 3 0 013.758 3.848A3.752 3.752 0 0118 19.5H6.75z" })); } const ForwardRef$v = reactExports.forwardRef(CloudArrowDownIcon); function PlayCircleIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M21 12a9 9 0 11-18 0 9 9 0 0118 0z" }), /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M15.91 11.672a.375.375 0 010 .656l-5.603 3.113a.375.375 0 01-.557-.328V8.887c0-.286.307-.466.557-.327l5.603 3.112z" })); } const ForwardRef$u = reactExports.forwardRef(PlayCircleIcon); function CogIcon$2({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M4.5 12a7.5 7.5 0 0015 0m-15 0a7.5 7.5 0 1115 0m-15 0H3m16.5 0H21m-1.5 0H12m-8.457 3.077l1.41-.513m14.095-5.13l1.41-.513M5.106 17.785l1.15-.964m11.49-9.642l1.149-.964M7.501 19.795l.75-1.3m7.5-12.99l.75-1.3m-6.063 16.658l.26-1.477m2.605-14.772l.26-1.477m0 17.726l-.26-1.477M10.698 4.614l-.26-1.477M16.5 19.794l-.75-1.299M7.5 4.205L12 12m6.894 5.785l-1.149-.964M6.256 7.178l-1.15-.964m15.352 8.864l-1.41-.513M4.954 9.435l-1.41-.514M12.002 12l-3.75 6.495" })); } const ForwardRef$t = reactExports.forwardRef(CogIcon$2); function PlusIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 4.5v15m7.5-7.5h-15" })); } reactExports.forwardRef(PlusIcon); function DocumentPlusIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m3.75 9v6m3-3H9m1.5-12H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" })); } reactExports.forwardRef(DocumentPlusIcon); function QuestionMarkCircleIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9 5.25h.008v.008H12v-.008z" })); } reactExports.forwardRef(QuestionMarkCircleIcon$1); function DocumentTextIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" })); } reactExports.forwardRef(DocumentTextIcon$1); function ShareIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M7.217 10.907a2.25 2.25 0 100 2.186m0-2.186c.18.324.283.696.283 1.093s-.103.77-.283 1.093m0-2.186l9.566-5.314m-9.566 7.5l9.566 5.314m0 0a2.25 2.25 0 103.935 2.186 2.25 2.25 0 00-3.935-2.186zm0-12.814a2.25 2.25 0 103.933-2.185 2.25 2.25 0 00-3.933 2.185z" })); } const ForwardRef$s = reactExports.forwardRef(ShareIcon); function EllipsisHorizontalIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M6.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM12.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM18.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0z" })); } const ForwardRef$r = reactExports.forwardRef(EllipsisHorizontalIcon$1); function ShieldExclamationIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 9v3.75m0-10.036A11.959 11.959 0 013.598 6 11.99 11.99 0 003 9.75c0 5.592 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.31-.21-2.57-.598-3.75h-.152c-3.196 0-6.1-1.249-8.25-3.286zm0 13.036h.008v.008H12v-.008z" })); } const ForwardRef$q = reactExports.forwardRef(ShieldExclamationIcon); function ExclamationCircleIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z" })); } const ForwardRef$p = reactExports.forwardRef(ExclamationCircleIcon$1); function SpeakerWaveIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M19.114 5.636a9 9 0 010 12.728M16.463 8.288a5.25 5.25 0 010 7.424M6.75 8.25l4.72-4.72a.75.75 0 011.28.53v15.88a.75.75 0 01-1.28.53l-4.72-4.72H4.51c-.88 0-1.704-.507-1.938-1.354A9.01 9.01 0 012.25 12c0-.83.112-1.633.322-2.396C2.806 8.756 3.63 8.25 4.51 8.25H6.75z" })); } reactExports.forwardRef(SpeakerWaveIcon); function ExclamationTriangleIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" })); } const ForwardRef$o = reactExports.forwardRef(ExclamationTriangleIcon$1); function TagIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M9.568 3H5.25A2.25 2.25 0 003 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581c.699.699 1.78.872 2.607.33a18.095 18.095 0 005.223-5.223c.542-.827.369-1.908-.33-2.607L11.16 3.66A2.25 2.25 0 009.568 3z" }), /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M6 6h.008v.008H6V6z" })); } reactExports.forwardRef(TagIcon); function EyeIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z" }), /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M15 12a3 3 0 11-6 0 3 3 0 016 0z" })); } const ForwardRef$n = reactExports.forwardRef(EyeIcon); function TrashIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" })); } const ForwardRef$m = reactExports.forwardRef(TrashIcon); function EyeSlashIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M3.98 8.223A10.477 10.477 0 001.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.45 10.45 0 0112 4.5c4.756 0 8.773 3.162 10.065 7.498a10.523 10.523 0 01-4.293 5.774M6.228 6.228L3 3m3.228 3.228l3.65 3.65m7.894 7.894L21 21m-3.228-3.228l-3.65-3.65m0 0a3 3 0 10-4.243-4.243m4.242 4.242L9.88 9.88" })); } const ForwardRef$l = reactExports.forwardRef(EyeSlashIcon); function UserCircleIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M17.982 18.725A7.488 7.488 0 0012 15.75a7.488 7.488 0 00-5.982 2.975m11.963 0a9 9 0 10-11.963 0m11.963 0A8.966 8.966 0 0112 21a8.966 8.966 0 01-5.982-2.275M15 9.75a3 3 0 11-6 0 3 3 0 016 0z" })); } reactExports.forwardRef(UserCircleIcon$1); function FaceSmileIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M15.182 15.182a4.5 4.5 0 01-6.364 0M21 12a9 9 0 11-18 0 9 9 0 0118 0zM9.75 9.75c0 .414-.168.75-.375.75S9 10.164 9 9.75 9.168 9 9.375 9s.375.336.375.75zm-.375 0h.008v.015h-.008V9.75zm5.625 0c0 .414-.168.75-.375.75s-.375-.336-.375-.75.168-.75.375-.75.375.336.375.75zm-.375 0h.008v.015h-.008V9.75z" })); } const ForwardRef$k = reactExports.forwardRef(FaceSmileIcon); function UserGroupIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" })); } reactExports.forwardRef(UserGroupIcon$1); function HashtagIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M5.25 8.25h15m-16.5 7.5h15m-1.8-13.5l-3.9 19.5m-2.1-19.5l-3.9 19.5" })); } reactExports.forwardRef(HashtagIcon$1); function UserPlusIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M19 7.5v3m0 0v3m0-3h3m-3 0h-3m-2.25-4.125a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zM4 19.235v-.11a6.375 6.375 0 0112.75 0v.109A12.318 12.318 0 0110.374 21c-2.331 0-4.512-.645-6.374-1.766z" })); } reactExports.forwardRef(UserPlusIcon$1); function HeartIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12z" })); } const ForwardRef$j = reactExports.forwardRef(HeartIcon$1); function UsersIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z" })); } reactExports.forwardRef(UsersIcon$1); function InboxIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M2.25 13.5h3.86a2.25 2.25 0 012.012 1.244l.256.512a2.25 2.25 0 002.013 1.244h3.218a2.25 2.25 0 002.013-1.244l.256-.512a2.25 2.25 0 012.013-1.244h3.859m-19.5.338V18a2.25 2.25 0 002.25 2.25h15A2.25 2.25 0 0021.75 18v-4.162c0-.224-.034-.447-.1-.661L19.24 5.338a2.25 2.25 0 00-2.15-1.588H6.911a2.25 2.25 0 00-2.15 1.588L2.35 13.177a2.25 2.25 0 00-.1.661z" })); } reactExports.forwardRef(InboxIcon$1); function XMarkIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M6 18L18 6M6 6l12 12" })); } const ForwardRef$i = reactExports.forwardRef(XMarkIcon$1); function InformationCircleIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M11.25 11.25l.041-.02a.75.75 0 011.063.852l-.708 2.836a.75.75 0 001.063.853l.041-.021M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9-3.75h.008v.008H12V8.25z" })); } const ForwardRef$h = reactExports.forwardRef(InformationCircleIcon); function ArrowDownIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M12 2.25a.75.75 0 01.75.75v16.19l6.22-6.22a.75.75 0 111.06 1.06l-7.5 7.5a.75.75 0 01-1.06 0l-7.5-7.5a.75.75 0 111.06-1.06l6.22 6.22V3a.75.75 0 01.75-.75z", clipRule: "evenodd" })); } const ForwardRef$g = reactExports.forwardRef(ArrowDownIcon); function ArrowPathIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M4.755 10.059a7.5 7.5 0 0112.548-3.364l1.903 1.903h-3.183a.75.75 0 100 1.5h4.992a.75.75 0 00.75-.75V4.356a.75.75 0 00-1.5 0v3.18l-1.9-1.9A9 9 0 003.306 9.67a.75.75 0 101.45.388zm15.408 3.352a.75.75 0 00-.919.53 7.5 7.5 0 01-12.548 3.364l-1.902-1.903h3.183a.75.75 0 000-1.5H2.984a.75.75 0 00-.75.75v4.992a.75.75 0 001.5 0v-3.18l1.9 1.9a9 9 0 0015.059-4.035.75.75 0 00-.53-.918z", clipRule: "evenodd" })); } const ForwardRef$f = reactExports.forwardRef(ArrowPathIcon); function ArrowUpIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M11.47 2.47a.75.75 0 011.06 0l7.5 7.5a.75.75 0 11-1.06 1.06l-6.22-6.22V21a.75.75 0 01-1.5 0V4.81l-6.22 6.22a.75.75 0 11-1.06-1.06l7.5-7.5z", clipRule: "evenodd" })); } const ForwardRef$e = reactExports.forwardRef(ArrowUpIcon); function ArrowUturnLeftIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M9.53 2.47a.75.75 0 010 1.06L4.81 8.25H15a6.75 6.75 0 010 13.5h-3a.75.75 0 010-1.5h3a5.25 5.25 0 100-10.5H4.81l4.72 4.72a.75.75 0 11-1.06 1.06l-6-6a.75.75 0 010-1.06l6-6a.75.75 0 011.06 0z", clipRule: "evenodd" })); } const ForwardRef$d = reactExports.forwardRef(ArrowUturnLeftIcon); function Bars3Icon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M3 6.75A.75.75 0 013.75 6h16.5a.75.75 0 010 1.5H3.75A.75.75 0 013 6.75zM3 12a.75.75 0 01.75-.75h16.5a.75.75 0 010 1.5H3.75A.75.75 0 013 12zm0 5.25a.75.75 0 01.75-.75h16.5a.75.75 0 010 1.5H3.75a.75.75 0 01-.75-.75z", clipRule: "evenodd" })); } reactExports.forwardRef(Bars3Icon); function BellIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M5.25 9a6.75 6.75 0 0113.5 0v.75c0 2.123.8 4.057 2.118 5.52a.75.75 0 01-.297 1.206c-1.544.57-3.16.99-4.831 1.243a3.75 3.75 0 11-7.48 0 24.585 24.585 0 01-4.831-1.244.75.75 0 01-.298-1.205A8.217 8.217 0 005.25 9.75V9zm4.502 8.9a2.25 2.25 0 104.496 0 25.057 25.057 0 01-4.496 0z", clipRule: "evenodd" })); } reactExports.forwardRef(BellIcon); function ChatBubbleOvalLeftEllipsisIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M4.804 21.644A6.707 6.707 0 006 21.75a6.721 6.721 0 003.583-1.029c.774.182 1.584.279 2.417.279 5.322 0 9.75-3.97 9.75-9 0-5.03-4.428-9-9.75-9s-9.75 3.97-9.75 9c0 2.409 1.025 4.587 2.674 6.192.232.226.277.428.254.543a3.73 3.73 0 01-.814 1.686.75.75 0 00.44 1.223zM8.25 10.875a1.125 1.125 0 100 2.25 1.125 1.125 0 000-2.25zM10.875 12a1.125 1.125 0 112.25 0 1.125 1.125 0 01-2.25 0zm4.875-1.125a1.125 1.125 0 100 2.25 1.125 1.125 0 000-2.25z", clipRule: "evenodd" })); } reactExports.forwardRef(ChatBubbleOvalLeftEllipsisIcon); function CheckBadgeIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M8.603 3.799A4.49 4.49 0 0112 2.25c1.357 0 2.573.6 3.397 1.549a4.49 4.49 0 013.498 1.307 4.491 4.491 0 011.307 3.497A4.49 4.49 0 0121.75 12a4.49 4.49 0 01-1.549 3.397 4.491 4.491 0 01-1.307 3.497 4.491 4.491 0 01-3.497 1.307A4.49 4.49 0 0112 21.75a4.49 4.49 0 01-3.397-1.549 4.49 4.49 0 01-3.498-1.306 4.491 4.491 0 01-1.307-3.498A4.49 4.49 0 012.25 12c0-1.357.6-2.573 1.549-3.397a4.49 4.49 0 011.307-3.497 4.49 4.49 0 013.497-1.307zm7.007 6.387a.75.75 0 10-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 00-1.06 1.06l2.25 2.25a.75.75 0 001.14-.094l3.75-5.25z", clipRule: "evenodd" })); } const ForwardRef$c = reactExports.forwardRef(CheckBadgeIcon); function CheckIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M19.916 4.626a.75.75 0 01.208 1.04l-9 13.5a.75.75 0 01-1.154.114l-6-6a.75.75 0 011.06-1.06l5.353 5.353 8.493-12.739a.75.75 0 011.04-.208z", clipRule: "evenodd" })); } reactExports.forwardRef(CheckIcon); function ChevronDownIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M12.53 16.28a.75.75 0 01-1.06 0l-7.5-7.5a.75.75 0 011.06-1.06L12 14.69l6.97-6.97a.75.75 0 111.06 1.06l-7.5 7.5z", clipRule: "evenodd" })); } const ForwardRef$b = reactExports.forwardRef(ChevronDownIcon$1); function ChevronLeftIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M7.72 12.53a.75.75 0 010-1.06l7.5-7.5a.75.75 0 111.06 1.06L9.31 12l6.97 6.97a.75.75 0 11-1.06 1.06l-7.5-7.5z", clipRule: "evenodd" })); } const ForwardRef$a = reactExports.forwardRef(ChevronLeftIcon); function ChevronRightIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M16.28 11.47a.75.75 0 010 1.06l-7.5 7.5a.75.75 0 01-1.06-1.06L14.69 12 7.72 5.03a.75.75 0 011.06-1.06l7.5 7.5z", clipRule: "evenodd" })); } const ForwardRef$9 = reactExports.forwardRef(ChevronRightIcon$1); function ChevronUpDownIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M11.47 4.72a.75.75 0 011.06 0l3.75 3.75a.75.75 0 01-1.06 1.06L12 6.31 8.78 9.53a.75.75 0 01-1.06-1.06l3.75-3.75zm-3.75 9.75a.75.75 0 011.06 0L12 17.69l3.22-3.22a.75.75 0 111.06 1.06l-3.75 3.75a.75.75 0 01-1.06 0l-3.75-3.75a.75.75 0 010-1.06z", clipRule: "evenodd" })); } reactExports.forwardRef(ChevronUpDownIcon); function ChevronUpIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M11.47 7.72a.75.75 0 011.06 0l7.5 7.5a.75.75 0 11-1.06 1.06L12 9.31l-6.97 6.97a.75.75 0 01-1.06-1.06l7.5-7.5z", clipRule: "evenodd" })); } const ForwardRef$8 = reactExports.forwardRef(ChevronUpIcon); function CogIcon$1({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { d: "M17.004 10.407c.138.435-.216.842-.672.842h-3.465a.75.75 0 01-.65-.375l-1.732-3c-.229-.396-.053-.907.393-1.004a5.252 5.252 0 016.126 3.537zM8.12 8.464c.307-.338.838-.235 1.066.16l1.732 3a.75.75 0 010 .75l-1.732 3.001c-.229.396-.76.498-1.067.16A5.231 5.231 0 016.75 12c0-1.362.519-2.603 1.37-3.536zM10.878 17.13c-.447-.097-.623-.608-.394-1.003l1.733-3.003a.75.75 0 01.65-.375h3.465c.457 0 .81.408.672.843a5.252 5.252 0 01-6.126 3.538z" }), /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M21 12.75a.75.75 0 000-1.5h-.783a8.22 8.22 0 00-.237-1.357l.734-.267a.75.75 0 10-.513-1.41l-.735.268a8.24 8.24 0 00-.689-1.191l.6-.504a.75.75 0 10-.964-1.149l-.6.504a8.3 8.3 0 00-1.054-.885l.391-.678a.75.75 0 10-1.299-.75l-.39.677a8.188 8.188 0 00-1.295-.471l.136-.77a.75.75 0 00-1.477-.26l-.136.77a8.364 8.364 0 00-1.377 0l-.136-.77a.75.75 0 10-1.477.26l.136.77c-.448.121-.88.28-1.294.47l-.39-.676a.75.75 0 00-1.3.75l.392.678a8.29 8.29 0 00-1.054.885l-.6-.504a.75.75 0 00-.965 1.149l.6.503a8.243 8.243 0 00-.689 1.192L3.8 8.217a.75.75 0 10-.513 1.41l.735.267a8.222 8.222 0 00-.238 1.355h-.783a.75.75 0 000 1.5h.783c.042.464.122.917.238 1.356l-.735.268a.75.75 0 10.513 1.41l.735-.268c.197.417.428.816.69 1.192l-.6.504a.75.75 0 10.963 1.149l.601-.505c.326.323.679.62 1.054.885l-.392.68a.75.75 0 101.3.75l.39-.679c.414.192.847.35 1.294.471l-.136.771a.75.75 0 101.477.26l.137-.772a8.376 8.376 0 001.376 0l.136.773a.75.75 0 101.477-.26l-.136-.772a8.19 8.19 0 001.294-.47l.391.677a.75.75 0 101.3-.75l-.393-.679a8.282 8.282 0 001.054-.885l.601.504a.75.75 0 10.964-1.15l-.6-.503a8.24 8.24 0 00.69-1.191l.735.268a.75.75 0 10.512-1.41l-.734-.268c.115-.438.195-.892.237-1.356h.784zm-2.657-3.06a6.744 6.744 0 00-1.19-2.053 6.784 6.784 0 00-1.82-1.51A6.704 6.704 0 0012 5.25a6.801 6.801 0 00-1.225.111 6.7 6.7 0 00-2.15.792 6.784 6.784 0 00-2.952 3.489.758.758 0 01-.036.099A6.74 6.74 0 005.251 12a6.739 6.739 0 003.355 5.835l.01.006.01.005a6.706 6.706 0 002.203.802c.007 0 .014.002.021.004a6.792 6.792 0 002.301 0l.022-.004a6.707 6.707 0 002.228-.816 6.781 6.781 0 001.762-1.483l.009-.01.009-.012a6.744 6.744 0 001.18-2.064c.253-.708.39-1.47.39-2.264a6.74 6.74 0 00-.408-2.308z", clipRule: "evenodd" })); } reactExports.forwardRef(CogIcon$1); function DocumentTextIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M5.625 1.5c-1.036 0-1.875.84-1.875 1.875v17.25c0 1.035.84 1.875 1.875 1.875h12.75c1.035 0 1.875-.84 1.875-1.875V12.75A3.75 3.75 0 0016.5 9h-1.875a1.875 1.875 0 01-1.875-1.875V5.25A3.75 3.75 0 009 1.5H5.625zM7.5 15a.75.75 0 01.75-.75h7.5a.75.75 0 010 1.5h-7.5A.75.75 0 017.5 15zm.75 2.25a.75.75 0 000 1.5H12a.75.75 0 000-1.5H8.25z", clipRule: "evenodd" }), /*#__PURE__*/reactExports.createElement("path", { d: "M12.971 1.816A5.23 5.23 0 0114.25 5.25v1.875c0 .207.168.375.375.375H16.5a5.23 5.23 0 013.434 1.279 9.768 9.768 0 00-6.963-6.963z" })); } reactExports.forwardRef(DocumentTextIcon); function EllipsisHorizontalIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M4.5 12a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zm6 0a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zm6 0a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0z", clipRule: "evenodd" })); } const ForwardRef$7 = reactExports.forwardRef(EllipsisHorizontalIcon); function ExclamationCircleIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z", clipRule: "evenodd" })); } reactExports.forwardRef(ExclamationCircleIcon); function HeartIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { d: "M11.645 20.91l-.007-.003-.022-.012a15.247 15.247 0 01-.383-.218 25.18 25.18 0 01-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0112 5.052 5.5 5.5 0 0116.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 01-4.244 3.17 15.247 15.247 0 01-.383.219l-.022.012-.007.004-.003.001a.752.752 0 01-.704 0l-.003-.001z" })); } const ForwardRef$6 = reactExports.forwardRef(HeartIcon); function InboxIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M6.912 3a3 3 0 00-2.868 2.118l-2.411 7.838a3 3 0 00-.133.882V18a3 3 0 003 3h15a3 3 0 003-3v-4.162c0-.299-.045-.596-.133-.882l-2.412-7.838A3 3 0 0017.088 3H6.912zm13.823 9.75l-2.213-7.191A1.5 1.5 0 0017.088 4.5H6.912a1.5 1.5 0 00-1.434 1.059L3.265 12.75H6.11a3 3 0 012.684 1.658l.256.513a1.5 1.5 0 001.342.829h3.218a1.5 1.5 0 001.342-.83l.256-.512a3 3 0 012.684-1.658h2.844z", clipRule: "evenodd" })); } reactExports.forwardRef(InboxIcon); function LifebuoyIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M19.449 8.448L16.388 11a4.52 4.52 0 010 2.002l3.061 2.55a8.275 8.275 0 000-7.103zM15.552 19.45L13 16.388a4.52 4.52 0 01-2.002 0l-2.55 3.061a8.275 8.275 0 007.103 0zM4.55 15.552L7.612 13a4.52 4.52 0 010-2.002L4.551 8.45a8.275 8.275 0 000 7.103zM8.448 4.55L11 7.612a4.52 4.52 0 012.002 0l2.55-3.061a8.275 8.275 0 00-7.103 0zm8.657-.86a9.776 9.776 0 011.79 1.415 9.776 9.776 0 011.414 1.788 9.764 9.764 0 010 10.211 9.777 9.777 0 01-1.415 1.79 9.777 9.777 0 01-1.788 1.414 9.764 9.764 0 01-10.212 0 9.776 9.776 0 01-1.788-1.415 9.776 9.776 0 01-1.415-1.788 9.764 9.764 0 010-10.212 9.774 9.774 0 011.415-1.788A9.774 9.774 0 016.894 3.69a9.764 9.764 0 0110.211 0zM14.121 9.88a2.985 2.985 0 00-1.11-.704 3.015 3.015 0 00-2.022 0 2.985 2.985 0 00-1.11.704c-.326.325-.56.705-.704 1.11a3.015 3.015 0 000 2.022c.144.405.378.785.704 1.11.325.326.705.56 1.11.704.652.233 1.37.233 2.022 0a2.985 2.985 0 001.11-.704c.326-.325.56-.705.704-1.11a3.016 3.016 0 000-2.022 2.985 2.985 0 00-.704-1.11z", clipRule: "evenodd" })); } reactExports.forwardRef(LifebuoyIcon); function LinkIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M19.902 4.098a3.75 3.75 0 00-5.304 0l-4.5 4.5a3.75 3.75 0 001.035 6.037.75.75 0 01-.646 1.353 5.25 5.25 0 01-1.449-8.45l4.5-4.5a5.25 5.25 0 117.424 7.424l-1.757 1.757a.75.75 0 11-1.06-1.06l1.757-1.757a3.75 3.75 0 000-5.304zm-7.389 4.267a.75.75 0 011-.353 5.25 5.25 0 011.449 8.45l-4.5 4.5a5.25 5.25 0 11-7.424-7.424l1.757-1.757a.75.75 0 111.06 1.06l-1.757 1.757a3.75 3.75 0 105.304 5.304l4.5-4.5a3.75 3.75 0 00-1.035-6.037.75.75 0 01-.354-1z", clipRule: "evenodd" })); } const ForwardRef$5 = reactExports.forwardRef(LinkIcon); function LockClosedIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M12 1.5a5.25 5.25 0 00-5.25 5.25v3a3 3 0 00-3 3v6.75a3 3 0 003 3h10.5a3 3 0 003-3v-6.75a3 3 0 00-3-3v-3c0-2.9-2.35-5.25-5.25-5.25zm3.75 8.25v-3a3.75 3.75 0 10-7.5 0v3h7.5z", clipRule: "evenodd" })); } const ForwardRef$4 = reactExports.forwardRef(LockClosedIcon); function MagnifyingGlassIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M10.5 3.75a6.75 6.75 0 100 13.5 6.75 6.75 0 000-13.5zM2.25 10.5a8.25 8.25 0 1114.59 5.28l4.69 4.69a.75.75 0 11-1.06 1.06l-4.69-4.69A8.25 8.25 0 012.25 10.5z", clipRule: "evenodd" })); } reactExports.forwardRef(MagnifyingGlassIcon); function NewspaperIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M4.125 3C3.089 3 2.25 3.84 2.25 4.875V18a3 3 0 003 3h15a3 3 0 01-3-3V4.875C17.25 3.839 16.41 3 15.375 3H4.125zM12 9.75a.75.75 0 000 1.5h1.5a.75.75 0 000-1.5H12zm-.75-2.25a.75.75 0 01.75-.75h1.5a.75.75 0 010 1.5H12a.75.75 0 01-.75-.75zM6 12.75a.75.75 0 000 1.5h7.5a.75.75 0 000-1.5H6zm-.75 3.75a.75.75 0 01.75-.75h7.5a.75.75 0 010 1.5H6a.75.75 0 01-.75-.75zM6 6.75a.75.75 0 00-.75.75v3c0 .414.336.75.75.75h3a.75.75 0 00.75-.75v-3A.75.75 0 009 6.75H6z", clipRule: "evenodd" }), /*#__PURE__*/reactExports.createElement("path", { d: "M18.75 6.75h1.875c.621 0 1.125.504 1.125 1.125V18a1.5 1.5 0 01-3 0V6.75z" })); } reactExports.forwardRef(NewspaperIcon); function PaintBrushIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M20.599 1.5c-.376 0-.743.111-1.055.32l-5.08 3.385a18.747 18.747 0 00-3.471 2.987 10.04 10.04 0 014.815 4.815 18.748 18.748 0 002.987-3.472l3.386-5.079A1.902 1.902 0 0020.599 1.5zm-8.3 14.025a18.76 18.76 0 001.896-1.207 8.026 8.026 0 00-4.513-4.513A18.75 18.75 0 008.475 11.7l-.278.5a5.26 5.26 0 013.601 3.602l.502-.278zM6.75 13.5A3.75 3.75 0 003 17.25a1.5 1.5 0 01-1.601 1.497.75.75 0 00-.7 1.123 5.25 5.25 0 009.8-2.62 3.75 3.75 0 00-3.75-3.75z", clipRule: "evenodd" })); } reactExports.forwardRef(PaintBrushIcon); function UserCircleIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M18.685 19.097A9.723 9.723 0 0021.75 12c0-5.385-4.365-9.75-9.75-9.75S2.25 6.615 2.25 12a9.723 9.723 0 003.065 7.097A9.716 9.716 0 0012 21.75a9.716 9.716 0 006.685-2.653zm-12.54-1.285A7.486 7.486 0 0112 15a7.486 7.486 0 015.855 2.812A8.224 8.224 0 0112 20.25a8.224 8.224 0 01-5.855-2.438zM15.75 9a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0z", clipRule: "evenodd" })); } reactExports.forwardRef(UserCircleIcon); function UserGroupIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M8.25 6.75a3.75 3.75 0 117.5 0 3.75 3.75 0 01-7.5 0zM15.75 9.75a3 3 0 116 0 3 3 0 01-6 0zM2.25 9.75a3 3 0 116 0 3 3 0 01-6 0zM6.31 15.117A6.745 6.745 0 0112 12a6.745 6.745 0 016.709 7.498.75.75 0 01-.372.568A12.696 12.696 0 0112 21.75c-2.305 0-4.47-.612-6.337-1.684a.75.75 0 01-.372-.568 6.787 6.787 0 011.019-4.38z", clipRule: "evenodd" }), /*#__PURE__*/reactExports.createElement("path", { d: "M5.082 14.254a8.287 8.287 0 00-1.308 5.135 9.687 9.687 0 01-1.764-.44l-.115-.04a.563.563 0 01-.373-.487l-.01-.121a3.75 3.75 0 013.57-4.047zM20.226 19.389a8.287 8.287 0 00-1.308-5.135 3.75 3.75 0 013.57 4.047l-.01.121a.563.563 0 01-.373.486l-.115.04c-.567.2-1.156.349-1.764.441z" })); } reactExports.forwardRef(UserGroupIcon); function UserIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M7.5 6a4.5 4.5 0 119 0 4.5 4.5 0 01-9 0zM3.751 20.105a8.25 8.25 0 0116.498 0 .75.75 0 01-.437.695A18.683 18.683 0 0112 22.5c-2.786 0-5.433-.608-7.812-1.7a.75.75 0 01-.437-.695z", clipRule: "evenodd" })); } const ForwardRef$3 = reactExports.forwardRef(UserIcon); function UserPlusIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { d: "M6.25 6.375a4.125 4.125 0 118.25 0 4.125 4.125 0 01-8.25 0zM3.25 19.125a7.125 7.125 0 0114.25 0v.003l-.001.119a.75.75 0 01-.363.63 13.067 13.067 0 01-6.761 1.873c-2.472 0-4.786-.684-6.76-1.873a.75.75 0 01-.364-.63l-.001-.122zM19.75 7.5a.75.75 0 00-1.5 0v2.25H16a.75.75 0 000 1.5h2.25v2.25a.75.75 0 001.5 0v-2.25H22a.75.75 0 000-1.5h-2.25V7.5z" })); } reactExports.forwardRef(UserPlusIcon); function UsersIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { d: "M4.5 6.375a4.125 4.125 0 118.25 0 4.125 4.125 0 01-8.25 0zM14.25 8.625a3.375 3.375 0 116.75 0 3.375 3.375 0 01-6.75 0zM1.5 19.125a7.125 7.125 0 0114.25 0v.003l-.001.119a.75.75 0 01-.363.63 13.067 13.067 0 01-6.761 1.873c-2.472 0-4.786-.684-6.76-1.873a.75.75 0 01-.364-.63l-.001-.122zM17.25 19.128l-.001.144a2.25 2.25 0 01-.233.96 10.088 10.088 0 005.06-1.01.75.75 0 00.42-.643 4.875 4.875 0 00-6.957-4.611 8.586 8.586 0 011.71 5.157v.003z" })); } reactExports.forwardRef(UsersIcon); function XMarkIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M5.47 5.47a.75.75 0 011.06 0L12 10.94l5.47-5.47a.75.75 0 111.06 1.06L13.06 12l5.47 5.47a.75.75 0 11-1.06 1.06L12 13.06l-5.47 5.47a.75.75 0 01-1.06-1.06L10.94 12 5.47 6.53a.75.75 0 010-1.06z", clipRule: "evenodd" })); } const ForwardRef$2 = reactExports.forwardRef(XMarkIcon); function ArrowUpTrayIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { d: "M9.25 13.25a.75.75 0 001.5 0V4.636l2.955 3.129a.75.75 0 001.09-1.03l-4.25-4.5a.75.75 0 00-1.09 0l-4.25 4.5a.75.75 0 101.09 1.03L9.25 4.636v8.614z" }), /*#__PURE__*/reactExports.createElement("path", { d: "M3.5 12.75a.75.75 0 00-1.5 0v2.5A2.75 2.75 0 004.75 18h10.5A2.75 2.75 0 0018 15.25v-2.5a.75.75 0 00-1.5 0v2.5c0 .69-.56 1.25-1.25 1.25H4.75c-.69 0-1.25-.56-1.25-1.25v-2.5z" })); } reactExports.forwardRef(ArrowUpTrayIcon); function CheckCircleIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z", clipRule: "evenodd" })); } reactExports.forwardRef(CheckCircleIcon); function ChevronDownIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z", clipRule: "evenodd" })); } reactExports.forwardRef(ChevronDownIcon); function ChevronRightIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z", clipRule: "evenodd" })); } reactExports.forwardRef(ChevronRightIcon); function ClockIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M10 18a8 8 0 100-16 8 8 0 000 16zm.75-13a.75.75 0 00-1.5 0v5c0 .414.336.75.75.75h4a.75.75 0 000-1.5h-3.25V5z", clipRule: "evenodd" })); } reactExports.forwardRef(ClockIcon); function CogIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { d: "M13.024 9.25c.47 0 .827-.433.637-.863a4 4 0 00-4.094-2.364c-.468.05-.665.576-.43.984l1.08 1.868a.75.75 0 00.649.375h2.158zM7.84 7.758c-.236-.408-.79-.5-1.068-.12A3.982 3.982 0 006 10c0 .884.287 1.7.772 2.363.278.38.832.287 1.068-.12l1.078-1.868a.75.75 0 000-.75L7.839 7.758zM9.138 12.993c-.235.408-.039.934.43.984a4 4 0 004.094-2.364c.19-.43-.168-.863-.638-.863h-2.158a.75.75 0 00-.65.375l-1.078 1.868z" }), /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M14.13 4.347l.644-1.117a.75.75 0 00-1.299-.75l-.644 1.116a6.954 6.954 0 00-2.081-.556V1.75a.75.75 0 00-1.5 0v1.29a6.954 6.954 0 00-2.081.556L6.525 2.48a.75.75 0 10-1.3.75l.645 1.117A7.04 7.04 0 004.347 5.87L3.23 5.225a.75.75 0 10-.75 1.3l1.116.644A6.954 6.954 0 003.04 9.25H1.75a.75.75 0 000 1.5h1.29c.078.733.27 1.433.556 2.081l-1.116.645a.75.75 0 10.75 1.298l1.117-.644a7.04 7.04 0 001.523 1.523l-.645 1.117a.75.75 0 101.3.75l.644-1.116a6.954 6.954 0 002.081.556v1.29a.75.75 0 001.5 0v-1.29a6.954 6.954 0 002.081-.556l.645 1.116a.75.75 0 001.299-.75l-.645-1.117a7.042 7.042 0 001.523-1.523l1.117.644a.75.75 0 00.75-1.298l-1.116-.645a6.954 6.954 0 00.556-2.081h1.29a.75.75 0 000-1.5h-1.29a6.954 6.954 0 00-.556-2.081l1.116-.644a.75.75 0 00-.75-1.3l-1.117.645a7.04 7.04 0 00-1.524-1.523zM10 4.5a5.475 5.475 0 00-2.781.754A5.527 5.527 0 005.22 7.277 5.475 5.475 0 004.5 10a5.475 5.475 0 00.752 2.777 5.527 5.527 0 002.028 2.004c.802.458 1.73.719 2.72.719a5.474 5.474 0 002.78-.753 5.527 5.527 0 002.001-2.027c.458-.802.719-1.73.719-2.72a5.475 5.475 0 00-.753-2.78 5.528 5.528 0 00-2.028-2.002A5.475 5.475 0 0010 4.5z", clipRule: "evenodd" })); } const ForwardRef$1 = reactExports.forwardRef(CogIcon); function ExclamationTriangleIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495zM10 5a.75.75 0 01.75.75v3.5a.75.75 0 01-1.5 0v-3.5A.75.75 0 0110 5zm0 9a1 1 0 100-2 1 1 0 000 2z", clipRule: "evenodd" })); } reactExports.forwardRef(ExclamationTriangleIcon); function HashtagIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M9.493 2.853a.75.75 0 00-1.486-.205L7.545 6H4.198a.75.75 0 000 1.5h3.14l-.69 5H3.302a.75.75 0 000 1.5h3.14l-.435 3.148a.75.75 0 001.486.205L7.955 14h2.986l-.434 3.148a.75.75 0 001.486.205L12.456 14h3.346a.75.75 0 000-1.5h-3.14l.69-5h3.346a.75.75 0 000-1.5h-3.14l.435-3.147a.75.75 0 00-1.486-.205L12.045 6H9.059l.434-3.147zM8.852 7.5l-.69 5h2.986l.69-5H8.852z", clipRule: "evenodd" })); } const ForwardRef = reactExports.forwardRef(HashtagIcon); function QuestionMarkCircleIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M18 10a8 8 0 11-16 0 8 8 0 0116 0zM8.94 6.94a.75.75 0 11-1.061-1.061 3 3 0 112.871 5.026v.345a.75.75 0 01-1.5 0v-.5c0-.72.57-1.172 1.081-1.287A1.5 1.5 0 108.94 6.94zM10 15a1 1 0 100-2 1 1 0 000 2z", clipRule: "evenodd" })); } reactExports.forwardRef(QuestionMarkCircleIcon); function XCircleIcon({ title, titleId, ...props }, svgRef) { return /*#__PURE__*/reactExports.createElement("svg", Object.assign({ xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true", ref: svgRef, "aria-labelledby": titleId }, props), title ? /*#__PURE__*/reactExports.createElement("title", { id: titleId }, title) : null, /*#__PURE__*/reactExports.createElement("path", { fillRule: "evenodd", d: "M10 18a8 8 0 100-16 8 8 0 000 16zM8.28 7.22a.75.75 0 00-1.06 1.06L8.94 10l-1.72 1.72a.75.75 0 101.06 1.06L10 11.06l1.72 1.72a.75.75 0 101.06-1.06L11.06 10l1.72-1.72a.75.75 0 00-1.06-1.06L10 8.94 8.28 7.22z", clipRule: "evenodd" })); } reactExports.forwardRef(XCircleIcon); 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$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); } /** * 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$c=/\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;function n$a(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$c),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$e=Object.create(null);function a$b(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$b,"")+"";case"comment":return e+"\x3c!--"+t.comment+"--\x3e"}}var c$b={parse:function(e,t){t||(t={}),t.components||(t.components=s$e);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$a(r);return l<0?(c.push(v),c):((u=o[l]).children.push(v),c)}if(f&&(l++,"tag"===(a=n$a(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$b("",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$b.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$1.createElement(c.type, _extends$2({}, 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 = (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(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()); } }); } function identity(x) { return x; } /** @internal */ function pipeFromArray(fns) { if (fns.length === 0) { return identity; } 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(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(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(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); /** * 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$6(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$6(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$1 = 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$4(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$1.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$4(key); value = encode$4(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$1(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$2(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$1, toString: toString$2 }; // // 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); 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(); 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) => `../${args.projectHandle}/index.html`, 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, {}), }, }, } ; /** @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$2 = ()=>{ // noop }; function createInnerProxy(callback, path) { const proxy = new Proxy(noop$2, { 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$2, { 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$1.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$1.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(); var classnames = {exports: {}}; /*! Copyright (c) 2018 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ (function (module) { /* global define */ (function () { var hasOwn = {}.hasOwnProperty; function classNames() { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { if (arg.length) { var inner = classNames.apply(null, arg); if (inner) { classes.push(inner); } } } else if (argType === 'object') { if (arg.toString === Object.prototype.toString) { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } else { classes.push(arg.toString()); } } } return classes.join(' '); } if (module.exports) { classNames.default = classNames; module.exports = classNames; } else { window.classNames = classNames; } }()); } (classnames)); var classnamesExports = classnames.exports; var classNames = /*@__PURE__*/getDefaultExportFromCjs(classnamesExports); var util$1; (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$1 || (util$1 = {})); const ZodIssueCode = util$1.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$1.assertNever(issue); } return { message }; }; let overrideErrorMap = defaultErrorMap; const setErrorMap = (map) => { overrideErrorMap = map; }; const ZodParsedType = util$1.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$1.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$1.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$1.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$1.objectKeys(mask).map((key) => { shape[key] = this.shape[key]; }); return new ZodObject({ ...this._def, shape: () => shape, }); } omit(mask) { const shape = {}; util$1.objectKeys(this.shape).map((key) => { if (util$1.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$1.objectKeys(this.shape).map((key) => { if (util$1.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$1.objectKeys(b); const sharedKeys = util$1 .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$1.getValidEnumValues(this._def.values); if (nativeEnumValues.indexOf(input.data) === -1) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_enum_value, options: util$1.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$1.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 }); const ButtonStyle = mod.enum(["pill", "roundrect", "authn"]); const ButtonColor = mod.enum([ "cherry", "strawberry", "mango", "not-black", "red", "green", "accent", "secondary", "authn-primary", "authn-other", ]); mod.object({ buttonStyle: ButtonStyle, color: ButtonColor, className: mod.string().optional(), }); const baseColors = classNames("bg-notWhite", "hover:text-notWhite"); // WHY NOT HAVE THESE AS INTERPOLATED CLASS NAMES? // tailwind jit doesn't handle interpolated class names! // you have to have the full class name written for it to pick up on a string as // a class name! so we do this const pillClasses = classNames( "font-atkinson", "font-bold", "rounded-full", "border-2" ); const roundrectClasses = classNames("body-2", "rounded-lg"); const authnStyleClasses = classNames( "flex", "h-12", "items-center", "justify-center", "rounded-lg", "px-6", "text-lg" ); const cherryClasses$1 = classNames( "border-cherry", "hover:bg-cherry", "text-cherry", "active:bg-cherry-600", "active:border-cherry-600", "disabled:text-cherry-300", "disabled:border-cherry-300", "focus:outline-cherry", "focus:ring-cherry", baseColors ); const strawberryClasses = classNames( "border-strawberry", "hover:bg-strawberry", "text-strawberry", "active:bg-strawberry-600", "active:border-strawberry-600", "disabled:text-strawberry-300", "disabled:border-strawberry-300", "focus:outline-strawberry", "focus:ring-strawberry", baseColors ); const redClasses = classNames( "border-red", "hover:bg-red", "text-red", "active:bg-red-600", "active:border-red-600", "disabled:text-red-300", "disabled:border-red-300", "focus:outline-red", baseColors ); const greenClasses$1 = classNames( "border-green", "hover:bg-green", "text-green", "active:bg-green-600", "active:border-green-600", "disabled:text-green-300", "disabled:border-green-300", "focus:outline-green", baseColors ); const mangoClasses$1 = classNames( "border-mango", "hover:bg-mango", "text-mango", "bg-notBlack", "hover:text-notBlack" ); const notBlackClasses = classNames( "border-notBlack", "hover:bg-notBlack", "text-notBlack", "focus:outline-notBlack", "focus:ring-notBlack", baseColors ); const accentClasses = classNames( "border-accent", "text-accent", "bg-foreground", "hover:bg-accent", "hover:text-text" ); const secondaryClasses = classNames( "bg-secondary", "text-notWhite", "dark:text-notBlack", "hover:bg-secondary-600" ); const authnPrimaryColorClasses = classNames( "bg-foreground", "text-text", "hover:bg-foreground-600", "active:bg-foreground-700", "disabled:bg-foreground-200" ); const authnOtherColorClasses = classNames( "border-2", "border-foreground", "text-foreground", "hover:bg-longan-200" ); const sharedClasses = (props) => classNames( "leading-none", "align-middle", "py-2", "px-4", "no-select", props.className, { [pillClasses]: props.buttonStyle === "pill", [roundrectClasses]: props.buttonStyle === "roundrect", [authnStyleClasses]: props.buttonStyle === "authn", [cherryClasses$1]: props.color === "cherry", [strawberryClasses]: props.color === "strawberry", [mangoClasses$1]: props.color === "mango", [notBlackClasses]: props.color === "not-black", [redClasses]: props.color === "red", [accentClasses]: props.color === "accent", [greenClasses$1]: props.color === "green", [secondaryClasses]: props.color === "secondary", [authnPrimaryColorClasses]: props.color === "authn-primary", [authnOtherColorClasses]: props.color === "authn-other", } ); const Button = React$1.forwardRef(({ buttonStyle, color, className, ...props }, ref) => { const classes = sharedClasses({ buttonStyle, color, className, ...props, }); return ( React$1.createElement('button', { ...props, className: classes, ref: ref,} , props.children ) ); }); Button.displayName = "Button"; const LinkButton = React$1.forwardRef(({ buttonStyle, color, ...props }, ref) => { const classes = sharedClasses({ buttonStyle, color, ...props }); return ( React$1.createElement('a', { ...props, className: classes, ref: ref,} , props.children ) ); }); LinkButton.displayName = "LinkButton"; const consoleLogger = { type: 'logger', log(args) { this.output('log', args); }, warn(args) { this.output('warn', args); }, error(args) { this.output('error', args); }, output(type, args) { if (console && console[type]) console[type].apply(console, args); } }; class Logger { constructor(concreteLogger) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; this.init(concreteLogger, options); } init(concreteLogger) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; this.prefix = options.prefix || 'i18next:'; this.logger = concreteLogger || consoleLogger; this.options = options; this.debug = options.debug; } log() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return this.forward(args, 'log', '', true); } warn() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return this.forward(args, 'warn', '', true); } error() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return this.forward(args, 'error', ''); } deprecate() { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true); } forward(args, lvl, prefix, debugOnly) { if (debugOnly && !this.debug) return null; if (typeof args[0] === 'string') args[0] = `${prefix}${this.prefix} ${args[0]}`; return this.logger[lvl](args); } create(moduleName) { return new Logger(this.logger, { ...{ prefix: `${this.prefix}:${moduleName}:` }, ...this.options }); } clone(options) { options = options || this.options; options.prefix = options.prefix || this.prefix; return new Logger(this.logger, options); } } var baseLogger = new Logger(); class EventEmitter { constructor() { this.observers = {}; } on(events, listener) { events.split(' ').forEach(event => { this.observers[event] = this.observers[event] || []; this.observers[event].push(listener); }); return this; } off(event, listener) { if (!this.observers[event]) return; if (!listener) { delete this.observers[event]; return; } this.observers[event] = this.observers[event].filter(l => l !== listener); } emit(event) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (this.observers[event]) { const cloned = [].concat(this.observers[event]); cloned.forEach(observer => { observer(...args); }); } if (this.observers['*']) { const cloned = [].concat(this.observers['*']); cloned.forEach(observer => { observer.apply(observer, [event, ...args]); }); } } } function defer() { let res; let rej; const promise = new Promise((resolve, reject) => { res = resolve; rej = reject; }); promise.resolve = res; promise.reject = rej; return promise; } function makeString(object) { if (object == null) return ''; return '' + object; } function copy(a, s, t) { a.forEach(m => { if (s[m]) t[m] = s[m]; }); } function getLastOfPath(object, path, Empty) { function cleanKey(key) { return key && key.indexOf('###') > -1 ? key.replace(/###/g, '.') : key; } function canNotTraverseDeeper() { return !object || typeof object === 'string'; } const stack = typeof path !== 'string' ? [].concat(path) : path.split('.'); while (stack.length > 1) { if (canNotTraverseDeeper()) return {}; const key = cleanKey(stack.shift()); if (!object[key] && Empty) object[key] = new Empty(); if (Object.prototype.hasOwnProperty.call(object, key)) { object = object[key]; } else { object = {}; } } if (canNotTraverseDeeper()) return {}; return { obj: object, k: cleanKey(stack.shift()) }; } function setPath(object, path, newValue) { const { obj, k } = getLastOfPath(object, path, Object); obj[k] = newValue; } function pushPath(object, path, newValue, concat) { const { obj, k } = getLastOfPath(object, path, Object); obj[k] = obj[k] || []; obj[k].push(newValue); } function getPath(object, path) { const { obj, k } = getLastOfPath(object, path); if (!obj) return undefined; return obj[k]; } function getPathWithDefaults(data, defaultData, key) { const value = getPath(data, key); if (value !== undefined) { return value; } return getPath(defaultData, key); } function deepExtend(target, source, overwrite) { for (const prop in source) { if (prop !== '__proto__' && prop !== 'constructor') { if (prop in target) { if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) { if (overwrite) target[prop] = source[prop]; } else { deepExtend(target[prop], source[prop], overwrite); } } else { target[prop] = source[prop]; } } } return target; } function regexEscape(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); } var _entityMap = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '/': '/' }; function escape$1(data) { if (typeof data === 'string') { return data.replace(/[&<>"'\/]/g, s => _entityMap[s]); } return data; } const chars = [' ', ',', '?', '!', ';']; function looksLikeObjectPath(key, nsSeparator, keySeparator) { nsSeparator = nsSeparator || ''; keySeparator = keySeparator || ''; const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0); if (possibleChars.length === 0) return true; const r = new RegExp(`(${possibleChars.map(c => c === '?' ? '\\?' : c).join('|')})`); let matched = !r.test(key); if (!matched) { const ki = key.indexOf(keySeparator); if (ki > 0 && !r.test(key.substring(0, ki))) { matched = true; } } return matched; } function deepFind(obj, path) { let keySeparator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.'; if (!obj) return undefined; if (obj[path]) return obj[path]; const paths = path.split(keySeparator); let current = obj; for (let i = 0; i < paths.length; ++i) { if (!current) return undefined; if (typeof current[paths[i]] === 'string' && i + 1 < paths.length) { return undefined; } if (current[paths[i]] === undefined) { let j = 2; let p = paths.slice(i, i + j).join(keySeparator); let mix = current[p]; while (mix === undefined && paths.length > i + j) { j++; p = paths.slice(i, i + j).join(keySeparator); mix = current[p]; } if (mix === undefined) return undefined; if (mix === null) return null; if (path.endsWith(p)) { if (typeof mix === 'string') return mix; if (p && typeof mix[p] === 'string') return mix[p]; } const joinedPath = paths.slice(i + j).join(keySeparator); if (joinedPath) return deepFind(mix, joinedPath, keySeparator); return undefined; } current = current[paths[i]]; } return current; } function getCleanedCode(code) { if (code && code.indexOf('_') > 0) return code.replace('_', '-'); return code; } class ResourceStore extends EventEmitter { constructor(data) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { ns: ['translation'], defaultNS: 'translation' }; super(); this.data = data || {}; this.options = options; if (this.options.keySeparator === undefined) { this.options.keySeparator = '.'; } if (this.options.ignoreJSONStructure === undefined) { this.options.ignoreJSONStructure = true; } } addNamespaces(ns) { if (this.options.ns.indexOf(ns) < 0) { this.options.ns.push(ns); } } removeNamespaces(ns) { const index = this.options.ns.indexOf(ns); if (index > -1) { this.options.ns.splice(index, 1); } } getResource(lng, ns, key) { let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator; const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure; let path = [lng, ns]; if (key && typeof key !== 'string') path = path.concat(key); if (key && typeof key === 'string') path = path.concat(keySeparator ? key.split(keySeparator) : key); if (lng.indexOf('.') > -1) { path = lng.split('.'); } const result = getPath(this.data, path); if (result || !ignoreJSONStructure || typeof key !== 'string') return result; return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator); } addResource(lng, ns, key, value) { let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : { silent: false }; const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator; let path = [lng, ns]; if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key); if (lng.indexOf('.') > -1) { path = lng.split('.'); value = ns; ns = path[1]; } this.addNamespaces(ns); setPath(this.data, path, value); if (!options.silent) this.emit('added', lng, ns, key, value); } addResources(lng, ns, resources) { let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { silent: false }; for (const m in resources) { if (typeof resources[m] === 'string' || Object.prototype.toString.apply(resources[m]) === '[object Array]') this.addResource(lng, ns, m, resources[m], { silent: true }); } if (!options.silent) this.emit('added', lng, ns, resources); } addResourceBundle(lng, ns, resources, deep, overwrite) { let options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : { silent: false }; let path = [lng, ns]; if (lng.indexOf('.') > -1) { path = lng.split('.'); deep = resources; resources = ns; ns = path[1]; } this.addNamespaces(ns); let pack = getPath(this.data, path) || {}; if (deep) { deepExtend(pack, resources, overwrite); } else { pack = { ...pack, ...resources }; } setPath(this.data, path, pack); if (!options.silent) this.emit('added', lng, ns, resources); } removeResourceBundle(lng, ns) { if (this.hasResourceBundle(lng, ns)) { delete this.data[lng][ns]; } this.removeNamespaces(ns); this.emit('removed', lng, ns); } hasResourceBundle(lng, ns) { return this.getResource(lng, ns) !== undefined; } getResourceBundle(lng, ns) { if (!ns) ns = this.options.defaultNS; if (this.options.compatibilityAPI === 'v1') return { ...{}, ...this.getResource(lng, ns) }; return this.getResource(lng, ns); } getDataByLanguage(lng) { return this.data[lng]; } hasLanguageSomeTranslations(lng) { const data = this.getDataByLanguage(lng); const n = data && Object.keys(data) || []; return !!n.find(v => data[v] && Object.keys(data[v]).length > 0); } toJSON() { return this.data; } } var postProcessor = { processors: {}, addPostProcessor(module) { this.processors[module.name] = module; }, handle(processors, value, key, options, translator) { processors.forEach(processor => { if (this.processors[processor]) value = this.processors[processor].process(value, key, options, translator); }); return value; } }; const checkedLoadedFor = {}; class Translator extends EventEmitter { constructor(services) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; super(); copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this); this.options = options; if (this.options.keySeparator === undefined) { this.options.keySeparator = '.'; } this.logger = baseLogger.create('translator'); } changeLanguage(lng) { if (lng) this.language = lng; } exists(key) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { interpolation: {} }; if (key === undefined || key === null) { return false; } const resolved = this.resolve(key, options); return resolved && resolved.res !== undefined; } extractFromKey(key, options) { let nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator; if (nsSeparator === undefined) nsSeparator = ':'; const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator; let namespaces = options.ns || this.options.defaultNS || []; const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1; const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator); if (wouldCheckForNsInKey && !seemsNaturalLanguage) { const m = key.match(this.interpolator.nestingRegexp); if (m && m.length > 0) { return { key, namespaces }; } const parts = key.split(nsSeparator); if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift(); key = parts.join(keySeparator); } if (typeof namespaces === 'string') namespaces = [namespaces]; return { key, namespaces }; } translate(keys, options, lastKey) { if (typeof options !== 'object' && this.options.overloadTranslationOptionHandler) { options = this.options.overloadTranslationOptionHandler(arguments); } if (typeof options === 'object') options = { ...options }; if (!options) options = {}; if (keys === undefined || keys === null) return ''; if (!Array.isArray(keys)) keys = [String(keys)]; const returnDetails = options.returnDetails !== undefined ? options.returnDetails : this.options.returnDetails; const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator; const { key, namespaces } = this.extractFromKey(keys[keys.length - 1], options); const namespace = namespaces[namespaces.length - 1]; const lng = options.lng || this.language; const appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode; if (lng && lng.toLowerCase() === 'cimode') { if (appendNamespaceToCIMode) { const nsSeparator = options.nsSeparator || this.options.nsSeparator; if (returnDetails) { return { res: `${namespace}${nsSeparator}${key}`, usedKey: key, exactUsedKey: key, usedLng: lng, usedNS: namespace }; } return `${namespace}${nsSeparator}${key}`; } if (returnDetails) { return { res: key, usedKey: key, exactUsedKey: key, usedLng: lng, usedNS: namespace }; } return key; } const resolved = this.resolve(keys, options); let res = resolved && resolved.res; const resUsedKey = resolved && resolved.usedKey || key; const resExactUsedKey = resolved && resolved.exactUsedKey || key; const resType = Object.prototype.toString.apply(res); const noObject = ['[object Number]', '[object Function]', '[object RegExp]']; const joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays; const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject; const handleAsObject = typeof res !== 'string' && typeof res !== 'boolean' && typeof res !== 'number'; if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === 'string' && resType === '[object Array]')) { if (!options.returnObjects && !this.options.returnObjects) { if (!this.options.returnedObjectHandler) { this.logger.warn('accessing an object - but returnObjects options is not enabled!'); } const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, { ...options, ns: namespaces }) : `key '${key} (${this.language})' returned an object instead of string.`; if (returnDetails) { resolved.res = r; return resolved; } return r; } if (keySeparator) { const resTypeIsArray = resType === '[object Array]'; const copy = resTypeIsArray ? [] : {}; const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey; for (const m in res) { if (Object.prototype.hasOwnProperty.call(res, m)) { const deepKey = `${newKeyToUse}${keySeparator}${m}`; copy[m] = this.translate(deepKey, { ...options, ...{ joinArrays: false, ns: namespaces } }); if (copy[m] === deepKey) copy[m] = res[m]; } } res = copy; } } else if (handleAsObjectInI18nFormat && typeof joinArrays === 'string' && resType === '[object Array]') { res = res.join(joinArrays); if (res) res = this.extendTranslation(res, keys, options, lastKey); } else { let usedDefault = false; let usedKey = false; const needsPluralHandling = options.count !== undefined && typeof options.count !== 'string'; const hasDefaultValue = Translator.hasDefaultValue(options); const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : ''; const defaultValueSuffixOrdinalFallback = options.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, { ordinal: false }) : ''; const defaultValue = options[`defaultValue${defaultValueSuffix}`] || options[`defaultValue${defaultValueSuffixOrdinalFallback}`] || options.defaultValue; if (!this.isValidLookup(res) && hasDefaultValue) { usedDefault = true; res = defaultValue; } if (!this.isValidLookup(res)) { usedKey = true; res = key; } const missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey; const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res; const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing; if (usedKey || usedDefault || updateMissing) { this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res); if (keySeparator) { const fk = this.resolve(key, { ...options, keySeparator: false }); if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.'); } let lngs = []; const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language); if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) { for (let i = 0; i < fallbackLngs.length; i++) { lngs.push(fallbackLngs[i]); } } else if (this.options.saveMissingTo === 'all') { lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language); } else { lngs.push(options.lng || this.language); } const send = (l, k, specificDefaultValue) => { const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing; if (this.options.missingKeyHandler) { this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options); } else if (this.backendConnector && this.backendConnector.saveMissing) { this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options); } this.emit('missingKey', l, namespace, k, res); }; if (this.options.saveMissing) { if (this.options.saveMissingPlurals && needsPluralHandling) { lngs.forEach(language => { this.pluralResolver.getSuffixes(language, options).forEach(suffix => { send([language], key + suffix, options[`defaultValue${suffix}`] || defaultValue); }); }); } else { send(lngs, key, defaultValue); } } } res = this.extendTranslation(res, keys, options, resolved, lastKey); if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = `${namespace}:${key}`; if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) { if (this.options.compatibilityAPI !== 'v1') { res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}:${key}` : key, usedDefault ? res : undefined); } else { res = this.options.parseMissingKeyHandler(res); } } } if (returnDetails) { resolved.res = res; return resolved; } return res; } extendTranslation(res, key, options, resolved, lastKey) { var _this = this; if (this.i18nFormat && this.i18nFormat.parse) { res = this.i18nFormat.parse(res, { ...this.options.interpolation.defaultVariables, ...options }, options.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, { resolved }); } else if (!options.skipInterpolation) { if (options.interpolation) this.interpolator.init({ ...options, ...{ interpolation: { ...this.options.interpolation, ...options.interpolation } } }); const skipOnVariables = typeof res === 'string' && (options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables); let nestBef; if (skipOnVariables) { const nb = res.match(this.interpolator.nestingRegexp); nestBef = nb && nb.length; } let data = options.replace && typeof options.replace !== 'string' ? options.replace : options; if (this.options.interpolation.defaultVariables) data = { ...this.options.interpolation.defaultVariables, ...data }; res = this.interpolator.interpolate(res, data, options.lng || this.language, options); if (skipOnVariables) { const na = res.match(this.interpolator.nestingRegexp); const nestAft = na && na.length; if (nestBef < nestAft) options.nest = false; } if (!options.lng && this.options.compatibilityAPI !== 'v1' && resolved && resolved.res) options.lng = resolved.usedLng; if (options.nest !== false) res = this.interpolator.nest(res, function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (lastKey && lastKey[0] === args[0] && !options.context) { _this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`); return null; } return _this.translate(...args, key); }, options); if (options.interpolation) this.interpolator.reset(); } const postProcess = options.postProcess || this.options.postProcess; const postProcessorNames = typeof postProcess === 'string' ? [postProcess] : postProcess; if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) { res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? { i18nResolved: resolved, ...options } : options, this); } return res; } resolve(keys) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; let found; let usedKey; let exactUsedKey; let usedLng; let usedNS; if (typeof keys === 'string') keys = [keys]; keys.forEach(k => { if (this.isValidLookup(found)) return; const extracted = this.extractFromKey(k, options); const key = extracted.key; usedKey = key; let namespaces = extracted.namespaces; if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS); const needsPluralHandling = options.count !== undefined && typeof options.count !== 'string'; const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && this.pluralResolver.shouldUseIntlApi(); const needsContextHandling = options.context !== undefined && (typeof options.context === 'string' || typeof options.context === 'number') && options.context !== ''; const codes = options.lngs ? options.lngs : this.languageUtils.toResolveHierarchy(options.lng || this.language, options.fallbackLng); namespaces.forEach(ns => { if (this.isValidLookup(found)) return; usedNS = ns; if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils && this.utils.hasLoadedNamespace && !this.utils.hasLoadedNamespace(usedNS)) { checkedLoadedFor[`${codes[0]}-${ns}`] = true; this.logger.warn(`key "${usedKey}" for languages "${codes.join(', ')}" won't get resolved as namespace "${usedNS}" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!'); } codes.forEach(code => { if (this.isValidLookup(found)) return; usedLng = code; const finalKeys = [key]; if (this.i18nFormat && this.i18nFormat.addLookupKeys) { this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options); } else { let pluralSuffix; if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, options.count, options); const zeroSuffix = `${this.options.pluralSeparator}zero`; const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`; if (needsPluralHandling) { finalKeys.push(key + pluralSuffix); if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) { finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator)); } if (needsZeroSuffixLookup) { finalKeys.push(key + zeroSuffix); } } if (needsContextHandling) { const contextKey = `${key}${this.options.contextSeparator}${options.context}`; finalKeys.push(contextKey); if (needsPluralHandling) { finalKeys.push(contextKey + pluralSuffix); if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) { finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator)); } if (needsZeroSuffixLookup) { finalKeys.push(contextKey + zeroSuffix); } } } } let possibleKey; while (possibleKey = finalKeys.pop()) { if (!this.isValidLookup(found)) { exactUsedKey = possibleKey; found = this.getResource(code, ns, possibleKey, options); } } }); }); }); return { res: found, usedKey, exactUsedKey, usedLng, usedNS }; } isValidLookup(res) { return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === ''); } getResource(code, ns, key) { let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options); return this.resourceStore.getResource(code, ns, key, options); } static hasDefaultValue(options) { const prefix = 'defaultValue'; for (const option in options) { if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) { return true; } } return false; } } function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1); } class LanguageUtil { constructor(options) { this.options = options; this.supportedLngs = this.options.supportedLngs || false; this.logger = baseLogger.create('languageUtils'); } getScriptPartFromCode(code) { code = getCleanedCode(code); if (!code || code.indexOf('-') < 0) return null; const p = code.split('-'); if (p.length === 2) return null; p.pop(); if (p[p.length - 1].toLowerCase() === 'x') return null; return this.formatLanguageCode(p.join('-')); } getLanguagePartFromCode(code) { code = getCleanedCode(code); if (!code || code.indexOf('-') < 0) return code; const p = code.split('-'); return this.formatLanguageCode(p[0]); } formatLanguageCode(code) { if (typeof code === 'string' && code.indexOf('-') > -1) { const specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab']; let p = code.split('-'); if (this.options.lowerCaseLng) { p = p.map(part => part.toLowerCase()); } else if (p.length === 2) { p[0] = p[0].toLowerCase(); p[1] = p[1].toUpperCase(); if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase()); } else if (p.length === 3) { p[0] = p[0].toLowerCase(); if (p[1].length === 2) p[1] = p[1].toUpperCase(); if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase(); if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase()); if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase()); } return p.join('-'); } return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code; } isSupportedCode(code) { if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) { code = this.getLanguagePartFromCode(code); } return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1; } getBestMatchFromCodes(codes) { if (!codes) return null; let found; codes.forEach(code => { if (found) return; const cleanedLng = this.formatLanguageCode(code); if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng; }); if (!found && this.options.supportedLngs) { codes.forEach(code => { if (found) return; const lngOnly = this.getLanguagePartFromCode(code); if (this.isSupportedCode(lngOnly)) return found = lngOnly; found = this.options.supportedLngs.find(supportedLng => { if (supportedLng === lngOnly) return supportedLng; if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return; if (supportedLng.indexOf(lngOnly) === 0) return supportedLng; }); }); } if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0]; return found; } getFallbackCodes(fallbacks, code) { if (!fallbacks) return []; if (typeof fallbacks === 'function') fallbacks = fallbacks(code); if (typeof fallbacks === 'string') fallbacks = [fallbacks]; if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks; if (!code) return fallbacks.default || []; let found = fallbacks[code]; if (!found) found = fallbacks[this.getScriptPartFromCode(code)]; if (!found) found = fallbacks[this.formatLanguageCode(code)]; if (!found) found = fallbacks[this.getLanguagePartFromCode(code)]; if (!found) found = fallbacks.default; return found || []; } toResolveHierarchy(code, fallbackCode) { const fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code); const codes = []; const addCode = c => { if (!c) return; if (this.isSupportedCode(c)) { codes.push(c); } else { this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`); } }; if (typeof code === 'string' && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) { if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code)); if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code)); if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code)); } else if (typeof code === 'string') { addCode(this.formatLanguageCode(code)); } fallbackCodes.forEach(fc => { if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc)); }); return codes; } } let sets = [{ lngs: ['ach', 'ak', 'am', 'arn', 'br', 'fil', 'gun', 'ln', 'mfe', 'mg', 'mi', 'oc', 'pt', 'pt-BR', 'tg', 'tl', 'ti', 'tr', 'uz', 'wa'], nr: [1, 2], fc: 1 }, { lngs: ['af', 'an', 'ast', 'az', 'bg', 'bn', 'ca', 'da', 'de', 'dev', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fi', 'fo', 'fur', 'fy', 'gl', 'gu', 'ha', 'hi', 'hu', 'hy', 'ia', 'it', 'kk', 'kn', 'ku', 'lb', 'mai', 'ml', 'mn', 'mr', 'nah', 'nap', 'nb', 'ne', 'nl', 'nn', 'no', 'nso', 'pa', 'pap', 'pms', 'ps', 'pt-PT', 'rm', 'sco', 'se', 'si', 'so', 'son', 'sq', 'sv', 'sw', 'ta', 'te', 'tk', 'ur', 'yo'], nr: [1, 2], fc: 2 }, { lngs: ['ay', 'bo', 'cgg', 'fa', 'ht', 'id', 'ja', 'jbo', 'ka', 'km', 'ko', 'ky', 'lo', 'ms', 'sah', 'su', 'th', 'tt', 'ug', 'vi', 'wo', 'zh'], nr: [1], fc: 3 }, { lngs: ['be', 'bs', 'cnr', 'dz', 'hr', 'ru', 'sr', 'uk'], nr: [1, 2, 5], fc: 4 }, { lngs: ['ar'], nr: [0, 1, 2, 3, 11, 100], fc: 5 }, { lngs: ['cs', 'sk'], nr: [1, 2, 5], fc: 6 }, { lngs: ['csb', 'pl'], nr: [1, 2, 5], fc: 7 }, { lngs: ['cy'], nr: [1, 2, 3, 8], fc: 8 }, { lngs: ['fr'], nr: [1, 2], fc: 9 }, { lngs: ['ga'], nr: [1, 2, 3, 7, 11], fc: 10 }, { lngs: ['gd'], nr: [1, 2, 3, 20], fc: 11 }, { lngs: ['is'], nr: [1, 2], fc: 12 }, { lngs: ['jv'], nr: [0, 1], fc: 13 }, { lngs: ['kw'], nr: [1, 2, 3, 4], fc: 14 }, { lngs: ['lt'], nr: [1, 2, 10], fc: 15 }, { lngs: ['lv'], nr: [1, 2, 0], fc: 16 }, { lngs: ['mk'], nr: [1, 2], fc: 17 }, { lngs: ['mnk'], nr: [0, 1, 2], fc: 18 }, { lngs: ['mt'], nr: [1, 2, 11, 20], fc: 19 }, { lngs: ['or'], nr: [2, 1], fc: 2 }, { lngs: ['ro'], nr: [1, 2, 20], fc: 20 }, { lngs: ['sl'], nr: [5, 1, 2, 3], fc: 21 }, { lngs: ['he', 'iw'], nr: [1, 2, 20, 21], fc: 22 }]; let _rulesPluralsTypes = { 1: function (n) { return Number(n > 1); }, 2: function (n) { return Number(n != 1); }, 3: function (n) { return 0; }, 4: function (n) { return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2); }, 5: function (n) { return Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5); }, 6: function (n) { return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2); }, 7: function (n) { return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2); }, 8: function (n) { return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3); }, 9: function (n) { return Number(n >= 2); }, 10: function (n) { return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4); }, 11: function (n) { return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3); }, 12: function (n) { return Number(n % 10 != 1 || n % 100 == 11); }, 13: function (n) { return Number(n !== 0); }, 14: function (n) { return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3); }, 15: function (n) { return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2); }, 16: function (n) { return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2); }, 17: function (n) { return Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1); }, 18: function (n) { return Number(n == 0 ? 0 : n == 1 ? 1 : 2); }, 19: function (n) { return Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3); }, 20: function (n) { return Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2); }, 21: function (n) { return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0); }, 22: function (n) { return Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3); } }; const nonIntlVersions = ['v1', 'v2', 'v3']; const intlVersions = ['v4']; const suffixesOrder = { zero: 0, one: 1, two: 2, few: 3, many: 4, other: 5 }; function createRules() { const rules = {}; sets.forEach(set => { set.lngs.forEach(l => { rules[l] = { numbers: set.nr, plurals: _rulesPluralsTypes[set.fc] }; }); }); return rules; } class PluralResolver { constructor(languageUtils) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; this.languageUtils = languageUtils; this.options = options; this.logger = baseLogger.create('pluralResolver'); if ((!this.options.compatibilityJSON || intlVersions.includes(this.options.compatibilityJSON)) && (typeof Intl === 'undefined' || !Intl.PluralRules)) { this.options.compatibilityJSON = 'v3'; this.logger.error('Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.'); } this.rules = createRules(); } addRule(lng, obj) { this.rules[lng] = obj; } getRule(code) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (this.shouldUseIntlApi()) { try { return new Intl.PluralRules(getCleanedCode(code), { type: options.ordinal ? 'ordinal' : 'cardinal' }); } catch { return; } } return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)]; } needsPlural(code) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; const rule = this.getRule(code, options); if (this.shouldUseIntlApi()) { return rule && rule.resolvedOptions().pluralCategories.length > 1; } return rule && rule.numbers.length > 1; } getPluralFormsOfKey(code, key) { let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`); } getSuffixes(code) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; const rule = this.getRule(code, options); if (!rule) { return []; } if (this.shouldUseIntlApi()) { return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`); } return rule.numbers.map(number => this.getSuffix(code, number, options)); } getSuffix(code, count) { let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; const rule = this.getRule(code, options); if (rule) { if (this.shouldUseIntlApi()) { return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`; } return this.getSuffixRetroCompatible(rule, count); } this.logger.warn(`no plural rule found for: ${code}`); return ''; } getSuffixRetroCompatible(rule, count) { const idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count)); let suffix = rule.numbers[idx]; if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) { if (suffix === 2) { suffix = 'plural'; } else if (suffix === 1) { suffix = ''; } } const returnSuffix = () => this.options.prepend && suffix.toString() ? this.options.prepend + suffix.toString() : suffix.toString(); if (this.options.compatibilityJSON === 'v1') { if (suffix === 1) return ''; if (typeof suffix === 'number') return `_plural_${suffix.toString()}`; return returnSuffix(); } else if (this.options.compatibilityJSON === 'v2') { return returnSuffix(); } else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) { return returnSuffix(); } return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString(); } shouldUseIntlApi() { return !nonIntlVersions.includes(this.options.compatibilityJSON); } } function deepFindWithDefaults(data, defaultData, key) { let keySeparator = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '.'; let ignoreJSONStructure = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true; let path = getPathWithDefaults(data, defaultData, key); if (!path && ignoreJSONStructure && typeof key === 'string') { path = deepFind(data, key, keySeparator); if (path === undefined) path = deepFind(defaultData, key, keySeparator); } return path; } class Interpolator { constructor() { let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.logger = baseLogger.create('interpolator'); this.options = options; this.format = options.interpolation && options.interpolation.format || (value => value); this.init(options); } init() { let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!options.interpolation) options.interpolation = { escapeValue: true }; const iOpts = options.interpolation; this.escape = iOpts.escape !== undefined ? iOpts.escape : escape$1; this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true; this.useRawValueToEscape = iOpts.useRawValueToEscape !== undefined ? iOpts.useRawValueToEscape : false; this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{'; this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}'; this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ','; this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-'; this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || ''; this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape('$t('); this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(')'); this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ','; this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000; this.alwaysFormat = iOpts.alwaysFormat !== undefined ? iOpts.alwaysFormat : false; this.resetRegExp(); } reset() { if (this.options) this.init(this.options); } resetRegExp() { const regexpStr = `${this.prefix}(.+?)${this.suffix}`; this.regexp = new RegExp(regexpStr, 'g'); const regexpUnescapeStr = `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`; this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g'); const nestingRegexpStr = `${this.nestingPrefix}(.+?)${this.nestingSuffix}`; this.nestingRegexp = new RegExp(nestingRegexpStr, 'g'); } interpolate(str, data, lng, options) { let match; let value; let replaces; const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {}; function regexSafe(val) { return val.replace(/\$/g, '$$$$'); } const handleFormat = key => { if (key.indexOf(this.formatSeparator) < 0) { const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure); return this.alwaysFormat ? this.format(path, undefined, lng, { ...options, ...data, interpolationkey: key }) : path; } const p = key.split(this.formatSeparator); const k = p.shift().trim(); const f = p.join(this.formatSeparator).trim(); return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, { ...options, ...data, interpolationkey: k }); }; this.resetRegExp(); const missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler; const skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables; const todos = [{ regex: this.regexpUnescape, safeValue: val => regexSafe(val) }, { regex: this.regexp, safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val) }]; todos.forEach(todo => { replaces = 0; while (match = todo.regex.exec(str)) { const matchedVar = match[1].trim(); value = handleFormat(matchedVar); if (value === undefined) { if (typeof missingInterpolationHandler === 'function') { const temp = missingInterpolationHandler(str, match, options); value = typeof temp === 'string' ? temp : ''; } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) { value = ''; } else if (skipOnVariables) { value = match[0]; continue; } else { this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`); value = ''; } } else if (typeof value !== 'string' && !this.useRawValueToEscape) { value = makeString(value); } const safeValue = todo.safeValue(value); str = str.replace(match[0], safeValue); if (skipOnVariables) { todo.regex.lastIndex += value.length; todo.regex.lastIndex -= match[0].length; } else { todo.regex.lastIndex = 0; } replaces++; if (replaces >= this.maxReplaces) { break; } } }); return str; } nest(str, fc) { let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; let match; let value; let clonedOptions; function handleHasOptions(key, inheritedOptions) { const sep = this.nestingOptionsSeparator; if (key.indexOf(sep) < 0) return key; const c = key.split(new RegExp(`${sep}[ ]*{`)); let optionsString = `{${c[1]}`; key = c[0]; optionsString = this.interpolate(optionsString, clonedOptions); const matchedSingleQuotes = optionsString.match(/'/g); const matchedDoubleQuotes = optionsString.match(/"/g); if (matchedSingleQuotes && matchedSingleQuotes.length % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) { optionsString = optionsString.replace(/'/g, '"'); } try { clonedOptions = JSON.parse(optionsString); if (inheritedOptions) clonedOptions = { ...inheritedOptions, ...clonedOptions }; } catch (e) { this.logger.warn(`failed parsing options string in nesting for key ${key}`, e); return `${key}${sep}${optionsString}`; } delete clonedOptions.defaultValue; return key; } while (match = this.nestingRegexp.exec(str)) { let formatters = []; clonedOptions = { ...options }; clonedOptions = clonedOptions.replace && typeof clonedOptions.replace !== 'string' ? clonedOptions.replace : clonedOptions; clonedOptions.applyPostProcessor = false; delete clonedOptions.defaultValue; let doReduce = false; if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) { const r = match[1].split(this.formatSeparator).map(elem => elem.trim()); match[1] = r.shift(); formatters = r; doReduce = true; } value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions); if (value && match[0] === str && typeof value !== 'string') return value; if (typeof value !== 'string') value = makeString(value); if (!value) { this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`); value = ''; } if (doReduce) { value = formatters.reduce((v, f) => this.format(v, f, options.lng, { ...options, interpolationkey: match[1].trim() }), value.trim()); } str = str.replace(match[0], value); this.regexp.lastIndex = 0; } return str; } } function parseFormatStr(formatStr) { let formatName = formatStr.toLowerCase().trim(); const formatOptions = {}; if (formatStr.indexOf('(') > -1) { const p = formatStr.split('('); formatName = p[0].toLowerCase().trim(); const optStr = p[1].substring(0, p[1].length - 1); if (formatName === 'currency' && optStr.indexOf(':') < 0) { if (!formatOptions.currency) formatOptions.currency = optStr.trim(); } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) { if (!formatOptions.range) formatOptions.range = optStr.trim(); } else { const opts = optStr.split(';'); opts.forEach(opt => { if (!opt) return; const [key, ...rest] = opt.split(':'); const val = rest.join(':').trim().replace(/^'+|'+$/g, ''); if (!formatOptions[key.trim()]) formatOptions[key.trim()] = val; if (val === 'false') formatOptions[key.trim()] = false; if (val === 'true') formatOptions[key.trim()] = true; if (!isNaN(val)) formatOptions[key.trim()] = parseInt(val, 10); }); } } return { formatName, formatOptions }; } function createCachedFormatter(fn) { const cache = {}; return function invokeFormatter(val, lng, options) { const key = lng + JSON.stringify(options); let formatter = cache[key]; if (!formatter) { formatter = fn(getCleanedCode(lng), options); cache[key] = formatter; } return formatter(val); }; } let Formatter$1 = class Formatter { constructor() { let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.logger = baseLogger.create('formatter'); this.options = options; this.formats = { number: createCachedFormatter((lng, opt) => { const formatter = new Intl.NumberFormat(lng, { ...opt }); return val => formatter.format(val); }), currency: createCachedFormatter((lng, opt) => { const formatter = new Intl.NumberFormat(lng, { ...opt, style: 'currency' }); return val => formatter.format(val); }), datetime: createCachedFormatter((lng, opt) => { const formatter = new Intl.DateTimeFormat(lng, { ...opt }); return val => formatter.format(val); }), relativetime: createCachedFormatter((lng, opt) => { const formatter = new Intl.RelativeTimeFormat(lng, { ...opt }); return val => formatter.format(val, opt.range || 'day'); }), list: createCachedFormatter((lng, opt) => { const formatter = new Intl.ListFormat(lng, { ...opt }); return val => formatter.format(val); }) }; this.init(options); } init(services) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { interpolation: {} }; const iOpts = options.interpolation; this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ','; } add(name, fc) { this.formats[name.toLowerCase().trim()] = fc; } addCached(name, fc) { this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc); } format(value, format, lng) { let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; const formats = format.split(this.formatSeparator); const result = formats.reduce((mem, f) => { const { formatName, formatOptions } = parseFormatStr(f); if (this.formats[formatName]) { let formatted = mem; try { const valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {}; const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng; formatted = this.formats[formatName](mem, l, { ...formatOptions, ...options, ...valOptions }); } catch (error) { this.logger.warn(error); } return formatted; } else { this.logger.warn(`there was no format function for ${formatName}`); } return mem; }, value); return result; } }; function removePending(q, name) { if (q.pending[name] !== undefined) { delete q.pending[name]; q.pendingCount--; } } class Connector extends EventEmitter { constructor(backend, store, services) { let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; super(); this.backend = backend; this.store = store; this.services = services; this.languageUtils = services.languageUtils; this.options = options; this.logger = baseLogger.create('backendConnector'); this.waitingReads = []; this.maxParallelReads = options.maxParallelReads || 10; this.readingCalls = 0; this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5; this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350; this.state = {}; this.queue = []; if (this.backend && this.backend.init) { this.backend.init(services, options.backend, options); } } queueLoad(languages, namespaces, options, callback) { const toLoad = {}; const pending = {}; const toLoadLanguages = {}; const toLoadNamespaces = {}; languages.forEach(lng => { let hasAllNamespaces = true; namespaces.forEach(ns => { const name = `${lng}|${ns}`; if (!options.reload && this.store.hasResourceBundle(lng, ns)) { this.state[name] = 2; } else if (this.state[name] < 0) ; else if (this.state[name] === 1) { if (pending[name] === undefined) pending[name] = true; } else { this.state[name] = 1; hasAllNamespaces = false; if (pending[name] === undefined) pending[name] = true; if (toLoad[name] === undefined) toLoad[name] = true; if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true; } }); if (!hasAllNamespaces) toLoadLanguages[lng] = true; }); if (Object.keys(toLoad).length || Object.keys(pending).length) { this.queue.push({ pending, pendingCount: Object.keys(pending).length, loaded: {}, errors: [], callback }); } return { toLoad: Object.keys(toLoad), pending: Object.keys(pending), toLoadLanguages: Object.keys(toLoadLanguages), toLoadNamespaces: Object.keys(toLoadNamespaces) }; } loaded(name, err, data) { const s = name.split('|'); const lng = s[0]; const ns = s[1]; if (err) this.emit('failedLoading', lng, ns, err); if (data) { this.store.addResourceBundle(lng, ns, data); } this.state[name] = err ? -1 : 2; const loaded = {}; this.queue.forEach(q => { pushPath(q.loaded, [lng], ns); removePending(q, name); if (err) q.errors.push(err); if (q.pendingCount === 0 && !q.done) { Object.keys(q.loaded).forEach(l => { if (!loaded[l]) loaded[l] = {}; const loadedKeys = q.loaded[l]; if (loadedKeys.length) { loadedKeys.forEach(n => { if (loaded[l][n] === undefined) loaded[l][n] = true; }); } }); q.done = true; if (q.errors.length) { q.callback(q.errors); } else { q.callback(); } } }); this.emit('loaded', loaded); this.queue = this.queue.filter(q => !q.done); } read(lng, ns, fcName) { let tried = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; let wait = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : this.retryTimeout; let callback = arguments.length > 5 ? arguments[5] : undefined; if (!lng.length) return callback(null, {}); if (this.readingCalls >= this.maxParallelReads) { this.waitingReads.push({ lng, ns, fcName, tried, wait, callback }); return; } this.readingCalls++; const resolver = (err, data) => { this.readingCalls--; if (this.waitingReads.length > 0) { const next = this.waitingReads.shift(); this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback); } if (err && data && tried < this.maxRetries) { setTimeout(() => { this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback); }, wait); return; } callback(err, data); }; const fc = this.backend[fcName].bind(this.backend); if (fc.length === 2) { try { const r = fc(lng, ns); if (r && typeof r.then === 'function') { r.then(data => resolver(null, data)).catch(resolver); } else { resolver(null, r); } } catch (err) { resolver(err); } return; } return fc(lng, ns, resolver); } prepareLoading(languages, namespaces) { let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; let callback = arguments.length > 3 ? arguments[3] : undefined; if (!this.backend) { this.logger.warn('No backend was added via i18next.use. Will not load resources.'); return callback && callback(); } if (typeof languages === 'string') languages = this.languageUtils.toResolveHierarchy(languages); if (typeof namespaces === 'string') namespaces = [namespaces]; const toLoad = this.queueLoad(languages, namespaces, options, callback); if (!toLoad.toLoad.length) { if (!toLoad.pending.length) callback(); return null; } toLoad.toLoad.forEach(name => { this.loadOne(name); }); } load(languages, namespaces, callback) { this.prepareLoading(languages, namespaces, {}, callback); } reload(languages, namespaces, callback) { this.prepareLoading(languages, namespaces, { reload: true }, callback); } loadOne(name) { let prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; const s = name.split('|'); const lng = s[0]; const ns = s[1]; this.read(lng, ns, 'read', undefined, undefined, (err, data) => { if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err); if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data); this.loaded(name, err, data); }); } saveMissing(languages, namespace, key, fallbackValue, isUpdate) { let options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {}; let clb = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : () => {}; if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) { this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!'); return; } if (key === undefined || key === null || key === '') return; if (this.backend && this.backend.create) { const opts = { ...options, isUpdate }; const fc = this.backend.create.bind(this.backend); if (fc.length < 6) { try { let r; if (fc.length === 5) { r = fc(languages, namespace, key, fallbackValue, opts); } else { r = fc(languages, namespace, key, fallbackValue); } if (r && typeof r.then === 'function') { r.then(data => clb(null, data)).catch(clb); } else { clb(null, r); } } catch (err) { clb(err); } } else { fc(languages, namespace, key, fallbackValue, clb, opts); } } if (!languages || !languages[0]) return; this.store.addResource(languages[0], namespace, key, fallbackValue); } } function get$4() { return { debug: false, initImmediate: true, ns: ['translation'], defaultNS: ['translation'], fallbackLng: ['dev'], fallbackNS: false, supportedLngs: false, nonExplicitSupportedLngs: false, load: 'all', preload: false, simplifyPluralSuffix: true, keySeparator: '.', nsSeparator: ':', pluralSeparator: '_', contextSeparator: '_', partialBundledLanguages: false, saveMissing: false, updateMissing: false, saveMissingTo: 'fallback', saveMissingPlurals: true, missingKeyHandler: false, missingInterpolationHandler: false, postProcess: false, postProcessPassResolved: false, returnNull: false, returnEmptyString: true, returnObjects: false, joinArrays: false, returnedObjectHandler: false, parseMissingKeyHandler: false, appendNamespaceToMissingKey: false, appendNamespaceToCIMode: false, overloadTranslationOptionHandler: function handle(args) { let ret = {}; if (typeof args[1] === 'object') ret = args[1]; if (typeof args[1] === 'string') ret.defaultValue = args[1]; if (typeof args[2] === 'string') ret.tDescription = args[2]; if (typeof args[2] === 'object' || typeof args[3] === 'object') { const options = args[3] || args[2]; Object.keys(options).forEach(key => { ret[key] = options[key]; }); } return ret; }, interpolation: { escapeValue: true, format: (value, format, lng, options) => value, prefix: '{{', suffix: '}}', formatSeparator: ',', unescapePrefix: '-', nestingPrefix: '$t(', nestingSuffix: ')', nestingOptionsSeparator: ',', maxReplaces: 1000, skipOnVariables: true } }; } function transformOptions(options) { if (typeof options.ns === 'string') options.ns = [options.ns]; if (typeof options.fallbackLng === 'string') options.fallbackLng = [options.fallbackLng]; if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS]; if (options.supportedLngs && options.supportedLngs.indexOf('cimode') < 0) { options.supportedLngs = options.supportedLngs.concat(['cimode']); } return options; } function noop$1() {} function bindMemberFunctions(inst) { const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst)); mems.forEach(mem => { if (typeof inst[mem] === 'function') { inst[mem] = inst[mem].bind(inst); } }); } class I18n extends EventEmitter { constructor() { let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; let callback = arguments.length > 1 ? arguments[1] : undefined; super(); this.options = transformOptions(options); this.services = {}; this.logger = baseLogger; this.modules = { external: [] }; bindMemberFunctions(this); if (callback && !this.isInitialized && !options.isClone) { if (!this.options.initImmediate) { this.init(options, callback); return this; } setTimeout(() => { this.init(options, callback); }, 0); } } init() { var _this = this; let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; let callback = arguments.length > 1 ? arguments[1] : undefined; if (typeof options === 'function') { callback = options; options = {}; } if (!options.defaultNS && options.defaultNS !== false && options.ns) { if (typeof options.ns === 'string') { options.defaultNS = options.ns; } else if (options.ns.indexOf('translation') < 0) { options.defaultNS = options.ns[0]; } } const defOpts = get$4(); this.options = { ...defOpts, ...this.options, ...transformOptions(options) }; if (this.options.compatibilityAPI !== 'v1') { this.options.interpolation = { ...defOpts.interpolation, ...this.options.interpolation }; } if (options.keySeparator !== undefined) { this.options.userDefinedKeySeparator = options.keySeparator; } if (options.nsSeparator !== undefined) { this.options.userDefinedNsSeparator = options.nsSeparator; } function createClassOnDemand(ClassOrObject) { if (!ClassOrObject) return null; if (typeof ClassOrObject === 'function') return new ClassOrObject(); return ClassOrObject; } if (!this.options.isClone) { if (this.modules.logger) { baseLogger.init(createClassOnDemand(this.modules.logger), this.options); } else { baseLogger.init(null, this.options); } let formatter; if (this.modules.formatter) { formatter = this.modules.formatter; } else if (typeof Intl !== 'undefined') { formatter = Formatter$1; } const lu = new LanguageUtil(this.options); this.store = new ResourceStore(this.options.resources, this.options); const s = this.services; s.logger = baseLogger; s.resourceStore = this.store; s.languageUtils = lu; s.pluralResolver = new PluralResolver(lu, { prepend: this.options.pluralSeparator, compatibilityJSON: this.options.compatibilityJSON, simplifyPluralSuffix: this.options.simplifyPluralSuffix }); if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) { s.formatter = createClassOnDemand(formatter); s.formatter.init(s, this.options); this.options.interpolation.format = s.formatter.format.bind(s.formatter); } s.interpolator = new Interpolator(this.options); s.utils = { hasLoadedNamespace: this.hasLoadedNamespace.bind(this) }; s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options); s.backendConnector.on('*', function (event) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } _this.emit(event, ...args); }); if (this.modules.languageDetector) { s.languageDetector = createClassOnDemand(this.modules.languageDetector); if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options); } if (this.modules.i18nFormat) { s.i18nFormat = createClassOnDemand(this.modules.i18nFormat); if (s.i18nFormat.init) s.i18nFormat.init(this); } this.translator = new Translator(this.services, this.options); this.translator.on('*', function (event) { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } _this.emit(event, ...args); }); this.modules.external.forEach(m => { if (m.init) m.init(this); }); } this.format = this.options.interpolation.format; if (!callback) callback = noop$1; if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) { const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng); if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0]; } if (!this.services.languageDetector && !this.options.lng) { this.logger.warn('init: no languageDetector is used and no lng is defined'); } const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage']; storeApi.forEach(fcName => { this[fcName] = function () { return _this.store[fcName](...arguments); }; }); const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle']; storeApiChained.forEach(fcName => { this[fcName] = function () { _this.store[fcName](...arguments); return _this; }; }); const deferred = defer(); const load = () => { const finish = (err, t) => { if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!'); this.isInitialized = true; if (!this.options.isClone) this.logger.log('initialized', this.options); this.emit('initialized', this.options); deferred.resolve(t); callback(err, t); }; if (this.languages && this.options.compatibilityAPI !== 'v1' && !this.isInitialized) return finish(null, this.t.bind(this)); this.changeLanguage(this.options.lng, finish); }; if (this.options.resources || !this.options.initImmediate) { load(); } else { setTimeout(load, 0); } return deferred; } loadResources(language) { let callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop$1; let usedCallback = callback; const usedLng = typeof language === 'string' ? language : this.language; if (typeof language === 'function') usedCallback = language; if (!this.options.resources || this.options.partialBundledLanguages) { if (usedLng && usedLng.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback(); const toLoad = []; const append = lng => { if (!lng) return; if (lng === 'cimode') return; const lngs = this.services.languageUtils.toResolveHierarchy(lng); lngs.forEach(l => { if (l === 'cimode') return; if (toLoad.indexOf(l) < 0) toLoad.push(l); }); }; if (!usedLng) { const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng); fallbacks.forEach(l => append(l)); } else { append(usedLng); } if (this.options.preload) { this.options.preload.forEach(l => append(l)); } this.services.backendConnector.load(toLoad, this.options.ns, e => { if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language); usedCallback(e); }); } else { usedCallback(null); } } reloadResources(lngs, ns, callback) { const deferred = defer(); if (!lngs) lngs = this.languages; if (!ns) ns = this.options.ns; if (!callback) callback = noop$1; this.services.backendConnector.reload(lngs, ns, err => { deferred.resolve(); callback(err); }); return deferred; } use(module) { if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()'); if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()'); if (module.type === 'backend') { this.modules.backend = module; } if (module.type === 'logger' || module.log && module.warn && module.error) { this.modules.logger = module; } if (module.type === 'languageDetector') { this.modules.languageDetector = module; } if (module.type === 'i18nFormat') { this.modules.i18nFormat = module; } if (module.type === 'postProcessor') { postProcessor.addPostProcessor(module); } if (module.type === 'formatter') { this.modules.formatter = module; } if (module.type === '3rdParty') { this.modules.external.push(module); } return this; } setResolvedLanguage(l) { if (!l || !this.languages) return; if (['cimode', 'dev'].indexOf(l) > -1) return; for (let li = 0; li < this.languages.length; li++) { const lngInLngs = this.languages[li]; if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue; if (this.store.hasLanguageSomeTranslations(lngInLngs)) { this.resolvedLanguage = lngInLngs; break; } } } changeLanguage(lng, callback) { var _this2 = this; this.isLanguageChangingTo = lng; const deferred = defer(); this.emit('languageChanging', lng); const setLngProps = l => { this.language = l; this.languages = this.services.languageUtils.toResolveHierarchy(l); this.resolvedLanguage = undefined; this.setResolvedLanguage(l); }; const done = (err, l) => { if (l) { setLngProps(l); this.translator.changeLanguage(l); this.isLanguageChangingTo = undefined; this.emit('languageChanged', l); this.logger.log('languageChanged', l); } else { this.isLanguageChangingTo = undefined; } deferred.resolve(function () { return _this2.t(...arguments); }); if (callback) callback(err, function () { return _this2.t(...arguments); }); }; const setLng = lngs => { if (!lng && !lngs && this.services.languageDetector) lngs = []; const l = typeof lngs === 'string' ? lngs : this.services.languageUtils.getBestMatchFromCodes(lngs); if (l) { if (!this.language) { setLngProps(l); } if (!this.translator.language) this.translator.changeLanguage(l); if (this.services.languageDetector && this.services.languageDetector.cacheUserLanguage) this.services.languageDetector.cacheUserLanguage(l); } this.loadResources(l, err => { done(err, l); }); }; if (!lng && this.services.languageDetector && !this.services.languageDetector.async) { setLng(this.services.languageDetector.detect()); } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) { if (this.services.languageDetector.detect.length === 0) { this.services.languageDetector.detect().then(setLng); } else { this.services.languageDetector.detect(setLng); } } else { setLng(lng); } return deferred; } getFixedT(lng, ns, keyPrefix) { var _this3 = this; const fixedT = function (key, opts) { let options; if (typeof opts !== 'object') { for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { rest[_key3 - 2] = arguments[_key3]; } options = _this3.options.overloadTranslationOptionHandler([key, opts].concat(rest)); } else { options = { ...opts }; } options.lng = options.lng || fixedT.lng; options.lngs = options.lngs || fixedT.lngs; options.ns = options.ns || fixedT.ns; options.keyPrefix = options.keyPrefix || keyPrefix || fixedT.keyPrefix; const keySeparator = _this3.options.keySeparator || '.'; let resultKey; if (options.keyPrefix && Array.isArray(key)) { resultKey = key.map(k => `${options.keyPrefix}${keySeparator}${k}`); } else { resultKey = options.keyPrefix ? `${options.keyPrefix}${keySeparator}${key}` : key; } return _this3.t(resultKey, options); }; if (typeof lng === 'string') { fixedT.lng = lng; } else { fixedT.lngs = lng; } fixedT.ns = ns; fixedT.keyPrefix = keyPrefix; return fixedT; } t() { return this.translator && this.translator.translate(...arguments); } exists() { return this.translator && this.translator.exists(...arguments); } setDefaultNamespace(ns) { this.options.defaultNS = ns; } hasLoadedNamespace(ns) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (!this.isInitialized) { this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages); return false; } if (!this.languages || !this.languages.length) { this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages); return false; } const lng = options.lng || this.resolvedLanguage || this.languages[0]; const fallbackLng = this.options ? this.options.fallbackLng : false; const lastLng = this.languages[this.languages.length - 1]; if (lng.toLowerCase() === 'cimode') return true; const loadNotPending = (l, n) => { const loadState = this.services.backendConnector.state[`${l}|${n}`]; return loadState === -1 || loadState === 2; }; if (options.precheck) { const preResult = options.precheck(this, loadNotPending); if (preResult !== undefined) return preResult; } if (this.hasResourceBundle(lng, ns)) return true; if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true; if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true; return false; } loadNamespaces(ns, callback) { const deferred = defer(); if (!this.options.ns) { if (callback) callback(); return Promise.resolve(); } if (typeof ns === 'string') ns = [ns]; ns.forEach(n => { if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n); }); this.loadResources(err => { deferred.resolve(); if (callback) callback(err); }); return deferred; } loadLanguages(lngs, callback) { const deferred = defer(); if (typeof lngs === 'string') lngs = [lngs]; const preloaded = this.options.preload || []; const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0); if (!newLngs.length) { if (callback) callback(); return Promise.resolve(); } this.options.preload = preloaded.concat(newLngs); this.loadResources(err => { deferred.resolve(); if (callback) callback(err); }); return deferred; } dir(lng) { if (!lng) lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language); if (!lng) return 'rtl'; const rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb']; const languageUtils = this.services && this.services.languageUtils || new LanguageUtil(get$4()); return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr'; } static createInstance() { let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; let callback = arguments.length > 1 ? arguments[1] : undefined; return new I18n(options, callback); } cloneInstance() { let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; let callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop$1; const forkResourceStore = options.forkResourceStore; if (forkResourceStore) delete options.forkResourceStore; const mergedOptions = { ...this.options, ...options, ...{ isClone: true } }; const clone = new I18n(mergedOptions); if (options.debug !== undefined || options.prefix !== undefined) { clone.logger = clone.logger.clone(options); } const membersToCopy = ['store', 'services', 'language']; membersToCopy.forEach(m => { clone[m] = this[m]; }); clone.services = { ...this.services }; clone.services.utils = { hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone) }; if (forkResourceStore) { clone.store = new ResourceStore(this.store.data, mergedOptions); clone.services.resourceStore = clone.store; } clone.translator = new Translator(clone.services, mergedOptions); clone.translator.on('*', function (event) { for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { args[_key4 - 1] = arguments[_key4]; } clone.emit(event, ...args); }); clone.init(mergedOptions, callback); clone.translator.options = mergedOptions; clone.translator.backendConnector.services.utils = { hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone) }; return clone; } toJSON() { return { options: this.options, store: this.store, language: this.language, languages: this.languages, resolvedLanguage: this.resolvedLanguage }; } } const instance = I18n.createInstance(); instance.createInstance = I18n.createInstance; instance.createInstance; instance.dir; instance.init; instance.loadResources; instance.reloadResources; instance.use; instance.changeLanguage; instance.getFixedT; const t$b = instance.t; instance.exists; instance.setDefaultNamespace; instance.hasLoadedNamespace; instance.loadNamespaces; instance.loadLanguages; var isCheckBoxInput = (element) => element.type === 'checkbox'; var isDateObject = (value) => value instanceof Date; var isNullOrUndefined = (value) => value == null; const isObjectType = (value) => typeof value === 'object'; var isObject$1 = (value) => !isNullOrUndefined(value) && !Array.isArray(value) && isObjectType(value) && !isDateObject(value); var getEventValue = (event) => isObject$1(event) && event.target ? isCheckBoxInput(event.target) ? event.target.checked : event.target.value : event; var getNodeParentName = (name) => name.substring(0, name.search(/.\d/)) || name; var isNameInFieldArray = (names, name) => [...names].some((current) => getNodeParentName(name) === current); var compact = (value) => value.filter(Boolean); var isUndefined$2 = (val) => val === undefined; var get$3 = (obj, path, defaultValue) => { if (!path || !isObject$1(obj)) { return defaultValue; } const result = compact(path.split(/[,[\].]+?/)).reduce((result, key) => isNullOrUndefined(result) ? result : result[key], obj); return isUndefined$2(result) || result === obj ? isUndefined$2(obj[path]) ? defaultValue : obj[path] : result; }; const EVENTS = { BLUR: 'blur', FOCUS_OUT: 'focusout', CHANGE: 'change', }; const VALIDATION_MODE = { onBlur: 'onBlur', onChange: 'onChange', onSubmit: 'onSubmit', onTouched: 'onTouched', all: 'all', }; const INPUT_VALIDATION_RULES = { max: 'max', min: 'min', maxLength: 'maxLength', minLength: 'minLength', pattern: 'pattern', required: 'required', validate: 'validate', }; var omit = (source, key) => { const copy = Object.assign({}, source); delete copy[key]; return copy; }; const HookFormContext = React$1.createContext(null); const useFormContext = () => React$1.useContext(HookFormContext); var getProxyFormState = (formState, _proxyFormState, localProxyFormState, isRoot = true) => { const result = {}; for (const key in formState) { Object.defineProperty(result, key, { get: () => { const _key = key; if (_proxyFormState[_key] !== VALIDATION_MODE.all) { _proxyFormState[_key] = !isRoot || VALIDATION_MODE.all; } localProxyFormState && (localProxyFormState[_key] = true); return formState[_key]; }, }); } return result; }; var isEmptyObject = (value) => isObject$1(value) && !Object.keys(value).length; var shouldRenderFormState = (formStateData, _proxyFormState, isRoot) => { const formState = omit(formStateData, 'name'); return (isEmptyObject(formState) || Object.keys(formState).length >= Object.keys(_proxyFormState).length || Object.keys(formState).find((key) => _proxyFormState[key] === (!isRoot || VALIDATION_MODE.all))); }; var convertToArrayPayload = (value) => (Array.isArray(value) ? value : [value]); var shouldSubscribeByName = (name, signalName, exact) => exact && signalName ? name === signalName : !name || !signalName || name === signalName || convertToArrayPayload(name).some((currentName) => currentName && (currentName.startsWith(signalName) || signalName.startsWith(currentName))); function useSubscribe(props) { const _props = React$1.useRef(props); _props.current = props; React$1.useEffect(() => { const tearDown = (subscription) => { if (subscription) { subscription.unsubscribe(); } }; const subscription = !props.disabled && _props.current.subject.subscribe({ next: _props.current.callback, }); return () => tearDown(subscription); }, [props.disabled]); } function useFormState(props) { const methods = useFormContext(); const { control = methods.control, disabled, name, exact } = props || {}; const [formState, updateFormState] = React$1.useState(control._formState); const _localProxyFormState = React$1.useRef({ isDirty: false, dirtyFields: false, touchedFields: false, isValidating: false, isValid: false, errors: false, }); const _name = React$1.useRef(name); const _mounted = React$1.useRef(true); _name.current = name; const callback = React$1.useCallback((value) => _mounted.current && shouldSubscribeByName(_name.current, value.name, exact) && shouldRenderFormState(value, _localProxyFormState.current) && updateFormState(Object.assign(Object.assign({}, control._formState), value)), [control, exact]); useSubscribe({ disabled, callback, subject: control._subjects.state, }); React$1.useEffect(() => () => { _mounted.current = false; }, []); return getProxyFormState(formState, control._proxyFormState, _localProxyFormState.current, false); } var isString$3 = (value) => typeof value === 'string'; var generateWatchOutput = (names, _names, formValues, isGlobal) => { const isArray = Array.isArray(names); if (isString$3(names)) { isGlobal && _names.watch.add(names); return get$3(formValues, names); } if (isArray) { return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get$3(formValues, fieldName))); } isGlobal && (_names.watchAll = true); return formValues; }; var isFunction$2 = (value) => typeof value === 'function'; var objectHasFunction = (data) => { for (const key in data) { if (isFunction$2(data[key])) { return true; } } return false; }; function useWatch(props) { const methods = useFormContext(); const { control = methods.control, name, defaultValue, disabled, exact, } = props || {}; const _name = React$1.useRef(name); _name.current = name; const callback = React$1.useCallback((formState) => { if (shouldSubscribeByName(_name.current, formState.name, exact)) { const fieldValues = generateWatchOutput(_name.current, control._names, formState.values || control._formValues); updateValue(isUndefined$2(_name.current) || (isObject$1(fieldValues) && !objectHasFunction(fieldValues)) ? Object.assign({}, fieldValues) : Array.isArray(fieldValues) ? [...fieldValues] : isUndefined$2(fieldValues) ? defaultValue : fieldValues); } }, [control, exact, defaultValue]); useSubscribe({ disabled, subject: control._subjects.watch, callback, }); const [value, updateValue] = React$1.useState(isUndefined$2(defaultValue) ? control._getWatch(name) : defaultValue); React$1.useEffect(() => { control._removeUnmounted(); }); return value; } function useController(props) { const methods = useFormContext(); const { name, control = methods.control, shouldUnregister } = props; const isArrayField = isNameInFieldArray(control._names.array, name); const value = useWatch({ control, name, defaultValue: get$3(control._formValues, name, get$3(control._defaultValues, name, props.defaultValue)), exact: !isArrayField, }); const formState = useFormState({ control, name, }); const _registerProps = React$1.useRef(control.register(name, Object.assign(Object.assign({}, props.rules), { value }))); React$1.useEffect(() => { const updateMounted = (name, value) => { const field = get$3(control._fields, name); if (field) { field._f.mount = value; } }; updateMounted(name, true); return () => { const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister; (isArrayField ? _shouldUnregisterField && !control._stateFlags.action : _shouldUnregisterField) ? control.unregister(name) : updateMounted(name, false); }; }, [name, control, isArrayField, shouldUnregister]); return { field: { name, value, onChange: React$1.useCallback((event) => { _registerProps.current.onChange({ target: { value: getEventValue(event), name: name, }, type: EVENTS.CHANGE, }); }, [name]), onBlur: React$1.useCallback(() => { _registerProps.current.onBlur({ target: { value: get$3(control._formValues, name), name: name, }, type: EVENTS.BLUR, }); }, [name, control]), ref: React$1.useCallback((elm) => { const field = get$3(control._fields, name); if (elm && field && elm.focus) { field._f.ref = { focus: () => elm.focus(), setCustomValidity: (message) => elm.setCustomValidity(message), reportValidity: () => elm.reportValidity(), }; } }, [name, control._fields]), }, formState, fieldState: control.getFieldState(name, formState), }; } const Controller = (props) => props.render(useController(props)); var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria ? Object.assign(Object.assign({}, errors[name]), { types: Object.assign(Object.assign({}, (errors[name] && errors[name].types ? errors[name].types : {})), { [type]: message || true }) }) : {}; var isKey = (value) => /^\w*$/.test(value); var stringToPath = (input) => compact(input.replace(/["|']|\]/g, '').split(/\.|\[/)); function set(object, path, value) { let index = -1; const tempPath = isKey(path) ? [path] : stringToPath(path); const length = tempPath.length; const lastIndex = length - 1; while (++index < length) { const key = tempPath[index]; let newValue = value; if (index !== lastIndex) { const objValue = object[key]; newValue = isObject$1(objValue) || Array.isArray(objValue) ? objValue : !isNaN(+tempPath[index + 1]) ? [] : {}; } object[key] = newValue; object = object[key]; } return object; } const focusFieldBy = (fields, callback, fieldsNames) => { for (const key of fieldsNames || Object.keys(fields)) { const field = get$3(fields, key); if (field) { const _f = field._f; const current = omit(field, '_f'); if (_f && callback(_f.name)) { if (_f.ref.focus && isUndefined$2(_f.ref.focus())) { break; } else if (_f.refs) { _f.refs[0].focus(); break; } } else if (isObject$1(current)) { focusFieldBy(current, callback); } } } }; var isWatched = (name, _names, isBlurEvent) => !isBlurEvent && (_names.watchAll || _names.watch.has(name) || [..._names.watch].some((watchName) => name.startsWith(watchName) && /^\.\w+/.test(name.slice(watchName.length)))); function cloneObject(data) { let copy; const isArray = Array.isArray(data); if (data instanceof Date) { copy = new Date(data); } else if (data instanceof Set) { copy = new Set(data); } else if (isArray || isObject$1(data)) { copy = isArray ? [] : {}; for (const key in data) { if (isFunction$2(data[key])) { copy = data; break; } copy[key] = cloneObject(data[key]); } } else { return data; } return copy; } function createSubject() { let _observers = []; const next = (value) => { for (const observer of _observers) { observer.next(value); } }; const subscribe = (observer) => { _observers.push(observer); return { unsubscribe: () => { _observers = _observers.filter((o) => o !== observer); }, }; }; const unsubscribe = () => { _observers = []; }; return { get observers() { return _observers; }, next, subscribe, unsubscribe, }; } var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value); function deepEqual$1(object1, object2) { if (isPrimitive(object1) || isPrimitive(object2)) { return object1 === object2; } if (isDateObject(object1) && isDateObject(object2)) { return object1.getTime() === object2.getTime(); } const keys1 = Object.keys(object1); const keys2 = Object.keys(object2); if (keys1.length !== keys2.length) { return false; } for (const key of keys1) { const val1 = object1[key]; if (!keys2.includes(key)) { return false; } if (key !== 'ref') { const val2 = object2[key]; if ((isDateObject(val1) && isDateObject(val2)) || (isObject$1(val1) && isObject$1(val2)) || (Array.isArray(val1) && Array.isArray(val2)) ? !deepEqual$1(val1, val2) : val1 !== val2) { return false; } } } return true; } var getValidationModes = (mode) => ({ isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit, isOnBlur: mode === VALIDATION_MODE.onBlur, isOnChange: mode === VALIDATION_MODE.onChange, isOnAll: mode === VALIDATION_MODE.all, isOnTouch: mode === VALIDATION_MODE.onTouched, }); var isBoolean = (value) => typeof value === 'boolean'; var isFileInput = (element) => element.type === 'file'; var isHTMLElement = (value) => value instanceof HTMLElement; var isMultipleSelect = (element) => element.type === `select-multiple`; var isRadioInput = (element) => element.type === 'radio'; var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref); var isWeb = typeof window !== 'undefined' && typeof window.HTMLElement !== 'undefined' && typeof document !== 'undefined'; var live = (ref) => isHTMLElement(ref) && ref.isConnected; function baseGet(object, updatePath) { const length = updatePath.slice(0, -1).length; let index = 0; while (index < length) { object = isUndefined$2(object) ? index++ : object[updatePath[index++]]; } return object; } function unset(object, path) { const updatePath = isKey(path) ? [path] : stringToPath(path); const childObject = updatePath.length == 1 ? object : baseGet(object, updatePath); const key = updatePath[updatePath.length - 1]; let previousObjRef; if (childObject) { delete childObject[key]; } for (let k = 0; k < updatePath.slice(0, -1).length; k++) { let index = -1; let objectRef; const currentPaths = updatePath.slice(0, -(k + 1)); const currentPathsLength = currentPaths.length - 1; if (k > 0) { previousObjRef = object; } while (++index < currentPaths.length) { const item = currentPaths[index]; objectRef = objectRef ? objectRef[item] : object[item]; if (currentPathsLength === index && ((isObject$1(objectRef) && isEmptyObject(objectRef)) || (Array.isArray(objectRef) && !objectRef.filter((data) => (isObject$1(data) && !isEmptyObject(data)) || isBoolean(data)).length))) { previousObjRef ? delete previousObjRef[item] : delete object[item]; } previousObjRef = objectRef; } } return object; } function markFieldsDirty(data, fields = {}) { const isParentNodeArray = Array.isArray(data); if (isObject$1(data) || isParentNodeArray) { for (const key in data) { if (Array.isArray(data[key]) || (isObject$1(data[key]) && !objectHasFunction(data[key]))) { fields[key] = Array.isArray(data[key]) ? [] : {}; markFieldsDirty(data[key], fields[key]); } else if (!isNullOrUndefined(data[key])) { fields[key] = true; } } } return fields; } function getDirtyFieldsFromDefaultValues(data, formValues, dirtyFieldsFromValues) { const isParentNodeArray = Array.isArray(data); if (isObject$1(data) || isParentNodeArray) { for (const key in data) { if (Array.isArray(data[key]) || (isObject$1(data[key]) && !objectHasFunction(data[key]))) { if (isUndefined$2(formValues) || isPrimitive(dirtyFieldsFromValues[key])) { dirtyFieldsFromValues[key] = Array.isArray(data[key]) ? markFieldsDirty(data[key], []) : Object.assign({}, markFieldsDirty(data[key])); } else { getDirtyFieldsFromDefaultValues(data[key], isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]); } } else { dirtyFieldsFromValues[key] = !deepEqual$1(data[key], formValues[key]); } } } return dirtyFieldsFromValues; } var getDirtyFields = (defaultValues, formValues) => getDirtyFieldsFromDefaultValues(defaultValues, formValues, markFieldsDirty(formValues)); const defaultResult = { value: false, isValid: false, }; const validResult = { value: true, isValid: true }; var getCheckboxValue = (options) => { if (Array.isArray(options)) { if (options.length > 1) { const values = options .filter((option) => option && option.checked && !option.disabled) .map((option) => option.value); return { value: values, isValid: !!values.length }; } return options[0].checked && !options[0].disabled ? // @ts-expect-error expected to work in the browser options[0].attributes && !isUndefined$2(options[0].attributes.value) ? isUndefined$2(options[0].value) || options[0].value === '' ? validResult : { value: options[0].value, isValid: true } : validResult : defaultResult; } return defaultResult; }; var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined$2(value) ? value : valueAsNumber ? value === '' ? NaN : +value : valueAsDate && isString$3(value) ? new Date(value) : setValueAs ? setValueAs(value) : value; const defaultReturn = { isValid: false, value: null, }; var getRadioValue = (options) => Array.isArray(options) ? options.reduce((previous, option) => option && option.checked && !option.disabled ? { isValid: true, value: option.value, } : previous, defaultReturn) : defaultReturn; function getFieldValue(_f) { const ref = _f.ref; if (_f.refs ? _f.refs.every((ref) => ref.disabled) : ref.disabled) { return; } if (isFileInput(ref)) { return ref.files; } if (isRadioInput(ref)) { return getRadioValue(_f.refs).value; } if (isMultipleSelect(ref)) { return [...ref.selectedOptions].map(({ value }) => value); } if (isCheckBoxInput(ref)) { return getCheckboxValue(_f.refs).value; } return getFieldValueAs(isUndefined$2(ref.value) ? _f.ref.value : ref.value, _f); } var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => { const fields = {}; for (const name of fieldsNames) { const field = get$3(_fields, name); field && set(fields, name, field._f); } return { criteriaMode, names: [...fieldsNames], fields, shouldUseNativeValidation, }; }; var isRegex = (value) => value instanceof RegExp; var getRuleValue = (rule) => isUndefined$2(rule) ? undefined : isRegex(rule) ? rule.source : isObject$1(rule) ? isRegex(rule.value) ? rule.value.source : rule.value : rule; var hasValidation = (options) => options.mount && (options.required || options.min || options.max || options.maxLength || options.minLength || options.pattern || options.validate); function schemaErrorLookup(errors, _fields, name) { const error = get$3(errors, name); if (error || isKey(name)) { return { error, name, }; } const names = name.split('.'); while (names.length) { const fieldName = names.join('.'); const field = get$3(_fields, fieldName); const foundError = get$3(errors, fieldName); if (field && !Array.isArray(field) && name !== fieldName) { return { name }; } if (foundError && foundError.type) { return { name: fieldName, error: foundError, }; } names.pop(); } return { name, }; } var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => { if (mode.isOnAll) { return false; } else if (!isSubmitted && mode.isOnTouch) { return !(isTouched || isBlurEvent); } else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) { return !isBlurEvent; } else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) { return isBlurEvent; } return true; }; var unsetEmptyArray = (ref, name) => !compact(get$3(ref, name)).length && unset(ref, name); var isMessage = (value) => isString$3(value) || React$1.isValidElement(value); function getValidateError(result, ref, type = 'validate') { if (isMessage(result) || (Array.isArray(result) && result.every(isMessage)) || (isBoolean(result) && !result)) { return { type, message: isMessage(result) ? result : '', ref, }; } } var getValueAndMessage = (validationData) => isObject$1(validationData) && !isRegex(validationData) ? validationData : { value: validationData, message: '', }; var validateField = async (field, inputValue, validateAllFieldCriteria, shouldUseNativeValidation) => { const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, disabled, } = field._f; if (!mount || disabled) { return {}; } const inputRef = refs ? refs[0] : ref; const setCustomValidity = (message) => { if (shouldUseNativeValidation && inputRef.reportValidity) { inputRef.setCustomValidity(isBoolean(message) ? '' : message || ' '); inputRef.reportValidity(); } }; const error = {}; const isRadio = isRadioInput(ref); const isCheckBox = isCheckBoxInput(ref); const isRadioOrCheckbox = isRadio || isCheckBox; const isEmpty = ((valueAsNumber || isFileInput(ref)) && !ref.value) || inputValue === '' || (Array.isArray(inputValue) && !inputValue.length); const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error); const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => { const message = exceedMax ? maxLengthMessage : minLengthMessage; error[name] = Object.assign({ type: exceedMax ? maxType : minType, message, ref }, appendErrorsCurry(exceedMax ? maxType : minType, message)); }; if (required && ((!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue))) || (isBoolean(inputValue) && !inputValue) || (isCheckBox && !getCheckboxValue(refs).isValid) || (isRadio && !getRadioValue(refs).isValid))) { const { value, message } = isMessage(required) ? { value: !!required, message: required } : getValueAndMessage(required); if (value) { error[name] = Object.assign({ type: INPUT_VALIDATION_RULES.required, message, ref: inputRef }, appendErrorsCurry(INPUT_VALIDATION_RULES.required, message)); if (!validateAllFieldCriteria) { setCustomValidity(message); return error; } } } if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) { let exceedMax; let exceedMin; const maxOutput = getValueAndMessage(max); const minOutput = getValueAndMessage(min); if (!isNaN(inputValue)) { const valueNumber = ref.valueAsNumber || parseFloat(inputValue); if (!isNullOrUndefined(maxOutput.value)) { exceedMax = valueNumber > maxOutput.value; } if (!isNullOrUndefined(minOutput.value)) { exceedMin = valueNumber < minOutput.value; } } else { const valueDate = ref.valueAsDate || new Date(inputValue); if (isString$3(maxOutput.value)) { exceedMax = valueDate > new Date(maxOutput.value); } if (isString$3(minOutput.value)) { exceedMin = valueDate < new Date(minOutput.value); } } if (exceedMax || exceedMin) { getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min); if (!validateAllFieldCriteria) { setCustomValidity(error[name].message); return error; } } } if ((maxLength || minLength) && !isEmpty && isString$3(inputValue)) { const maxLengthOutput = getValueAndMessage(maxLength); const minLengthOutput = getValueAndMessage(minLength); const exceedMax = !isNullOrUndefined(maxLengthOutput.value) && inputValue.length > maxLengthOutput.value; const exceedMin = !isNullOrUndefined(minLengthOutput.value) && inputValue.length < minLengthOutput.value; if (exceedMax || exceedMin) { getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message); if (!validateAllFieldCriteria) { setCustomValidity(error[name].message); return error; } } } if (pattern && !isEmpty && isString$3(inputValue)) { const { value: patternValue, message } = getValueAndMessage(pattern); if (isRegex(patternValue) && !inputValue.match(patternValue)) { error[name] = Object.assign({ type: INPUT_VALIDATION_RULES.pattern, message, ref }, appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message)); if (!validateAllFieldCriteria) { setCustomValidity(message); return error; } } } if (validate) { if (isFunction$2(validate)) { const result = await validate(inputValue); const validateError = getValidateError(result, inputRef); if (validateError) { error[name] = Object.assign(Object.assign({}, validateError), appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message)); if (!validateAllFieldCriteria) { setCustomValidity(validateError.message); return error; } } } else if (isObject$1(validate)) { let validationResult = {}; for (const key in validate) { if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) { break; } const validateError = getValidateError(await validate[key](inputValue), inputRef, key); if (validateError) { validationResult = Object.assign(Object.assign({}, validateError), appendErrorsCurry(key, validateError.message)); setCustomValidity(validateError.message); if (validateAllFieldCriteria) { error[name] = validationResult; } } } if (!isEmptyObject(validationResult)) { error[name] = Object.assign({ ref: inputRef }, validationResult); if (!validateAllFieldCriteria) { return error; } } } } setCustomValidity(true); return error; }; const defaultOptions$1 = { mode: VALIDATION_MODE.onSubmit, reValidateMode: VALIDATION_MODE.onChange, shouldFocusError: true, }; function createFormControl(props = {}) { let _options = Object.assign(Object.assign({}, defaultOptions$1), props); let _formState = { isDirty: false, isValidating: false, dirtyFields: {}, isSubmitted: false, submitCount: 0, touchedFields: {}, isSubmitting: false, isSubmitSuccessful: false, isValid: false, errors: {}, }; let _fields = {}; let _defaultValues = _options.defaultValues || {}; let _formValues = _options.shouldUnregister ? {} : cloneObject(_defaultValues); let _stateFlags = { action: false, mount: false, watch: false, }; let _names = { mount: new Set(), unMount: new Set(), array: new Set(), watch: new Set(), }; let delayErrorCallback; let timer = 0; let validateFields = {}; const _proxyFormState = { isDirty: false, dirtyFields: false, touchedFields: false, isValidating: false, isValid: false, errors: false, }; const _subjects = { watch: createSubject(), array: createSubject(), state: createSubject(), }; const validationModeBeforeSubmit = getValidationModes(_options.mode); const validationModeAfterSubmit = getValidationModes(_options.reValidateMode); const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all; const debounce = (callback, wait) => (...args) => { clearTimeout(timer); timer = window.setTimeout(() => callback(...args), wait); }; const _updateValid = async (shouldSkipRender) => { let isValid = false; if (_proxyFormState.isValid) { isValid = _options.resolver ? isEmptyObject((await _executeSchema()).errors) : await executeBuildInValidation(_fields, true); if (!shouldSkipRender && isValid !== _formState.isValid) { _formState.isValid = isValid; _subjects.state.next({ isValid, }); } } return isValid; }; const _updateFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndErrors = true) => { if (args && method) { _stateFlags.action = true; if (shouldUpdateFieldsAndErrors && Array.isArray(get$3(_fields, name))) { const fieldValues = method(get$3(_fields, name), args.argA, args.argB); shouldSetValues && set(_fields, name, fieldValues); } if (_proxyFormState.errors && shouldUpdateFieldsAndErrors && Array.isArray(get$3(_formState.errors, name))) { const errors = method(get$3(_formState.errors, name), args.argA, args.argB); shouldSetValues && set(_formState.errors, name, errors); unsetEmptyArray(_formState.errors, name); } if (_proxyFormState.touchedFields && Array.isArray(get$3(_formState.touchedFields, name))) { const touchedFields = method(get$3(_formState.touchedFields, name), args.argA, args.argB); shouldSetValues && set(_formState.touchedFields, name, touchedFields); } if (_proxyFormState.dirtyFields) { _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues); } _subjects.state.next({ isDirty: _getDirty(name, values), dirtyFields: _formState.dirtyFields, errors: _formState.errors, isValid: _formState.isValid, }); } else { set(_formValues, name, values); } }; const updateErrors = (name, error) => (set(_formState.errors, name, error), _subjects.state.next({ errors: _formState.errors, })); const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => { const field = get$3(_fields, name); if (field) { const defaultValue = get$3(_formValues, name, isUndefined$2(value) ? get$3(_defaultValues, name) : value); isUndefined$2(defaultValue) || (ref && ref.defaultChecked) || shouldSkipSetValueAs ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f)) : setFieldValue(name, defaultValue); _stateFlags.mount && _updateValid(); } }; const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => { let isFieldDirty = false; const output = { name, }; const isPreviousFieldTouched = get$3(_formState.touchedFields, name); if (_proxyFormState.isDirty) { const isPreviousFormDirty = _formState.isDirty; _formState.isDirty = output.isDirty = _getDirty(); isFieldDirty = isPreviousFormDirty !== output.isDirty; } if (_proxyFormState.dirtyFields && (!isBlurEvent || shouldDirty)) { const isPreviousFieldDirty = get$3(_formState.dirtyFields, name); const isCurrentFieldPristine = deepEqual$1(get$3(_defaultValues, name), fieldValue); isCurrentFieldPristine ? unset(_formState.dirtyFields, name) : set(_formState.dirtyFields, name, true); output.dirtyFields = _formState.dirtyFields; isFieldDirty = isFieldDirty || isPreviousFieldDirty !== get$3(_formState.dirtyFields, name); } if (isBlurEvent && !isPreviousFieldTouched) { set(_formState.touchedFields, name, isBlurEvent); output.touchedFields = _formState.touchedFields; isFieldDirty = isFieldDirty || (_proxyFormState.touchedFields && isPreviousFieldTouched !== isBlurEvent); } isFieldDirty && shouldRender && _subjects.state.next(output); return isFieldDirty ? output : {}; }; const shouldRenderByError = async (shouldSkipRender, name, isValid, error, fieldState) => { const previousFieldError = get$3(_formState.errors, name); const shouldUpdateValid = _proxyFormState.isValid && _formState.isValid !== isValid; if (props.delayError && error) { delayErrorCallback = delayErrorCallback || debounce(updateErrors, props.delayError); delayErrorCallback(name, error); } else { clearTimeout(timer); error ? set(_formState.errors, name, error) : unset(_formState.errors, name); } if (((error ? !deepEqual$1(previousFieldError, error) : previousFieldError) || !isEmptyObject(fieldState) || shouldUpdateValid) && !shouldSkipRender) { const updatedFormState = Object.assign(Object.assign(Object.assign({}, fieldState), (shouldUpdateValid ? { isValid } : {})), { errors: _formState.errors, name }); _formState = Object.assign(Object.assign({}, _formState), updatedFormState); _subjects.state.next(updatedFormState); } validateFields[name]--; if (_proxyFormState.isValidating && !validateFields[name]) { _subjects.state.next({ isValidating: false, }); validateFields = {}; } }; const _executeSchema = async (name) => _options.resolver ? await _options.resolver(Object.assign({}, _formValues), _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation)) : {}; const executeSchemaAndUpdateState = async (names) => { const { errors } = await _executeSchema(); if (names) { for (const name of names) { const error = get$3(errors, name); error ? set(_formState.errors, name, error) : unset(_formState.errors, name); } } else { _formState.errors = errors; } return errors; }; const executeBuildInValidation = async (fields, shouldOnlyCheckValid, context = { valid: true, }) => { for (const name in fields) { const field = fields[name]; if (field) { const fieldReference = field._f; const fieldValue = omit(field, '_f'); if (fieldReference) { const fieldError = await validateField(field, get$3(_formValues, fieldReference.name), shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation); if (fieldError[fieldReference.name]) { context.valid = false; if (shouldOnlyCheckValid) { break; } } if (!shouldOnlyCheckValid) { fieldError[fieldReference.name] ? set(_formState.errors, fieldReference.name, fieldError[fieldReference.name]) : unset(_formState.errors, fieldReference.name); } } fieldValue && (await executeBuildInValidation(fieldValue, shouldOnlyCheckValid, context)); } } return context.valid; }; const _removeUnmounted = () => { for (const name of _names.unMount) { const field = get$3(_fields, name); field && (field._f.refs ? field._f.refs.every((ref) => !live(ref)) : !live(field._f.ref)) && unregister(name); } _names.unMount = new Set(); }; const _getDirty = (name, data) => (name && data && set(_formValues, name, data), !deepEqual$1(getValues(), _defaultValues)); const _getWatch = (names, defaultValue, isGlobal) => { const fieldValues = Object.assign({}, (_stateFlags.mount ? _formValues : isUndefined$2(defaultValue) ? _defaultValues : isString$3(names) ? { [names]: defaultValue } : defaultValue)); return generateWatchOutput(names, _names, fieldValues, isGlobal); }; const _getFieldArray = (name) => compact(get$3(_stateFlags.mount ? _formValues : _defaultValues, name, props.shouldUnregister ? get$3(_defaultValues, name, []) : [])); const setFieldValue = (name, value, options = {}) => { const field = get$3(_fields, name); let fieldValue = value; if (field) { const fieldReference = field._f; if (fieldReference) { !fieldReference.disabled && set(_formValues, name, getFieldValueAs(value, fieldReference)); fieldValue = isWeb && isHTMLElement(fieldReference.ref) && isNullOrUndefined(value) ? '' : value; if (isMultipleSelect(fieldReference.ref)) { [...fieldReference.ref.options].forEach((selectRef) => (selectRef.selected = fieldValue.includes(selectRef.value))); } else if (fieldReference.refs) { if (isCheckBoxInput(fieldReference.ref)) { fieldReference.refs.length > 1 ? fieldReference.refs.forEach((checkboxRef) => (checkboxRef.checked = Array.isArray(fieldValue) ? !!fieldValue.find((data) => data === checkboxRef.value) : fieldValue === checkboxRef.value)) : fieldReference.refs[0] && (fieldReference.refs[0].checked = !!fieldValue); } else { fieldReference.refs.forEach((radioRef) => (radioRef.checked = radioRef.value === fieldValue)); } } else if (isFileInput(fieldReference.ref)) { fieldReference.ref.value = ''; } else { fieldReference.ref.value = fieldValue; if (!fieldReference.ref.type) { _subjects.watch.next({ name, }); } } } } (options.shouldDirty || options.shouldTouch) && updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, true); options.shouldValidate && trigger(name); }; const setValues = (name, value, options) => { for (const fieldKey in value) { const fieldValue = value[fieldKey]; const fieldName = `${name}.${fieldKey}`; const field = get$3(_fields, fieldName); (_names.array.has(name) || !isPrimitive(fieldValue) || (field && !field._f)) && !isDateObject(fieldValue) ? setValues(fieldName, fieldValue, options) : setFieldValue(fieldName, fieldValue, options); } }; const setValue = (name, value, options = {}) => { const field = get$3(_fields, name); const isFieldArray = _names.array.has(name); const cloneValue = cloneObject(value); set(_formValues, name, cloneValue); if (isFieldArray) { _subjects.array.next({ name, values: _formValues, }); if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields) && options.shouldDirty) { _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues); _subjects.state.next({ name, dirtyFields: _formState.dirtyFields, isDirty: _getDirty(name, cloneValue), }); } } else { field && !field._f && !isNullOrUndefined(cloneValue) ? setValues(name, cloneValue, options) : setFieldValue(name, cloneValue, options); } isWatched(name, _names) && _subjects.state.next({}); _subjects.watch.next({ name, }); }; const onChange = async (event) => { const target = event.target; let name = target.name; const field = get$3(_fields, name); if (field) { let error; let isValid; const fieldValue = target.type ? getFieldValue(field._f) : getEventValue(event); const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT; const shouldSkipValidation = (!hasValidation(field._f) && !_options.resolver && !get$3(_formState.errors, name) && !field._f.deps) || skipValidation(isBlurEvent, get$3(_formState.touchedFields, name), _formState.isSubmitted, validationModeAfterSubmit, validationModeBeforeSubmit); const watched = isWatched(name, _names, isBlurEvent); set(_formValues, name, fieldValue); if (isBlurEvent) { field._f.onBlur && field._f.onBlur(event); } else if (field._f.onChange) { field._f.onChange(event); } const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent, false); const shouldRender = !isEmptyObject(fieldState) || watched; !isBlurEvent && _subjects.watch.next({ name, type: event.type, }); if (shouldSkipValidation) { return (shouldRender && _subjects.state.next(Object.assign({ name }, (watched ? {} : fieldState)))); } !isBlurEvent && watched && _subjects.state.next({}); validateFields[name] = validateFields[name] ? +1 : 1; _subjects.state.next({ isValidating: true, }); if (_options.resolver) { const { errors } = await _executeSchema([name]); const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name); const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name); error = errorLookupResult.error; name = errorLookupResult.name; isValid = isEmptyObject(errors); } else { error = (await validateField(field, get$3(_formValues, name), shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name]; isValid = await _updateValid(true); } field._f.deps && trigger(field._f.deps); shouldRenderByError(false, name, isValid, error, fieldState); } }; const trigger = async (name, options = {}) => { let isValid; let validationResult; const fieldNames = convertToArrayPayload(name); _subjects.state.next({ isValidating: true, }); if (_options.resolver) { const errors = await executeSchemaAndUpdateState(isUndefined$2(name) ? name : fieldNames); isValid = isEmptyObject(errors); validationResult = name ? !fieldNames.some((name) => get$3(errors, name)) : isValid; } else if (name) { validationResult = (await Promise.all(fieldNames.map(async (fieldName) => { const field = get$3(_fields, fieldName); return await executeBuildInValidation(field && field._f ? { [fieldName]: field } : field); }))).every(Boolean); !(!validationResult && !_formState.isValid) && _updateValid(); } else { validationResult = isValid = await executeBuildInValidation(_fields); } _subjects.state.next(Object.assign(Object.assign(Object.assign({}, (!isString$3(name) || (_proxyFormState.isValid && isValid !== _formState.isValid) ? {} : { name })), (_options.resolver ? { isValid } : {})), { errors: _formState.errors, isValidating: false })); options.shouldFocus && !validationResult && focusFieldBy(_fields, (key) => get$3(_formState.errors, key), name ? fieldNames : _names.mount); return validationResult; }; const getValues = (fieldNames) => { const values = Object.assign(Object.assign({}, _defaultValues), (_stateFlags.mount ? _formValues : {})); return isUndefined$2(fieldNames) ? values : isString$3(fieldNames) ? get$3(values, fieldNames) : fieldNames.map((name) => get$3(values, name)); }; const getFieldState = (name, formState) => ({ invalid: !!get$3((formState || _formState).errors, name), isDirty: !!get$3((formState || _formState).dirtyFields, name), isTouched: !!get$3((formState || _formState).touchedFields, name), error: get$3((formState || _formState).errors, name), }); const clearErrors = (name) => { name ? convertToArrayPayload(name).forEach((inputName) => unset(_formState.errors, inputName)) : (_formState.errors = {}); _subjects.state.next({ errors: _formState.errors, }); }; const setError = (name, error, options) => { const ref = (get$3(_fields, name, { _f: {} })._f || {}).ref; set(_formState.errors, name, Object.assign(Object.assign({}, error), { ref })); _subjects.state.next({ name, errors: _formState.errors, isValid: false, }); options && options.shouldFocus && ref && ref.focus && ref.focus(); }; const watch = (name, defaultValue) => isFunction$2(name) ? _subjects.watch.subscribe({ next: (info) => name(_getWatch(undefined, defaultValue), info), }) : _getWatch(name, defaultValue, true); const unregister = (name, options = {}) => { for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) { _names.mount.delete(fieldName); _names.array.delete(fieldName); if (get$3(_fields, fieldName)) { if (!options.keepValue) { unset(_fields, fieldName); unset(_formValues, fieldName); } !options.keepError && unset(_formState.errors, fieldName); !options.keepDirty && unset(_formState.dirtyFields, fieldName); !options.keepTouched && unset(_formState.touchedFields, fieldName); !_options.shouldUnregister && !options.keepDefaultValue && unset(_defaultValues, fieldName); } } _subjects.watch.next({}); _subjects.state.next(Object.assign(Object.assign({}, _formState), (!options.keepDirty ? {} : { isDirty: _getDirty() }))); !options.keepIsValid && _updateValid(); }; const register = (name, options = {}) => { let field = get$3(_fields, name); const disabledIsDefined = isBoolean(options.disabled); set(_fields, name, { _f: Object.assign(Object.assign(Object.assign({}, (field && field._f ? field._f : { ref: { name } })), { name, mount: true }), options), }); _names.mount.add(name); field ? disabledIsDefined && set(_formValues, name, options.disabled ? undefined : get$3(_formValues, name, getFieldValue(field._f))) : updateValidAndValue(name, true, options.value); return Object.assign(Object.assign(Object.assign({}, (disabledIsDefined ? { disabled: options.disabled } : {})), (_options.shouldUseNativeValidation ? { required: !!options.required, min: getRuleValue(options.min), max: getRuleValue(options.max), minLength: getRuleValue(options.minLength), maxLength: getRuleValue(options.maxLength), pattern: getRuleValue(options.pattern), } : {})), { name, onChange, onBlur: onChange, ref: (ref) => { if (ref) { register(name, options); field = get$3(_fields, name); const fieldRef = isUndefined$2(ref.value) ? ref.querySelectorAll ? ref.querySelectorAll('input,select,textarea')[0] || ref : ref : ref; const radioOrCheckbox = isRadioOrCheckbox(fieldRef); const refs = field._f.refs || []; if (radioOrCheckbox ? refs.find((option) => option === fieldRef) : fieldRef === field._f.ref) { return; } set(_fields, name, { _f: Object.assign(Object.assign({}, field._f), (radioOrCheckbox ? { refs: refs.concat(fieldRef).filter(live), ref: { type: fieldRef.type, name }, } : { ref: fieldRef })), }); updateValidAndValue(name, false, undefined, fieldRef); } else { field = get$3(_fields, name, {}); if (field._f) { field._f.mount = false; } (_options.shouldUnregister || options.shouldUnregister) && !(isNameInFieldArray(_names.array, name) && _stateFlags.action) && _names.unMount.add(name); } } }); }; const handleSubmit = (onValid, onInvalid) => async (e) => { if (e) { e.preventDefault && e.preventDefault(); e.persist && e.persist(); } let hasNoPromiseError = true; let fieldValues = _options.shouldUnregister ? cloneObject(_formValues) : Object.assign({}, _formValues); _subjects.state.next({ isSubmitting: true, }); try { if (_options.resolver) { const { errors, values } = await _executeSchema(); _formState.errors = errors; fieldValues = values; } else { await executeBuildInValidation(_fields); } if (isEmptyObject(_formState.errors) && Object.keys(_formState.errors).every((name) => get$3(fieldValues, name))) { _subjects.state.next({ errors: {}, isSubmitting: true, }); await onValid(fieldValues, e); } else { onInvalid && (await onInvalid(_formState.errors, e)); _options.shouldFocusError && focusFieldBy(_fields, (key) => get$3(_formState.errors, key), _names.mount); } } catch (err) { hasNoPromiseError = false; throw err; } finally { _formState.isSubmitted = true; _subjects.state.next({ isSubmitted: true, isSubmitting: false, isSubmitSuccessful: isEmptyObject(_formState.errors) && hasNoPromiseError, submitCount: _formState.submitCount + 1, errors: _formState.errors, }); } }; const resetField = (name, options = {}) => { if (get$3(_fields, name)) { if (isUndefined$2(options.defaultValue)) { setValue(name, get$3(_defaultValues, name)); } else { setValue(name, options.defaultValue); set(_defaultValues, name, options.defaultValue); } if (!options.keepTouched) { unset(_formState.touchedFields, name); } if (!options.keepDirty) { unset(_formState.dirtyFields, name); _formState.isDirty = options.defaultValue ? _getDirty(name, get$3(_defaultValues, name)) : _getDirty(); } if (!options.keepError) { unset(_formState.errors, name); _proxyFormState.isValid && _updateValid(); } _subjects.state.next(Object.assign({}, _formState)); } }; const reset = (formValues, keepStateOptions = {}) => { const updatedValues = formValues || _defaultValues; const cloneUpdatedValues = cloneObject(updatedValues); const values = formValues && !isEmptyObject(formValues) ? cloneUpdatedValues : _defaultValues; if (!keepStateOptions.keepDefaultValues) { _defaultValues = updatedValues; } if (!keepStateOptions.keepValues) { if (isWeb && isUndefined$2(formValues)) { for (const name of _names.mount) { const field = get$3(_fields, name); if (field && field._f) { const fieldReference = Array.isArray(field._f.refs) ? field._f.refs[0] : field._f.ref; try { isHTMLElement(fieldReference) && fieldReference.closest('form').reset(); break; } catch (_a) { } } } } _formValues = props.shouldUnregister ? keepStateOptions.keepDefaultValues ? cloneObject(_defaultValues) : {} : cloneUpdatedValues; _fields = {}; _subjects.array.next({ values, }); _subjects.watch.next({ values, }); } _names = { mount: new Set(), unMount: new Set(), array: new Set(), watch: new Set(), watchAll: false, focus: '', }; _stateFlags.mount = !_proxyFormState.isValid || !!keepStateOptions.keepIsValid; _stateFlags.watch = !!props.shouldUnregister; _subjects.state.next({ submitCount: keepStateOptions.keepSubmitCount ? _formState.submitCount : 0, isDirty: keepStateOptions.keepDirty ? _formState.isDirty : keepStateOptions.keepDefaultValues ? !deepEqual$1(formValues, _defaultValues) : false, isSubmitted: keepStateOptions.keepIsSubmitted ? _formState.isSubmitted : false, dirtyFields: keepStateOptions.keepDirty ? _formState.dirtyFields : (keepStateOptions.keepDefaultValues && formValues ? Object.entries(formValues).reduce((previous, [key, value]) => (Object.assign(Object.assign({}, previous), { [key]: value !== get$3(_defaultValues, key) })), {}) : {}), touchedFields: keepStateOptions.keepTouched ? _formState.touchedFields : {}, errors: keepStateOptions.keepErrors ? _formState.errors : {}, isSubmitting: false, isSubmitSuccessful: false, }); }; const setFocus = (name) => { const field = get$3(_fields, name)._f; (field.ref.focus ? field.ref : field.refs[0]).focus(); }; return { control: { register, unregister, getFieldState, _executeSchema, _getWatch, _getDirty, _updateValid, _removeUnmounted, _updateFieldArray, _getFieldArray, _subjects, _proxyFormState, get _fields() { return _fields; }, get _formValues() { return _formValues; }, get _stateFlags() { return _stateFlags; }, set _stateFlags(value) { _stateFlags = value; }, get _defaultValues() { return _defaultValues; }, get _names() { return _names; }, set _names(value) { _names = value; }, get _formState() { return _formState; }, set _formState(value) { _formState = value; }, get _options() { return _options; }, set _options(value) { _options = Object.assign(Object.assign({}, _options), value); }, }, trigger, register, handleSubmit, watch, setValue, getValues, reset, resetField, clearErrors, unregister, setError, setFocus, getFieldState, }; } function useForm(props = {}) { const _formControl = React$1.useRef(); const [formState, updateFormState] = React$1.useState({ isDirty: false, isValidating: false, dirtyFields: {}, isSubmitted: false, submitCount: 0, touchedFields: {}, isSubmitting: false, isSubmitSuccessful: false, isValid: false, errors: {}, }); if (_formControl.current) { _formControl.current.control._options = props; } else { _formControl.current = Object.assign(Object.assign({}, createFormControl(props)), { formState }); } const control = _formControl.current.control; const callback = React$1.useCallback((value) => { if (shouldRenderFormState(value, control._proxyFormState, true)) { control._formState = Object.assign(Object.assign({}, control._formState), value); updateFormState(Object.assign({}, control._formState)); } }, [control]); useSubscribe({ subject: control._subjects.state, callback, }); React$1.useEffect(() => { if (!control._stateFlags.mount) { control._proxyFormState.isValid && control._updateValid(); control._stateFlags.mount = true; } if (control._stateFlags.watch) { control._stateFlags.watch = false; control._subjects.state.next({}); } control._removeUnmounted(); }); _formControl.current.formState = getProxyFormState(formState, control._proxyFormState); return _formControl.current; } /** * Adapted from https://css-tricks.com/the-cleanest-trick-for-autogrowing-textareas/ */ const copyStyles = ( styles, node, minRows ) => { node.style.fontSize = styles.fontSize; node.style.fontFamily = styles.fontFamily; node.style.fontWeight = styles.fontWeight; node.style.fontStyle = styles.fontStyle; node.style.letterSpacing = styles.letterSpacing; node.style.textTransform = styles.textTransform; node.style.padding = styles.padding; node.style.lineHeight = styles.lineHeight; node.style.minHeight = `${minRows * parseInt(styles.lineHeight)}px`; }; const ExpandingTextArea = reactExports.forwardRef (({ minRows, className, ...props }, ref) => { const textAreaRef = reactExports.useRef(null); reactExports.useImperativeHandle( ref, () => textAreaRef.current ); const resizerRef = reactExports.useRef(null); reactExports.useEffect(() => { if (resizerRef.current && textAreaRef.current) { const styles = window.getComputedStyle(textAreaRef.current); copyStyles(styles, resizerRef.current, minRows); } }, [minRows]); const classes = reactExports.useMemo( () => `${ className ?? "" } w-full row-start-1 row-end-2 col-start-1 col-end-2 min-h-0`, [className] ); return ( React$1.createElement('div', { className: `relative grid w-full overflow-auto`,} , React$1.createElement('div', { ref: resizerRef, className: `invisible col-start-1 col-end-2 row-start-1 row-end-2 h-min overflow-auto whitespace-pre-wrap break-words`,} , props.value, " " ) , React$1.createElement('textarea', { style: { resize: "none", overflow: "hidden", }, ...props, className: classes, ref: textAreaRef, rows: 1,} ) ) ); }); ExpandingTextArea.displayName = "ExpandingTextArea"; var build = {}; var tinyEmitter = {exports: {}}; function E$6 () { // 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$6.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$6; tinyEmitter.exports.TinyEmitter = E$6; var tinyEmitterExports = tinyEmitter.exports; var metrics = {}; // Simplified version of: https://github.com/Unleash/unleash-client-node/blob/main/src/metrics.ts 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); }; 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$6(__assign$6({}, 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$8 = 0; i$8 < 256; ++i$8) { byteToHex.push((i$8 + 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$5 = (commonjsGlobal && commonjsGlobal.__assign) || function () { __assign$5 = 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$5.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$5(__assign$5({}, 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 = {}; Object.defineProperty(util, "__esModule", { value: true }); util.notNullOrUndefined = void 0; var notNullOrUndefined = function (_a) { var value = _a[1]; return value !== undefined && value !== null; }; util.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; 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] {}); 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$1() { _extends$1 = 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$1.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(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(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(o, minLen); } function _arrayLikeToArray(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(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$9 = "numeric", s$d = "short", l$b = "long"; var DATE_SHORT = { year: n$9, month: n$9, day: n$9 }; var DATE_MED = { year: n$9, month: s$d, day: n$9 }; var DATE_MED_WITH_WEEKDAY = { year: n$9, month: s$d, day: n$9, weekday: s$d }; var DATE_FULL = { year: n$9, month: l$b, day: n$9 }; var DATE_HUGE = { year: n$9, month: l$b, day: n$9, weekday: l$b }; var TIME_SIMPLE = { hour: n$9, minute: n$9 }; var TIME_WITH_SECONDS = { hour: n$9, minute: n$9, second: n$9 }; var TIME_WITH_SHORT_OFFSET = { hour: n$9, minute: n$9, second: n$9, timeZoneName: s$d }; var TIME_WITH_LONG_OFFSET = { hour: n$9, minute: n$9, second: n$9, timeZoneName: l$b }; var TIME_24_SIMPLE = { hour: n$9, minute: n$9, hourCycle: "h23" }; var TIME_24_WITH_SECONDS = { hour: n$9, minute: n$9, second: n$9, hourCycle: "h23" }; var TIME_24_WITH_SHORT_OFFSET = { hour: n$9, minute: n$9, second: n$9, hourCycle: "h23", timeZoneName: s$d }; var TIME_24_WITH_LONG_OFFSET = { hour: n$9, minute: n$9, second: n$9, hourCycle: "h23", timeZoneName: l$b }; var DATETIME_SHORT = { year: n$9, month: n$9, day: n$9, hour: n$9, minute: n$9 }; var DATETIME_SHORT_WITH_SECONDS = { year: n$9, month: n$9, day: n$9, hour: n$9, minute: n$9, second: n$9 }; var DATETIME_MED = { year: n$9, month: s$d, day: n$9, hour: n$9, minute: n$9 }; var DATETIME_MED_WITH_SECONDS = { year: n$9, month: s$d, day: n$9, hour: n$9, minute: n$9, second: n$9 }; var DATETIME_MED_WITH_WEEKDAY = { year: n$9, month: s$d, day: n$9, weekday: s$d, hour: n$9, minute: n$9 }; var DATETIME_FULL = { year: n$9, month: l$b, day: n$9, hour: n$9, minute: n$9, timeZoneName: s$d }; var DATETIME_FULL_WITH_SECONDS = { year: n$9, month: l$b, day: n$9, hour: n$9, minute: n$9, second: n$9, timeZoneName: s$d }; var DATETIME_HUGE = { year: n$9, month: l$b, day: n$9, weekday: l$b, hour: n$9, minute: n$9, timeZoneName: l$b }; var DATETIME_HUGE_WITH_SECONDS = { year: n$9, month: l$b, day: n$9, weekday: l$b, hour: n$9, minute: n$9, second: n$9, timeZoneName: l$b }; /** * @private */ // TYPES function isUndefined$1(o) { return typeof o === "undefined"; } function isNumber$1(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$1(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(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$1({ 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 = /*#__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$1({}, this.opts, opts)); return df.format(); }; _proto.formatDateTime = function formatDateTime(dt, opts) { if (opts === void 0) { opts = {}; } var df = this.loc.dtFormatter(dt, _extends$1({}, this.opts, opts)); return df.format(); }; _proto.formatDateTimeParts = function formatDateTimeParts(dt, opts) { if (opts === void 0) { opts = {}; } var df = this.loc.dtFormatter(dt, _extends$1({}, this.opts, opts)); return df.formatToParts(); }; _proto.resolvedOptions = function resolvedOptions(dt, opts) { if (opts === void 0) { opts = {}; } var df = this.loc.dtFormatter(dt, _extends$1({}, 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$1({}, 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$1(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 = 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; } /** * 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 = 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(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$1({}, 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$1({ 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$1({}, alts, { defaultToEN: true })); }; _proto4.redefaultToSystem = function redefaultToSystem(alts) { if (alts === void 0) { alts = {}; } return this.clone(_extends$1({}, 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$1({}, mergedVals, val), mergedZone || zone, next]; }, [{}, null, 1]).slice(0, 2); }; } function parse$5(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$5(s, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset]); } function parseRFC2822Date(s) { return parse$5(preprocessRFC2822(s), [rfc2822, extractRFC2822]); } function parseHTTPDate(s) { return parse$5(s, [rfc1123, extractRFC1123Or850], [rfc850, extractRFC1123Or850], [ascii, extractASCII]); } function parseISODuration(s) { return parse$5(s, [isoDuration, extractISODuration]); } var extractISOTimeOnly = combineExtractors(extractISOTime); function parseISOTimeOnly(s) { return parse$5(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$5(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$1({ 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$1({ 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$1({}, 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$5(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$5(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$1({}, opts, { floor: opts.round !== false && opts.floor !== false }); return this.isValid ? Formatter.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$1({}, 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(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$1({ 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$1({}, 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$1(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$5(this.matrix, vals, down, built, k); } } // otherwise, keep it in the wings to boil it later } else if (isNumber$1(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$1(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.macroTokenToFormatOpts(token.val); if (!formatOpts) { return token; } var formatter = Formatter.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.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$1({ 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$1({ 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$1({ 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$1({ 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$1({}, 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$1({}, 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$1({}, 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.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(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$1(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$1(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$1(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.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$1({}, gregorianToWeek(this.c), normalized)); } else if (!isUndefined$1(normalized.ordinal)) { mixed = ordinalToGregorian(_extends$1({}, gregorianToOrdinal(this.c), normalized)); } else { mixed = _extends$1({}, 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.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.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.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$1({}, 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$1({ 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$1({}, 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$1({}, 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$1(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$1 = "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$1; luxon.Zone = Zone; const UserInfoContext = React$1.createContext({ loggedIn: false, email: null, modMode: false, projectId: null, userId: null, activated: false, readOnly: true, emailVerifyCanceled: null, emailVerified: null, twoFactorActive: false, deleteAfter: null, }); const useUserInfo = () => reactExports.useContext(UserInfoContext); const UserNote = ({ projectId, }) => { const { loggedIn } = useUserInfo(); const initialContents = trpc.projects.userNote.query.useQuery( { describedProjectId: projectId }, { suspense: true, refetchInterval: false, refetchOnMount: false, refetchOnReconnect: false, refetchOnWindowFocus: false, enabled: loggedIn, } ).data?.contents; const userNoteMutation = trpc.projects.userNote.mutate.useMutation(); const onSubmit = reactExports.useCallback( async ({ contents }) => { await userNoteMutation.mutateAsync({ describedProjectId: projectId, contents: contents, }); }, [projectId, userNoteMutation] ); const { handleSubmit, control } = useForm({ defaultValues: { contents: initialContents || "", }, mode: "all", }); if (!loggedIn) { return null; } return ( React$1.createElement('div', { className: "cohost-shadow-light dark:cohost-shadow-dark flex flex-col divide-y divide-gray-300 rounded-lg bg-white lg:max-w-sm" ,} , React$1.createElement('div', { className: "flex flex-row items-center rounded-t-lg bg-longan p-3 uppercase text-notBlack" ,}, "Private Note" ) , React$1.createElement('div', { className: "flex flex-col gap-2 px-3 py-2 text-notBlack" ,} , React$1.createElement('div', null , React$1.createElement('em', null, "Only you can see this" ) ) , React$1.createElement('form', { className: "flex flex-col gap-3" , onSubmit: handleSubmit(onSubmit),} , React$1.createElement(Controller, { control: control, name: "contents", render: ({ field: { ref, onChange, ...field } }) => ( React$1.createElement(ExpandingTextArea, { ...field, className: "border-cherry", onInput: onChange, ref: ref, minRows: 1, autoComplete: "off", placeholder: t$b( "client:private-note.placeholder", { defaultValue: "add note", } ),} ) ),} ) , React$1.createElement('div', { className: "flex w-full flex-row items-center justify-end gap-4" ,} , userNoteMutation.isSuccess ? ( React$1.createElement('p', { className: "font-bold text-green" ,}, "Note saved!" ) ) : null , userNoteMutation.isError ? ( React$1.createElement('p', { className: "text-red",}, `Sorry, we couldn't save your note. ${userNoteMutation.error.message}`) ) : null , React$1.createElement('button', { className: `rounded-lg bg-cherry py-2 px-4 text-sm font-bold text-notWhite hover:bg-cherry-600 active:bg-cherry-700 disabled:bg-cherry-200`,} , t$b("client:new-comment.save", { defaultValue: "save", }) ) ) ) ) ) ); }; const SilenceIcon = (props) => ( React$1.createElement('svg', { viewBox: "0 0 24 24" , fill: "none", xmlns: "http://www.w3.org/2000/svg", ...props,} , React$1.createElement('path', { fillRule: "evenodd", clipRule: "evenodd", d: "M8.58579 15.002H7C6.44772 15.002 6 14.5543 6 14.002V10.002C6 9.44972 6.44772 9.002 7 9.002H8.58579L13.2929 4.2949C13.9229 3.66493 15 4.1111 15 5.002V19.002C15 19.8929 13.9229 20.3391 13.2929 19.7091L8.58579 15.002Z" , stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round",} ) , React$1.createElement('path', { d: "M20 4L16.8096 7.19036M4 20L7.19005 16.81L10.1144 13.8856M10.1144 13.8856L13.8856 10.1144L16.8096 7.19036M10.1144 13.8856L16.8096 7.19036" , stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round",} ) ) ); var axios$3 = {exports: {}}; var bind$2 = 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$1 = bind$2; // utils is a library of generic helper functions non-specific to axios var toString$1 = 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$1.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(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(val) && val.constructor !== null && !isUndefined(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$1.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$1(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(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(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$2(val) { if (toString$1.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(val) { return toString$1.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(val) { return toString$1.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$1.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$1(val) { return toString$1.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(val) && isFunction$1(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$3(/* obj1, obj2, obj3, ... */) { var result = {}; function assignValue(val, key) { if (isPlainObject$2(result[key]) && isPlainObject$2(val)) { result[key] = merge$3(result[key], val); } else if (isPlainObject$2(val)) { result[key] = merge$3({}, 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$1(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$1, isNumber: isNumber, isObject: isObject, isPlainObject: isPlainObject$2, isUndefined: isUndefined, isDate: isDate, isFile: isFile, isBlob: isBlob, isFunction: isFunction$1, isStream: isStream, isURLSearchParams: isURLSearchParams, isStandardBrowserEnv: isStandardBrowserEnv, forEach: forEach, merge: merge$3, extend: extend$2, trim: trim$1, stripBOM: stripBOM }; var utils$7 = utils$8; function encode$3(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$3(key) + '=' + encode$3(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 = /*@__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; } 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 = 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 + '] 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 = bind$2; 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(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); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var __assign$4 = function() { __assign$4 = Object.assign || function __assign(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$4.apply(this, arguments); }; function __rest$1(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read$1(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spreadArray(to, from, pack) { if (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)); } var ActionTypes; (function (ActionTypes) { ActionTypes["Start"] = "xstate.start"; ActionTypes["Stop"] = "xstate.stop"; ActionTypes["Raise"] = "xstate.raise"; ActionTypes["Send"] = "xstate.send"; ActionTypes["Cancel"] = "xstate.cancel"; ActionTypes["NullEvent"] = ""; ActionTypes["Assign"] = "xstate.assign"; ActionTypes["After"] = "xstate.after"; ActionTypes["DoneState"] = "done.state"; ActionTypes["DoneInvoke"] = "done.invoke"; ActionTypes["Log"] = "xstate.log"; ActionTypes["Init"] = "xstate.init"; ActionTypes["Invoke"] = "xstate.invoke"; ActionTypes["ErrorExecution"] = "error.execution"; ActionTypes["ErrorCommunication"] = "error.communication"; ActionTypes["ErrorPlatform"] = "error.platform"; ActionTypes["ErrorCustom"] = "xstate.error"; ActionTypes["Update"] = "xstate.update"; ActionTypes["Pure"] = "xstate.pure"; ActionTypes["Choose"] = "xstate.choose"; })(ActionTypes || (ActionTypes = {})); var SpecialTargets; (function (SpecialTargets) { SpecialTargets["Parent"] = "#_parent"; SpecialTargets["Internal"] = "#_internal"; })(SpecialTargets || (SpecialTargets = {})); var start$1 = ActionTypes.Start; var stop$1 = ActionTypes.Stop; var raise$1 = ActionTypes.Raise; var send$1 = ActionTypes.Send; var cancel$1 = ActionTypes.Cancel; var nullEvent = ActionTypes.NullEvent; var assign$2 = ActionTypes.Assign; ActionTypes.After; ActionTypes.DoneState; var log = ActionTypes.Log; var init = ActionTypes.Init; var invoke = ActionTypes.Invoke; ActionTypes.ErrorExecution; var errorPlatform = ActionTypes.ErrorPlatform; var error$1 = ActionTypes.ErrorCustom; var update = ActionTypes.Update; var choose = ActionTypes.Choose; var pure = ActionTypes.Pure; var STATE_DELIMITER = '.'; var EMPTY_ACTIVITY_MAP = {}; var DEFAULT_GUARD_TYPE = 'xstate.guard'; var TARGETLESS_KEY = ''; var _a$1; function matchesState(parentStateId, childStateId, delimiter) { if (delimiter === void 0) { delimiter = STATE_DELIMITER; } var parentStateValue = toStateValue(parentStateId, delimiter); var childStateValue = toStateValue(childStateId, delimiter); if (isString(childStateValue)) { if (isString(parentStateValue)) { return childStateValue === parentStateValue; } // Parent more specific than child return false; } if (isString(parentStateValue)) { return parentStateValue in childStateValue; } return Object.keys(parentStateValue).every(function (key) { if (!(key in childStateValue)) { return false; } return matchesState(parentStateValue[key], childStateValue[key]); }); } function getEventType(event) { try { return isString(event) || typeof event === 'number' ? "".concat(event) : event.type; } catch (e) { throw new Error('Events must be strings or objects with a string event.type property.'); } } function toStatePath(stateId, delimiter) { try { if (isArray$1(stateId)) { return stateId; } return stateId.toString().split(delimiter); } catch (e) { throw new Error("'".concat(stateId, "' is not a valid state path.")); } } function isStateLike(state) { return typeof state === 'object' && 'value' in state && 'context' in state && 'event' in state && '_event' in state; } function toStateValue(stateValue, delimiter) { if (isStateLike(stateValue)) { return stateValue.value; } if (isArray$1(stateValue)) { return pathToStateValue(stateValue); } if (typeof stateValue !== 'string') { return stateValue; } var statePath = toStatePath(stateValue, delimiter); return pathToStateValue(statePath); } function pathToStateValue(statePath) { if (statePath.length === 1) { return statePath[0]; } var value = {}; var marker = value; for (var i = 0; i < statePath.length - 1; i++) { if (i === statePath.length - 2) { marker[statePath[i]] = statePath[i + 1]; } else { marker[statePath[i]] = {}; marker = marker[statePath[i]]; } } return value; } function mapValues(collection, iteratee) { var result = {}; var collectionKeys = Object.keys(collection); for (var i = 0; i < collectionKeys.length; i++) { var key = collectionKeys[i]; result[key] = iteratee(collection[key], key, collection, i); } return result; } function mapFilterValues(collection, iteratee, predicate) { var e_1, _a; var result = {}; try { for (var _b = __values(Object.keys(collection)), _c = _b.next(); !_c.done; _c = _b.next()) { var key = _c.value; var item = collection[key]; if (!predicate(item)) { continue; } result[key] = iteratee(item, key, collection); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } return result; } /** * Retrieves a value at the given path. * @param props The deep path to the prop of the desired value */ var path$3 = function (props) { return function (object) { var e_2, _a; var result = object; try { for (var props_1 = __values(props), props_1_1 = props_1.next(); !props_1_1.done; props_1_1 = props_1.next()) { var prop = props_1_1.value; result = result[prop]; } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (props_1_1 && !props_1_1.done && (_a = props_1.return)) _a.call(props_1); } finally { if (e_2) throw e_2.error; } } return result; }; }; /** * Retrieves a value at the given path via the nested accessor prop. * @param props The deep path to the prop of the desired value */ function nestedPath(props, accessorProp) { return function (object) { var e_3, _a; var result = object; try { for (var props_2 = __values(props), props_2_1 = props_2.next(); !props_2_1.done; props_2_1 = props_2.next()) { var prop = props_2_1.value; result = result[accessorProp][prop]; } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (props_2_1 && !props_2_1.done && (_a = props_2.return)) _a.call(props_2); } finally { if (e_3) throw e_3.error; } } return result; }; } function toStatePaths(stateValue) { if (!stateValue) { return [[]]; } if (isString(stateValue)) { return [[stateValue]]; } var result = flatten(Object.keys(stateValue).map(function (key) { var subStateValue = stateValue[key]; if (typeof subStateValue !== 'string' && (!subStateValue || !Object.keys(subStateValue).length)) { return [[key]]; } return toStatePaths(stateValue[key]).map(function (subPath) { return [key].concat(subPath); }); })); return result; } function flatten(array) { var _a; return (_a = []).concat.apply(_a, __spreadArray([], __read$1(array), false)); } function toArrayStrict(value) { if (isArray$1(value)) { return value; } return [value]; } function toArray(value) { if (value === undefined) { return []; } return toArrayStrict(value); } function mapContext(mapper, context, _event) { var e_5, _a; if (isFunction(mapper)) { return mapper(context, _event.data); } var result = {}; try { for (var _b = __values(Object.keys(mapper)), _c = _b.next(); !_c.done; _c = _b.next()) { var key = _c.value; var subMapper = mapper[key]; if (isFunction(subMapper)) { result[key] = subMapper(context, _event.data); } else { result[key] = subMapper; } } } catch (e_5_1) { e_5 = { error: e_5_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_5) throw e_5.error; } } return result; } function isBuiltInEvent(eventType) { return /^(done|error)\./.test(eventType); } function isPromiseLike(value) { if (value instanceof Promise) { return true; } // Check if shape matches the Promise/A+ specification for a "thenable". if (value !== null && (isFunction(value) || typeof value === 'object') && isFunction(value.then)) { return true; } return false; } function isBehavior(value) { return value !== null && typeof value === 'object' && 'transition' in value && typeof value.transition === 'function'; } function partition$1(items, predicate) { var e_6, _a; var _b = __read$1([[], []], 2), truthy = _b[0], falsy = _b[1]; try { for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) { var item = items_1_1.value; if (predicate(item)) { truthy.push(item); } else { falsy.push(item); } } } catch (e_6_1) { e_6 = { error: e_6_1 }; } finally { try { if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1); } finally { if (e_6) throw e_6.error; } } return [truthy, falsy]; } function updateHistoryStates(hist, stateValue) { return mapValues(hist.states, function (subHist, key) { if (!subHist) { return undefined; } var subStateValue = (isString(stateValue) ? undefined : stateValue[key]) || (subHist ? subHist.current : undefined); if (!subStateValue) { return undefined; } return { current: subStateValue, states: updateHistoryStates(subHist, subStateValue) }; }); } function updateHistoryValue(hist, stateValue) { return { current: stateValue, states: updateHistoryStates(hist, stateValue) }; } function updateContext(context, _event, assignActions, state) { var updatedContext = context ? assignActions.reduce(function (acc, assignAction) { var e_7, _a; var assignment = assignAction.assignment; var meta = { state: state, action: assignAction, _event: _event }; var partialUpdate = {}; if (isFunction(assignment)) { partialUpdate = assignment(acc, _event.data, meta); } else { try { for (var _b = __values(Object.keys(assignment)), _c = _b.next(); !_c.done; _c = _b.next()) { var key = _c.value; var propAssignment = assignment[key]; partialUpdate[key] = isFunction(propAssignment) ? propAssignment(acc, _event.data, meta) : propAssignment; } } catch (e_7_1) { e_7 = { error: e_7_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_7) throw e_7.error; } } } return Object.assign({}, acc, partialUpdate); }, context) : context; return updatedContext; } // tslint:disable-next-line:no-empty var warn = function () {}; function isArray$1(value) { return Array.isArray(value); } // tslint:disable-next-line:ban-types function isFunction(value) { return typeof value === 'function'; } function isString(value) { return typeof value === 'string'; } function toGuard(condition, guardMap) { if (!condition) { return undefined; } if (isString(condition)) { return { type: DEFAULT_GUARD_TYPE, name: condition, predicate: guardMap ? guardMap[condition] : undefined }; } if (isFunction(condition)) { return { type: DEFAULT_GUARD_TYPE, name: condition.name, predicate: condition }; } return condition; } function isObservable(value) { try { return 'subscribe' in value && isFunction(value.subscribe); } catch (e) { return false; } } var symbolObservable = /*#__PURE__*/function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; }(); // TODO: to be removed in v5, left it out just to minimize the scope of the change and maintain compatibility with older versions of integration paackages (_a$1 = {}, _a$1[symbolObservable] = function () { return this; }, _a$1[Symbol.observable] = function () { return this; }, _a$1); function isMachine(value) { return !!value && '__xstatenode' in value; } function isActor$1(value) { return !!value && typeof value.send === 'function'; } function toEventObject(event, payload // id?: TEvent['type'] ) { if (isString(event) || typeof event === 'number') { return __assign$4({ type: event }, payload); } return event; } function toSCXMLEvent(event, scxmlEvent) { if (!isString(event) && '$$type' in event && event.$$type === 'scxml') { return event; } var eventObject = toEventObject(event); return __assign$4({ name: eventObject.type, data: eventObject, $$type: 'scxml', type: 'external' }, scxmlEvent); } function toTransitionConfigArray(event, configLike) { var transitions = toArrayStrict(configLike).map(function (transitionLike) { if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string' || isMachine(transitionLike)) { return { target: transitionLike, event: event }; } return __assign$4(__assign$4({}, transitionLike), { event: event }); }); return transitions; } function normalizeTarget(target) { if (target === undefined || target === TARGETLESS_KEY) { return undefined; } return toArray(target); } function evaluateGuard(machine, guard, context, _event, state) { var guards = machine.options.guards; var guardMeta = { state: state, cond: guard, _event: _event }; // TODO: do not hardcode! if (guard.type === DEFAULT_GUARD_TYPE) { return ((guards === null || guards === void 0 ? void 0 : guards[guard.name]) || guard.predicate)(context, _event.data, guardMeta); } var condFn = guards === null || guards === void 0 ? void 0 : guards[guard.type]; if (!condFn) { throw new Error("Guard '".concat(guard.type, "' is not implemented on machine '").concat(machine.id, "'.")); } return condFn(context, _event.data, guardMeta); } function toInvokeSource$1(src) { if (typeof src === 'string') { return { type: src }; } return src; } function toObserver(nextHandler, errorHandler, completionHandler) { if (typeof nextHandler === 'object') { return nextHandler; } var noop = function () { return void 0; }; return { next: nextHandler, error: errorHandler || noop, complete: completionHandler || noop }; } function createInvokeId(stateNodeId, index) { return "".concat(stateNodeId, ":invocation[").concat(index, "]"); } var initEvent = /*#__PURE__*/toSCXMLEvent({ type: init }); function getActionFunction(actionType, actionFunctionMap) { return actionFunctionMap ? actionFunctionMap[actionType] || undefined : undefined; } function toActionObject(action, actionFunctionMap) { var actionObject; if (isString(action) || typeof action === 'number') { var exec = getActionFunction(action, actionFunctionMap); if (isFunction(exec)) { actionObject = { type: action, exec: exec }; } else if (exec) { actionObject = exec; } else { actionObject = { type: action, exec: undefined }; } } else if (isFunction(action)) { actionObject = { // Convert action to string if unnamed type: action.name || action.toString(), exec: action }; } else { var exec = getActionFunction(action.type, actionFunctionMap); if (isFunction(exec)) { actionObject = __assign$4(__assign$4({}, action), { exec: exec }); } else if (exec) { var actionType = exec.type || action.type; actionObject = __assign$4(__assign$4(__assign$4({}, exec), action), { type: actionType }); } else { actionObject = action; } } return actionObject; } var toActionObjects = function (action, actionFunctionMap) { if (!action) { return []; } var actions = isArray$1(action) ? action : [action]; return actions.map(function (subAction) { return toActionObject(subAction, actionFunctionMap); }); }; function toActivityDefinition(action) { var actionObject = toActionObject(action); return __assign$4(__assign$4({ id: isString(action) ? action : actionObject.id }, actionObject), { type: actionObject.type }); } /** * Raises an event. This places the event in the internal event queue, so that * the event is immediately consumed by the machine in the current step. * * @param eventType The event to raise. */ function raise(event) { if (!isString(event)) { return send(event, { to: SpecialTargets.Internal }); } return { type: raise$1, event: event }; } function resolveRaise(action) { return { type: raise$1, _event: toSCXMLEvent(action.event) }; } /** * Sends an event. This returns an action that will be read by an interpreter to * send the event in the next step, after the current step is finished executing. * * @param event The event to send. * @param options Options to pass into the send event: * - `id` - The unique send event identifier (used with `cancel()`). * - `delay` - The number of milliseconds to delay the sending of the event. * - `to` - The target of this event (by default, the machine the event was sent from). */ function send(event, options) { return { to: options ? options.to : undefined, type: send$1, event: isFunction(event) ? event : toEventObject(event), delay: options ? options.delay : undefined, id: options && options.id !== undefined ? options.id : isFunction(event) ? event.name : getEventType(event) }; } function resolveSend(action, ctx, _event, delaysMap) { var meta = { _event: _event }; // TODO: helper function for resolving Expr var resolvedEvent = toSCXMLEvent(isFunction(action.event) ? action.event(ctx, _event.data, meta) : action.event); var resolvedDelay; if (isString(action.delay)) { var configDelay = delaysMap && delaysMap[action.delay]; resolvedDelay = isFunction(configDelay) ? configDelay(ctx, _event.data, meta) : configDelay; } else { resolvedDelay = isFunction(action.delay) ? action.delay(ctx, _event.data, meta) : action.delay; } var resolvedTarget = isFunction(action.to) ? action.to(ctx, _event.data, meta) : action.to; return __assign$4(__assign$4({}, action), { to: resolvedTarget, _event: resolvedEvent, event: resolvedEvent.data, delay: resolvedDelay }); } var resolveLog = function (action, ctx, _event) { return __assign$4(__assign$4({}, action), { value: isString(action.expr) ? action.expr : action.expr(ctx, _event.data, { _event: _event }) }); }; /** * Cancels an in-flight `send(...)` action. A canceled sent action will not * be executed, nor will its event be sent, unless it has already been sent * (e.g., if `cancel(...)` is called after the `send(...)` action's `delay`). * * @param sendId The `id` of the `send(...)` action to cancel. */ var cancel = function (sendId) { return { type: cancel$1, sendId: sendId }; }; /** * Starts an activity. * * @param activity The activity to start. */ function start(activity) { var activityDef = toActivityDefinition(activity); return { type: ActionTypes.Start, activity: activityDef, exec: undefined }; } /** * Stops an activity. * * @param actorRef The activity to stop. */ function stop(actorRef) { var activity = isFunction(actorRef) ? actorRef : toActivityDefinition(actorRef); return { type: ActionTypes.Stop, activity: activity, exec: undefined }; } function resolveStop(action, context, _event) { var actorRefOrString = isFunction(action.activity) ? action.activity(context, _event.data) : action.activity; var resolvedActorRef = typeof actorRefOrString === 'string' ? { id: actorRefOrString } : actorRefOrString; var actionObject = { type: ActionTypes.Stop, activity: resolvedActorRef }; return actionObject; } /** * Updates the current context of the machine. * * @param assignment An object that represents the partial context to update. */ var assign$1 = function (assignment) { return { type: assign$2, assignment: assignment }; }; /** * Returns an event type that represents an implicit event that * is sent after the specified `delay`. * * @param delayRef The delay in milliseconds * @param id The state node ID where this event is handled */ function after(delayRef, id) { var idSuffix = id ? "#".concat(id) : ''; return "".concat(ActionTypes.After, "(").concat(delayRef, ")").concat(idSuffix); } /** * Returns an event that represents that a final state node * has been reached in the parent state node. * * @param id The final state node's parent state node `id` * @param data The data to pass into the event */ function done(id, data) { var type = "".concat(ActionTypes.DoneState, ".").concat(id); var eventObject = { type: type, data: data }; eventObject.toString = function () { return type; }; return eventObject; } /** * Returns an event that represents that an invoked service has terminated. * * An invoked service is terminated when it has reached a top-level final state node, * but not when it is canceled. * * @param id The final state node ID * @param data The data to pass into the event */ function doneInvoke(id, data) { var type = "".concat(ActionTypes.DoneInvoke, ".").concat(id); var eventObject = { type: type, data: data }; eventObject.toString = function () { return type; }; return eventObject; } function error(id, data) { var type = "".concat(ActionTypes.ErrorPlatform, ".").concat(id); var eventObject = { type: type, data: data }; eventObject.toString = function () { return type; }; return eventObject; } function resolveActions(machine, currentState, currentContext, _event, actions, preserveActionOrder) { if (preserveActionOrder === void 0) { preserveActionOrder = false; } var _a = __read$1(preserveActionOrder ? [[], actions] : partition$1(actions, function (action) { return action.type === assign$2; }), 2), assignActions = _a[0], otherActions = _a[1]; var updatedContext = assignActions.length ? updateContext(currentContext, _event, assignActions, currentState) : currentContext; var preservedContexts = preserveActionOrder ? [currentContext] : undefined; var resolvedActions = flatten(otherActions.map(function (actionObject) { var _a; switch (actionObject.type) { case raise$1: return resolveRaise(actionObject); case send$1: var sendAction = resolveSend(actionObject, updatedContext, _event, machine.options.delays); // TODO: fix ActionTypes.Init return sendAction; case log: return resolveLog(actionObject, updatedContext, _event); case choose: { var chooseAction = actionObject; var matchedActions = (_a = chooseAction.conds.find(function (condition) { var guard = toGuard(condition.cond, machine.options.guards); return !guard || evaluateGuard(machine, guard, updatedContext, _event, currentState); })) === null || _a === void 0 ? void 0 : _a.actions; if (!matchedActions) { return []; } var _b = __read$1(resolveActions(machine, currentState, updatedContext, _event, toActionObjects(toArray(matchedActions), machine.options.actions), preserveActionOrder), 2), resolvedActionsFromChoose = _b[0], resolvedContextFromChoose = _b[1]; updatedContext = resolvedContextFromChoose; preservedContexts === null || preservedContexts === void 0 ? void 0 : preservedContexts.push(updatedContext); return resolvedActionsFromChoose; } case pure: { var matchedActions = actionObject.get(updatedContext, _event.data); if (!matchedActions) { return []; } var _c = __read$1(resolveActions(machine, currentState, updatedContext, _event, toActionObjects(toArray(matchedActions), machine.options.actions), preserveActionOrder), 2), resolvedActionsFromPure = _c[0], resolvedContext = _c[1]; updatedContext = resolvedContext; preservedContexts === null || preservedContexts === void 0 ? void 0 : preservedContexts.push(updatedContext); return resolvedActionsFromPure; } case stop$1: { return resolveStop(actionObject, updatedContext, _event); } case assign$2: { updatedContext = updateContext(updatedContext, _event, [actionObject], currentState); preservedContexts === null || preservedContexts === void 0 ? void 0 : preservedContexts.push(updatedContext); break; } default: var resolvedActionObject = toActionObject(actionObject, machine.options.actions); var exec_1 = resolvedActionObject.exec; if (exec_1 && preservedContexts) { var contextIndex_1 = preservedContexts.length - 1; resolvedActionObject = __assign$4(__assign$4({}, resolvedActionObject), { exec: function (_ctx) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } exec_1.apply(void 0, __spreadArray([preservedContexts[contextIndex_1]], __read$1(args), false)); } }); } return resolvedActionObject; } }).filter(function (a) { return !!a; })); return [resolvedActions, updatedContext]; } /** * Maintains a stack of the current service in scope. * This is used to provide the correct service to spawn(). */ var provide = function (service, fn) { var result = fn(service); return result; }; function createNullActor(id) { var _a; return _a = { id: id, send: function () { return void 0; }, subscribe: function () { return { unsubscribe: function () { return void 0; } }; }, getSnapshot: function () { return undefined; }, toJSON: function () { return { id: id }; } }, _a[symbolObservable] = function () { return this; }, _a; } /** * Creates a deferred actor that is able to be invoked given the provided * invocation information in its `.meta` value. * * @param invokeDefinition The meta information needed to invoke the actor. */ function createInvocableActor(invokeDefinition, machine, context, _event) { var _a; var invokeSrc = toInvokeSource$1(invokeDefinition.src); var serviceCreator = (_a = machine === null || machine === void 0 ? void 0 : machine.options.services) === null || _a === void 0 ? void 0 : _a[invokeSrc.type]; var resolvedData = invokeDefinition.data ? mapContext(invokeDefinition.data, context, _event) : undefined; var tempActor = serviceCreator ? createDeferredActor(serviceCreator, invokeDefinition.id, resolvedData) : createNullActor(invokeDefinition.id); // @ts-ignore tempActor.meta = invokeDefinition; return tempActor; } function createDeferredActor(entity, id, data) { var tempActor = createNullActor(id); // @ts-ignore tempActor.deferred = true; if (isMachine(entity)) { // "mute" the existing service scope so potential spawned actors within the `.initialState` stay deferred here var initialState_1 = tempActor.state = provide(undefined, function () { return (data ? entity.withContext(data) : entity).initialState; }); tempActor.getSnapshot = function () { return initialState_1; }; } return tempActor; } function isActor(item) { try { return typeof item.send === 'function'; } catch (e) { return false; } } function isSpawnedActor(item) { return isActor(item) && 'id' in item; } // TODO: refactor the return type, this could be written in a better way but it's best to avoid unneccessary breaking changes now function toActorRef(actorRefLike) { var _a; return __assign$4((_a = { subscribe: function () { return { unsubscribe: function () { return void 0; } }; }, id: 'anonymous', getSnapshot: function () { return undefined; } }, _a[symbolObservable] = function () { return this; }, _a), actorRefLike); } var isLeafNode = function (stateNode) { return stateNode.type === 'atomic' || stateNode.type === 'final'; }; function getChildren$1(stateNode) { return Object.keys(stateNode.states).map(function (key) { return stateNode.states[key]; }).filter(function (sn) { return sn.type !== 'history'; }); } function getAllStateNodes(stateNode) { var stateNodes = [stateNode]; if (isLeafNode(stateNode)) { return stateNodes; } return stateNodes.concat(flatten(getChildren$1(stateNode).map(getAllStateNodes))); } function getConfiguration(prevStateNodes, stateNodes) { var e_1, _a, e_2, _b, e_3, _c, e_4, _d; var prevConfiguration = new Set(prevStateNodes); var prevAdjList = getAdjList(prevConfiguration); var configuration = new Set(stateNodes); try { // add all ancestors for (var configuration_1 = __values(configuration), configuration_1_1 = configuration_1.next(); !configuration_1_1.done; configuration_1_1 = configuration_1.next()) { var s = configuration_1_1.value; var m = s.parent; while (m && !configuration.has(m)) { configuration.add(m); m = m.parent; } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (configuration_1_1 && !configuration_1_1.done && (_a = configuration_1.return)) _a.call(configuration_1); } finally { if (e_1) throw e_1.error; } } var adjList = getAdjList(configuration); try { // add descendants for (var configuration_2 = __values(configuration), configuration_2_1 = configuration_2.next(); !configuration_2_1.done; configuration_2_1 = configuration_2.next()) { var s = configuration_2_1.value; // if previously active, add existing child nodes if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) { if (prevAdjList.get(s)) { prevAdjList.get(s).forEach(function (sn) { return configuration.add(sn); }); } else { s.initialStateNodes.forEach(function (sn) { return configuration.add(sn); }); } } else { if (s.type === 'parallel') { try { for (var _e = (e_3 = void 0, __values(getChildren$1(s))), _f = _e.next(); !_f.done; _f = _e.next()) { var child = _f.value; if (!configuration.has(child)) { configuration.add(child); if (prevAdjList.get(child)) { prevAdjList.get(child).forEach(function (sn) { return configuration.add(sn); }); } else { child.initialStateNodes.forEach(function (sn) { return configuration.add(sn); }); } } } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (_f && !_f.done && (_c = _e.return)) _c.call(_e); } finally { if (e_3) throw e_3.error; } } } } } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (configuration_2_1 && !configuration_2_1.done && (_b = configuration_2.return)) _b.call(configuration_2); } finally { if (e_2) throw e_2.error; } } try { // add all ancestors for (var configuration_3 = __values(configuration), configuration_3_1 = configuration_3.next(); !configuration_3_1.done; configuration_3_1 = configuration_3.next()) { var s = configuration_3_1.value; var m = s.parent; while (m && !configuration.has(m)) { configuration.add(m); m = m.parent; } } } catch (e_4_1) { e_4 = { error: e_4_1 }; } finally { try { if (configuration_3_1 && !configuration_3_1.done && (_d = configuration_3.return)) _d.call(configuration_3); } finally { if (e_4) throw e_4.error; } } return configuration; } function getValueFromAdj(baseNode, adjList) { var childStateNodes = adjList.get(baseNode); if (!childStateNodes) { return {}; // todo: fix? } if (baseNode.type === 'compound') { var childStateNode = childStateNodes[0]; if (childStateNode) { if (isLeafNode(childStateNode)) { return childStateNode.key; } } else { return {}; } } var stateValue = {}; childStateNodes.forEach(function (csn) { stateValue[csn.key] = getValueFromAdj(csn, adjList); }); return stateValue; } function getAdjList(configuration) { var e_5, _a; var adjList = new Map(); try { for (var configuration_4 = __values(configuration), configuration_4_1 = configuration_4.next(); !configuration_4_1.done; configuration_4_1 = configuration_4.next()) { var s = configuration_4_1.value; if (!adjList.has(s)) { adjList.set(s, []); } if (s.parent) { if (!adjList.has(s.parent)) { adjList.set(s.parent, []); } adjList.get(s.parent).push(s); } } } catch (e_5_1) { e_5 = { error: e_5_1 }; } finally { try { if (configuration_4_1 && !configuration_4_1.done && (_a = configuration_4.return)) _a.call(configuration_4); } finally { if (e_5) throw e_5.error; } } return adjList; } function getValue(rootNode, configuration) { var config = getConfiguration([rootNode], configuration); return getValueFromAdj(rootNode, getAdjList(config)); } function has(iterable, item) { if (Array.isArray(iterable)) { return iterable.some(function (member) { return member === item; }); } if (iterable instanceof Set) { return iterable.has(item); } return false; // TODO: fix } function nextEvents(configuration) { return __spreadArray([], __read$1(new Set(flatten(__spreadArray([], __read$1(configuration.map(function (sn) { return sn.ownEvents; })), false)))), false); } function isInFinalState(configuration, stateNode) { if (stateNode.type === 'compound') { return getChildren$1(stateNode).some(function (s) { return s.type === 'final' && has(configuration, s); }); } if (stateNode.type === 'parallel') { return getChildren$1(stateNode).every(function (sn) { return isInFinalState(configuration, sn); }); } return false; } function getMeta(configuration) { if (configuration === void 0) { configuration = []; } return configuration.reduce(function (acc, stateNode) { if (stateNode.meta !== undefined) { acc[stateNode.id] = stateNode.meta; } return acc; }, {}); } function getTagsFromConfiguration(configuration) { return new Set(flatten(configuration.map(function (sn) { return sn.tags; }))); } function stateValuesEqual(a, b) { if (a === b) { return true; } if (a === undefined || b === undefined) { return false; } if (isString(a) || isString(b)) { return a === b; } var aKeys = Object.keys(a); var bKeys = Object.keys(b); return aKeys.length === bKeys.length && aKeys.every(function (key) { return stateValuesEqual(a[key], b[key]); }); } function isStateConfig(state) { if (typeof state !== 'object' || state === null) { return false; } return 'value' in state && '_event' in state; } function bindActionToState(action, state) { var exec = action.exec; var boundAction = __assign$4(__assign$4({}, action), { exec: exec !== undefined ? function () { return exec(state.context, state.event, { action: action, state: state, _event: state._event }); } : undefined }); return boundAction; } var State = /*#__PURE__*/ /** @class */ function () { /** * Creates a new State instance. * @param value The state value * @param context The extended state * @param historyValue The tree representing historical values of the state nodes * @param history The previous state * @param actions An array of action objects to execute as side-effects * @param activities A mapping of activities and whether they are started (`true`) or stopped (`false`). * @param meta * @param events Internal event queue. Should be empty with run-to-completion semantics. * @param configuration */ function State(config) { var _this = this; var _a; this.actions = []; this.activities = EMPTY_ACTIVITY_MAP; this.meta = {}; this.events = []; this.value = config.value; this.context = config.context; this._event = config._event; this._sessionid = config._sessionid; this.event = this._event.data; this.historyValue = config.historyValue; this.history = config.history; this.actions = config.actions || []; this.activities = config.activities || EMPTY_ACTIVITY_MAP; this.meta = getMeta(config.configuration); this.events = config.events || []; this.matches = this.matches.bind(this); this.toStrings = this.toStrings.bind(this); this.configuration = config.configuration; this.transitions = config.transitions; this.children = config.children; this.done = !!config.done; this.tags = (_a = Array.isArray(config.tags) ? new Set(config.tags) : config.tags) !== null && _a !== void 0 ? _a : new Set(); this.machine = config.machine; Object.defineProperty(this, 'nextEvents', { get: function () { return nextEvents(_this.configuration); } }); } /** * Creates a new State instance for the given `stateValue` and `context`. * @param stateValue * @param context */ State.from = function (stateValue, context) { if (stateValue instanceof State) { if (stateValue.context !== context) { return new State({ value: stateValue.value, context: context, _event: stateValue._event, _sessionid: null, historyValue: stateValue.historyValue, history: stateValue.history, actions: [], activities: stateValue.activities, meta: {}, events: [], configuration: [], transitions: [], children: {} }); } return stateValue; } var _event = initEvent; return new State({ value: stateValue, context: context, _event: _event, _sessionid: null, historyValue: undefined, history: undefined, actions: [], activities: undefined, meta: undefined, events: [], configuration: [], transitions: [], children: {} }); }; /** * Creates a new State instance for the given `config`. * @param config The state config */ State.create = function (config) { return new State(config); }; /** * Creates a new `State` instance for the given `stateValue` and `context` with no actions (side-effects). * @param stateValue * @param context */ State.inert = function (stateValue, context) { if (stateValue instanceof State) { if (!stateValue.actions.length) { return stateValue; } var _event = initEvent; return new State({ value: stateValue.value, context: context, _event: _event, _sessionid: null, historyValue: stateValue.historyValue, history: stateValue.history, activities: stateValue.activities, configuration: stateValue.configuration, transitions: [], children: {} }); } return State.from(stateValue, context); }; /** * Returns an array of all the string leaf state node paths. * @param stateValue * @param delimiter The character(s) that separate each subpath in the string state node path. */ State.prototype.toStrings = function (stateValue, delimiter) { var _this = this; if (stateValue === void 0) { stateValue = this.value; } if (delimiter === void 0) { delimiter = '.'; } if (isString(stateValue)) { return [stateValue]; } var valueKeys = Object.keys(stateValue); return valueKeys.concat.apply(valueKeys, __spreadArray([], __read$1(valueKeys.map(function (key) { return _this.toStrings(stateValue[key], delimiter).map(function (s) { return key + delimiter + s; }); })), false)); }; State.prototype.toJSON = function () { var _a = this; _a.configuration; _a.transitions; var tags = _a.tags; _a.machine; var jsonValues = __rest$1(_a, ["configuration", "transitions", "tags", "machine"]); return __assign$4(__assign$4({}, jsonValues), { tags: Array.from(tags) }); }; State.prototype.matches = function (parentStateValue) { return matchesState(parentStateValue, this.value); }; /** * Whether the current state configuration has a state node with the specified `tag`. * @param tag */ State.prototype.hasTag = function (tag) { return this.tags.has(tag); }; /** * Determines whether sending the `event` will cause a non-forbidden transition * to be selected, even if the transitions have no actions nor * change the state value. * * @param event The event to test * @returns Whether the event will cause a transition */ State.prototype.can = function (event) { var _a; { warn(!!this.machine); } var transitionData = (_a = this.machine) === null || _a === void 0 ? void 0 : _a.getTransitionData(this, event); return !!(transitionData === null || transitionData === void 0 ? void 0 : transitionData.transitions.length) && // Check that at least one transition is not forbidden transitionData.transitions.some(function (t) { return t.target !== undefined || t.actions.length; }); }; return State; }(); var defaultOptions = { deferEvents: false }; var Scheduler = /*#__PURE__*/ /** @class */ function () { function Scheduler(options) { this.processingEvent = false; this.queue = []; this.initialized = false; this.options = __assign$4(__assign$4({}, defaultOptions), options); } Scheduler.prototype.initialize = function (callback) { this.initialized = true; if (callback) { if (!this.options.deferEvents) { this.schedule(callback); return; } this.process(callback); } this.flushEvents(); }; Scheduler.prototype.schedule = function (task) { if (!this.initialized || this.processingEvent) { this.queue.push(task); return; } if (this.queue.length !== 0) { throw new Error('Event queue should be empty when it is not processing events'); } this.process(task); this.flushEvents(); }; Scheduler.prototype.clear = function () { this.queue = []; }; Scheduler.prototype.flushEvents = function () { var nextCallback = this.queue.shift(); while (nextCallback) { this.process(nextCallback); nextCallback = this.queue.shift(); } }; Scheduler.prototype.process = function (callback) { this.processingEvent = true; try { callback(); } catch (e) { // there is no use to keep the future events // as the situation is not anymore the same this.clear(); throw e; } finally { this.processingEvent = false; } }; return Scheduler; }(); var children = /*#__PURE__*/new Map(); var sessionIdIndex = 0; var registry = { bookId: function () { return "x:".concat(sessionIdIndex++); }, register: function (id, actor) { children.set(id, actor); return id; }, get: function (id) { return children.get(id); }, free: function (id) { children.delete(id); } }; function getGlobal() { if (typeof globalThis !== 'undefined') { return globalThis; } if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } } function getDevTools() { var global = getGlobal(); if (global && '__xstate__' in global) { return global.__xstate__; } return undefined; } function registerService(service) { if (!getGlobal()) { return; } var devTools = getDevTools(); if (devTools) { devTools.register(service); } } function spawnBehavior(behavior, options) { if (options === void 0) { options = {}; } var state = behavior.initialState; var observers = new Set(); var mailbox = []; var flushing = false; var flush = function () { if (flushing) { return; } flushing = true; while (mailbox.length > 0) { var event_1 = mailbox.shift(); state = behavior.transition(state, event_1, actorCtx); observers.forEach(function (observer) { return observer.next(state); }); } flushing = false; }; var actor = toActorRef({ id: options.id, send: function (event) { mailbox.push(event); flush(); }, getSnapshot: function () { return state; }, subscribe: function (next, handleError, complete) { var observer = toObserver(next, handleError, complete); observers.add(observer); observer.next(state); return { unsubscribe: function () { observers.delete(observer); } }; } }); var actorCtx = { parent: options.parent, self: actor, id: options.id || 'anonymous', observers: observers }; state = behavior.start ? behavior.start(actorCtx) : state; return actor; } var DEFAULT_SPAWN_OPTIONS = { sync: false, autoForward: false }; var InterpreterStatus; (function (InterpreterStatus) { InterpreterStatus[InterpreterStatus["NotStarted"] = 0] = "NotStarted"; InterpreterStatus[InterpreterStatus["Running"] = 1] = "Running"; InterpreterStatus[InterpreterStatus["Stopped"] = 2] = "Stopped"; })(InterpreterStatus || (InterpreterStatus = {})); var Interpreter = /*#__PURE__*/ /** @class */ function () { /** * Creates a new Interpreter instance (i.e., service) for the given machine with the provided options, if any. * * @param machine The machine to be interpreted * @param options Interpreter options */ function Interpreter(machine, options) { var _this = this; if (options === void 0) { options = Interpreter.defaultOptions; } this.machine = machine; this.delayedEventsMap = {}; this.listeners = new Set(); this.contextListeners = new Set(); this.stopListeners = new Set(); this.doneListeners = new Set(); this.eventListeners = new Set(); this.sendListeners = new Set(); /** * Whether the service is started. */ this.initialized = false; this.status = InterpreterStatus.NotStarted; this.children = new Map(); this.forwardTo = new Set(); /** * Alias for Interpreter.prototype.start */ this.init = this.start; /** * Sends an event to the running interpreter to trigger a transition. * * An array of events (batched) can be sent as well, which will send all * batched events to the running interpreter. The listeners will be * notified only **once** when all events are processed. * * @param event The event(s) to send */ this.send = function (event, payload) { if (isArray$1(event)) { _this.batch(event); return _this.state; } var _event = toSCXMLEvent(toEventObject(event, payload)); if (_this.status === InterpreterStatus.Stopped) { return _this.state; } if (_this.status !== InterpreterStatus.Running && !_this.options.deferEvents) { throw new Error("Event \"".concat(_event.name, "\" was sent to uninitialized service \"").concat(_this.machine.id // tslint:disable-next-line:max-line-length , "\". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.\nEvent: ").concat(JSON.stringify(_event.data))); } _this.scheduler.schedule(function () { // Forward copy of event to child actors _this.forward(_event); var nextState = _this.nextState(_event); _this.update(nextState, _event); }); return _this._state; // TODO: deprecate (should return void) // tslint:disable-next-line:semicolon }; this.sendTo = function (event, to) { var isParent = _this.parent && (to === SpecialTargets.Parent || _this.parent.id === to); var target = isParent ? _this.parent : isString(to) ? _this.children.get(to) || registry.get(to) : isActor$1(to) ? to : undefined; if (!target) { if (!isParent) { throw new Error("Unable to send event to child '".concat(to, "' from service '").concat(_this.id, "'.")); } // tslint:disable-next-line:no-console return; } if ('machine' in target) { // Send SCXML events to machines target.send(__assign$4(__assign$4({}, event), { name: event.name === error$1 ? "".concat(error(_this.id)) : event.name, origin: _this.sessionId })); } else { // Send normal events to other targets target.send(event.data); } }; var resolvedOptions = __assign$4(__assign$4({}, Interpreter.defaultOptions), options); var clock = resolvedOptions.clock, logger = resolvedOptions.logger, parent = resolvedOptions.parent, id = resolvedOptions.id; var resolvedId = id !== undefined ? id : machine.id; this.id = resolvedId; this.logger = logger; this.clock = clock; this.parent = parent; this.options = resolvedOptions; this.scheduler = new Scheduler({ deferEvents: this.options.deferEvents }); this.sessionId = registry.bookId(); } Object.defineProperty(Interpreter.prototype, "initialState", { get: function () { var _this = this; if (this._initialState) { return this._initialState; } return provide(this, function () { _this._initialState = _this.machine.initialState; return _this._initialState; }); }, enumerable: false, configurable: true }); Object.defineProperty(Interpreter.prototype, "state", { get: function () { return this._state; }, enumerable: false, configurable: true }); /** * Executes the actions of the given state, with that state's `context` and `event`. * * @param state The state whose actions will be executed * @param actionsConfig The action implementations to use */ Interpreter.prototype.execute = function (state, actionsConfig) { var e_1, _a; try { for (var _b = __values(state.actions), _c = _b.next(); !_c.done; _c = _b.next()) { var action = _c.value; this.exec(action, state, actionsConfig); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } }; Interpreter.prototype.update = function (state, _event) { var e_2, _a, e_3, _b, e_4, _c, e_5, _d; var _this = this; // Attach session ID to state state._sessionid = this.sessionId; // Update state this._state = state; // Execute actions if (this.options.execute) { this.execute(this.state); } // Update children this.children.forEach(function (child) { _this.state.children[child.id] = child; }); // Dev tools if (this.devTools) { this.devTools.send(_event.data, state); } // Execute listeners if (state.event) { try { for (var _e = __values(this.eventListeners), _f = _e.next(); !_f.done; _f = _e.next()) { var listener = _f.value; listener(state.event); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_f && !_f.done && (_a = _e.return)) _a.call(_e); } finally { if (e_2) throw e_2.error; } } } try { for (var _g = __values(this.listeners), _h = _g.next(); !_h.done; _h = _g.next()) { var listener = _h.value; listener(state, state.event); } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (_h && !_h.done && (_b = _g.return)) _b.call(_g); } finally { if (e_3) throw e_3.error; } } try { for (var _j = __values(this.contextListeners), _k = _j.next(); !_k.done; _k = _j.next()) { var contextListener = _k.value; contextListener(this.state.context, this.state.history ? this.state.history.context : undefined); } } catch (e_4_1) { e_4 = { error: e_4_1 }; } finally { try { if (_k && !_k.done && (_c = _j.return)) _c.call(_j); } finally { if (e_4) throw e_4.error; } } var isDone = isInFinalState(state.configuration || [], this.machine); if (this.state.configuration && isDone) { // get final child state node var finalChildStateNode = state.configuration.find(function (sn) { return sn.type === 'final' && sn.parent === _this.machine; }); var doneData = finalChildStateNode && finalChildStateNode.doneData ? mapContext(finalChildStateNode.doneData, state.context, _event) : undefined; try { for (var _l = __values(this.doneListeners), _m = _l.next(); !_m.done; _m = _l.next()) { var listener = _m.value; listener(doneInvoke(this.id, doneData)); } } catch (e_5_1) { e_5 = { error: e_5_1 }; } finally { try { if (_m && !_m.done && (_d = _l.return)) _d.call(_l); } finally { if (e_5) throw e_5.error; } } this.stop(); } }; /* * Adds a listener that is notified whenever a state transition happens. The listener is called with * the next state and the event object that caused the state transition. * * @param listener The state listener */ Interpreter.prototype.onTransition = function (listener) { this.listeners.add(listener); // Send current state to listener if (this.status === InterpreterStatus.Running) { listener(this.state, this.state.event); } return this; }; Interpreter.prototype.subscribe = function (nextListenerOrObserver, _, // TODO: error listener completeListener) { var _this = this; if (!nextListenerOrObserver) { return { unsubscribe: function () { return void 0; } }; } var listener; var resolvedCompleteListener = completeListener; if (typeof nextListenerOrObserver === 'function') { listener = nextListenerOrObserver; } else { listener = nextListenerOrObserver.next.bind(nextListenerOrObserver); resolvedCompleteListener = nextListenerOrObserver.complete.bind(nextListenerOrObserver); } this.listeners.add(listener); // Send current state to listener if (this.status !== InterpreterStatus.NotStarted) { listener(this.state); } if (resolvedCompleteListener) { if (this.status === InterpreterStatus.Stopped) { resolvedCompleteListener(); } else { this.onDone(resolvedCompleteListener); } } return { unsubscribe: function () { listener && _this.listeners.delete(listener); resolvedCompleteListener && _this.doneListeners.delete(resolvedCompleteListener); } }; }; /** * Adds an event listener that is notified whenever an event is sent to the running interpreter. * @param listener The event listener */ Interpreter.prototype.onEvent = function (listener) { this.eventListeners.add(listener); return this; }; /** * Adds an event listener that is notified whenever a `send` event occurs. * @param listener The event listener */ Interpreter.prototype.onSend = function (listener) { this.sendListeners.add(listener); return this; }; /** * Adds a context listener that is notified whenever the state context changes. * @param listener The context listener */ Interpreter.prototype.onChange = function (listener) { this.contextListeners.add(listener); return this; }; /** * Adds a listener that is notified when the machine is stopped. * @param listener The listener */ Interpreter.prototype.onStop = function (listener) { this.stopListeners.add(listener); return this; }; /** * Adds a state listener that is notified when the statechart has reached its final state. * @param listener The state listener */ Interpreter.prototype.onDone = function (listener) { this.doneListeners.add(listener); return this; }; /** * Removes a listener. * @param listener The listener to remove */ Interpreter.prototype.off = function (listener) { this.listeners.delete(listener); this.eventListeners.delete(listener); this.sendListeners.delete(listener); this.stopListeners.delete(listener); this.doneListeners.delete(listener); this.contextListeners.delete(listener); return this; }; /** * Starts the interpreter from the given state, or the initial state. * @param initialState The state to start the statechart from */ Interpreter.prototype.start = function (initialState) { var _this = this; if (this.status === InterpreterStatus.Running) { // Do not restart the service if it is already started return this; } // yes, it's a hack but we need the related cache to be populated for some things to work (like delayed transitions) // this is usually called by `machine.getInitialState` but if we rehydrate from a state we might bypass this call // we also don't want to call this method here as it resolves the full initial state which might involve calling assign actions // and that could potentially lead to some unwanted side-effects (even such as creating some rogue actors) this.machine._init(); registry.register(this.sessionId, this); this.initialized = true; this.status = InterpreterStatus.Running; var resolvedState = initialState === undefined ? this.initialState : provide(this, function () { return isStateConfig(initialState) ? _this.machine.resolveState(initialState) : _this.machine.resolveState(State.from(initialState, _this.machine.context)); }); if (this.options.devTools) { this.attachDev(); } this.scheduler.initialize(function () { _this.update(resolvedState, initEvent); }); return this; }; /** * Stops the interpreter and unsubscribe all listeners. * * This will also notify the `onStop` listeners. */ Interpreter.prototype.stop = function () { var e_6, _a, e_7, _b, e_8, _c, e_9, _d, e_10, _e; var _this = this; try { for (var _f = __values(this.listeners), _g = _f.next(); !_g.done; _g = _f.next()) { var listener = _g.value; this.listeners.delete(listener); } } catch (e_6_1) { e_6 = { error: e_6_1 }; } finally { try { if (_g && !_g.done && (_a = _f.return)) _a.call(_f); } finally { if (e_6) throw e_6.error; } } try { for (var _h = __values(this.stopListeners), _j = _h.next(); !_j.done; _j = _h.next()) { var listener = _j.value; // call listener, then remove listener(); this.stopListeners.delete(listener); } } catch (e_7_1) { e_7 = { error: e_7_1 }; } finally { try { if (_j && !_j.done && (_b = _h.return)) _b.call(_h); } finally { if (e_7) throw e_7.error; } } try { for (var _k = __values(this.contextListeners), _l = _k.next(); !_l.done; _l = _k.next()) { var listener = _l.value; this.contextListeners.delete(listener); } } catch (e_8_1) { e_8 = { error: e_8_1 }; } finally { try { if (_l && !_l.done && (_c = _k.return)) _c.call(_k); } finally { if (e_8) throw e_8.error; } } try { for (var _m = __values(this.doneListeners), _o = _m.next(); !_o.done; _o = _m.next()) { var listener = _o.value; this.doneListeners.delete(listener); } } catch (e_9_1) { e_9 = { error: e_9_1 }; } finally { try { if (_o && !_o.done && (_d = _m.return)) _d.call(_m); } finally { if (e_9) throw e_9.error; } } if (!this.initialized) { // Interpreter already stopped; do nothing return this; } __spreadArray([], __read$1(this.state.configuration), false).sort(function (a, b) { return b.order - a.order; }).forEach(function (stateNode) { var e_11, _a; try { for (var _b = __values(stateNode.definition.exit), _c = _b.next(); !_c.done; _c = _b.next()) { var action = _c.value; _this.exec(action, _this.state); } } catch (e_11_1) { e_11 = { error: e_11_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_11) throw e_11.error; } } }); // Stop all children this.children.forEach(function (child) { if (isFunction(child.stop)) { child.stop(); } }); this.children.clear(); try { // Cancel all delayed events for (var _p = __values(Object.keys(this.delayedEventsMap)), _q = _p.next(); !_q.done; _q = _p.next()) { var key = _q.value; this.clock.clearTimeout(this.delayedEventsMap[key]); } } catch (e_10_1) { e_10 = { error: e_10_1 }; } finally { try { if (_q && !_q.done && (_e = _p.return)) _e.call(_p); } finally { if (e_10) throw e_10.error; } } this.scheduler.clear(); this.scheduler = new Scheduler({ deferEvents: this.options.deferEvents }); this.initialized = false; this.status = InterpreterStatus.Stopped; this._initialState = undefined; registry.free(this.sessionId); return this; }; Interpreter.prototype.batch = function (events) { var _this = this; if (this.status === InterpreterStatus.NotStarted && this.options.deferEvents) ; else if (this.status !== InterpreterStatus.Running) { throw new Error( // tslint:disable-next-line:max-line-length "".concat(events.length, " event(s) were sent to uninitialized service \"").concat(this.machine.id, "\". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.")); } this.scheduler.schedule(function () { var e_12, _a; var nextState = _this.state; var batchChanged = false; var batchedActions = []; var _loop_1 = function (event_1) { var _event = toSCXMLEvent(event_1); _this.forward(_event); nextState = provide(_this, function () { return _this.machine.transition(nextState, _event); }); batchedActions.push.apply(batchedActions, __spreadArray([], __read$1(nextState.actions.map(function (a) { return bindActionToState(a, nextState); })), false)); batchChanged = batchChanged || !!nextState.changed; }; try { for (var events_1 = __values(events), events_1_1 = events_1.next(); !events_1_1.done; events_1_1 = events_1.next()) { var event_1 = events_1_1.value; _loop_1(event_1); } } catch (e_12_1) { e_12 = { error: e_12_1 }; } finally { try { if (events_1_1 && !events_1_1.done && (_a = events_1.return)) _a.call(events_1); } finally { if (e_12) throw e_12.error; } } nextState.changed = batchChanged; nextState.actions = batchedActions; _this.update(nextState, toSCXMLEvent(events[events.length - 1])); }); }; /** * Returns a send function bound to this interpreter instance. * * @param event The event to be sent by the sender. */ Interpreter.prototype.sender = function (event) { return this.send.bind(this, event); }; /** * Returns the next state given the interpreter's current state and the event. * * This is a pure method that does _not_ update the interpreter's state. * * @param event The event to determine the next state */ Interpreter.prototype.nextState = function (event) { var _this = this; var _event = toSCXMLEvent(event); if (_event.name.indexOf(errorPlatform) === 0 && !this.state.nextEvents.some(function (nextEvent) { return nextEvent.indexOf(errorPlatform) === 0; })) { throw _event.data.data; } var nextState = provide(this, function () { return _this.machine.transition(_this.state, _event); }); return nextState; }; Interpreter.prototype.forward = function (event) { var e_13, _a; try { for (var _b = __values(this.forwardTo), _c = _b.next(); !_c.done; _c = _b.next()) { var id = _c.value; var child = this.children.get(id); if (!child) { throw new Error("Unable to forward event '".concat(event, "' from interpreter '").concat(this.id, "' to nonexistant child '").concat(id, "'.")); } child.send(event); } } catch (e_13_1) { e_13 = { error: e_13_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_13) throw e_13.error; } } }; Interpreter.prototype.defer = function (sendAction) { var _this = this; this.delayedEventsMap[sendAction.id] = this.clock.setTimeout(function () { if (sendAction.to) { _this.sendTo(sendAction._event, sendAction.to); } else { _this.send(sendAction._event); } }, sendAction.delay); }; Interpreter.prototype.cancel = function (sendId) { this.clock.clearTimeout(this.delayedEventsMap[sendId]); delete this.delayedEventsMap[sendId]; }; Interpreter.prototype.exec = function (action, state, actionFunctionMap) { if (actionFunctionMap === void 0) { actionFunctionMap = this.machine.options.actions; } var context = state.context, _event = state._event; var actionOrExec = action.exec || getActionFunction(action.type, actionFunctionMap); var exec = isFunction(actionOrExec) ? actionOrExec : actionOrExec ? actionOrExec.exec : action.exec; if (exec) { try { return exec(context, _event.data, { action: action, state: this.state, _event: _event }); } catch (err) { if (this.parent) { this.parent.send({ type: 'xstate.error', data: err }); } throw err; } } switch (action.type) { case send$1: var sendAction = action; if (typeof sendAction.delay === 'number') { this.defer(sendAction); return; } else { if (sendAction.to) { this.sendTo(sendAction._event, sendAction.to); } else { this.send(sendAction._event); } } break; case cancel$1: this.cancel(action.sendId); break; case start$1: { if (this.status !== InterpreterStatus.Running) { return; } var activity = action.activity; // If the activity will be stopped right after it's started // (such as in transient states) // don't bother starting the activity. if (!this.state.activities[activity.id || activity.type]) { break; } // Invoked services if (activity.type === ActionTypes.Invoke) { var invokeSource = toInvokeSource$1(activity.src); var serviceCreator = this.machine.options.services ? this.machine.options.services[invokeSource.type] : undefined; var id = activity.id, data = activity.data; var autoForward = 'autoForward' in activity ? activity.autoForward : !!activity.forward; if (!serviceCreator) { return; } var resolvedData = data ? mapContext(data, context, _event) : undefined; if (typeof serviceCreator === 'string') { // TODO: warn return; } var source = isFunction(serviceCreator) ? serviceCreator(context, _event.data, { data: resolvedData, src: invokeSource, meta: activity.meta }) : serviceCreator; if (!source) { // TODO: warn? return; } var options = void 0; if (isMachine(source)) { source = resolvedData ? source.withContext(resolvedData) : source; options = { autoForward: autoForward }; } this.spawn(source, id, options); } else { this.spawnActivity(activity); } break; } case stop$1: { this.stopChild(action.activity.id); break; } case log: var label = action.label, value = action.value; if (label) { this.logger(label, value); } else { this.logger(value); } break; } return undefined; }; Interpreter.prototype.removeChild = function (childId) { var _a; this.children.delete(childId); this.forwardTo.delete(childId); // this.state might not exist at the time this is called, // such as when a child is added then removed while initializing the state (_a = this.state) === null || _a === void 0 ? true : delete _a.children[childId]; }; Interpreter.prototype.stopChild = function (childId) { var child = this.children.get(childId); if (!child) { return; } this.removeChild(childId); if (isFunction(child.stop)) { child.stop(); } }; Interpreter.prototype.spawn = function (entity, name, options) { if (isPromiseLike(entity)) { return this.spawnPromise(Promise.resolve(entity), name); } else if (isFunction(entity)) { return this.spawnCallback(entity, name); } else if (isSpawnedActor(entity)) { return this.spawnActor(entity, name); } else if (isObservable(entity)) { return this.spawnObservable(entity, name); } else if (isMachine(entity)) { return this.spawnMachine(entity, __assign$4(__assign$4({}, options), { id: name })); } else if (isBehavior(entity)) { return this.spawnBehavior(entity, name); } else { throw new Error("Unable to spawn entity \"".concat(name, "\" of type \"").concat(typeof entity, "\".")); } }; Interpreter.prototype.spawnMachine = function (machine, options) { var _this = this; if (options === void 0) { options = {}; } var childService = new Interpreter(machine, __assign$4(__assign$4({}, this.options), { parent: this, id: options.id || machine.id })); var resolvedOptions = __assign$4(__assign$4({}, DEFAULT_SPAWN_OPTIONS), options); if (resolvedOptions.sync) { childService.onTransition(function (state) { _this.send(update, { state: state, id: childService.id }); }); } var actor = childService; this.children.set(childService.id, actor); if (resolvedOptions.autoForward) { this.forwardTo.add(childService.id); } childService.onDone(function (doneEvent) { _this.removeChild(childService.id); _this.send(toSCXMLEvent(doneEvent, { origin: childService.id })); }).start(); return actor; }; Interpreter.prototype.spawnBehavior = function (behavior, id) { var actorRef = spawnBehavior(behavior, { id: id, parent: this }); this.children.set(id, actorRef); return actorRef; }; Interpreter.prototype.spawnPromise = function (promise, id) { var _a; var _this = this; var canceled = false; var resolvedData; promise.then(function (response) { if (!canceled) { resolvedData = response; _this.removeChild(id); _this.send(toSCXMLEvent(doneInvoke(id, response), { origin: id })); } }, function (errorData) { if (!canceled) { _this.removeChild(id); var errorEvent = error(id, errorData); try { // Send "error.platform.id" to this (parent). _this.send(toSCXMLEvent(errorEvent, { origin: id })); } catch (error) { if (_this.devTools) { _this.devTools.send(errorEvent, _this.state); } if (_this.machine.strict) { // it would be better to always stop the state machine if unhandled // exception/promise rejection happens but because we don't want to // break existing code so enforce it on strict mode only especially so // because documentation says that onError is optional _this.stop(); } } } }); var actor = (_a = { id: id, send: function () { return void 0; }, subscribe: function (next, handleError, complete) { var observer = toObserver(next, handleError, complete); var unsubscribed = false; promise.then(function (response) { if (unsubscribed) { return; } observer.next(response); if (unsubscribed) { return; } observer.complete(); }, function (err) { if (unsubscribed) { return; } observer.error(err); }); return { unsubscribe: function () { return unsubscribed = true; } }; }, stop: function () { canceled = true; }, toJSON: function () { return { id: id }; }, getSnapshot: function () { return resolvedData; } }, _a[symbolObservable] = function () { return this; }, _a); this.children.set(id, actor); return actor; }; Interpreter.prototype.spawnCallback = function (callback, id) { var _a; var _this = this; var canceled = false; var receivers = new Set(); var listeners = new Set(); var emitted; var receive = function (e) { emitted = e; listeners.forEach(function (listener) { return listener(e); }); if (canceled) { return; } _this.send(toSCXMLEvent(e, { origin: id })); }; var callbackStop; try { callbackStop = callback(receive, function (newListener) { receivers.add(newListener); }); } catch (err) { this.send(error(id, err)); } if (isPromiseLike(callbackStop)) { // it turned out to be an async function, can't reliably check this before calling `callback` // because transpiled async functions are not recognizable return this.spawnPromise(callbackStop, id); } var actor = (_a = { id: id, send: function (event) { return receivers.forEach(function (receiver) { return receiver(event); }); }, subscribe: function (next) { var observer = toObserver(next); listeners.add(observer.next); return { unsubscribe: function () { listeners.delete(observer.next); } }; }, stop: function () { canceled = true; if (isFunction(callbackStop)) { callbackStop(); } }, toJSON: function () { return { id: id }; }, getSnapshot: function () { return emitted; } }, _a[symbolObservable] = function () { return this; }, _a); this.children.set(id, actor); return actor; }; Interpreter.prototype.spawnObservable = function (source, id) { var _a; var _this = this; var emitted; var subscription = source.subscribe(function (value) { emitted = value; _this.send(toSCXMLEvent(value, { origin: id })); }, function (err) { _this.removeChild(id); _this.send(toSCXMLEvent(error(id, err), { origin: id })); }, function () { _this.removeChild(id); _this.send(toSCXMLEvent(doneInvoke(id), { origin: id })); }); var actor = (_a = { id: id, send: function () { return void 0; }, subscribe: function (next, handleError, complete) { return source.subscribe(next, handleError, complete); }, stop: function () { return subscription.unsubscribe(); }, getSnapshot: function () { return emitted; }, toJSON: function () { return { id: id }; } }, _a[symbolObservable] = function () { return this; }, _a); this.children.set(id, actor); return actor; }; Interpreter.prototype.spawnActor = function (actor, name) { this.children.set(name, actor); return actor; }; Interpreter.prototype.spawnActivity = function (activity) { var implementation = this.machine.options && this.machine.options.activities ? this.machine.options.activities[activity.type] : undefined; if (!implementation) { return; } // Start implementation var dispose = implementation(this.state.context, activity); this.spawnEffect(activity.id, dispose); }; Interpreter.prototype.spawnEffect = function (id, dispose) { var _a; this.children.set(id, (_a = { id: id, send: function () { return void 0; }, subscribe: function () { return { unsubscribe: function () { return void 0; } }; }, stop: dispose || undefined, getSnapshot: function () { return undefined; }, toJSON: function () { return { id: id }; } }, _a[symbolObservable] = function () { return this; }, _a)); }; Interpreter.prototype.attachDev = function () { var global = getGlobal(); if (this.options.devTools && global) { if (global.__REDUX_DEVTOOLS_EXTENSION__) { var devToolsOptions = typeof this.options.devTools === 'object' ? this.options.devTools : undefined; this.devTools = global.__REDUX_DEVTOOLS_EXTENSION__.connect(__assign$4(__assign$4({ name: this.id, autoPause: true, stateSanitizer: function (state) { return { value: state.value, context: state.context, actions: state.actions }; } }, devToolsOptions), { features: __assign$4({ jump: false, skip: false }, devToolsOptions ? devToolsOptions.features : undefined) }), this.machine); this.devTools.init(this.state); } // add XState-specific dev tooling hook registerService(this); } }; Interpreter.prototype.toJSON = function () { return { id: this.id }; }; Interpreter.prototype[symbolObservable] = function () { return this; }; Interpreter.prototype.getSnapshot = function () { if (this.status === InterpreterStatus.NotStarted) { return this.initialState; } return this._state; }; /** * The default interpreter options: * * - `clock` uses the global `setTimeout` and `clearTimeout` functions * - `logger` uses the global `console.log()` method */ Interpreter.defaultOptions = { execute: true, deferEvents: true, clock: { setTimeout: function (fn, ms) { return setTimeout(fn, ms); }, clearTimeout: function (id) { return clearTimeout(id); } }, logger: /*#__PURE__*/console.log.bind(console), devTools: false }; Interpreter.interpret = interpret; return Interpreter; }(); /** * Creates a new Interpreter instance for the given machine with the provided options, if any. * * @param machine The machine to interpret * @param options Interpreter options */ function interpret(machine, options) { var interpreter = new Interpreter(machine, options); return interpreter; } function toInvokeSource(src) { if (typeof src === 'string') { var simpleSrc = { type: src }; simpleSrc.toString = function () { return src; }; // v4 compat - TODO: remove in v5 return simpleSrc; } return src; } function toInvokeDefinition(invokeConfig) { return __assign$4(__assign$4({ type: invoke }, invokeConfig), { toJSON: function () { invokeConfig.onDone; invokeConfig.onError; var invokeDef = __rest$1(invokeConfig, ["onDone", "onError"]); return __assign$4(__assign$4({}, invokeDef), { type: invoke, src: toInvokeSource(invokeConfig.src) }); } }); } var NULL_EVENT = ''; var STATE_IDENTIFIER = '#'; var WILDCARD = '*'; var EMPTY_OBJECT = {}; var isStateId = function (str) { return str[0] === STATE_IDENTIFIER; }; var createDefaultOptions = function () { return { actions: {}, guards: {}, services: {}, activities: {}, delays: {} }; }; var StateNode = /*#__PURE__*/ /** @class */ function () { function StateNode( /** * The raw config used to create the machine. */ config, options, /** * The initial extended state */ _context, // TODO: this is unsafe, but we're removing it in v5 anyway _stateInfo) { var _this = this; if (_context === void 0) { _context = 'context' in config ? config.context : undefined; } var _a; this.config = config; this._context = _context; /** * The order this state node appears. Corresponds to the implicit SCXML document order. */ this.order = -1; this.__xstatenode = true; this.__cache = { events: undefined, relativeValue: new Map(), initialStateValue: undefined, initialState: undefined, on: undefined, transitions: undefined, candidates: {}, delayedTransitions: undefined }; this.idMap = {}; this.tags = []; this.options = Object.assign(createDefaultOptions(), options); this.parent = _stateInfo === null || _stateInfo === void 0 ? void 0 : _stateInfo.parent; this.key = this.config.key || (_stateInfo === null || _stateInfo === void 0 ? void 0 : _stateInfo.key) || this.config.id || '(machine)'; this.machine = this.parent ? this.parent.machine : this; this.path = this.parent ? this.parent.path.concat(this.key) : []; this.delimiter = this.config.delimiter || (this.parent ? this.parent.delimiter : STATE_DELIMITER); this.id = this.config.id || __spreadArray([this.machine.key], __read$1(this.path), false).join(this.delimiter); this.version = this.parent ? this.parent.version : this.config.version; this.type = this.config.type || (this.config.parallel ? 'parallel' : this.config.states && Object.keys(this.config.states).length ? 'compound' : this.config.history ? 'history' : 'atomic'); this.schema = this.parent ? this.machine.schema : (_a = this.config.schema) !== null && _a !== void 0 ? _a : {}; this.description = this.config.description; this.initial = this.config.initial; this.states = this.config.states ? mapValues(this.config.states, function (stateConfig, key) { var _a; var stateNode = new StateNode(stateConfig, {}, undefined, { parent: _this, key: key }); Object.assign(_this.idMap, __assign$4((_a = {}, _a[stateNode.id] = stateNode, _a), stateNode.idMap)); return stateNode; }) : EMPTY_OBJECT; // Document order var order = 0; function dfs(stateNode) { var e_1, _a; stateNode.order = order++; try { for (var _b = __values(getChildren$1(stateNode)), _c = _b.next(); !_c.done; _c = _b.next()) { var child = _c.value; dfs(child); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } } dfs(this); // History config this.history = this.config.history === true ? 'shallow' : this.config.history || false; this._transient = !!this.config.always || (!this.config.on ? false : Array.isArray(this.config.on) ? this.config.on.some(function (_a) { var event = _a.event; return event === NULL_EVENT; }) : NULL_EVENT in this.config.on); this.strict = !!this.config.strict; // TODO: deprecate (entry) this.onEntry = toArray(this.config.entry || this.config.onEntry).map(function (action) { return toActionObject(action); }); // TODO: deprecate (exit) this.onExit = toArray(this.config.exit || this.config.onExit).map(function (action) { return toActionObject(action); }); this.meta = this.config.meta; this.doneData = this.type === 'final' ? this.config.data : undefined; this.invoke = toArray(this.config.invoke).map(function (invokeConfig, i) { var _a, _b; if (isMachine(invokeConfig)) { var invokeId = createInvokeId(_this.id, i); _this.machine.options.services = __assign$4((_a = {}, _a[invokeId] = invokeConfig, _a), _this.machine.options.services); return toInvokeDefinition({ src: invokeId, id: invokeId }); } else if (isString(invokeConfig.src)) { var invokeId = invokeConfig.id || createInvokeId(_this.id, i); return toInvokeDefinition(__assign$4(__assign$4({}, invokeConfig), { id: invokeId, src: invokeConfig.src })); } else if (isMachine(invokeConfig.src) || isFunction(invokeConfig.src)) { var invokeId = invokeConfig.id || createInvokeId(_this.id, i); _this.machine.options.services = __assign$4((_b = {}, _b[invokeId] = invokeConfig.src, _b), _this.machine.options.services); return toInvokeDefinition(__assign$4(__assign$4({ id: invokeId }, invokeConfig), { src: invokeId })); } else { var invokeSource = invokeConfig.src; return toInvokeDefinition(__assign$4(__assign$4({ id: createInvokeId(_this.id, i) }, invokeConfig), { src: invokeSource })); } }); this.activities = toArray(this.config.activities).concat(this.invoke).map(function (activity) { return toActivityDefinition(activity); }); this.transition = this.transition.bind(this); this.tags = toArray(this.config.tags); // TODO: this is the real fix for initialization once // state node getters are deprecated // if (!this.parent) { // this._init(); // } } StateNode.prototype._init = function () { if (this.__cache.transitions) { return; } getAllStateNodes(this).forEach(function (stateNode) { return stateNode.on; }); }; /** * Clones this state machine with custom options and context. * * @param options Options (actions, guards, activities, services) to recursively merge with the existing options. * @param context Custom context (will override predefined context) */ StateNode.prototype.withConfig = function (options, context) { var _a = this.options, actions = _a.actions, activities = _a.activities, guards = _a.guards, services = _a.services, delays = _a.delays; return new StateNode(this.config, { actions: __assign$4(__assign$4({}, actions), options.actions), activities: __assign$4(__assign$4({}, activities), options.activities), guards: __assign$4(__assign$4({}, guards), options.guards), services: __assign$4(__assign$4({}, services), options.services), delays: __assign$4(__assign$4({}, delays), options.delays) }, context !== null && context !== void 0 ? context : this.context); }; /** * Clones this state machine with custom context. * * @param context Custom context (will override predefined context, not recursive) */ StateNode.prototype.withContext = function (context) { return new StateNode(this.config, this.options, context); }; Object.defineProperty(StateNode.prototype, "context", { get: function () { return isFunction(this._context) ? this._context() : this._context; }, enumerable: false, configurable: true }); Object.defineProperty(StateNode.prototype, "definition", { /** * The well-structured state node definition. */ get: function () { return { id: this.id, key: this.key, version: this.version, context: this.context, type: this.type, initial: this.initial, history: this.history, states: mapValues(this.states, function (state) { return state.definition; }), on: this.on, transitions: this.transitions, entry: this.onEntry, exit: this.onExit, activities: this.activities || [], meta: this.meta, order: this.order || -1, data: this.doneData, invoke: this.invoke, description: this.description, tags: this.tags }; }, enumerable: false, configurable: true }); StateNode.prototype.toJSON = function () { return this.definition; }; Object.defineProperty(StateNode.prototype, "on", { /** * The mapping of events to transitions. */ get: function () { if (this.__cache.on) { return this.__cache.on; } var transitions = this.transitions; return this.__cache.on = transitions.reduce(function (map, transition) { map[transition.eventType] = map[transition.eventType] || []; map[transition.eventType].push(transition); return map; }, {}); }, enumerable: false, configurable: true }); Object.defineProperty(StateNode.prototype, "after", { get: function () { return this.__cache.delayedTransitions || (this.__cache.delayedTransitions = this.getDelayedTransitions(), this.__cache.delayedTransitions); }, enumerable: false, configurable: true }); Object.defineProperty(StateNode.prototype, "transitions", { /** * All the transitions that can be taken from this state node. */ get: function () { return this.__cache.transitions || (this.__cache.transitions = this.formatTransitions(), this.__cache.transitions); }, enumerable: false, configurable: true }); StateNode.prototype.getCandidates = function (eventName) { if (this.__cache.candidates[eventName]) { return this.__cache.candidates[eventName]; } var transient = eventName === NULL_EVENT; var candidates = this.transitions.filter(function (transition) { var sameEventType = transition.eventType === eventName; // null events should only match against eventless transitions return transient ? sameEventType : sameEventType || transition.eventType === WILDCARD; }); this.__cache.candidates[eventName] = candidates; return candidates; }; /** * All delayed transitions from the config. */ StateNode.prototype.getDelayedTransitions = function () { var _this = this; var afterConfig = this.config.after; if (!afterConfig) { return []; } var mutateEntryExit = function (delay, i) { var delayRef = isFunction(delay) ? "".concat(_this.id, ":delay[").concat(i, "]") : delay; var eventType = after(delayRef, _this.id); _this.onEntry.push(send(eventType, { delay: delay })); _this.onExit.push(cancel(eventType)); return eventType; }; var delayedTransitions = isArray$1(afterConfig) ? afterConfig.map(function (transition, i) { var eventType = mutateEntryExit(transition.delay, i); return __assign$4(__assign$4({}, transition), { event: eventType }); }) : flatten(Object.keys(afterConfig).map(function (delay, i) { var configTransition = afterConfig[delay]; var resolvedTransition = isString(configTransition) ? { target: configTransition } : configTransition; var resolvedDelay = !isNaN(+delay) ? +delay : delay; var eventType = mutateEntryExit(resolvedDelay, i); return toArray(resolvedTransition).map(function (transition) { return __assign$4(__assign$4({}, transition), { event: eventType, delay: resolvedDelay }); }); })); return delayedTransitions.map(function (delayedTransition) { var delay = delayedTransition.delay; return __assign$4(__assign$4({}, _this.formatTransition(delayedTransition)), { delay: delay }); }); }; /** * Returns the state nodes represented by the current state value. * * @param state The state value or State instance */ StateNode.prototype.getStateNodes = function (state) { var _a; var _this = this; if (!state) { return []; } var stateValue = state instanceof State ? state.value : toStateValue(state, this.delimiter); if (isString(stateValue)) { var initialStateValue = this.getStateNode(stateValue).initial; return initialStateValue !== undefined ? this.getStateNodes((_a = {}, _a[stateValue] = initialStateValue, _a)) : [this, this.states[stateValue]]; } var subStateKeys = Object.keys(stateValue); var subStateNodes = [this]; subStateNodes.push.apply(subStateNodes, __spreadArray([], __read$1(flatten(subStateKeys.map(function (subStateKey) { return _this.getStateNode(subStateKey).getStateNodes(stateValue[subStateKey]); }))), false)); return subStateNodes; }; /** * Returns `true` if this state node explicitly handles the given event. * * @param event The event in question */ StateNode.prototype.handles = function (event) { var eventType = getEventType(event); return this.events.includes(eventType); }; /** * Resolves the given `state` to a new `State` instance relative to this machine. * * This ensures that `.events` and `.nextEvents` represent the correct values. * * @param state The state to resolve */ StateNode.prototype.resolveState = function (state) { var stateFromConfig = state instanceof State ? state : State.create(state); var configuration = Array.from(getConfiguration([], this.getStateNodes(stateFromConfig.value))); return new State(__assign$4(__assign$4({}, stateFromConfig), { value: this.resolve(stateFromConfig.value), configuration: configuration, done: isInFinalState(configuration, this), tags: getTagsFromConfiguration(configuration), machine: this.machine })); }; StateNode.prototype.transitionLeafNode = function (stateValue, state, _event) { var stateNode = this.getStateNode(stateValue); var next = stateNode.next(state, _event); if (!next || !next.transitions.length) { return this.next(state, _event); } return next; }; StateNode.prototype.transitionCompoundNode = function (stateValue, state, _event) { var subStateKeys = Object.keys(stateValue); var stateNode = this.getStateNode(subStateKeys[0]); var next = stateNode._transition(stateValue[subStateKeys[0]], state, _event); if (!next || !next.transitions.length) { return this.next(state, _event); } return next; }; StateNode.prototype.transitionParallelNode = function (stateValue, state, _event) { var e_2, _a; var transitionMap = {}; try { for (var _b = __values(Object.keys(stateValue)), _c = _b.next(); !_c.done; _c = _b.next()) { var subStateKey = _c.value; var subStateValue = stateValue[subStateKey]; if (!subStateValue) { continue; } var subStateNode = this.getStateNode(subStateKey); var next = subStateNode._transition(subStateValue, state, _event); if (next) { transitionMap[subStateKey] = next; } } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_2) throw e_2.error; } } var stateTransitions = Object.keys(transitionMap).map(function (key) { return transitionMap[key]; }); var enabledTransitions = flatten(stateTransitions.map(function (st) { return st.transitions; })); var willTransition = stateTransitions.some(function (st) { return st.transitions.length > 0; }); if (!willTransition) { return this.next(state, _event); } var entryNodes = flatten(stateTransitions.map(function (t) { return t.entrySet; })); var configuration = flatten(Object.keys(transitionMap).map(function (key) { return transitionMap[key].configuration; })); return { transitions: enabledTransitions, entrySet: entryNodes, exitSet: flatten(stateTransitions.map(function (t) { return t.exitSet; })), configuration: configuration, source: state, actions: flatten(Object.keys(transitionMap).map(function (key) { return transitionMap[key].actions; })) }; }; StateNode.prototype._transition = function (stateValue, state, _event) { // leaf node if (isString(stateValue)) { return this.transitionLeafNode(stateValue, state, _event); } // hierarchical node if (Object.keys(stateValue).length === 1) { return this.transitionCompoundNode(stateValue, state, _event); } // orthogonal node return this.transitionParallelNode(stateValue, state, _event); }; StateNode.prototype.getTransitionData = function (state, event) { return this._transition(state.value, state, toSCXMLEvent(event)); }; StateNode.prototype.next = function (state, _event) { var e_3, _a; var _this = this; var eventName = _event.name; var actions = []; var nextStateNodes = []; var selectedTransition; try { for (var _b = __values(this.getCandidates(eventName)), _c = _b.next(); !_c.done; _c = _b.next()) { var candidate = _c.value; var cond = candidate.cond, stateIn = candidate.in; var resolvedContext = state.context; var isInState = stateIn ? isString(stateIn) && isStateId(stateIn) ? // Check if in state by ID state.matches(toStateValue(this.getStateNodeById(stateIn).path, this.delimiter)) : // Check if in state by relative grandparent matchesState(toStateValue(stateIn, this.delimiter), path$3(this.path.slice(0, -2))(state.value)) : true; var guardPassed = false; try { guardPassed = !cond || evaluateGuard(this.machine, cond, resolvedContext, _event, state); } catch (err) { throw new Error("Unable to evaluate guard '".concat(cond.name || cond.type, "' in transition for event '").concat(eventName, "' in state node '").concat(this.id, "':\n").concat(err.message)); } if (guardPassed && isInState) { if (candidate.target !== undefined) { nextStateNodes = candidate.target; } actions.push.apply(actions, __spreadArray([], __read$1(candidate.actions), false)); selectedTransition = candidate; break; } } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_3) throw e_3.error; } } if (!selectedTransition) { return undefined; } if (!nextStateNodes.length) { return { transitions: [selectedTransition], entrySet: [], exitSet: [], configuration: state.value ? [this] : [], source: state, actions: actions }; } var allNextStateNodes = flatten(nextStateNodes.map(function (stateNode) { return _this.getRelativeStateNodes(stateNode, state.historyValue); })); var isInternal = !!selectedTransition.internal; var reentryNodes = isInternal ? [] : flatten(allNextStateNodes.map(function (n) { return _this.nodesFromChild(n); })); return { transitions: [selectedTransition], entrySet: reentryNodes, exitSet: isInternal ? [] : [this], configuration: allNextStateNodes, source: state, actions: actions }; }; StateNode.prototype.nodesFromChild = function (childStateNode) { if (childStateNode.escapes(this)) { return []; } var nodes = []; var marker = childStateNode; while (marker && marker !== this) { nodes.push(marker); marker = marker.parent; } nodes.push(this); // inclusive return nodes; }; /** * Whether the given state node "escapes" this state node. If the `stateNode` is equal to or the parent of * this state node, it does not escape. */ StateNode.prototype.escapes = function (stateNode) { if (this === stateNode) { return false; } var parent = this.parent; while (parent) { if (parent === stateNode) { return false; } parent = parent.parent; } return true; }; StateNode.prototype.getActions = function (transition, currentContext, _event, prevState) { var e_4, _a, e_5, _b; var prevConfig = getConfiguration([], prevState ? this.getStateNodes(prevState.value) : [this]); var resolvedConfig = transition.configuration.length ? getConfiguration(prevConfig, transition.configuration) : prevConfig; try { for (var resolvedConfig_1 = __values(resolvedConfig), resolvedConfig_1_1 = resolvedConfig_1.next(); !resolvedConfig_1_1.done; resolvedConfig_1_1 = resolvedConfig_1.next()) { var sn = resolvedConfig_1_1.value; if (!has(prevConfig, sn)) { transition.entrySet.push(sn); } } } catch (e_4_1) { e_4 = { error: e_4_1 }; } finally { try { if (resolvedConfig_1_1 && !resolvedConfig_1_1.done && (_a = resolvedConfig_1.return)) _a.call(resolvedConfig_1); } finally { if (e_4) throw e_4.error; } } try { for (var prevConfig_1 = __values(prevConfig), prevConfig_1_1 = prevConfig_1.next(); !prevConfig_1_1.done; prevConfig_1_1 = prevConfig_1.next()) { var sn = prevConfig_1_1.value; if (!has(resolvedConfig, sn) || has(transition.exitSet, sn.parent)) { transition.exitSet.push(sn); } } } catch (e_5_1) { e_5 = { error: e_5_1 }; } finally { try { if (prevConfig_1_1 && !prevConfig_1_1.done && (_b = prevConfig_1.return)) _b.call(prevConfig_1); } finally { if (e_5) throw e_5.error; } } var doneEvents = flatten(transition.entrySet.map(function (sn) { var events = []; if (sn.type !== 'final') { return events; } var parent = sn.parent; if (!parent.parent) { return events; } events.push(done(sn.id, sn.doneData), // TODO: deprecate - final states should not emit done events for their own state. done(parent.id, sn.doneData ? mapContext(sn.doneData, currentContext, _event) : undefined)); var grandparent = parent.parent; if (grandparent.type === 'parallel') { if (getChildren$1(grandparent).every(function (parentNode) { return isInFinalState(transition.configuration, parentNode); })) { events.push(done(grandparent.id)); } } return events; })); transition.exitSet.sort(function (a, b) { return b.order - a.order; }); transition.entrySet.sort(function (a, b) { return a.order - b.order; }); var entryStates = new Set(transition.entrySet); var exitStates = new Set(transition.exitSet); var _c = __read$1([flatten(Array.from(entryStates).map(function (stateNode) { return __spreadArray(__spreadArray([], __read$1(stateNode.activities.map(function (activity) { return start(activity); })), false), __read$1(stateNode.onEntry), false); })).concat(doneEvents.map(raise)), flatten(Array.from(exitStates).map(function (stateNode) { return __spreadArray(__spreadArray([], __read$1(stateNode.onExit), false), __read$1(stateNode.activities.map(function (activity) { return stop(activity); })), false); }))], 2), entryActions = _c[0], exitActions = _c[1]; var actions = toActionObjects(exitActions.concat(transition.actions).concat(entryActions), this.machine.options.actions); return actions; }; /** * Determines the next state given the current `state` and sent `event`. * * @param state The current State instance or state value * @param event The event that was sent at the current state * @param context The current context (extended state) of the current state */ StateNode.prototype.transition = function (state, event, context) { if (state === void 0) { state = this.initialState; } var _event = toSCXMLEvent(event); var currentState; if (state instanceof State) { currentState = context === undefined ? state : this.resolveState(State.from(state, context)); } else { var resolvedStateValue = isString(state) ? this.resolve(pathToStateValue(this.getResolvedPath(state))) : this.resolve(state); var resolvedContext = context !== null && context !== void 0 ? context : this.machine.context; currentState = this.resolveState(State.from(resolvedStateValue, resolvedContext)); } if (this.strict) { if (!this.events.includes(_event.name) && !isBuiltInEvent(_event.name)) { throw new Error("Machine '".concat(this.id, "' does not accept event '").concat(_event.name, "'")); } } var stateTransition = this._transition(currentState.value, currentState, _event) || { transitions: [], configuration: [], entrySet: [], exitSet: [], source: currentState, actions: [] }; var prevConfig = getConfiguration([], this.getStateNodes(currentState.value)); var resolvedConfig = stateTransition.configuration.length ? getConfiguration(prevConfig, stateTransition.configuration) : prevConfig; stateTransition.configuration = __spreadArray([], __read$1(resolvedConfig), false); return this.resolveTransition(stateTransition, currentState, currentState.context, _event); }; StateNode.prototype.resolveRaisedTransition = function (state, _event, originalEvent) { var _a; var currentActions = state.actions; state = this.transition(state, _event); // Save original event to state // TODO: this should be the raised event! Delete in V5 (breaking) state._event = originalEvent; state.event = originalEvent.data; (_a = state.actions).unshift.apply(_a, __spreadArray([], __read$1(currentActions), false)); return state; }; StateNode.prototype.resolveTransition = function (stateTransition, currentState, context, _event) { var e_6, _a; var _this = this; if (_event === void 0) { _event = initEvent; } var configuration = stateTransition.configuration; // Transition will "apply" if: // - this is the initial state (there is no current state) // - OR there are transitions var willTransition = !currentState || stateTransition.transitions.length > 0; var resolvedStateValue = willTransition ? getValue(this.machine, configuration) : undefined; var historyValue = currentState ? currentState.historyValue ? currentState.historyValue : stateTransition.source ? this.machine.historyValue(currentState.value) : undefined : undefined; var actions = this.getActions(stateTransition, context, _event, currentState); var activities = currentState ? __assign$4({}, currentState.activities) : {}; try { for (var actions_1 = __values(actions), actions_1_1 = actions_1.next(); !actions_1_1.done; actions_1_1 = actions_1.next()) { var action = actions_1_1.value; if (action.type === start$1) { activities[action.activity.id || action.activity.type] = action; } else if (action.type === stop$1) { activities[action.activity.id || action.activity.type] = false; } } } catch (e_6_1) { e_6 = { error: e_6_1 }; } finally { try { if (actions_1_1 && !actions_1_1.done && (_a = actions_1.return)) _a.call(actions_1); } finally { if (e_6) throw e_6.error; } } var _b = __read$1(resolveActions(this, currentState, context, _event, actions, this.machine.config.preserveActionOrder), 2), resolvedActions = _b[0], updatedContext = _b[1]; var _c = __read$1(partition$1(resolvedActions, function (action) { return action.type === raise$1 || action.type === send$1 && action.to === SpecialTargets.Internal; }), 2), raisedEvents = _c[0], nonRaisedActions = _c[1]; var invokeActions = resolvedActions.filter(function (action) { var _a; return action.type === start$1 && ((_a = action.activity) === null || _a === void 0 ? void 0 : _a.type) === invoke; }); var children = invokeActions.reduce(function (acc, action) { acc[action.activity.id] = createInvocableActor(action.activity, _this.machine, updatedContext, _event); return acc; }, currentState ? __assign$4({}, currentState.children) : {}); var resolvedConfiguration = willTransition ? stateTransition.configuration : currentState ? currentState.configuration : []; var isDone = isInFinalState(resolvedConfiguration, this); var nextState = new State({ value: resolvedStateValue || currentState.value, context: updatedContext, _event: _event, // Persist _sessionid between states _sessionid: currentState ? currentState._sessionid : null, historyValue: resolvedStateValue ? historyValue ? updateHistoryValue(historyValue, resolvedStateValue) : undefined : currentState ? currentState.historyValue : undefined, history: !resolvedStateValue || stateTransition.source ? currentState : undefined, actions: resolvedStateValue ? nonRaisedActions : [], activities: resolvedStateValue ? activities : currentState ? currentState.activities : {}, events: [], configuration: resolvedConfiguration, transitions: stateTransition.transitions, children: children, done: isDone, tags: getTagsFromConfiguration(resolvedConfiguration), machine: this }); var didUpdateContext = context !== updatedContext; nextState.changed = _event.name === update || didUpdateContext; // Dispose of penultimate histories to prevent memory leaks var history = nextState.history; if (history) { delete history.history; } // There are transient transitions if the machine is not in a final state // and if some of the state nodes have transient ("always") transitions. var isTransient = !isDone && (this._transient || configuration.some(function (stateNode) { return stateNode._transient; })); // If there are no enabled transitions, check if there are transient transitions. // If there are transient transitions, continue checking for more transitions // because an transient transition should be triggered even if there are no // enabled transitions. // // If we're already working on an transient transition (by checking // if the event is a NULL_EVENT), then stop to prevent an infinite loop. // // Otherwise, if there are no enabled nor transient transitions, we are done. if (!willTransition && (!isTransient || _event.name === NULL_EVENT)) { return nextState; } var maybeNextState = nextState; if (!isDone) { if (isTransient) { maybeNextState = this.resolveRaisedTransition(maybeNextState, { type: nullEvent }, _event); } while (raisedEvents.length) { var raisedEvent = raisedEvents.shift(); maybeNextState = this.resolveRaisedTransition(maybeNextState, raisedEvent._event, _event); } } // Detect if state changed var changed = maybeNextState.changed || (history ? !!maybeNextState.actions.length || didUpdateContext || typeof history.value !== typeof maybeNextState.value || !stateValuesEqual(maybeNextState.value, history.value) : undefined); maybeNextState.changed = changed; // Preserve original history after raised events maybeNextState.history = history; return maybeNextState; }; /** * Returns the child state node from its relative `stateKey`, or throws. */ StateNode.prototype.getStateNode = function (stateKey) { if (isStateId(stateKey)) { return this.machine.getStateNodeById(stateKey); } if (!this.states) { throw new Error("Unable to retrieve child state '".concat(stateKey, "' from '").concat(this.id, "'; no child states exist.")); } var result = this.states[stateKey]; if (!result) { throw new Error("Child state '".concat(stateKey, "' does not exist on '").concat(this.id, "'")); } return result; }; /** * Returns the state node with the given `stateId`, or throws. * * @param stateId The state ID. The prefix "#" is removed. */ StateNode.prototype.getStateNodeById = function (stateId) { var resolvedStateId = isStateId(stateId) ? stateId.slice(STATE_IDENTIFIER.length) : stateId; if (resolvedStateId === this.id) { return this; } var stateNode = this.machine.idMap[resolvedStateId]; if (!stateNode) { throw new Error("Child state node '#".concat(resolvedStateId, "' does not exist on machine '").concat(this.id, "'")); } return stateNode; }; /** * Returns the relative state node from the given `statePath`, or throws. * * @param statePath The string or string array relative path to the state node. */ StateNode.prototype.getStateNodeByPath = function (statePath) { if (typeof statePath === 'string' && isStateId(statePath)) { try { return this.getStateNodeById(statePath.slice(1)); } catch (e) {// try individual paths // throw e; } } var arrayStatePath = toStatePath(statePath, this.delimiter).slice(); var currentStateNode = this; while (arrayStatePath.length) { var key = arrayStatePath.shift(); if (!key.length) { break; } currentStateNode = currentStateNode.getStateNode(key); } return currentStateNode; }; /** * Resolves a partial state value with its full representation in this machine. * * @param stateValue The partial state value to resolve. */ StateNode.prototype.resolve = function (stateValue) { var _a; var _this = this; if (!stateValue) { return this.initialStateValue || EMPTY_OBJECT; // TODO: type-specific properties } switch (this.type) { case 'parallel': return mapValues(this.initialStateValue, function (subStateValue, subStateKey) { return subStateValue ? _this.getStateNode(subStateKey).resolve(stateValue[subStateKey] || subStateValue) : EMPTY_OBJECT; }); case 'compound': if (isString(stateValue)) { var subStateNode = this.getStateNode(stateValue); if (subStateNode.type === 'parallel' || subStateNode.type === 'compound') { return _a = {}, _a[stateValue] = subStateNode.initialStateValue, _a; } return stateValue; } if (!Object.keys(stateValue).length) { return this.initialStateValue || {}; } return mapValues(stateValue, function (subStateValue, subStateKey) { return subStateValue ? _this.getStateNode(subStateKey).resolve(subStateValue) : EMPTY_OBJECT; }); default: return stateValue || EMPTY_OBJECT; } }; StateNode.prototype.getResolvedPath = function (stateIdentifier) { if (isStateId(stateIdentifier)) { var stateNode = this.machine.idMap[stateIdentifier.slice(STATE_IDENTIFIER.length)]; if (!stateNode) { throw new Error("Unable to find state node '".concat(stateIdentifier, "'")); } return stateNode.path; } return toStatePath(stateIdentifier, this.delimiter); }; Object.defineProperty(StateNode.prototype, "initialStateValue", { get: function () { var _a; if (this.__cache.initialStateValue) { return this.__cache.initialStateValue; } var initialStateValue; if (this.type === 'parallel') { initialStateValue = mapFilterValues(this.states, function (state) { return state.initialStateValue || EMPTY_OBJECT; }, function (stateNode) { return !(stateNode.type === 'history'); }); } else if (this.initial !== undefined) { if (!this.states[this.initial]) { throw new Error("Initial state '".concat(this.initial, "' not found on '").concat(this.key, "'")); } initialStateValue = isLeafNode(this.states[this.initial]) ? this.initial : (_a = {}, _a[this.initial] = this.states[this.initial].initialStateValue, _a); } else { // The finite state value of a machine without child states is just an empty object initialStateValue = {}; } this.__cache.initialStateValue = initialStateValue; return this.__cache.initialStateValue; }, enumerable: false, configurable: true }); StateNode.prototype.getInitialState = function (stateValue, context) { this._init(); // TODO: this should be in the constructor (see note in constructor) var configuration = this.getStateNodes(stateValue); return this.resolveTransition({ configuration: configuration, entrySet: configuration, exitSet: [], transitions: [], source: undefined, actions: [] }, undefined, context !== null && context !== void 0 ? context : this.machine.context, undefined); }; Object.defineProperty(StateNode.prototype, "initialState", { /** * The initial State instance, which includes all actions to be executed from * entering the initial state. */ get: function () { var initialStateValue = this.initialStateValue; if (!initialStateValue) { throw new Error("Cannot retrieve initial state from simple state '".concat(this.id, "'.")); } return this.getInitialState(initialStateValue); }, enumerable: false, configurable: true }); Object.defineProperty(StateNode.prototype, "target", { /** * The target state value of the history state node, if it exists. This represents the * default state value to transition to if no history value exists yet. */ get: function () { var target; if (this.type === 'history') { var historyConfig = this.config; if (isString(historyConfig.target)) { target = isStateId(historyConfig.target) ? pathToStateValue(this.machine.getStateNodeById(historyConfig.target).path.slice(this.path.length - 1)) : historyConfig.target; } else { target = historyConfig.target; } } return target; }, enumerable: false, configurable: true }); /** * Returns the leaf nodes from a state path relative to this state node. * * @param relativeStateId The relative state path to retrieve the state nodes * @param history The previous state to retrieve history * @param resolve Whether state nodes should resolve to initial child state nodes */ StateNode.prototype.getRelativeStateNodes = function (relativeStateId, historyValue, resolve) { if (resolve === void 0) { resolve = true; } return resolve ? relativeStateId.type === 'history' ? relativeStateId.resolveHistory(historyValue) : relativeStateId.initialStateNodes : [relativeStateId]; }; Object.defineProperty(StateNode.prototype, "initialStateNodes", { get: function () { var _this = this; if (isLeafNode(this)) { return [this]; } // Case when state node is compound but no initial state is defined if (this.type === 'compound' && !this.initial) { return [this]; } var initialStateNodePaths = toStatePaths(this.initialStateValue); return flatten(initialStateNodePaths.map(function (initialPath) { return _this.getFromRelativePath(initialPath); })); }, enumerable: false, configurable: true }); /** * Retrieves state nodes from a relative path to this state node. * * @param relativePath The relative path from this state node * @param historyValue */ StateNode.prototype.getFromRelativePath = function (relativePath) { if (!relativePath.length) { return [this]; } var _a = __read$1(relativePath), stateKey = _a[0], childStatePath = _a.slice(1); if (!this.states) { throw new Error("Cannot retrieve subPath '".concat(stateKey, "' from node with no states")); } var childStateNode = this.getStateNode(stateKey); if (childStateNode.type === 'history') { return childStateNode.resolveHistory(); } if (!this.states[stateKey]) { throw new Error("Child state '".concat(stateKey, "' does not exist on '").concat(this.id, "'")); } return this.states[stateKey].getFromRelativePath(childStatePath); }; StateNode.prototype.historyValue = function (relativeStateValue) { if (!Object.keys(this.states).length) { return undefined; } return { current: relativeStateValue || this.initialStateValue, states: mapFilterValues(this.states, function (stateNode, key) { if (!relativeStateValue) { return stateNode.historyValue(); } var subStateValue = isString(relativeStateValue) ? undefined : relativeStateValue[key]; return stateNode.historyValue(subStateValue || stateNode.initialStateValue); }, function (stateNode) { return !stateNode.history; }) }; }; /** * Resolves to the historical value(s) of the parent state node, * represented by state nodes. * * @param historyValue */ StateNode.prototype.resolveHistory = function (historyValue) { var _this = this; if (this.type !== 'history') { return [this]; } var parent = this.parent; if (!historyValue) { var historyTarget = this.target; return historyTarget ? flatten(toStatePaths(historyTarget).map(function (relativeChildPath) { return parent.getFromRelativePath(relativeChildPath); })) : parent.initialStateNodes; } var subHistoryValue = nestedPath(parent.path, 'states')(historyValue).current; if (isString(subHistoryValue)) { return [parent.getStateNode(subHistoryValue)]; } return flatten(toStatePaths(subHistoryValue).map(function (subStatePath) { return _this.history === 'deep' ? parent.getFromRelativePath(subStatePath) : [parent.states[subStatePath[0]]]; })); }; Object.defineProperty(StateNode.prototype, "stateIds", { /** * All the state node IDs of this state node and its descendant state nodes. */ get: function () { var _this = this; var childStateIds = flatten(Object.keys(this.states).map(function (stateKey) { return _this.states[stateKey].stateIds; })); return [this.id].concat(childStateIds); }, enumerable: false, configurable: true }); Object.defineProperty(StateNode.prototype, "events", { /** * All the event types accepted by this state node and its descendants. */ get: function () { var e_7, _a, e_8, _b; if (this.__cache.events) { return this.__cache.events; } var states = this.states; var events = new Set(this.ownEvents); if (states) { try { for (var _c = __values(Object.keys(states)), _d = _c.next(); !_d.done; _d = _c.next()) { var stateId = _d.value; var state = states[stateId]; if (state.states) { try { for (var _e = (e_8 = void 0, __values(state.events)), _f = _e.next(); !_f.done; _f = _e.next()) { var event_1 = _f.value; events.add("".concat(event_1)); } } catch (e_8_1) { e_8 = { error: e_8_1 }; } finally { try { if (_f && !_f.done && (_b = _e.return)) _b.call(_e); } finally { if (e_8) throw e_8.error; } } } } } catch (e_7_1) { e_7 = { error: e_7_1 }; } finally { try { if (_d && !_d.done && (_a = _c.return)) _a.call(_c); } finally { if (e_7) throw e_7.error; } } } return this.__cache.events = Array.from(events); }, enumerable: false, configurable: true }); Object.defineProperty(StateNode.prototype, "ownEvents", { /** * All the events that have transitions directly from this state node. * * Excludes any inert events. */ get: function () { var events = new Set(this.transitions.filter(function (transition) { return !(!transition.target && !transition.actions.length && transition.internal); }).map(function (transition) { return transition.eventType; })); return Array.from(events); }, enumerable: false, configurable: true }); StateNode.prototype.resolveTarget = function (_target) { var _this = this; if (_target === undefined) { // an undefined target signals that the state node should not transition from that state when receiving that event return undefined; } return _target.map(function (target) { if (!isString(target)) { return target; } var isInternalTarget = target[0] === _this.delimiter; // If internal target is defined on machine, // do not include machine key on target if (isInternalTarget && !_this.parent) { return _this.getStateNodeByPath(target.slice(1)); } var resolvedTarget = isInternalTarget ? _this.key + target : target; if (_this.parent) { try { var targetStateNode = _this.parent.getStateNodeByPath(resolvedTarget); return targetStateNode; } catch (err) { throw new Error("Invalid transition definition for state node '".concat(_this.id, "':\n").concat(err.message)); } } else { return _this.getStateNodeByPath(resolvedTarget); } }); }; StateNode.prototype.formatTransition = function (transitionConfig) { var _this = this; var normalizedTarget = normalizeTarget(transitionConfig.target); var internal = 'internal' in transitionConfig ? transitionConfig.internal : normalizedTarget ? normalizedTarget.some(function (_target) { return isString(_target) && _target[0] === _this.delimiter; }) : true; var guards = this.machine.options.guards; var target = this.resolveTarget(normalizedTarget); var transition = __assign$4(__assign$4({}, transitionConfig), { actions: toActionObjects(toArray(transitionConfig.actions)), cond: toGuard(transitionConfig.cond, guards), target: target, source: this, internal: internal, eventType: transitionConfig.event, toJSON: function () { return __assign$4(__assign$4({}, transition), { target: transition.target ? transition.target.map(function (t) { return "#".concat(t.id); }) : undefined, source: "#".concat(_this.id) }); } }); return transition; }; StateNode.prototype.formatTransitions = function () { var e_9, _a; var _this = this; var onConfig; if (!this.config.on) { onConfig = []; } else if (Array.isArray(this.config.on)) { onConfig = this.config.on; } else { var _b = this.config.on, _c = WILDCARD, _d = _b[_c], wildcardConfigs = _d === void 0 ? [] : _d, strictTransitionConfigs_1 = __rest$1(_b, [typeof _c === "symbol" ? _c : _c + ""]); onConfig = flatten(Object.keys(strictTransitionConfigs_1).map(function (key) { var transitionConfigArray = toTransitionConfigArray(key, strictTransitionConfigs_1[key]); return transitionConfigArray; }).concat(toTransitionConfigArray(WILDCARD, wildcardConfigs))); } var eventlessConfig = this.config.always ? toTransitionConfigArray('', this.config.always) : []; var doneConfig = this.config.onDone ? toTransitionConfigArray(String(done(this.id)), this.config.onDone) : []; var invokeConfig = flatten(this.invoke.map(function (invokeDef) { var settleTransitions = []; if (invokeDef.onDone) { settleTransitions.push.apply(settleTransitions, __spreadArray([], __read$1(toTransitionConfigArray(String(doneInvoke(invokeDef.id)), invokeDef.onDone)), false)); } if (invokeDef.onError) { settleTransitions.push.apply(settleTransitions, __spreadArray([], __read$1(toTransitionConfigArray(String(error(invokeDef.id)), invokeDef.onError)), false)); } return settleTransitions; })); var delayedTransitions = this.after; var formattedTransitions = flatten(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read$1(doneConfig), false), __read$1(invokeConfig), false), __read$1(onConfig), false), __read$1(eventlessConfig), false).map(function (transitionConfig) { return toArray(transitionConfig).map(function (transition) { return _this.formatTransition(transition); }); })); try { for (var delayedTransitions_1 = __values(delayedTransitions), delayedTransitions_1_1 = delayedTransitions_1.next(); !delayedTransitions_1_1.done; delayedTransitions_1_1 = delayedTransitions_1.next()) { var delayedTransition = delayedTransitions_1_1.value; formattedTransitions.push(delayedTransition); } } catch (e_9_1) { e_9 = { error: e_9_1 }; } finally { try { if (delayedTransitions_1_1 && !delayedTransitions_1_1.done && (_a = delayedTransitions_1.return)) _a.call(delayedTransitions_1); } finally { if (e_9) throw e_9.error; } } return formattedTransitions; }; return StateNode; }(); function createMachine(config, options) { return new StateNode(config, options); } var assign = assign$1; let vanillaClient; function getVanillaClient() { if (!vanillaClient) { const url = sitemap.public.apiV1.trpc().toString(); vanillaClient = createTRPCProxyClient({ links: [ httpBatchLink({ url, fetch(url, options) { return fetch(url, { ...options, credentials: "include", }); }, maxURLLength: 2083, }), ], }); } return vanillaClient; } async function submitPostReport(context) { const response = await axios$1.post( sitemap.public.apiV1.reporting.reportPost().toString(), { postId: context.postId , // TODO: actually make sure this is filled in reportingReason: context.reportingReason , additionalDetails: context.additionalDetails, } ); if (response.status >= 200 && response.status <= 400) { return Promise.resolve(); } else { throw new Error(response.statusText); } } async function submitProjectReport(context) { if (!context.projectId) { throw new Error("project id not set"); } if (!context.reportingReason) { throw new Error("reporting reason not set"); } const vanillaClient = getVanillaClient(); await vanillaClient.reporting.reportProject.mutate({ additionalDetails: context.additionalDetails, projectId: context.projectId, reportingReason: context.reportingReason, }); } async function submitCommentReport(context) { if (!context.commentId) { throw new Error("comment id not set"); } if (!context.reportingReason) { throw new Error("reporting reason not set"); } const vanillaClient = getVanillaClient(); await vanillaClient.reporting.reportComment.mutate({ additionalDetails: context.additionalDetails, commentId: context.commentId, reportingReason: context.reportingReason, }); } async function submitAskReport(context) { if (!context.askId) { throw new Error("ask id not set"); } if (!context.reportingReason) { throw new Error("reporting reason not set"); } const vanillaClient = getVanillaClient(); await vanillaClient.reporting.reportAsk.mutate({ additionalDetails: context.additionalDetails, askId: context.askId, reportingReason: context.reportingReason, }); } async function submitArtistAlleyReport(context) { if (!context.artistAlleyListingId) { throw new Error("listing id not set"); } if (!context.reportingReason) { throw new Error("reporting reason not set"); } const vanillaClient = getVanillaClient(); await vanillaClient.reporting.reportArtistAlleyListing.mutate({ additionalDetails: context.additionalDetails, artistAlleyListingId: context.artistAlleyListingId, reportingReason: context.reportingReason, }); } createMachine ( { initial: "closed", strict: true, context: {}, states: { closed: { entry: assign(() => { return {}; }), on: { START_REPORT: { target: "editingReport", actions: assign((_context, event) => { return { postId: event.postId, projectId: event.projectId, commentId: event.commentId, askId: event.askId, artistAlleyListingId: event.artistAlleyListingId, }; }), }, }, }, editingReport: { on: { CLOSE: { target: "closed" }, SUBMIT: { target: "submitting", actions: assign((context, event) => { return { ...context, reportingReason: event.reportingReason, additionalDetails: event.additionalDetails, }; }), }, }, }, submitting: { invoke: { src: "submit", onDone: { target: "acknowledging", }, onError: { target: "displayingError", }, }, }, acknowledging: { on: { ACKNOWLEDGE: { target: "closed", }, CLOSE: { target: "closed", }, }, }, displayingError: { on: { CLOSE: { target: "closed", }, }, }, }, }, { services: { submit: async (context) => { if (context.postId) { return submitPostReport(context); } else if (context.projectId) { return submitProjectReport(context); } else if (context.commentId) { return submitCommentReport(context); } else if (context.askId) { return submitAskReport(context); } else if (context.artistAlleyListingId) { return submitArtistAlleyReport(context); } else { // todo: rollbar throw new Error("submit with invalid state shape"); } }, }, } ); const ReportingUIContext = reactExports.createContext( {} ); var AccessResult; (function (AccessResult) { const Allowed = "allowed"; AccessResult["Allowed"] = Allowed; const NotAllowed = "not-allowed"; AccessResult["NotAllowed"] = NotAllowed; const LogInFirst = "log-in-first"; AccessResult["LogInFirst"] = LogInFirst; const Blocked = "blocked"; AccessResult["Blocked"] = Blocked; })(AccessResult || (AccessResult = {})); mod.nativeEnum(AccessResult); // separate regular expression for existing pages; fixes tRPC bugs with pages that are invalid DNS names but already exist const EXTANT_PAGE_LEGAL_REGEX = /^[a-zA-Z0-9-]{3,}/; // based on https://github.com/colinhacks/zod/issues/678#issuecomment-962387521 function refinement$1() { return function (val) { return true; }; } const BigIntId = mod .string() .or(mod.number().transform((val) => val.toString())) .refine((val) => { try { // BigInt throws on non-integer strings const num = BigInt(val); return num > BigInt(0); } catch (e) { return false; } }); const AttachmentId = mod .string() .uuid() .refine(refinement$1()); mod.number().int().refine(refinement$1()); const ProjectId = mod .number() .int() .refine(refinement$1()); mod.number().int().refine(refinement$1()); const ProjectHandle = mod .string() // use the old legal regex to prevent tRPC errors with DNS-illegal usernames .regex(EXTANT_PAGE_LEGAL_REGEX) .refine(refinement$1()); mod .string() .uuid() .refine(refinement$1()); BigIntId.refine(refinement$1()); mod .string() .uuid() .refine(refinement$1()); mod .string() .uuid() .refine(refinement$1()); mod .string() .uuid() .refine(refinement$1()); mod .string() .uuid() .refine(refinement$1()); const ISODateString = mod .string() .refine((string) => DateTime_1.fromISO(string).isValid, { message: "Not a valid ISO date!", }); const AskId = BigIntId.refine(refinement$1()); BigIntId.refine( refinement$1() ); mod .string() .refine(refinement$1()); mod .string() .refine(refinement$1()); BigIntId.refine(refinement$1()); mod .string() .refine(refinement$1()); mod .string() .refine(refinement$1()); mod .string() .uuid() .refine(refinement$1()); BigIntId.refine( refinement$1() ); BigIntId.refine( refinement$1() ); BigIntId.refine( refinement$1() ); var ProjectPrivacy; (function (ProjectPrivacy) { const Public = "public"; ProjectPrivacy["Public"] = Public; const Private = "private"; ProjectPrivacy["Private"] = Private; })(ProjectPrivacy || (ProjectPrivacy = {})); const ProjectPrivacyEnum = mod.nativeEnum(ProjectPrivacy); // shout out https://stackoverflow.com/a/61129291 const ProjectFlag = mod.enum([ "staff", "staffMember", "friendOfTheSite", "noTransparentAvatar", "suspended", "automated", // used for the bot badge "parody", // used for the "un-verified" badge ]); // TODO: the DB also supports "all-ages", but this setting doesn't currently // work because of an NYI access checker upgrade. const LoggedOutPostVisibility = mod.enum(["public", "none"]); const AvatarShape = mod.enum([ "circle", "roundrect", "squircle", "capsule-big", "capsule-small", "egg", ]); const ContactCardVisibility = mod.enum([ "public", "logged-in", "follows", "following-you", ]); const ContactCardRow = mod.object({ service: mod.string(), value: mod.string(), visibility: ContactCardVisibility, }); const WireProjectModel = mod.object({ projectId: ProjectId, handle: ProjectHandle, displayName: mod.string(), dek: mod.string(), description: mod.string(), avatarURL: mod.string().url(), avatarPreviewURL: mod.string().url(), headerURL: mod.string().url().nullable(), headerPreviewURL: mod.string().url().nullable(), privacy: ProjectPrivacyEnum, url: mod.string().nullable(), pronouns: mod.string().nullable(), flags: ProjectFlag.array(), avatarShape: AvatarShape, loggedOutPostVisibility: LoggedOutPostVisibility, frequentlyUsedTags: mod.string().array(), askSettings: mod.object({ enabled: mod.boolean(), allowAnon: mod.boolean(), requireLoggedInAnon: mod.boolean(), }), contactCard: ContactCardRow.array(), deleteAfter: ISODateString.nullable(), isSelfProject: mod.boolean().nullable(), }); WireProjectModel.extend({ lastActivityTime: ISODateString.nullable(), handleSuspicionResult: mod .object({ match: mod.string(), score: mod.number(), }) .nullable(), }); mod .object({ asks: mod .object({ enabled: mod.boolean().default(false), allowAnon: mod.boolean().default(false), requireLoggedInAnon: mod.boolean().default(true), }) .default({}), }) .default({}); var i$7=Object.defineProperty;var d$b=(t,e,n)=>e in t?i$7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var r$8=(t,e,n)=>(d$b(t,typeof e!="symbol"?e+"":e,n),n);let o$7 = class o{constructor(){r$8(this,"current",this.detect());r$8(this,"handoffState","pending");r$8(this,"currentId",0);}set(e){this.current!==e&&(this.handoffState="pending",this.currentId=0,this.current=e);}reset(){this.set(this.detect());}nextId(){return ++this.currentId}get isServer(){return this.current==="server"}get isClient(){return this.current==="client"}detect(){return typeof window=="undefined"||typeof document=="undefined"?"server":"client"}handoff(){this.handoffState==="pending"&&(this.handoffState="complete");}get isHandoffComplete(){return this.handoffState==="complete"}};let s$c=new o$7; let l$a=(e,f)=>{s$c.isServer?reactExports.useEffect(e,f):reactExports.useLayoutEffect(e,f);}; function l$9(){let[e,f]=reactExports.useState(s$c.isHandoffComplete);return e&&s$c.isHandoffComplete===!1&&f(!1),reactExports.useEffect(()=>{e!==!0&&f(!0);},[e]),reactExports.useEffect(()=>s$c.handoff(),[]),e} var o$6;let I$7=(o$6=React$1.useId)!=null?o$6:function(){let n=l$9(),[e,u]=React$1.useState(n?()=>s$c.nextId():null);return l$a(()=>{e===null&&u(s$c.nextId());},[e]),e!=null?""+e:void 0}; function e$6(...n){return n.filter(Boolean).join(" ")} function u$c(r,n,...a){if(r in n){let e=n[r];return typeof e=="function"?e(...a):e}let t=new Error(`Tried to handle "${r}" but there is no handler defined. Only defined handlers are: ${Object.keys(n).map(e=>`"${e}"`).join(", ")}.`);throw Error.captureStackTrace&&Error.captureStackTrace(t,u$c),t} var S$b=(a=>(a[a.None=0]="None",a[a.RenderStrategy=1]="RenderStrategy",a[a.Static=2]="Static",a))(S$b||{}),j$3=(e=>(e[e.Unmount=0]="Unmount",e[e.Hidden=1]="Hidden",e))(j$3||{});function X$7({ourProps:r,theirProps:t,slot:e,defaultTag:a,features:s,visible:n=!0,name:f}){let o=N$4(t,r);if(n)return c$a(o,e,a,f);let u=s!=null?s:0;if(u&2){let{static:l=!1,...p}=o;if(l)return c$a(p,e,a,f)}if(u&1){let{unmount:l=!0,...p}=o;return u$c(l?0:1,{[0](){return null},[1](){return c$a({...p,hidden:!0,style:{display:"none"}},e,a,f)}})}return c$a(o,e,a,f)}function c$a(r,t={},e,a){let{as:s=e,children:n,refName:f="ref",...o}=g$4(r,["unmount","static"]),u=r.ref!==void 0?{[f]:r.ref}:{},l=typeof n=="function"?n(t):n;"className"in o&&o.className&&typeof o.className=="function"&&(o.className=o.className(t));let p={};if(t){let i=!1,m=[];for(let[y,d]of Object.entries(t))typeof d=="boolean"&&(i=!0),d===!0&&m.push(y);i&&(p["data-headlessui-state"]=m.join(" "));}if(s===reactExports.Fragment&&Object.keys(R$5(o)).length>0){if(!reactExports.isValidElement(l)||Array.isArray(l)&&l.length>1)throw new Error(['Passing props on "Fragment"!',"",`The current component <${a} /> is rendering a "Fragment".`,"However we need to passthrough the following props:",Object.keys(o).map(d=>` - ${d}`).join(` `),"","You can apply a few solutions:",['Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".',"Render a single element as the child so that we can forward the props onto that element."].map(d=>` - ${d}`).join(` `)].join(` `));let i=l.props,m=typeof(i==null?void 0:i.className)=="function"?(...d)=>e$6(i==null?void 0:i.className(...d),o.className):e$6(i==null?void 0:i.className,o.className),y=m?{className:m}:{};return reactExports.cloneElement(l,Object.assign({},N$4(l.props,R$5(g$4(o,["ref"]))),p,u,w$8(l.ref,u.ref),y))}return reactExports.createElement(s,Object.assign({},g$4(o,["ref"]),s!==reactExports.Fragment&&u,s!==reactExports.Fragment&&p),l)}function w$8(...r){return {ref:r.every(t=>t==null)?void 0:t=>{for(let e of r)e!=null&&(typeof e=="function"?e(t):e.current=t);}}}function N$4(...r){if(r.length===0)return {};if(r.length===1)return r[0];let t={},e={};for(let s of r)for(let n in s)n.startsWith("on")&&typeof s[n]=="function"?((e[n])!=null||(e[n]=[]),e[n].push(s[n])):t[n]=s[n];if(t.disabled||t["aria-disabled"])return Object.assign(t,Object.fromEntries(Object.keys(e).map(s=>[s,void 0])));for(let s in e)Object.assign(t,{[s](n,...f){let o=e[s];for(let u of o){if((n instanceof Event||(n==null?void 0:n.nativeEvent)instanceof Event)&&n.defaultPrevented)return;u(n,...f);}}});return t}function D$8(r){var t;return Object.assign(reactExports.forwardRef(r),{displayName:(t=r.displayName)!=null?t:r.name})}function R$5(r){let t=Object.assign({},r);for(let e in t)t[e]===void 0&&delete t[e];return t}function g$4(r,t=[]){let e=Object.assign({},r);for(let a of t)a in e&&delete e[a];return e} function s$b(e){let r=reactExports.useRef(e);return l$a(()=>{r.current=e;},[e]),r} let o$5=function(t){let e=s$b(t);return React$1.useCallback((...r)=>e.current(...r),[e])}; let u$b=Symbol();function T$7(t,n=!0){return Object.assign(t,{[u$b]:n})}function y$a(...t){let n=reactExports.useRef(t);reactExports.useEffect(()=>{n.current=t;},[t]);let c=o$5(e=>{for(let o of n.current)o!=null&&(typeof o=="function"?o(e):o.current=e);});return t.every(e=>e==null||(e==null?void 0:e[u$b]))?void 0:c} let d$a=reactExports.createContext(null);function f$9(){let r=reactExports.useContext(d$a);if(r===null){let t=new Error("You used a component, but it is not inside a relevant parent.");throw Error.captureStackTrace&&Error.captureStackTrace(t,f$9),t}return r}function M$a(){let[r,t]=reactExports.useState([]);return [r.length>0?r.join(" "):void 0,reactExports.useMemo(()=>function(e){let i=o$5(s=>(t(o=>[...o,s]),()=>t(o=>{let p=o.slice(),c=p.indexOf(s);return c!==-1&&p.splice(c,1),p}))),n=reactExports.useMemo(()=>({register:i,slot:e.slot,name:e.name,props:e.props}),[i,e.slot,e.name,e.props]);return React$1.createElement(d$a.Provider,{value:n},e.children)},[t])]}let S$a="p";function h$8(r,t){let a=I$7(),{id:e=`headlessui-description-${a}`,...i}=r,n=f$9(),s=y$a(t);l$a(()=>n.register(e),[e,n.register]);let o={ref:s,...n.props,id:e};return X$7({ourProps:o,theirProps:i,slot:n.slot||{},defaultTag:S$a,name:n.name||"Description"})}let y$9=D$8(h$8),b$3=Object.assign(y$9,{}); var o$4=(r=>(r.Space=" ",r.Enter="Enter",r.Escape="Escape",r.Backspace="Backspace",r.Delete="Delete",r.ArrowLeft="ArrowLeft",r.ArrowUp="ArrowUp",r.ArrowRight="ArrowRight",r.ArrowDown="ArrowDown",r.Home="Home",r.End="End",r.PageUp="PageUp",r.PageDown="PageDown",r.Tab="Tab",r))(o$4||{}); function r$7(n){let e=n.parentElement,l=null;for(;e&&!(e instanceof HTMLFieldSetElement);)e instanceof HTMLLegendElement&&(l=e),e=e.parentElement;let t=(e==null?void 0:e.getAttribute("disabled"))==="";return t&&i$6(l)?!1:t}function i$6(n){if(!n)return !1;let e=n.previousElementSibling;for(;e!==null;){if(e instanceof HTMLLegendElement)return !1;e=e.previousElementSibling;}return !0} let a$a="div";var p$b=(e=>(e[e.None=1]="None",e[e.Focusable=2]="Focusable",e[e.Hidden=4]="Hidden",e))(p$b||{});function s$a(t,o){let{features:n=1,...e}=t,d={ref:o,"aria-hidden":(n&2)===2?!0:void 0,style:{position:"fixed",top:1,left:1,width:1,height:0,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0",...(n&4)===4&&(n&2)!==2&&{display:"none"}}};return X$7({ourProps:d,theirProps:e,slot:{},defaultTag:a$a,name:"Hidden"})}let c$9=D$8(s$a); function t$a(e){typeof queueMicrotask=="function"?queueMicrotask(e):Promise.resolve().then(e).catch(o=>setTimeout(()=>{throw o}));} function o$3(){let n=[],r={addEventListener(e,t,s,a){return e.addEventListener(t,s,a),r.add(()=>e.removeEventListener(t,s,a))},requestAnimationFrame(...e){let t=requestAnimationFrame(...e);return r.add(()=>cancelAnimationFrame(t))},nextFrame(...e){return r.requestAnimationFrame(()=>r.requestAnimationFrame(...e))},setTimeout(...e){let t=setTimeout(...e);return r.add(()=>clearTimeout(t))},microTask(...e){let t={current:!0};return t$a(()=>{t.current&&e[0]();}),r.add(()=>{t.current=!1;})},style(e,t,s){let a=e.style.getPropertyValue(t);return Object.assign(e.style,{[t]:s}),this.add(()=>{Object.assign(e.style,{[t]:a});})},group(e){let t=o$3();return e(t),this.add(()=>t.dispose())},add(e){return n.push(e),()=>{let t=n.indexOf(e);if(t>=0)for(let s of n.splice(t,1))s();}},dispose(){for(let e of n.splice(0))e();}};return r} function e$5(r){return s$c.isServer?null:r instanceof Node?r.ownerDocument:r!=null&&r.hasOwnProperty("current")&&r.current instanceof Node?r.current.ownerDocument:document} let c$8=["[contentEditable=true]","[tabindex]","a[href]","area[href]","button:not([disabled])","iframe","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].map(e=>`${e}:not([tabindex='-1'])`).join(",");var M$9=(n=>(n[n.First=1]="First",n[n.Previous=2]="Previous",n[n.Next=4]="Next",n[n.Last=8]="Last",n[n.WrapAround=16]="WrapAround",n[n.NoScroll=32]="NoScroll",n))(M$9||{}),N$3=(o=>(o[o.Error=0]="Error",o[o.Overflow=1]="Overflow",o[o.Success=2]="Success",o[o.Underflow=3]="Underflow",o))(N$3||{}),F$9=(t=>(t[t.Previous=-1]="Previous",t[t.Next=1]="Next",t))(F$9||{});function f$8(e=document.body){return e==null?[]:Array.from(e.querySelectorAll(c$8)).sort((r,t)=>Math.sign((r.tabIndex||Number.MAX_SAFE_INTEGER)-(t.tabIndex||Number.MAX_SAFE_INTEGER)))}var T$6=(t=>(t[t.Strict=0]="Strict",t[t.Loose=1]="Loose",t))(T$6||{});function h$7(e,r=0){var t;return e===((t=e$5(e))==null?void 0:t.body)?!1:u$c(r,{[0](){return e.matches(c$8)},[1](){let l=e;for(;l!==null;){if(l.matches(c$8))return !0;l=l.parentElement;}return !1}})}function D$7(e){let r=e$5(e);o$3().nextFrame(()=>{r&&!h$7(r.activeElement,0)&&y$8(e);});}var w$7=(t=>(t[t.Keyboard=0]="Keyboard",t[t.Mouse=1]="Mouse",t))(w$7||{});typeof window!="undefined"&&typeof document!="undefined"&&(document.addEventListener("keydown",e=>{e.metaKey||e.altKey||e.ctrlKey||(document.documentElement.dataset.headlessuiFocusVisible="");},!0),document.addEventListener("click",e=>{e.detail===1?delete document.documentElement.dataset.headlessuiFocusVisible:e.detail===0&&(document.documentElement.dataset.headlessuiFocusVisible="");},!0));function y$8(e){e==null||e.focus({preventScroll:!0});}let S$9=["textarea","input"].join(",");function H$9(e){var r,t;return (t=(r=e==null?void 0:e.matches)==null?void 0:r.call(e,S$9))!=null?t:!1}function I$6(e,r=t=>t){return e.slice().sort((t,l)=>{let o=r(t),i=r(l);if(o===null||i===null)return 0;let n=o.compareDocumentPosition(i);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0})}function _$4(e,r){return O$7(f$8(),r,{relativeTo:e})}function O$7(e,r,{sorted:t=!0,relativeTo:l=null,skipElements:o=[]}={}){let i=Array.isArray(e)?e.length>0?e[0].ownerDocument:document:e.ownerDocument,n=Array.isArray(e)?t?I$6(e):e:f$8(e);o.length>0&&n.length>1&&(n=n.filter(s=>!o.includes(s))),l=l!=null?l:i.activeElement;let E=(()=>{if(r&5)return 1;if(r&10)return -1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),x=(()=>{if(r&1)return 0;if(r&2)return Math.max(0,n.indexOf(l))-1;if(r&4)return Math.max(0,n.indexOf(l))+1;if(r&8)return n.length-1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),p=r&32?{preventScroll:!0}:{},d=0,a=n.length,u;do{if(d>=a||d+a<=0)return 0;let s=x+d;if(r&16)s=(s+a)%a;else {if(s<0)return 3;if(s>=a)return 1}u=n[s],u==null||u.focus(p),d+=E;}while(u!==i.activeElement);return r&6&&H$9(u)&&u.select(),2} function s$9(e,r,n){let o=s$b(r);reactExports.useEffect(()=>{function t(i){o.current(i);}return window.addEventListener(e,t,n),()=>window.removeEventListener(e,t,n)},[e,n]);} var s$8=(r=>(r[r.Forwards=0]="Forwards",r[r.Backwards=1]="Backwards",r))(s$8||{});function n$8(){let e=reactExports.useRef(0);return s$9("keydown",o=>{o.key==="Tab"&&(e.current=o.shiftKey?1:0);},!0),e} function f$7(){let e=reactExports.useRef(!1);return l$a(()=>(e.current=!0,()=>{e.current=!1;}),[]),e} function n$7(...e){return reactExports.useMemo(()=>e$5(...e),[...e])} function E$5(n,e,a,t){let i=s$b(a);reactExports.useEffect(()=>{n=n!=null?n:window;function r(o){i.current(o);}return n.addEventListener(e,r,t),()=>n.removeEventListener(e,r,t)},[n,e,t]);} function m$5(u,t){let e=reactExports.useRef([]),r=o$5(u);reactExports.useEffect(()=>{let o=[...e.current];for(let[n,a]of t.entries())if(e.current[n]!==a){let l=r(t,o);return e.current=t,l}},[r,...t]);} function p$a(){let[e]=reactExports.useState(o$3);return reactExports.useEffect(()=>()=>e.dispose(),[e]),e} function t$9(n){function e(){document.readyState!=="loading"&&(n(),document.removeEventListener("DOMContentLoaded",e));}typeof window!="undefined"&&typeof document!="undefined"&&(document.addEventListener("DOMContentLoaded",e),e());} function P$5(t){if(!t)return new Set;if(typeof t=="function")return new Set(t());let n=new Set;for(let e of t.current)e.current instanceof HTMLElement&&n.add(e.current);return n}let J$3="div";var h$6=(r=>(r[r.None=1]="None",r[r.InitialFocus=2]="InitialFocus",r[r.TabLock=4]="TabLock",r[r.FocusLock=8]="FocusLock",r[r.RestoreFocus=16]="RestoreFocus",r[r.All=30]="All",r))(h$6||{});function X$6(t,n){let e=reactExports.useRef(null),o=y$a(e,n),{initialFocus:u,containers:i,features:r=30,...l}=t;l$9()||(r=1);let m=n$7(e);Y$6({ownerDocument:m},Boolean(r&16));let c=Z$7({ownerDocument:m,container:e,initialFocus:u},Boolean(r&2));$$9({ownerDocument:m,container:e,containers:i,previousActiveElement:c},Boolean(r&8));let v=n$8(),R=o$5(s=>{let T=e.current;if(!T)return;(B=>B())(()=>{u$c(v.current,{[s$8.Forwards]:()=>{O$7(T,M$9.First,{skipElements:[s.relatedTarget]});},[s$8.Backwards]:()=>{O$7(T,M$9.Last,{skipElements:[s.relatedTarget]});}});});}),_=p$a(),H=reactExports.useRef(!1),j={ref:o,onKeyDown(s){s.key=="Tab"&&(H.current=!0,_.requestAnimationFrame(()=>{H.current=!1;}));},onBlur(s){let T=P$5(i);e.current instanceof HTMLElement&&T.add(e.current);let E=s.relatedTarget;E instanceof HTMLElement&&E.dataset.headlessuiFocusGuard!=="true"&&(S$8(T,E)||(H.current?O$7(e.current,u$c(v.current,{[s$8.Forwards]:()=>M$9.Next,[s$8.Backwards]:()=>M$9.Previous})|M$9.WrapAround,{relativeTo:s.target}):s.target instanceof HTMLElement&&y$8(s.target)));}};return React$1.createElement(React$1.Fragment,null,Boolean(r&4)&&React$1.createElement(c$9,{as:"button",type:"button","data-headlessui-focus-guard":!0,onFocus:R,features:p$b.Focusable}),X$7({ourProps:j,theirProps:l,defaultTag:J$3,name:"FocusTrap"}),Boolean(r&4)&&React$1.createElement(c$9,{as:"button",type:"button","data-headlessui-focus-guard":!0,onFocus:R,features:p$b.Focusable}))}let z$6=D$8(X$6),Re$4=Object.assign(z$6,{features:h$6}),a$9=[];t$9(()=>{function t(n){n.target instanceof HTMLElement&&n.target!==document.body&&a$9[0]!==n.target&&(a$9.unshift(n.target),a$9=a$9.filter(e=>e!=null&&e.isConnected),a$9.splice(10));}window.addEventListener("click",t,{capture:!0}),window.addEventListener("mousedown",t,{capture:!0}),window.addEventListener("focus",t,{capture:!0}),document.body.addEventListener("click",t,{capture:!0}),document.body.addEventListener("mousedown",t,{capture:!0}),document.body.addEventListener("focus",t,{capture:!0});});function Q$5(t=!0){let n=reactExports.useRef(a$9.slice());return m$5(([e],[o])=>{o===!0&&e===!1&&t$a(()=>{n.current.splice(0);}),o===!1&&e===!0&&(n.current=a$9.slice());},[t,a$9,n]),o$5(()=>{var e;return (e=n.current.find(o=>o!=null&&o.isConnected))!=null?e:null})}function Y$6({ownerDocument:t},n){let e=Q$5(n);m$5(()=>{n||(t==null?void 0:t.activeElement)===(t==null?void 0:t.body)&&y$8(e());},[n]);let o=reactExports.useRef(!1);reactExports.useEffect(()=>(o.current=!1,()=>{o.current=!0,t$a(()=>{o.current&&y$8(e());});}),[]);}function Z$7({ownerDocument:t,container:n,initialFocus:e},o){let u=reactExports.useRef(null),i=f$7();return m$5(()=>{if(!o)return;let r=n.current;r&&t$a(()=>{if(!i.current)return;let l=t==null?void 0:t.activeElement;if(e!=null&&e.current){if((e==null?void 0:e.current)===l){u.current=l;return}}else if(r.contains(l)){u.current=l;return}e!=null&&e.current?y$8(e.current):O$7(r,M$9.First)===N$3.Error&&console.warn("There are no focusable elements inside the "),u.current=t==null?void 0:t.activeElement;});},[o]),u}function $$9({ownerDocument:t,container:n,containers:e,previousActiveElement:o},u){let i=f$7();E$5(t==null?void 0:t.defaultView,"focus",r=>{if(!u||!i.current)return;let l=P$5(e);n.current instanceof HTMLElement&&l.add(n.current);let m=o.current;if(!m)return;let c=r.target;c&&c instanceof HTMLElement?S$8(l,c)?(o.current=c,y$8(c)):(r.preventDefault(),r.stopPropagation(),y$8(m)):y$8(o.current);},!0);}function S$8(t,n){for(let e of t)if(e.contains(n))return !0;return !1} let e$4=reactExports.createContext(!1);function l$8(){return reactExports.useContext(e$4)}function P$4(o){return React$1.createElement(e$4.Provider,{value:o.force},o.children)} function H$8(u){let a=l$8(),o=reactExports.useContext(c$7),e=n$7(u),[l,n]=reactExports.useState(()=>{if(!a&&o!==null||s$c.isServer)return null;let t=e==null?void 0:e.getElementById("headlessui-portal-root");if(t)return t;if(e===null)return null;let r=e.createElement("div");return r.setAttribute("id","headlessui-portal-root"),e.body.appendChild(r)});return reactExports.useEffect(()=>{l!==null&&(e!=null&&e.body.contains(l)||e==null||e.body.appendChild(l));},[l,e]),reactExports.useEffect(()=>{a||o!==null&&n(o.current);},[o,n,a]),l}let O$6=reactExports.Fragment;function _$3(u,a){let o=u,e=reactExports.useRef(null),l=y$a(T$7(p=>{e.current=p;}),a),n=n$7(e),t=H$8(e),[r]=reactExports.useState(()=>{var p;return s$c.isServer?null:(p=n==null?void 0:n.createElement("div"))!=null?p:null}),y=l$9(),f=reactExports.useRef(!1);return l$a(()=>{if(f.current=!1,!(!t||!r))return t.contains(r)||(r.setAttribute("data-headlessui-portal",""),t.appendChild(r)),()=>{f.current=!0,t$a(()=>{var p;f.current&&(!t||!r||(r instanceof Node&&t.contains(r)&&t.removeChild(r),t.childNodes.length<=0&&((p=t.parentElement)==null||p.removeChild(t))));});}},[t,r]),y?!t||!r?null:reactDomExports.createPortal(X$7({ourProps:{ref:l},theirProps:o,defaultTag:O$6,name:"Portal"}),r):null}let F$8=reactExports.Fragment,c$7=reactExports.createContext(null);function U$5(u,a){let{target:o,...e}=u,n={ref:y$a(a)};return React$1.createElement(c$7.Provider,{value:o},X$7({ourProps:n,theirProps:e,defaultTag:F$8,name:"Popover.Group"}))}let S$7=D$8(_$3),j$2=D$8(U$5),te$2=Object.assign(S$7,{Group:j$2}); let n$6=reactExports.createContext(null);n$6.displayName="OpenClosedContext";var d$9=(e=>(e[e.Open=1]="Open",e[e.Closed=2]="Closed",e[e.Closing=4]="Closing",e[e.Opening=8]="Opening",e))(d$9||{});function C$4(){return reactExports.useContext(n$6)}function c$6({value:o,children:r}){return React$1.createElement(n$6.Provider,{value:o},r)} let a$8=reactExports.createContext(()=>{});a$8.displayName="StackContext";var s$7=(e=>(e[e.Add=0]="Add",e[e.Remove=1]="Remove",e))(s$7||{});function x$6(){return reactExports.useContext(a$8)}function M$8({children:i,onUpdate:r,type:e,element:n,enabled:u}){let l=x$6(),o=o$5((...t)=>{r==null||r(...t),l(...t);});return l$a(()=>{let t=u===void 0||u===!0;return t&&o(0,e,n),()=>{t&&o(1,e,n);}},[o,e,n,u]),React$1.createElement(a$8.Provider,{value:o},i)} function d$8(e,r,n){let o=s$b(r);reactExports.useEffect(()=>{function t(u){o.current(u);}return document.addEventListener(e,t,n),()=>document.removeEventListener(e,t,n)},[e,n]);} function L$6(m,E,c=!0){let i=reactExports.useRef(!1);reactExports.useEffect(()=>{requestAnimationFrame(()=>{i.current=c;});},[c]);function f(e,o){if(!i.current||e.defaultPrevented)return;let l=function r(t){return typeof t=="function"?r(t()):Array.isArray(t)||t instanceof Set?t:[t]}(m),n=o(e);if(n!==null&&n.getRootNode().contains(n)){for(let r of l){if(r===null)continue;let t=r instanceof HTMLElement?r:r.current;if(t!=null&&t.contains(n)||e.composed&&e.composedPath().includes(t))return}return !h$7(n,T$6.Loose)&&n.tabIndex!==-1&&e.preventDefault(),E(e,n)}}let u=reactExports.useRef(null);d$8("mousedown",e=>{var o,l;i.current&&(u.current=((l=(o=e.composedPath)==null?void 0:o.call(e))==null?void 0:l[0])||e.target);},!0),d$8("click",e=>{u.current&&(f(e,()=>u.current),u.current=null);},!0),d$8("blur",e=>f(e,()=>window.document.activeElement instanceof HTMLIFrameElement?window.document.activeElement:null),!0);} function i$5(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}const d$7=typeof Object.is=="function"?Object.is:i$5,{useState:u$a,useEffect:h$5,useLayoutEffect:f$6,useDebugValue:p$9}=e$9;function y$7(e,t,c){const a=t(),[{inst:n},o]=u$a({inst:{value:a,getSnapshot:t}});return f$6(()=>{n.value=a,n.getSnapshot=t,r$6(n)&&o({inst:n});},[e,a,t]),h$5(()=>(r$6(n)&&o({inst:n}),e(()=>{r$6(n)&&o({inst:n});})),[e]),p$9(a),a}function r$6(e){const t=e.getSnapshot,c=e.value;try{const a=t();return !d$7(c,a)}catch{return !0}} const useSyncExternalStore = null; const r$5=typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.document.createElement!="undefined",s$6=!r$5,c$5=s$6?useSyncExternalStore:y$7,a$7="useSyncExternalStore"in e$9?(n=>n.useSyncExternalStore)(e$9):c$5; function S$6(t){return a$7(t.subscribe,t.getSnapshot,t.getSnapshot)} function a$6(o,r){let t=o(),n=new Set;return {getSnapshot(){return t},subscribe(e){return n.add(e),()=>n.delete(e)},dispatch(e,...s){let i=r[e].call(t,...s);i&&(t=i,n.forEach(c=>c()));}}} function c$4(){let o;return {before({doc:e}){var l;let n=e.documentElement;o=((l=e.defaultView)!=null?l:window).innerWidth-n.clientWidth;},after({doc:e,d:n}){let t=e.documentElement,l=t.clientWidth-t.offsetWidth,r=o-l;n.style(t,"paddingRight",`${r}px`);}}} function t$8(){return /iPhone/gi.test(window.navigator.platform)||/Mac/gi.test(window.navigator.platform)&&window.navigator.maxTouchPoints>0} function p$8(){if(!t$8())return {};let o;return {before(){o=window.pageYOffset;},after({doc:r,d:l,meta:s}){function i(e){return s.containers.flatMap(t=>t()).some(t=>t.contains(e))}l.style(r.body,"marginTop",`-${o}px`),window.scrollTo(0,0);let n=null;l.addEventListener(r,"click",e=>{if(e.target instanceof HTMLElement)try{let t=e.target.closest("a");if(!t)return;let{hash:c}=new URL(t.href),a=r.querySelector(c);a&&!i(a)&&(n=a);}catch{}},!0),l.addEventListener(r,"touchmove",e=>{e.target instanceof HTMLElement&&!i(e.target)&&e.preventDefault();},{passive:!1}),l.add(()=>{window.scrollTo(0,window.pageYOffset+o),n&&n.isConnected&&(n.scrollIntoView({block:"nearest"}),n=null);});}}} function l$7(){return {before({doc:e,d:o}){o.style(e.documentElement,"overflow","hidden");}}} function m$4(e){let n={};for(let t of e)Object.assign(n,t(n));return n}let a$5=a$6(()=>new Map,{PUSH(e,n){var o;let t=(o=this.get(e))!=null?o:{doc:e,count:0,d:o$3(),meta:new Set};return t.count++,t.meta.add(n),this.set(e,t),this},POP(e,n){let t=this.get(e);return t&&(t.count--,t.meta.delete(n)),this},SCROLL_PREVENT({doc:e,d:n,meta:t}){let o={doc:e,d:n,meta:m$4(t)},c=[p$8(),c$4(),l$7()];c.forEach(({before:r})=>r==null?void 0:r(o)),c.forEach(({after:r})=>r==null?void 0:r(o));},SCROLL_ALLOW({d:e}){e.dispose();},TEARDOWN({doc:e}){this.delete(e);}});a$5.subscribe(()=>{let e=a$5.getSnapshot(),n=new Map;for(let[t]of e)n.set(t,t.documentElement.style.overflow);for(let t of e.values()){let o=n.get(t.doc)==="hidden",c=t.count!==0;(c&&!o||!c&&o)&&a$5.dispatch(t.count>0?"SCROLL_PREVENT":"SCROLL_ALLOW",t),t.count===0&&a$5.dispatch("TEARDOWN",t);}}); function p$7(e,r,n){let f=S$6(a$5),o=e?f.get(e):void 0,i=o?o.count>0:!1;return l$a(()=>{if(!(!e||!r))return a$5.dispatch("PUSH",e,n),()=>a$5.dispatch("POP",e,n)},[r,e]),i} let u$9=new Map,t$7=new Map;function h$4(r,l=!0){l$a(()=>{var o;if(!l)return;let e=typeof r=="function"?r():r.current;if(!e)return;function a(){var d;if(!e)return;let i=(d=t$7.get(e))!=null?d:1;if(i===1?t$7.delete(e):t$7.set(e,i-1),i!==1)return;let n=u$9.get(e);n&&(n["aria-hidden"]===null?e.removeAttribute("aria-hidden"):e.setAttribute("aria-hidden",n["aria-hidden"]),e.inert=n.inert,u$9.delete(e));}let f=(o=t$7.get(e))!=null?o:0;return t$7.set(e,f+1),f!==0||(u$9.set(e,{"aria-hidden":e.getAttribute("aria-hidden"),inert:e.inert}),e.setAttribute("aria-hidden","true"),e.inert=!0),a},[r,l]);} var Se$4=(o=>(o[o.Open=0]="Open",o[o.Closed=1]="Closed",o))(Se$4||{}),Fe$3=(e=>(e[e.SetTitleId=0]="SetTitleId",e))(Fe$3||{});let ke$1={[0](t,e){return t.titleId===e.id?t:{...t,titleId:e.id}}},M$7=reactExports.createContext(null);M$7.displayName="DialogContext";function S$5(t){let e=reactExports.useContext(M$7);if(e===null){let o=new Error(`<${t} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(o,S$5),o}return e}function xe$4(t,e,o=()=>[document.body]){p$7(t,e,s=>{var n;return {containers:[...(n=s.containers)!=null?n:[],o]}});}function _e$2(t,e){return u$c(e.type,ke$1,t,e)}let Me$4="div",He$4=S$b.RenderStrategy|S$b.Static;function Ie$4(t,e){let o=I$7(),{id:s=`headlessui-dialog-${o}`,open:n,onClose:l,initialFocus:d,__demoMode:c=!1,...D}=t,[P,F]=reactExports.useState(0),i=C$4();n===void 0&&i!==null&&(n=(i&d$9.Open)===d$9.Open);let m=reactExports.useRef(null),Q=y$a(m,e),y=reactExports.useRef(null),p=n$7(m),U=t.hasOwnProperty("open")||i!==null,N=t.hasOwnProperty("onClose");if(!U&&!N)throw new Error("You have to provide an `open` and an `onClose` prop to the `Dialog` component.");if(!U)throw new Error("You provided an `onClose` prop to the `Dialog`, but forgot an `open` prop.");if(!N)throw new Error("You provided an `open` prop to the `Dialog`, but forgot an `onClose` prop.");if(typeof n!="boolean")throw new Error(`You provided an \`open\` prop to the \`Dialog\`, but the value is not a boolean. Received: ${n}`);if(typeof l!="function")throw new Error(`You provided an \`onClose\` prop to the \`Dialog\`, but the value is not a function. Received: ${l}`);let u=n?0:1,[E,Z]=reactExports.useReducer(_e$2,{titleId:null,descriptionId:null,panelRef:reactExports.createRef()}),A=o$5(()=>l(!1)),Y=o$5(r=>Z({type:0,id:r})),k=l$9()?c?!1:u===0:!1,x=P>1,$=reactExports.useContext(M$7)!==null,ee=x?"parent":"leaf",W=i!==null?(i&d$9.Closing)===d$9.Closing:!1,te=(()=>$||W?!1:k)(),oe=reactExports.useCallback(()=>{var r,f;return (f=Array.from((r=p==null?void 0:p.querySelectorAll("body > *"))!=null?r:[]).find(a=>a.id==="headlessui-portal-root"?!1:a.contains(y.current)&&a instanceof HTMLElement))!=null?f:null},[y]);h$4(oe,te);let re=(()=>x?!0:k)(),ne=reactExports.useCallback(()=>{var r,f;return (f=Array.from((r=p==null?void 0:p.querySelectorAll("[data-headlessui-portal]"))!=null?r:[]).find(a=>a.contains(y.current)&&a instanceof HTMLElement))!=null?f:null},[y]);h$4(ne,re);let H=o$5(()=>{var f,a;return [...Array.from((f=p==null?void 0:p.querySelectorAll("html > *, body > *, [data-headlessui-portal]"))!=null?f:[]).filter(T=>!(T===document.body||T===document.head||!(T instanceof HTMLElement)||T.contains(y.current)||E.panelRef.current&&T.contains(E.panelRef.current))),(a=E.panelRef.current)!=null?a:m.current]}),le=(()=>!(!k||x))();L$6(()=>H(),A,le);let ae=(()=>!(x||u!==0))();E$5(p==null?void 0:p.defaultView,"keydown",r=>{ae&&(r.defaultPrevented||r.key===o$4.Escape&&(r.preventDefault(),r.stopPropagation(),A()));});let ie=(()=>!(W||u!==0||$))();xe$4(p,ie,H),reactExports.useEffect(()=>{if(u!==0||!m.current)return;let r=new ResizeObserver(f=>{for(let a of f){let T=a.target.getBoundingClientRect();T.x===0&&T.y===0&&T.width===0&&T.height===0&&A();}});return r.observe(m.current),()=>r.disconnect()},[u,m,A]);let[se,pe]=M$a(),de=reactExports.useMemo(()=>[{dialogState:u,close:A,setTitleId:Y},E],[u,E,A,Y]),J=reactExports.useMemo(()=>({open:u===0}),[u]),ue={ref:Q,id:s,role:"dialog","aria-modal":u===0?!0:void 0,"aria-labelledby":E.titleId,"aria-describedby":se};return React$1.createElement(M$8,{type:"Dialog",enabled:u===0,element:m,onUpdate:o$5((r,f)=>{f==="Dialog"&&u$c(r,{[s$7.Add]:()=>F(a=>a+1),[s$7.Remove]:()=>F(a=>a-1)});})},React$1.createElement(P$4,{force:!0},React$1.createElement(te$2,null,React$1.createElement(M$7.Provider,{value:de},React$1.createElement(te$2.Group,{target:m},React$1.createElement(P$4,{force:!1},React$1.createElement(pe,{slot:J,name:"Dialog.Description"},React$1.createElement(Re$4,{initialFocus:d,containers:H,features:k?u$c(ee,{parent:Re$4.features.RestoreFocus,leaf:Re$4.features.All&~Re$4.features.FocusLock}):Re$4.features.None},X$7({ourProps:ue,theirProps:D,slot:J,defaultTag:Me$4,features:He$4,visible:u===0,name:"Dialog"})))))))),React$1.createElement(c$9,{features:p$b.Hidden,ref:y}))}let we$2="div";function Be$3(t,e){let o=I$7(),{id:s=`headlessui-dialog-overlay-${o}`,...n}=t,[{dialogState:l,close:d}]=S$5("Dialog.Overlay"),c=y$a(e),D=o$5(i=>{if(i.target===i.currentTarget){if(r$7(i.currentTarget))return i.preventDefault();i.preventDefault(),i.stopPropagation(),d();}}),P=reactExports.useMemo(()=>({open:l===0}),[l]);return X$7({ourProps:{ref:c,id:s,"aria-hidden":!0,onClick:D},theirProps:n,slot:P,defaultTag:we$2,name:"Dialog.Overlay"})}let Ge$3="div";function Ue$2(t,e){let o=I$7(),{id:s=`headlessui-dialog-backdrop-${o}`,...n}=t,[{dialogState:l},d]=S$5("Dialog.Backdrop"),c=y$a(e);reactExports.useEffect(()=>{if(d.panelRef.current===null)throw new Error("A component is being used, but a component is missing.")},[d.panelRef]);let D=reactExports.useMemo(()=>({open:l===0}),[l]);return React$1.createElement(P$4,{force:!0},React$1.createElement(te$2,null,X$7({ourProps:{ref:c,id:s,"aria-hidden":!0},theirProps:n,slot:D,defaultTag:Ge$3,name:"Dialog.Backdrop"})))}let Ne$4="div";function Ye$2(t,e){let o=I$7(),{id:s=`headlessui-dialog-panel-${o}`,...n}=t,[{dialogState:l},d]=S$5("Dialog.Panel"),c=y$a(e,d.panelRef),D=reactExports.useMemo(()=>({open:l===0}),[l]),P=o$5(i=>{i.stopPropagation();});return X$7({ourProps:{ref:c,id:s,onClick:P},theirProps:n,slot:D,defaultTag:Ne$4,name:"Dialog.Panel"})}let $e$3="h2";function We$3(t,e){let o=I$7(),{id:s=`headlessui-dialog-title-${o}`,...n}=t,[{dialogState:l,setTitleId:d}]=S$5("Dialog.Title"),c=y$a(e);reactExports.useEffect(()=>(d(s),()=>d(null)),[s,d]);let D=reactExports.useMemo(()=>({open:l===0}),[l]);return X$7({ourProps:{ref:c,id:s},theirProps:n,slot:D,defaultTag:$e$3,name:"Dialog.Title"})}let Je$3=D$8(Ie$4),Xe$3=D$8(Ue$2),je$3=D$8(Ye$2),Ke$3=D$8(Be$3),Ve$3=D$8(We$3),St$1=Object.assign(Je$3,{Backdrop:Xe$3,Panel:je$3,Overlay:Ke$3,Title:Ve$3,Description:b$3}); function i$4(t){var n;if(t.type)return t.type;let e=(n=t.as)!=null?n:"button";if(typeof e=="string"&&e.toLowerCase()==="button")return "button"}function s$5(t,e){let[n,u]=reactExports.useState(()=>i$4(t));return l$a(()=>{u(i$4(t));},[t.type,t.as]),l$a(()=>{n||e.current&&e.current instanceof HTMLButtonElement&&!e.current.hasAttribute("type")&&u("button");},[n,e]),n} var t$6;let a$4=(t$6=React$1.startTransition)!=null?t$6:function(i){i();}; var q$7=(o=>(o[o.Open=0]="Open",o[o.Closed=1]="Closed",o))(q$7||{}),z$5=(t=>(t[t.ToggleDisclosure=0]="ToggleDisclosure",t[t.CloseDisclosure=1]="CloseDisclosure",t[t.SetButtonId=2]="SetButtonId",t[t.SetPanelId=3]="SetPanelId",t[t.LinkPanel=4]="LinkPanel",t[t.UnlinkPanel=5]="UnlinkPanel",t))(z$5||{});let Q$4={[0]:e=>({...e,disclosureState:u$c(e.disclosureState,{[0]:1,[1]:0})}),[1]:e=>e.disclosureState===1?e:{...e,disclosureState:1},[4](e){return e.linkedPanel===!0?e:{...e,linkedPanel:!0}},[5](e){return e.linkedPanel===!1?e:{...e,linkedPanel:!1}},[2](e,n){return e.buttonId===n.buttonId?e:{...e,buttonId:n.buttonId}},[3](e,n){return e.panelId===n.panelId?e:{...e,panelId:n.panelId}}},k$6=reactExports.createContext(null);k$6.displayName="DisclosureContext";function M$6(e){let n=reactExports.useContext(k$6);if(n===null){let o=new Error(`<${e} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(o,M$6),o}return n}let v$9=reactExports.createContext(null);v$9.displayName="DisclosureAPIContext";function w$6(e){let n=reactExports.useContext(v$9);if(n===null){let o=new Error(`<${e} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(o,w$6),o}return n}let H$7=reactExports.createContext(null);H$7.displayName="DisclosurePanelContext";function V$4(){return reactExports.useContext(H$7)}function Y$5(e,n){return u$c(n.type,Q$4,e,n)}let Z$6=reactExports.Fragment;function ee$2(e,n){let{defaultOpen:o=!1,...u}=e,T=reactExports.useRef(null),l=y$a(n,T$7(a=>{T.current=a;},e.as===void 0||e.as===reactExports.Fragment)),t=reactExports.useRef(null),f=reactExports.useRef(null),s=reactExports.useReducer(Y$5,{disclosureState:o?0:1,linkedPanel:!1,buttonRef:f,panelRef:t,buttonId:null,panelId:null}),[{disclosureState:i,buttonId:c},D]=s,d=o$5(a=>{D({type:1});let r=e$5(T);if(!r||!c)return;let p=(()=>a?a instanceof HTMLElement?a:a.current instanceof HTMLElement?a.current:r.getElementById(c):r.getElementById(c))();p==null||p.focus();}),P=reactExports.useMemo(()=>({close:d}),[d]),b=reactExports.useMemo(()=>({open:i===0,close:d}),[i,d]),y={ref:l};return React$1.createElement(k$6.Provider,{value:s},React$1.createElement(v$9.Provider,{value:P},React$1.createElement(c$6,{value:u$c(i,{[0]:d$9.Open,[1]:d$9.Closed})},X$7({ourProps:y,theirProps:u,slot:b,defaultTag:Z$6,name:"Disclosure"}))))}let te$1="button";function ne$3(e,n){let o=I$7(),{id:u=`headlessui-disclosure-button-${o}`,...T}=e,[l,t]=M$6("Disclosure.Button"),f=V$4(),s=f===null?!1:f===l.panelId,i=reactExports.useRef(null),c=y$a(i,n,s?null:l.buttonRef);reactExports.useEffect(()=>{if(!s)return t({type:2,buttonId:u}),()=>{t({type:2,buttonId:null});}},[u,t,s]);let D=o$5(r=>{var p;if(s){if(l.disclosureState===1)return;switch(r.key){case o$4.Space:case o$4.Enter:r.preventDefault(),r.stopPropagation(),t({type:0}),(p=l.buttonRef.current)==null||p.focus();break}}else switch(r.key){case o$4.Space:case o$4.Enter:r.preventDefault(),r.stopPropagation(),t({type:0});break}}),d=o$5(r=>{switch(r.key){case o$4.Space:r.preventDefault();break}}),P=o$5(r=>{var p;r$7(r.currentTarget)||e.disabled||(s?(t({type:0}),(p=l.buttonRef.current)==null||p.focus()):t({type:0}));}),b=reactExports.useMemo(()=>({open:l.disclosureState===0}),[l]),y=s$5(e,i),a=s?{ref:c,type:y,onKeyDown:D,onClick:P}:{ref:c,id:u,type:y,"aria-expanded":e.disabled?void 0:l.disclosureState===0,"aria-controls":l.linkedPanel?l.panelId:void 0,onKeyDown:D,onKeyUp:d,onClick:P};return X$7({ourProps:a,theirProps:T,slot:b,defaultTag:te$1,name:"Disclosure.Button"})}let le$2="div",oe$1=S$b.RenderStrategy|S$b.Static;function re$3(e,n){let o=I$7(),{id:u=`headlessui-disclosure-panel-${o}`,...T}=e,[l,t]=M$6("Disclosure.Panel"),{close:f}=w$6("Disclosure.Panel"),s=y$a(n,l.panelRef,P=>{a$4(()=>t({type:P?4:5}));});reactExports.useEffect(()=>(t({type:3,panelId:u}),()=>{t({type:3,panelId:null});}),[u,t]);let i=C$4(),c=(()=>i!==null?(i&d$9.Open)===d$9.Open:l.disclosureState===0)(),D=reactExports.useMemo(()=>({open:l.disclosureState===0,close:f}),[l,f]),d={ref:s,id:u};return React$1.createElement(H$7.Provider,{value:l.panelId},X$7({ourProps:d,theirProps:T,slot:D,defaultTag:le$2,features:oe$1,visible:c,name:"Disclosure.Panel"}))}let se$2=D$8(ee$2),ue$2=D$8(ne$3),ie$2=D$8(re$3);Object.assign(se$2,{Button:ue$2,Panel:ie$2}); let d$6=reactExports.createContext(null);function u$8(){let o=reactExports.useContext(d$6);if(o===null){let t=new Error("You used a