ui.shipaid.com 0.3.45 → 0.3.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/widget.es.js +443 -11998
- package/dist/widget.iife.js +62 -77
- package/dist/widget.umd.js +62 -77
- package/dist-types/widget/src/shipaid-widget.d.ts +2 -18
- package/package.json +2 -3
package/dist/widget.iife.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
var ShipAidWidget=function(
|
|
1
|
+
var ShipAidWidget=function(t){"use strict";function e(t){var e;return(null==(e=null==t?void 0:t.match(/\d+/))?void 0:e[0])??null}const i={calculateProtectionTotal:function(t,e,i){var o,r;if(!t)throw new Error("Missing store settings.");if(!e)throw new Error("Missing protectionProduct.");if(!i)throw new Error("Missing Shopify cart.");const s=null==t?void 0:t.protectionSettings;if(!s)throw new Error("Tried to find protection variant, but protection settings for this store are missing.");const n=Array.isArray(null==t?void 0:t.excludedProductSkus)?t.excludedProductSkus.map((t=>t.trim())):[],a=Array.isArray(null==t?void 0:t.excludedProductsVariantsId)?t.excludedProductsVariantsId.map((t=>{var e;return parseInt((null==(e=t.match(/\d+/))?void 0:e[0])??"",10)})):[],p=(i.items??[]).reduce(((t,e)=>(t=>!(!t.sku||!n.includes(t.sku.trim()))||!(!t.variant_id||!a.includes(t.variant_id)))(e)?t-e.final_line_price:t),i.total_price||0)-((null==(o=i.items)?void 0:o.filter((t=>{var i;return null==(i=null==e?void 0:e.variants)?void 0:i.some((e=>e.id===t.variant_id))})))??[]).reduce(((t,e)=>t+e.final_line_price),0);if(0===p)return p;if("FIXED"===s.protectionType){if("number"!=typeof s.defaultFee)throw new Error("Missing default fee amount.");if(!(null==(r=s.rules)?void 0:r.length))return s.defaultFee;const t=p/100,e=s.rules.sort(((t,e)=>t.rangeLower&&e.rangeLower?t.rangeLower-e.rangeLower:0)).find((e=>{const i=Boolean(e.rangeLower&&e.rangeLower<t);return e.rangeUpper?i&&e.rangeUpper>=t:i}));return"number"==typeof(null==e?void 0:e.fee)?e.fee:s.defaultFee}if("PERCENTAGE"===s.protectionType){const t=p*s.percentage/100;return t>=s.minimumFee?t:s.minimumFee}throw new Error("No protection type handler found for this store.")},findProtectionVariant:function(t,e,i){var o;if(!(null==t?void 0:t.protectionSettings)||!(null==(o=null==e?void 0:e.variants)?void 0:o.length))throw new Error("Missing product and variants from protection settings.");const r=null==e?void 0:e.variants.flatMap((t=>{if(!(null==t?void 0:t.price))return[];const e=Number(t.price);return[{...t,formattedPrice:e}]})).sort(((t,e)=>t.formattedPrice-e.formattedPrice)),s=r.find((t=>t.formattedPrice>=i));return s||r[r.length-1]}},o=(t,e)=>"method"===e.kind&&e.descriptor&&!("value"in e.descriptor)?{...e,finisher(i){i.createProperty(e.key,t)}}:{kind:"field",key:Symbol(),placement:"own",descriptor:{},originalKey:e.key,initializer(){"function"==typeof e.initializer&&(this[e.key]=e.initializer.call(this))},finisher(i){i.createProperty(e.key,t)}},r=(t,e,i)=>{e.constructor.createProperty(i,t)};
|
|
2
2
|
/**
|
|
3
3
|
* @license
|
|
4
4
|
* Copyright 2017 Google LLC
|
|
5
5
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
6
|
-
*/function
|
|
6
|
+
*/function s(t){return(e,i)=>void 0!==i?r(t,e,i):o(t,e)}
|
|
7
7
|
/**
|
|
8
8
|
* @license
|
|
9
9
|
* Copyright 2017 Google LLC
|
|
10
10
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
11
|
-
*/function
|
|
11
|
+
*/function n(t){return s({...t,state:!0})}
|
|
12
12
|
/**
|
|
13
13
|
* @license
|
|
14
14
|
* Copyright 2021 Google LLC
|
|
@@ -19,50 +19,50 @@ var ShipAidWidget=function(e){"use strict";function t(e){var t;return(null==(t=n
|
|
|
19
19
|
* Copyright 2019 Google LLC
|
|
20
20
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
21
21
|
*/
|
|
22
|
-
const
|
|
22
|
+
const p=window,d=p.ShadowRoot&&(void 0===p.ShadyCSS||p.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,l=Symbol(),c=new WeakMap;let h=class{constructor(t,e,i){if(this._$cssResult$=!0,i!==l)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const e=this.t;if(d&&void 0===t){const i=void 0!==e&&1===e.length;i&&(t=c.get(e)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&c.set(e,t))}return t}toString(){return this.cssText}};const u=(t,...e)=>{const i=1===t.length?t[0]:e.reduce(((e,i,o)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+t[o+1]),t[0]);return new h(i,t,l)},f=d?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const i of t.cssRules)e+=i.cssText;return(t=>new h("string"==typeof t?t:t+"",void 0,l))(e)})(t):t
|
|
23
23
|
/**
|
|
24
24
|
* @license
|
|
25
25
|
* Copyright 2017 Google LLC
|
|
26
26
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
27
|
-
*/;var
|
|
27
|
+
*/;var m;const g=window,v=g.trustedTypes,b=v?v.emptyScript:"",_=g.reactiveElementPolyfillSupport,y={toAttribute(t,e){switch(e){case Boolean:t=t?b:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,e){let i=t;switch(e){case Boolean:i=null!==t;break;case Number:i=null===t?null:Number(t);break;case Object:case Array:try{i=JSON.parse(t)}catch(o){i=null}}return i}},C=(t,e)=>e!==t&&(e==e||t==t),w={attribute:!0,type:String,converter:y,reflect:!1,hasChanged:C},x="finalized";let $=class extends HTMLElement{constructor(){super(),this._$Ei=new Map,this.isUpdatePending=!1,this.hasUpdated=!1,this._$El=null,this._$Eu()}static addInitializer(t){var e;this.finalize(),(null!==(e=this.h)&&void 0!==e?e:this.h=[]).push(t)}static get observedAttributes(){this.finalize();const t=[];return this.elementProperties.forEach(((e,i)=>{const o=this._$Ep(i,e);void 0!==o&&(this._$Ev.set(o,i),t.push(o))})),t}static createProperty(t,e=w){if(e.state&&(e.attribute=!1),this.finalize(),this.elementProperties.set(t,e),!e.noAccessor&&!this.prototype.hasOwnProperty(t)){const i="symbol"==typeof t?Symbol():"__"+t,o=this.getPropertyDescriptor(t,i,e);void 0!==o&&Object.defineProperty(this.prototype,t,o)}}static getPropertyDescriptor(t,e,i){return{get(){return this[e]},set(o){const r=this[t];this[e]=o,this.requestUpdate(t,r,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)||w}static finalize(){if(this.hasOwnProperty(x))return!1;this[x]=!0;const t=Object.getPrototypeOf(this);if(t.finalize(),void 0!==t.h&&(this.h=[...t.h]),this.elementProperties=new Map(t.elementProperties),this._$Ev=new Map,this.hasOwnProperty("properties")){const t=this.properties,e=[...Object.getOwnPropertyNames(t),...Object.getOwnPropertySymbols(t)];for(const i of e)this.createProperty(i,t[i])}return this.elementStyles=this.finalizeStyles(this.styles),!0}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const t of i)e.unshift(f(t))}else void 0!==t&&e.push(f(t));return e}static _$Ep(t,e){const i=e.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof t?t.toLowerCase():void 0}_$Eu(){var t;this._$E_=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$Eg(),this.requestUpdate(),null===(t=this.constructor.h)||void 0===t||t.forEach((t=>t(this)))}addController(t){var e,i;(null!==(e=this._$ES)&&void 0!==e?e:this._$ES=[]).push(t),void 0!==this.renderRoot&&this.isConnected&&(null===(i=t.hostConnected)||void 0===i||i.call(t))}removeController(t){var e;null===(e=this._$ES)||void 0===e||e.splice(this._$ES.indexOf(t)>>>0,1)}_$Eg(){this.constructor.elementProperties.forEach(((t,e)=>{this.hasOwnProperty(e)&&(this._$Ei.set(e,this[e]),delete this[e])}))}createRenderRoot(){var t;const e=null!==(t=this.shadowRoot)&&void 0!==t?t:this.attachShadow(this.constructor.shadowRootOptions);return((t,e)=>{d?t.adoptedStyleSheets=e.map((t=>t instanceof CSSStyleSheet?t:t.styleSheet)):e.forEach((e=>{const i=document.createElement("style"),o=p.litNonce;void 0!==o&&i.setAttribute("nonce",o),i.textContent=e.cssText,t.appendChild(i)}))})(e,this.constructor.elementStyles),e}connectedCallback(){var t;void 0===this.renderRoot&&(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),null===(t=this._$ES)||void 0===t||t.forEach((t=>{var e;return null===(e=t.hostConnected)||void 0===e?void 0:e.call(t)}))}enableUpdating(t){}disconnectedCallback(){var t;null===(t=this._$ES)||void 0===t||t.forEach((t=>{var e;return null===(e=t.hostDisconnected)||void 0===e?void 0:e.call(t)}))}attributeChangedCallback(t,e,i){this._$AK(t,i)}_$EO(t,e,i=w){var o;const r=this.constructor._$Ep(t,i);if(void 0!==r&&!0===i.reflect){const s=(void 0!==(null===(o=i.converter)||void 0===o?void 0:o.toAttribute)?i.converter:y).toAttribute(e,i.type);this._$El=t,null==s?this.removeAttribute(r):this.setAttribute(r,s),this._$El=null}}_$AK(t,e){var i;const o=this.constructor,r=o._$Ev.get(t);if(void 0!==r&&this._$El!==r){const t=o.getPropertyOptions(r),s="function"==typeof t.converter?{fromAttribute:t.converter}:void 0!==(null===(i=t.converter)||void 0===i?void 0:i.fromAttribute)?t.converter:y;this._$El=r,this[r]=s.fromAttribute(e,t.type),this._$El=null}}requestUpdate(t,e,i){let o=!0;void 0!==t&&(((i=i||this.constructor.getPropertyOptions(t)).hasChanged||C)(this[t],e)?(this._$AL.has(t)||this._$AL.set(t,e),!0===i.reflect&&this._$El!==t&&(void 0===this._$EC&&(this._$EC=new Map),this._$EC.set(t,i))):o=!1),!this.isUpdatePending&&o&&(this._$E_=this._$Ej())}async _$Ej(){this.isUpdatePending=!0;try{await this._$E_}catch(e){Promise.reject(e)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var t;if(!this.isUpdatePending)return;this.hasUpdated,this._$Ei&&(this._$Ei.forEach(((t,e)=>this[e]=t)),this._$Ei=void 0);let e=!1;const i=this._$AL;try{e=this.shouldUpdate(i),e?(this.willUpdate(i),null===(t=this._$ES)||void 0===t||t.forEach((t=>{var e;return null===(e=t.hostUpdate)||void 0===e?void 0:e.call(t)})),this.update(i)):this._$Ek()}catch(o){throw e=!1,this._$Ek(),o}e&&this._$AE(i)}willUpdate(t){}_$AE(t){var e;null===(e=this._$ES)||void 0===e||e.forEach((t=>{var e;return null===(e=t.hostUpdated)||void 0===e?void 0:e.call(t)})),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$Ek(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$E_}shouldUpdate(t){return!0}update(t){void 0!==this._$EC&&(this._$EC.forEach(((t,e)=>this._$EO(e,this[e],t))),this._$EC=void 0),this._$Ek()}updated(t){}firstUpdated(t){}};
|
|
28
28
|
/**
|
|
29
29
|
* @license
|
|
30
30
|
* Copyright 2017 Google LLC
|
|
31
31
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
32
32
|
*/
|
|
33
|
-
var S
|
|
33
|
+
var S;$[x]=!0,$.elementProperties=new Map,$.elementStyles=[],$.shadowRootOptions={mode:"open"},null==_||_({ReactiveElement:$}),(null!==(m=g.reactiveElementVersions)&&void 0!==m?m:g.reactiveElementVersions=[]).push("1.6.3");const A=window,L=A.trustedTypes,P=L?L.createPolicy("lit-html",{createHTML:t=>t}):void 0,k="$lit$",z=`lit$${(Math.random()+"").slice(9)}$`,E="?"+z,M=`<${E}>`,q=document,I=()=>q.createComment(""),T=t=>null===t||"object"!=typeof t&&"function"!=typeof t,N=Array.isArray,O="[ \t\n\f\r]",j=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,R=/-->/g,U=/>/g,V=RegExp(`>|${O}(?:([^\\s"'>=/]+)(${O}*=${O}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),D=/'/g,B=/"/g,H=/^(?:script|style|textarea|title)$/i,F=(Y=1,(t,...e)=>({_$litType$:Y,strings:t,values:e})),W=Symbol.for("lit-noChange"),Z=Symbol.for("lit-nothing"),G=new WeakMap,K=q.createTreeWalker(q,129,null,!1);var Y;function J(t,e){if(!Array.isArray(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==P?P.createHTML(e):e}class X{constructor({strings:t,_$litType$:e},i){let o;this.parts=[];let r=0,s=0;const n=t.length-1,a=this.parts,[p,d]=((t,e)=>{const i=t.length-1,o=[];let r,s=2===e?"<svg>":"",n=j;for(let a=0;a<i;a++){const e=t[a];let i,p,d=-1,l=0;for(;l<e.length&&(n.lastIndex=l,p=n.exec(e),null!==p);)l=n.lastIndex,n===j?"!--"===p[1]?n=R:void 0!==p[1]?n=U:void 0!==p[2]?(H.test(p[2])&&(r=RegExp("</"+p[2],"g")),n=V):void 0!==p[3]&&(n=V):n===V?">"===p[0]?(n=null!=r?r:j,d=-1):void 0===p[1]?d=-2:(d=n.lastIndex-p[2].length,i=p[1],n=void 0===p[3]?V:'"'===p[3]?B:D):n===B||n===D?n=V:n===R||n===U?n=j:(n=V,r=void 0);const c=n===V&&t[a+1].startsWith("/>")?" ":"";s+=n===j?e+M:d>=0?(o.push(i),e.slice(0,d)+k+e.slice(d)+z+c):e+z+(-2===d?(o.push(void 0),a):c)}return[J(t,s+(t[i]||"<?>")+(2===e?"</svg>":"")),o]})(t,e);if(this.el=X.createElement(p,i),K.currentNode=this.el.content,2===e){const t=this.el.content,e=t.firstChild;e.remove(),t.append(...e.childNodes)}for(;null!==(o=K.nextNode())&&a.length<n;){if(1===o.nodeType){if(o.hasAttributes()){const t=[];for(const e of o.getAttributeNames())if(e.endsWith(k)||e.startsWith(z)){const i=d[s++];if(t.push(e),void 0!==i){const t=o.getAttribute(i.toLowerCase()+k).split(z),e=/([.?@])?(.*)/.exec(i);a.push({type:1,index:r,name:e[2],strings:t,ctor:"."===e[1]?ot:"?"===e[1]?st:"@"===e[1]?nt:it})}else a.push({type:6,index:r})}for(const e of t)o.removeAttribute(e)}if(H.test(o.tagName)){const t=o.textContent.split(z),e=t.length-1;if(e>0){o.textContent=L?L.emptyScript:"";for(let i=0;i<e;i++)o.append(t[i],I()),K.nextNode(),a.push({type:2,index:++r});o.append(t[e],I())}}}else if(8===o.nodeType)if(o.data===E)a.push({type:2,index:r});else{let t=-1;for(;-1!==(t=o.data.indexOf(z,t+1));)a.push({type:7,index:r}),t+=z.length-1}r++}}static createElement(t,e){const i=q.createElement("template");return i.innerHTML=t,i}}function Q(t,e,i=t,o){var r,s,n,a;if(e===W)return e;let p=void 0!==o?null===(r=i._$Co)||void 0===r?void 0:r[o]:i._$Cl;const d=T(e)?void 0:e._$litDirective$;return(null==p?void 0:p.constructor)!==d&&(null===(s=null==p?void 0:p._$AO)||void 0===s||s.call(p,!1),void 0===d?p=void 0:(p=new d(t),p._$AT(t,i,o)),void 0!==o?(null!==(n=(a=i)._$Co)&&void 0!==n?n:a._$Co=[])[o]=p:i._$Cl=p),void 0!==p&&(e=Q(t,p._$AS(t,e.values),p,o)),e}class tt{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){var e;const{el:{content:i},parts:o}=this._$AD,r=(null!==(e=null==t?void 0:t.creationScope)&&void 0!==e?e:q).importNode(i,!0);K.currentNode=r;let s=K.nextNode(),n=0,a=0,p=o[0];for(;void 0!==p;){if(n===p.index){let e;2===p.type?e=new et(s,s.nextSibling,this,t):1===p.type?e=new p.ctor(s,p.name,p.strings,this,t):6===p.type&&(e=new at(s,this,t)),this._$AV.push(e),p=o[++a]}n!==(null==p?void 0:p.index)&&(s=K.nextNode(),n++)}return K.currentNode=q,r}v(t){let e=0;for(const i of this._$AV)void 0!==i&&(void 0!==i.strings?(i._$AI(t,i,e),e+=i.strings.length-2):i._$AI(t[e])),e++}}class et{constructor(t,e,i,o){var r;this.type=2,this._$AH=Z,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=i,this.options=o,this._$Cp=null===(r=null==o?void 0:o.isConnected)||void 0===r||r}get _$AU(){var t,e;return null!==(e=null===(t=this._$AM)||void 0===t?void 0:t._$AU)&&void 0!==e?e:this._$Cp}get parentNode(){let t=this._$AA.parentNode;const e=this._$AM;return void 0!==e&&11===(null==t?void 0:t.nodeType)&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=Q(this,t,e),T(t)?t===Z||null==t||""===t?(this._$AH!==Z&&this._$AR(),this._$AH=Z):t!==this._$AH&&t!==W&&this._(t):void 0!==t._$litType$?this.g(t):void 0!==t.nodeType?this.$(t):(t=>N(t)||"function"==typeof(null==t?void 0:t[Symbol.iterator]))(t)?this.T(t):this._(t)}k(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}$(t){this._$AH!==t&&(this._$AR(),this._$AH=this.k(t))}_(t){this._$AH!==Z&&T(this._$AH)?this._$AA.nextSibling.data=t:this.$(q.createTextNode(t)),this._$AH=t}g(t){var e;const{values:i,_$litType$:o}=t,r="number"==typeof o?this._$AC(t):(void 0===o.el&&(o.el=X.createElement(J(o.h,o.h[0]),this.options)),o);if((null===(e=this._$AH)||void 0===e?void 0:e._$AD)===r)this._$AH.v(i);else{const t=new tt(r,this),e=t.u(this.options);t.v(i),this.$(e),this._$AH=t}}_$AC(t){let e=G.get(t.strings);return void 0===e&&G.set(t.strings,e=new X(t)),e}T(t){N(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let i,o=0;for(const r of t)o===e.length?e.push(i=new et(this.k(I()),this.k(I()),this,this.options)):i=e[o],i._$AI(r),o++;o<e.length&&(this._$AR(i&&i._$AB.nextSibling,o),e.length=o)}_$AR(t=this._$AA.nextSibling,e){var i;for(null===(i=this._$AP)||void 0===i||i.call(this,!1,!0,e);t&&t!==this._$AB;){const e=t.nextSibling;t.remove(),t=e}}setConnected(t){var e;void 0===this._$AM&&(this._$Cp=t,null===(e=this._$AP)||void 0===e||e.call(this,t))}}class it{constructor(t,e,i,o,r){this.type=1,this._$AH=Z,this._$AN=void 0,this.element=t,this.name=e,this._$AM=o,this.options=r,i.length>2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=Z}get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}_$AI(t,e=this,i,o){const r=this.strings;let s=!1;if(void 0===r)t=Q(this,t,e,0),s=!T(t)||t!==this._$AH&&t!==W,s&&(this._$AH=t);else{const o=t;let n,a;for(t=r[0],n=0;n<r.length-1;n++)a=Q(this,o[i+n],e,n),a===W&&(a=this._$AH[n]),s||(s=!T(a)||a!==this._$AH[n]),a===Z?t=Z:t!==Z&&(t+=(null!=a?a:"")+r[n+1]),this._$AH[n]=a}s&&!o&&this.j(t)}j(t){t===Z?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,null!=t?t:"")}}class ot extends it{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===Z?void 0:t}}const rt=L?L.emptyScript:"";class st extends it{constructor(){super(...arguments),this.type=4}j(t){t&&t!==Z?this.element.setAttribute(this.name,rt):this.element.removeAttribute(this.name)}}class nt extends it{constructor(t,e,i,o,r){super(t,e,i,o,r),this.type=5}_$AI(t,e=this){var i;if((t=null!==(i=Q(this,t,e,0))&&void 0!==i?i:Z)===W)return;const o=this._$AH,r=t===Z&&o!==Z||t.capture!==o.capture||t.once!==o.once||t.passive!==o.passive,s=t!==Z&&(o===Z||r);r&&this.element.removeEventListener(this.name,this,o),s&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){var e,i;"function"==typeof this._$AH?this._$AH.call(null!==(i=null===(e=this.options)||void 0===e?void 0:e.host)&&void 0!==i?i:this.element,t):this._$AH.handleEvent(t)}}class at{constructor(t,e,i){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(t){Q(this,t)}}const pt=A.litHtmlPolyfillSupport;null==pt||pt(X,et),(null!==(S=A.litHtmlVersions)&&void 0!==S?S:A.litHtmlVersions=[]).push("2.8.0");const dt=(t,e,i)=>{var o,r;const s=null!==(o=null==i?void 0:i.renderBefore)&&void 0!==o?o:e;let n=s._$litPart$;if(void 0===n){const t=null!==(r=null==i?void 0:i.renderBefore)&&void 0!==r?r:null;s._$litPart$=n=new et(e.insertBefore(I(),t),t,void 0,null!=i?i:{})}return n._$AI(t),n};
|
|
34
34
|
/**
|
|
35
35
|
* @license
|
|
36
36
|
* Copyright 2017 Google LLC
|
|
37
37
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
38
|
-
*/var
|
|
38
|
+
*/var lt,ct;let ht=class extends ${constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var t,e;const i=super.createRenderRoot();return null!==(t=(e=this.renderOptions).renderBefore)&&void 0!==t||(e.renderBefore=i.firstChild),i}update(t){const e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=dt(e,this.renderRoot,this.renderOptions)}connectedCallback(){var t;super.connectedCallback(),null===(t=this._$Do)||void 0===t||t.setConnected(!0)}disconnectedCallback(){var t;super.disconnectedCallback(),null===(t=this._$Do)||void 0===t||t.setConnected(!1)}render(){return W}};ht.finalized=!0,ht._$litElement$=!0,null===(lt=globalThis.litElementHydrateSupport)||void 0===lt||lt.call(globalThis,{LitElement:ht});const ut=globalThis.litElementPolyfillSupport;null==ut||ut({LitElement:ht}),(null!==(ct=globalThis.litElementVersions)&&void 0!==ct?ct:globalThis.litElementVersions=[]).push("3.3.3");const ft="langChanged";function mt(t,e,i){return Object.entries(vt(e||{})).reduce(((t,[e,i])=>t.replace(new RegExp(`{{[ ]*${e}[ ]*}}`,"gm"),String(vt(i)))),t)}function gt(t,e){const i=t.split(".");let o=e.strings;for(;null!=o&&i.length>0;)o=o[i.shift()];return null!=o?o.toString():null}function vt(t){return"function"==typeof t?t():t}let bt={loader:()=>Promise.resolve({}),empty:t=>`[${t}]`,lookup:gt,interpolate:mt,translationCache:{}};function _t(t,e,i=bt){var o;o={previousStrings:i.strings,previousLang:i.lang,lang:i.lang=t,strings:i.strings=e},window.dispatchEvent(new CustomEvent(ft,{detail:o}))}
|
|
39
39
|
/**
|
|
40
40
|
* @license
|
|
41
41
|
* Copyright 2017 Google LLC
|
|
42
42
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
43
43
|
*/
|
|
44
|
-
const
|
|
44
|
+
const yt=2;class Ct{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}}
|
|
45
45
|
/**
|
|
46
46
|
* @license
|
|
47
47
|
* Copyright 2020 Google LLC
|
|
48
48
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
49
|
-
*/const
|
|
49
|
+
*/const wt=(t,e)=>{var i,o;const r=t._$AN;if(void 0===r)return!1;for(const s of r)null===(o=(i=s)._$AO)||void 0===o||o.call(i,e,!1),wt(s,e);return!0},xt=t=>{let e,i;do{if(void 0===(e=t._$AM))break;i=e._$AN,i.delete(t),t=e}while(0===(null==i?void 0:i.size))},$t=t=>{for(let e;e=t._$AM;t=e){let i=e._$AN;if(void 0===i)e._$AN=i=new Set;else if(i.has(t))break;i.add(t),Lt(e)}};
|
|
50
50
|
/**
|
|
51
51
|
* @license
|
|
52
52
|
* Copyright 2017 Google LLC
|
|
53
53
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
54
|
-
*/function
|
|
54
|
+
*/function St(t){void 0!==this._$AN?(xt(this),this._$AM=t,$t(this)):this._$AM=t}function At(t,e=!1,i=0){const o=this._$AH,r=this._$AN;if(void 0!==r&&0!==r.size)if(e)if(Array.isArray(o))for(let s=i;s<o.length;s++)wt(o[s],!1),xt(o[s]);else null!=o&&(wt(o,!1),xt(o));else wt(this,t)}const Lt=t=>{var e,i,o,r;t.type==yt&&(null!==(e=(o=t)._$AP)&&void 0!==e||(o._$AP=At),null!==(i=(r=t)._$AQ)&&void 0!==i||(r._$AQ=St))};class Pt extends Ct{constructor(){super(...arguments),this._$AN=void 0}_$AT(t,e,i){super._$AT(t,e,i),$t(this),this.isConnected=t._$AU}_$AO(t,e=!0){var i,o;t!==this.isConnected&&(this.isConnected=t,t?null===(i=this.reconnected)||void 0===i||i.call(this):null===(o=this.disconnected)||void 0===o||o.call(this)),e&&(wt(this,t),xt(this))}setValue(t){if(void 0===this._$Ct.strings)this._$Ct._$AI(t,this);else{const e=[...this._$Ct._$AH];e[this._$Ci]=t,this._$Ct._$AI(e,this,0)}}disconnected(){}reconnected(){}}class kt extends Pt{constructor(){super(...arguments),this.langChangedSubscription=null,this.getValue=()=>""}renderValue(t){return this.getValue=t,this.subscribe(),this.getValue()}langChanged(t){this.setValue(this.getValue(t))}subscribe(){null==this.langChangedSubscription&&(this.langChangedSubscription=function(t,e){const i=e=>t(e.detail);return window.addEventListener(ft,i,e),()=>window.removeEventListener(ft,i)}(this.langChanged.bind(this)))}unsubscribe(){null!=this.langChangedSubscription&&this.langChangedSubscription()}disconnected(){this.unsubscribe()}reconnected(){this.subscribe()}}const zt=(t=>(...e)=>({_$litDirective$:t,values:e}))(class extends kt{render(t,e,i){return this.renderValue((()=>function(t,e,i=bt){let o=i.translationCache[t]||(i.translationCache[t]=i.lookup(t,i)||i.empty(t,i));return null!=(e=null!=e?vt(e):null)?i.interpolate(o,e,i):o}(t,e,i)))}});
|
|
55
55
|
/**
|
|
56
56
|
* @license
|
|
57
57
|
* Copyright 2017 Google LLC
|
|
58
58
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
59
|
-
*/class
|
|
59
|
+
*/class Et extends Ct{constructor(t){if(super(t),this.et=Z,t.type!==yt)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===Z||null==t)return this.ft=void 0,this.et=t;if(t===W)return t;if("string"!=typeof t)throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.et)return this.ft;this.et=t;const e=[t];return e.raw=e,this.ft={_$litType$:this.constructor.resultType,strings:e,values:[]}}}Et.directiveName="unsafeHTML",Et.resultType=1;const Mt="__registered_effects";function qt(t){const e=t;if(e[Mt])return e;const i=function(t){if(!t.dispatchEvent||!t.requestUpdate)throw new Error("Element missing required functions (dispatchEvent/requestUpdate)");return t}(t),o=i.updated;return e[Mt]={index:0,count:0,effects:[]},i.updated=t=>(e[Mt].index=0,o(t)),e}function It(t,e,i){const o=function(t,e){const i=qt(t),{index:o,count:r}=i[Mt];return o===r?(i[Mt].index++,i[Mt].count++,i[Mt].effects.push(e),e):(i[Mt].index++,i[Mt].effects[o])}(t,{on:e,observe:["__initial__dirty"]});o.observe.some(((t,e)=>i[e]!==t))&&o.on(),o.observe=i}
|
|
60
60
|
/**
|
|
61
61
|
* @license
|
|
62
62
|
* Copyright 2021 Google LLC
|
|
63
63
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
64
64
|
*/
|
|
65
|
-
function
|
|
65
|
+
function Tt(t,e,i){return t?e():null==i?void 0:i()}const Nt=u`
|
|
66
66
|
:host {
|
|
67
67
|
--shipaid-primary: #0056d6;
|
|
68
68
|
--shipaid-secondary: #0076ff;
|
|
@@ -266,7 +266,7 @@ function Le(e,t,r){return e?t():null==r?void 0:r()}const De=p`
|
|
|
266
266
|
background: transparent;
|
|
267
267
|
z-index: -1;
|
|
268
268
|
}
|
|
269
|
-
|
|
269
|
+
`,Ot=F`
|
|
270
270
|
<svg
|
|
271
271
|
version="1.0"
|
|
272
272
|
width="50.000000pt"
|
|
@@ -287,7 +287,7 @@ function Le(e,t,r){return e?t():null==r?void 0:r()}const De=p`
|
|
|
287
287
|
/>
|
|
288
288
|
</g>
|
|
289
289
|
</svg>
|
|
290
|
-
`,
|
|
290
|
+
`,jt=F`
|
|
291
291
|
<svg
|
|
292
292
|
version="1.0"
|
|
293
293
|
width="50.000000pt"
|
|
@@ -308,7 +308,7 @@ function Le(e,t,r){return e?t():null==r?void 0:r()}const De=p`
|
|
|
308
308
|
/>
|
|
309
309
|
</g>
|
|
310
310
|
</svg>
|
|
311
|
-
`,
|
|
311
|
+
`,Rt=F`
|
|
312
312
|
<svg
|
|
313
313
|
width="50.000000pt"
|
|
314
314
|
height="50.000000pt"
|
|
@@ -392,7 +392,7 @@ function Le(e,t,r){return e?t():null==r?void 0:r()}const De=p`
|
|
|
392
392
|
/>
|
|
393
393
|
</g>
|
|
394
394
|
</svg>
|
|
395
|
-
`,
|
|
395
|
+
`,Ut=F`
|
|
396
396
|
<svg
|
|
397
397
|
width="300.000000pt"
|
|
398
398
|
height="75.000000pt"
|
|
@@ -476,7 +476,7 @@ function Le(e,t,r){return e?t():null==r?void 0:r()}const De=p`
|
|
|
476
476
|
/>
|
|
477
477
|
</g>
|
|
478
478
|
</svg>
|
|
479
|
-
`,
|
|
479
|
+
`,Vt=F`
|
|
480
480
|
<svg
|
|
481
481
|
version="1.0"
|
|
482
482
|
viewBox="0 0 500.000000 500.000000"
|
|
@@ -501,7 +501,7 @@ function Le(e,t,r){return e?t():null==r?void 0:r()}const De=p`
|
|
|
501
501
|
/>
|
|
502
502
|
</g>
|
|
503
503
|
</svg>
|
|
504
|
-
`,
|
|
504
|
+
`,Dt=F`
|
|
505
505
|
<svg
|
|
506
506
|
version="1.0"
|
|
507
507
|
viewBox="0 0 500.000000 500.000000"
|
|
@@ -520,7 +520,7 @@ function Le(e,t,r){return e?t():null==r?void 0:r()}const De=p`
|
|
|
520
520
|
/>
|
|
521
521
|
</g>
|
|
522
522
|
</svg>
|
|
523
|
-
`,
|
|
523
|
+
`,Bt=F`
|
|
524
524
|
<svg
|
|
525
525
|
version="1.0"
|
|
526
526
|
viewBox="0 0 500.000000 500.000000"
|
|
@@ -545,7 +545,7 @@ function Le(e,t,r){return e?t():null==r?void 0:r()}const De=p`
|
|
|
545
545
|
/>
|
|
546
546
|
</g>
|
|
547
547
|
</svg>
|
|
548
|
-
`,
|
|
548
|
+
`,Ht=F`
|
|
549
549
|
<svg
|
|
550
550
|
xmlns="http://www.w3.org/2000/svg"
|
|
551
551
|
version="1.0"
|
|
@@ -571,37 +571,37 @@ function Le(e,t,r){return e?t():null==r?void 0:r()}const De=p`
|
|
|
571
571
|
/>
|
|
572
572
|
</g>
|
|
573
573
|
</svg>
|
|
574
|
-
`;var
|
|
574
|
+
`;var Ft=Object.defineProperty;const Wt=class extends ht{constructor(){super(...arguments),this.active=!1}handleClosePopup(){const t=new Event("close");this.dispatchEvent(t)}render(){return F`
|
|
575
575
|
<div class=${`shipaid-popup ${this.active&&"active"}`}>
|
|
576
576
|
<button
|
|
577
577
|
type="button"
|
|
578
578
|
class="popup-close"
|
|
579
579
|
@click=${this.handleClosePopup}
|
|
580
580
|
>
|
|
581
|
-
${
|
|
581
|
+
${zt("learn-more-popup.close")}
|
|
582
582
|
</button>
|
|
583
|
-
<div class="popup-logo">${
|
|
584
|
-
<p class="popup-title">${
|
|
583
|
+
<div class="popup-logo">${Ut}</div>
|
|
584
|
+
<p class="popup-title">${zt("learn-more-popup.title")}</p>
|
|
585
585
|
<div class="popup-disclaimer-subtitle">
|
|
586
|
-
<div class="popup-icon">${
|
|
587
|
-
<p>${
|
|
586
|
+
<div class="popup-icon">${Vt}</div>
|
|
587
|
+
<p>${zt("learn-more-popup.disclaimer.subtitle-enable")}</p>
|
|
588
588
|
</div>
|
|
589
589
|
<div class="popup-disclaimer-subtitle">
|
|
590
|
-
<div class="popup-icon">${
|
|
591
|
-
<p>${
|
|
590
|
+
<div class="popup-icon">${Dt}</div>
|
|
591
|
+
<p>${zt("learn-more-popup.disclaimer.subtitle-monitor")}</p>
|
|
592
592
|
</div>
|
|
593
593
|
<div class="popup-disclaimer-subtitle">
|
|
594
|
-
<div class="popup-icon-b">${
|
|
595
|
-
<p>${
|
|
594
|
+
<div class="popup-icon-b">${Ht}</div>
|
|
595
|
+
<p>${zt("learn-more-popup.disclaimer.subtitle-notify")}</p>
|
|
596
596
|
</div>
|
|
597
597
|
<div class="popup-disclaimer-subtitle">
|
|
598
|
-
<div class="popup-icon-bell">${
|
|
598
|
+
<div class="popup-icon-bell">${Bt}</div>
|
|
599
599
|
<p>
|
|
600
|
-
${
|
|
600
|
+
${zt("learn-more-popup.disclaimer.subtitle-resolution")}
|
|
601
601
|
</p>
|
|
602
602
|
</div>
|
|
603
603
|
<p class="popup-disclaimer">
|
|
604
|
-
${
|
|
604
|
+
${zt("learn-more-popup.disclaimer.text")}
|
|
605
605
|
</p>
|
|
606
606
|
<hr class="popup-divider" />
|
|
607
607
|
<div class="popup-footer">
|
|
@@ -611,14 +611,14 @@ function Le(e,t,r){return e?t():null==r?void 0:r()}const De=p`
|
|
|
611
611
|
target="_blank"
|
|
612
612
|
rel="noreferrer"
|
|
613
613
|
>
|
|
614
|
-
${
|
|
614
|
+
${zt("learn-more-popup.links.terms")}
|
|
615
615
|
</a>
|
|
616
616
|
<a
|
|
617
617
|
href="https://www.shipaid.com/privacy-policy"
|
|
618
618
|
target="_blank"
|
|
619
619
|
rel="noreferrer"
|
|
620
620
|
>
|
|
621
|
-
${
|
|
621
|
+
${zt("learn-more-popup.links.privacy")}
|
|
622
622
|
</a>
|
|
623
623
|
</div>
|
|
624
624
|
<div class="footer-date">
|
|
@@ -631,7 +631,7 @@ function Le(e,t,r){return e?t():null==r?void 0:r()}const De=p`
|
|
|
631
631
|
</div>
|
|
632
632
|
</div>
|
|
633
633
|
<div class="blocker" @click=${this.handleClosePopup}></div>
|
|
634
|
-
`}};
|
|
634
|
+
`}};Wt.styles=Nt;let Zt=Wt;((t,e,i,o)=>{for(var r,s=void 0,n=t.length-1;n>=0;n--)(r=t[n])&&(s=r(e,i,s)||s);s&&Ft(e,i,s)})([s({type:Boolean,attribute:!0})],Zt.prototype,"active"),customElements.get("shipaid-popup-learn-more")||customElements.define("shipaid-popup-learn-more",Zt);const Gt=u`
|
|
635
635
|
:host {
|
|
636
636
|
--shipaid-primary: #0056d6;
|
|
637
637
|
--shipaid-secondary: #0076ff;
|
|
@@ -775,7 +775,7 @@ function Le(e,t,r){return e?t():null==r?void 0:r()}const De=p`
|
|
|
775
775
|
background: transparent;
|
|
776
776
|
z-index: -1;
|
|
777
777
|
}
|
|
778
|
-
`;var
|
|
778
|
+
`;var Kt=Object.defineProperty;const Yt=class extends ht{constructor(){super(...arguments),this.active=!1}handleClosePopup(){const t=new Event("close");this.dispatchEvent(t)}handleRemoveProtection(){const t=new Event("remove-protection");this.dispatchEvent(t)}render(){return F`
|
|
779
779
|
<div class=${`shipaid-confirmation-popup ${this.active&&"active"}`}>
|
|
780
780
|
<p class="popup-title">Are you sure?</p>
|
|
781
781
|
<div class="popup-subtitle">
|
|
@@ -799,7 +799,7 @@ function Le(e,t,r){return e?t():null==r?void 0:r()}const De=p`
|
|
|
799
799
|
</div>
|
|
800
800
|
</div>
|
|
801
801
|
<div class="blocker" @click=${this.handleClosePopup}></div>
|
|
802
|
-
`}};
|
|
802
|
+
`}};Yt.styles=Gt;let Jt=Yt;((t,e,i,o)=>{for(var r,s=void 0,n=t.length-1;n>=0;n--)(r=t[n])&&(s=r(e,i,s)||s);s&&Kt(e,i,s)})([s({type:Boolean,attribute:!0})],Jt.prototype,"active"),customElements.get("shipaid-popup-confirmation")||customElements.define("shipaid-popup-confirmation",Jt);const Xt="Loading ShipAid Widget...",Qt="Delivery Guarantee",te="in case of Loss, Damage or Theft",ee={button:"Powered by"},ie={add:"Add",remove:"Remove",loading:"Loading..."},oe={loading:Xt,title:Qt,description:te,footer:ee,actions:ie,"learn-more-popup":{close:"Close",title:"Delivery Guarantee",disclaimer:{"subtitle-enable":"We enable your favorite brands to provide a delivery guarantee because we know that every order is precious, and things happen!","subtitle-monitor":"We continuously monitor your package and offer a convenient portal for you to track your order's progress at any moment!","subtitle-notify":"You'll be notified throughout the entire shipping process, ensuring you stay up to date every step of the way.","subtitle-resolution":"In case of any issues during transit, we offer a quick and easy method to report the problem directly to the brand, for a swift resolution.",text:"By purchasing this delivery guarantee, you agree to our Terms Of Service and Privacy Policy. You are not obligated to purchase this guarantee. This guarantee is NOT insurance and does not provide indemnification against loss, damage, or liability arising from a contingent or unknown event, but rather, through ShipAid brands provide a delivery guarantee whereby if the product you ordered is not delivered in satisfactory condition, the brand from which you ordered the product may replace the product free of charge. ShipAid does not provide any products or services directly to consumers, but instead provides a service that allow brands to facilitate product replacement to their customers. Purchasing this guarantee does not mean that you will automatically be reimbursed for any product or shipping costs because the resolution process and decision for compensation is strictly decided by the brand you a purchasing from. The brand will require proof of damage or undelivered product."},links:{terms:"Terms of Service",privacy:"Privacy Policy"}}},re=Object.freeze(Object.defineProperty({__proto__:null,actions:ie,default:oe,description:te,footer:ee,loading:Xt,title:Qt},Symbol.toStringTag,{value:"Module"})),se=u`
|
|
803
803
|
:host {
|
|
804
804
|
--shipaid-primary: #002bd6;
|
|
805
805
|
--shipaid-secondary: #0076ff;
|
|
@@ -955,80 +955,65 @@ function Le(e,t,r){return e?t():null==r?void 0:r()}const De=p`
|
|
|
955
955
|
.shipaid-prompt .prompt-footer .prompt-footer-badge svg {
|
|
956
956
|
height:var(--shipaid-footer-badge-logo-height, 9px);
|
|
957
957
|
}
|
|
958
|
-
`;var ot=(e=>(e.LOADED="shipaid-loaded",e.STATUS_UPDATE="shipaid-protection-status",e))(ot||{});class st extends Error{}function at(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(t)}catch(r){return atob(t)}}function ct(e,t){if("string"!=typeof e)throw new st("Invalid token specified: must be a string");t||(t={});const r=!0===t.header?0:1,n=e.split(".")[r];if("string"!=typeof n)throw new st(`Invalid token specified: missing part #${r+1}`);let i;try{i=at(n)}catch(o){throw new st(`Invalid token specified: invalid base64 for part #${r+1} (${o.message})`)}try{return JSON.parse(i)}catch(o){throw new st(`Invalid token specified: invalid json for part #${r+1} (${o.message})`)}}
|
|
959
|
-
/*! *****************************************************************************
|
|
960
|
-
Copyright (c) Microsoft Corporation.
|
|
961
|
-
|
|
962
|
-
Permission to use, copy, modify, and/or distribute this software for any
|
|
963
|
-
purpose with or without fee is hereby granted.
|
|
964
|
-
|
|
965
|
-
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
966
|
-
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
967
|
-
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
968
|
-
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
969
|
-
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
970
|
-
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
971
|
-
PERFORMANCE OF THIS SOFTWARE.
|
|
972
|
-
***************************************************************************** */st.prototype.name="InvalidTokenError";var lt,ut,dt,ht,pt=function(){return pt=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},pt.apply(this,arguments)};function ft(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}function vt(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function mt(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(a){i={error:a}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s}function gt(e,t,r){if(2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}(ut=lt||(lt={})).Start="xstate.start",ut.Stop="xstate.stop",ut.Raise="xstate.raise",ut.Send="xstate.send",ut.Cancel="xstate.cancel",ut.NullEvent="",ut.Assign="xstate.assign",ut.After="xstate.after",ut.DoneState="done.state",ut.DoneInvoke="done.invoke",ut.Log="xstate.log",ut.Init="xstate.init",ut.Invoke="xstate.invoke",ut.ErrorExecution="error.execution",ut.ErrorCommunication="error.communication",ut.ErrorPlatform="error.platform",ut.ErrorCustom="xstate.error",ut.Update="xstate.update",ut.Pure="xstate.pure",ut.Choose="xstate.choose",(ht=dt||(dt={})).Parent="#_parent",ht.Internal="#_internal";var yt=lt.Start,wt=lt.Stop,bt=lt.Raise,Et=lt.Send,_t=lt.Cancel,Tt=lt.NullEvent,xt=lt.Assign;lt.After,lt.DoneState;var St=lt.Log,kt=lt.Init,At=lt.Invoke;lt.ErrorExecution;var Ct,It=lt.ErrorPlatform,Ot=lt.ErrorCustom,Nt=lt.Update,Pt=lt.Choose,Rt=lt.Pure,Lt={},Dt="xstate.guard",$t="production"===process.env.NODE_ENV;function Ut(e,t,r){void 0===r&&(r=".");var n=Vt(e,r),i=Vt(t,r);return rr(i)?!!rr(n)&&i===n:rr(n)?n in i:Object.keys(n).every((function(e){return e in i&&Ut(n[e],i[e])}))}function Mt(e){try{return rr(e)||"number"==typeof e?"".concat(e):e.type}catch(t){throw new Error("Events must be strings or objects with a string event.type property.")}}function jt(e,t){try{return er(e)?e:e.toString().split(t)}catch(r){throw new Error("'".concat(e,"' is not a valid state path."))}}function Vt(e,t){return"object"==typeof(r=e)&&"value"in r&&"context"in r&&"event"in r&&"_event"in r?e.value:er(e)?Ft(e):"string"!=typeof e?e:Ft(jt(e,t));var r}function Ft(e){if(1===e.length)return e[0];for(var t={},r=t,n=0;n<e.length-1;n++)n===e.length-2?r[e[n]]=e[n+1]:(r[e[n]]={},r=r[e[n]]);return t}function zt(e,t){for(var r={},n=Object.keys(e),i=0;i<n.length;i++){var o=n[i];r[o]=t(e[o],o,e,i)}return r}function qt(e,t,r){var n,i,o={};try{for(var s=vt(Object.keys(e)),a=s.next();!a.done;a=s.next()){var c=a.value,l=e[c];r(l)&&(o[c]=t(l,c,e))}}catch(u){n={error:u}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}var Bt=function(e){return function(t){var r,n,i=t;try{for(var o=vt(e),s=o.next();!s.done;s=o.next()){i=i[s.value]}}catch(a){r={error:a}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return i}};function Ht(e){return e?rr(e)?[[e]]:Kt(Object.keys(e).map((function(t){var r=e[t];return"string"==typeof r||r&&Object.keys(r).length?Ht(e[t]).map((function(e){return[t].concat(e)})):[[t]]}))):[[]]}function Kt(e){var t;return(t=[]).concat.apply(t,gt([],mt(e),!1))}function Gt(e){return er(e)?e:[e]}function Yt(e){return void 0===e?[]:Gt(e)}function Wt(e,t,r){var n,i;if(tr(e))return e(t,r.data);var o={};try{for(var s=vt(Object.keys(e)),a=s.next();!a.done;a=s.next()){var c=a.value,l=e[c];tr(l)?o[c]=l(t,r.data):o[c]=l}}catch(u){n={error:u}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}function Jt(e){return e instanceof Promise||!(null===e||!tr(e)&&"object"!=typeof e||!tr(e.then))}function Qt(e,t){return zt(e.states,(function(e,r){if(e){var n=(rr(t)?void 0:t[r])||(e?e.current:void 0);if(n)return{current:n,states:Qt(e,n)}}}))}function Xt(e,t,r,n){return $t||Zt(!!e,"Attempting to update undefined context"),e?r.reduce((function(e,r){var i,o,s=r.assignment,a={state:n,action:r,_event:t},c={};if(tr(s))c=s(e,t.data,a);else try{for(var l=vt(Object.keys(s)),u=l.next();!u.done;u=l.next()){var d=u.value,h=s[d];c[d]=tr(h)?h(e,t.data,a):h}}catch(p){i={error:p}}finally{try{u&&!u.done&&(o=l.return)&&o.call(l)}finally{if(i)throw i.error}}return Object.assign({},e,c)}),e):e}var Zt=function(){};function er(e){return Array.isArray(e)}function tr(e){return"function"==typeof e}function rr(e){return"string"==typeof e}function nr(e,t){if(e)return rr(e)?{type:Dt,name:e,predicate:t?t[e]:void 0}:tr(e)?{type:Dt,name:e.name,predicate:e}:e}$t||(Zt=function(e,t){var r=e instanceof Error?e:void 0;if((r||!e)&&void 0!==console){var n=["Warning: ".concat(t)];r&&n.push(r),console.warn.apply(console,n)}});var ir=function(){return"function"==typeof Symbol&&Symbol.observable||"@@observable"}();function or(e){return!!e&&"__xstatenode"in e}function sr(e,t){return rr(e)||"number"==typeof e?pt({type:e},t):e}function ar(e,t){if(!rr(e)&&"$$type"in e&&"scxml"===e.$$type)return e;var r=sr(e);return pt({name:r.type,data:r,$$type:"scxml",type:"external"},t)}function cr(e,t){return Gt(t).map((function(t){return void 0===t||"string"==typeof t||or(t)?{target:t,event:e}:pt(pt({},t),{event:e})}))}function lr(e,t,r,n,i){var o=e.options.guards,s={state:i,cond:t,_event:n};if(t.type===Dt)return((null==o?void 0:o[t.name])||t.predicate)(r,n.data,s);var a=null==o?void 0:o[t.type];if(!a)throw new Error("Guard '".concat(t.type,"' is not implemented on machine '").concat(e.id,"'."));return a(r,n.data,s)}function ur(e){return"string"==typeof e?{type:e}:e}function dr(e,t,r){var n=function(){},i="object"==typeof e,o=i?e:null;return{next:((i?e.next:e)||n).bind(o),error:((i?e.error:t)||n).bind(o),complete:((i?e.complete:r)||n).bind(o)}}function hr(e,t){return"".concat(e,":invocation[").concat(t,"]")}function pr(e){return(e.type===bt||e.type===Et&&e.to===dt.Internal)&&"number"!=typeof e.delay}(Ct={})[ir]=function(){return this},Ct[Symbol.observable]=function(){return this};var fr=ar({type:kt});function vr(e,t){return t&&t[e]||void 0}function mr(e,t){var r;if(rr(e)||"number"==typeof e)r=tr(n=vr(e,t))?{type:e,exec:n}:n||{type:e,exec:void 0};else if(tr(e))r={type:e.name||e.toString(),exec:e};else{var n;if(tr(n=vr(e.type,t)))r=pt(pt({},e),{exec:n});else if(n){var i=n.type||e.type;r=pt(pt(pt({},n),e),{type:i})}else r=e}return r}var gr=function(e,t){return e?(er(e)?e:[e]).map((function(e){return mr(e,t)})):[]};function yr(e){var t=mr(e);return pt(pt({id:rr(e)?e:t.id},t),{type:t.type})}function wr(e,t){return{to:t?t.to:void 0,type:Et,event:tr(e)?e:sr(e),delay:t?t.delay:void 0,id:t&&void 0!==t.id?t.id:tr(e)?e.name:Mt(e)}}function br(e,t){var r="".concat(lt.DoneState,".").concat(e),n={type:r,data:t,toString:function(){return r}};return n}function Er(e,t){var r="".concat(lt.DoneInvoke,".").concat(e),n={type:r,data:t,toString:function(){return r}};return n}function _r(e,t){var r="".concat(lt.ErrorPlatform,".").concat(e),n={type:r,data:t,toString:function(){return r}};return n}function Tr(e,t,r,n,i,o,s){void 0===s&&(s=!1);var a=s?[]:function(e){var t,r,n=[];try{for(var i=vt(e),o=i.next();!o.done;o=i.next())for(var s=o.value,a=0;a<s.actions.length;)s.actions[a].type!==xt?a++:(n.push(s.actions[a]),s.actions.splice(a,1))}catch(c){t={error:c}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return n}(i),c=a.length?Xt(r,n,a,t):r,l=s?[r]:void 0,u=[];function d(i,a){var d;switch(a.type){case bt:var h=function(e,t,r,n){var i,o={_event:r},s=ar(tr(e.event)?e.event(t,r.data,o):e.event);if(rr(e.delay)){var a=n&&n[e.delay];i=tr(a)?a(t,r.data,o):a}else i=tr(e.delay)?e.delay(t,r.data,o):e.delay;return pt(pt({},e),{type:bt,_event:s,delay:i})}(a,c,n,e.options.delays);return o&&"number"==typeof h.delay&&o(h,c,n),h;case Et:var p=function(e,t,r,n){var i,o={_event:r},s=ar(tr(e.event)?e.event(t,r.data,o):e.event);if(rr(e.delay)){var a=n&&n[e.delay];i=tr(a)?a(t,r.data,o):a}else i=tr(e.delay)?e.delay(t,r.data,o):e.delay;var c=tr(e.to)?e.to(t,r.data,o):e.to;return pt(pt({},e),{to:c,_event:s,event:s.data,delay:i})}(a,c,n,e.options.delays);if(!$t){var f=a.delay;Zt(!rr(f)||"number"==typeof p.delay,"No delay reference for delay expression '".concat(f,"' was found on machine '").concat(e.id,"'"))}return o&&p.to!==dt.Internal&&("entry"===i?u.push(p):o(p,c,n)),p;case St:var v=function(e,t,r){return pt(pt({},e),{value:rr(e.expr)?e.expr:e.expr(t,r.data,{_event:r})})}(a,c,n);return null==o||o(v,c,n),v;case Pt:if(!(w=null===(d=a.conds.find((function(r){var i=nr(r.cond,e.options.guards);return!i||lr(e,i,c,n,o?void 0:t)})))||void 0===d?void 0:d.actions))return[];var m=mt(Tr(e,t,c,n,[{type:i,actions:gr(Yt(w),e.options.actions)}],o,s),2),g=m[0],y=m[1];return c=y,null==l||l.push(c),g;case Rt:var w;if(!(w=a.get(c,n.data)))return[];var b=mt(Tr(e,t,c,n,[{type:i,actions:gr(Yt(w),e.options.actions)}],o,s),2),E=b[0],_=b[1];return c=_,null==l||l.push(c),E;case wt:v=function(e,t,r){var n=tr(e.activity)?e.activity(t,r.data):e.activity,i="string"==typeof n?{id:n}:n;return{type:lt.Stop,activity:i}}(a,c,n);return null==o||o(v,r,n),v;case xt:c=Xt(c,n,[a],o?void 0:t),null==l||l.push(c);break;default:var T=mr(a,e.options.actions),x=T.exec;if(o)o(T,c,n);else if(x&&l){var S=l.length-1,k=pt(pt({},T),{exec:function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];x.apply(void 0,gt([l[S]],mt(t),!1))}});T=k}return T}}return[Kt(i.map((function(e){var t,r,i=[];try{for(var s=vt(e.actions),a=s.next();!a.done;a=s.next()){var l=a.value,h=d(e.type,l);h&&(i=i.concat(h))}}catch(p){t={error:p}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}return u.forEach((function(e){o(e,c,n)})),u.length=0,i}))),c]}var xr=function(e,t){return t(e)};function Sr(e){var t;return(t={id:e,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},getSnapshot:function(){},toJSON:function(){return{id:e}}})[ir]=function(){return this},t}function kr(e,t,r){var n=Sr(t);if(n.deferred=!0,or(e)){var i=n.state=xr(void 0,(function(){return(r?e.withContext(r):e).initialState}));n.getSnapshot=function(){return i}}return n}var Ar=function(e){return"atomic"===e.type||"final"===e.type};function Cr(e){return Object.keys(e.states).map((function(t){return e.states[t]}))}function Ir(e){return Cr(e).filter((function(e){return"history"!==e.type}))}function Or(e){var t=[e];return Ar(e)?t:t.concat(Kt(Ir(e).map(Or)))}function Nr(e,t){var r,n,i,o,s,a,c,l,u=Rr(new Set(e)),d=new Set(t);try{for(var h=vt(d),p=h.next();!p.done;p=h.next())for(var f=(T=p.value).parent;f&&!d.has(f);)d.add(f),f=f.parent}catch(x){r={error:x}}finally{try{p&&!p.done&&(n=h.return)&&n.call(h)}finally{if(r)throw r.error}}var v=Rr(d);try{for(var m=vt(d),g=m.next();!g.done;g=m.next()){if("compound"!==(T=g.value).type||v.get(T)&&v.get(T).length){if("parallel"===T.type)try{for(var y=(s=void 0,vt(Ir(T))),w=y.next();!w.done;w=y.next()){var b=w.value;d.has(b)||(d.add(b),u.get(b)?u.get(b).forEach((function(e){return d.add(e)})):b.initialStateNodes.forEach((function(e){return d.add(e)})))}}catch(S){s={error:S}}finally{try{w&&!w.done&&(a=y.return)&&a.call(y)}finally{if(s)throw s.error}}}else u.get(T)?u.get(T).forEach((function(e){return d.add(e)})):T.initialStateNodes.forEach((function(e){return d.add(e)}))}}catch(k){i={error:k}}finally{try{g&&!g.done&&(o=m.return)&&o.call(m)}finally{if(i)throw i.error}}try{for(var E=vt(d),_=E.next();!_.done;_=E.next()){var T;for(f=(T=_.value).parent;f&&!d.has(f);)d.add(f),f=f.parent}}catch(A){c={error:A}}finally{try{_&&!_.done&&(l=E.return)&&l.call(E)}finally{if(c)throw c.error}}return d}function Pr(e,t){var r=t.get(e);if(!r)return{};if("compound"===e.type){var n=r[0];if(!n)return{};if(Ar(n))return n.key}var i={};return r.forEach((function(e){i[e.key]=Pr(e,t)})),i}function Rr(e){var t,r,n=new Map;try{for(var i=vt(e),o=i.next();!o.done;o=i.next()){var s=o.value;n.has(s)||n.set(s,[]),s.parent&&(n.has(s.parent)||n.set(s.parent,[]),n.get(s.parent).push(s))}}catch(a){t={error:a}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return n}function Lr(e,t){return Pr(e,Rr(Nr([e],t)))}function Dr(e,t){return Array.isArray(e)?e.some((function(e){return e===t})):e instanceof Set&&e.has(t)}function $r(e,t){return"compound"===t.type?Ir(t).some((function(t){return"final"===t.type&&Dr(e,t)})):"parallel"===t.type&&Ir(t).every((function(t){return $r(e,t)}))}function Ur(e){return new Set(Kt(e.map((function(e){return e.tags}))))}function Mr(e,t){if(e===t)return!0;if(void 0===e||void 0===t)return!1;if(rr(e)||rr(t))return e===t;var r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every((function(r){return Mr(e[r],t[r])}))}var jr=function(){function e(e){var t,r,n=this;this.actions=[],this.activities=Lt,this.meta={},this.events=[],this.value=e.value,this.context=e.context,this._event=e._event,this._sessionid=e._sessionid,this.event=this._event.data,this.historyValue=e.historyValue,this.history=e.history,this.actions=e.actions||[],this.activities=e.activities||Lt,this.meta=(void 0===(r=e.configuration)&&(r=[]),r.reduce((function(e,t){return void 0!==t.meta&&(e[t.id]=t.meta),e}),{})),this.events=e.events||[],this.matches=this.matches.bind(this),this.toStrings=this.toStrings.bind(this),this.configuration=e.configuration,this.transitions=e.transitions,this.children=e.children,this.done=!!e.done,this.tags=null!==(t=Array.isArray(e.tags)?new Set(e.tags):e.tags)&&void 0!==t?t:new Set,this.machine=e.machine,Object.defineProperty(this,"nextEvents",{get:function(){return function(e){return gt([],mt(new Set(Kt(gt([],mt(e.map((function(e){return e.ownEvents}))),!1)))),!1)}(n.configuration)}})}return e.from=function(t,r){return t instanceof e?t.context!==r?new e({value:t.value,context:r,_event:t._event,_sessionid:null,historyValue:t.historyValue,history:t.history,actions:[],activities:t.activities,meta:{},events:[],configuration:[],transitions:[],children:{}}):t:new e({value:t,context:r,_event:fr,_sessionid:null,historyValue:void 0,history:void 0,actions:[],activities:void 0,meta:void 0,events:[],configuration:[],transitions:[],children:{}})},e.create=function(t){return new e(t)},e.inert=function(t,r){if(t instanceof e){if(!t.actions.length)return t;var n=fr;return new e({value:t.value,context:r,_event:n,_sessionid:null,historyValue:t.historyValue,history:t.history,activities:t.activities,configuration:t.configuration,transitions:[],children:{}})}return e.from(t,r)},e.prototype.toStrings=function(e,t){var r=this;if(void 0===e&&(e=this.value),void 0===t&&(t="."),rr(e))return[e];var n=Object.keys(e);return n.concat.apply(n,gt([],mt(n.map((function(n){return r.toStrings(e[n],t).map((function(e){return n+t+e}))}))),!1))},e.prototype.toJSON=function(){var e=this;e.configuration,e.transitions;var t=e.tags;e.machine;var r=ft(e,["configuration","transitions","tags","machine"]);return pt(pt({},r),{tags:Array.from(t)})},e.prototype.matches=function(e){return Ut(e,this.value)},e.prototype.hasTag=function(e){return this.tags.has(e)},e.prototype.can=function(e){var t;$t&&Zt(!!this.machine,"state.can(...) used outside of a machine-created State object; this will always return false.");var r=null===(t=this.machine)||void 0===t?void 0:t.getTransitionData(this,e);return!!(null==r?void 0:r.transitions.length)&&r.transitions.some((function(e){return void 0!==e.target||e.actions.length}))},e}(),Vr={deferEvents:!1},Fr=function(){function e(e){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=pt(pt({},Vr),e)}return e.prototype.initialize=function(e){if(this.initialized=!0,e){if(!this.options.deferEvents)return void this.schedule(e);this.process(e)}this.flushEvents()},e.prototype.schedule=function(e){if(this.initialized&&!this.processingEvent){if(0!==this.queue.length)throw new Error("Event queue should be empty when it is not processing events");this.process(e),this.flushEvents()}else this.queue.push(e)},e.prototype.clear=function(){this.queue=[]},e.prototype.flushEvents=function(){for(var e=this.queue.shift();e;)this.process(e),e=this.queue.shift()},e.prototype.process=function(e){this.processingEvent=!0;try{e()}catch(t){throw this.clear(),t}finally{this.processingEvent=!1}},e}(),zr=new Map,qr=0,Br=function(){return"x:".concat(qr++)},Hr=function(e,t){return zr.set(e,t),e},Kr=function(e){return zr.get(e)},Gr=function(e){zr.delete(e)};function Yr(){return"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window||"undefined"!=typeof window?window:void($t||console.warn("XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues"))}function Wr(e){if(Yr()){var t=function(){var e=Yr();if(e&&"__xstate__"in e)return e.__xstate__}();t&&t.register(e)}}function Jr(e,t){void 0===t&&(t={});var r,n,i=e.initialState,o=new Set,s=[],a=!1,c=(r={id:t.id,send:function(t){s.push(t),function(){if(!a){for(a=!0;s.length>0;){var t=s.shift();i=e.transition(i,t,l),o.forEach((function(e){return e.next(i)}))}a=!1}}()},getSnapshot:function(){return i},subscribe:function(e,t,r){var n=dr(e,t,r);return o.add(n),n.next(i),{unsubscribe:function(){o.delete(n)}}}},pt(((n={subscribe:function(){return{unsubscribe:function(){}}},id:"anonymous",getSnapshot:function(){}})[ir]=function(){return this},n),r)),l={parent:t.parent,self:c,id:t.id||"anonymous",observers:o};return i=e.start?e.start(l):i,c}var Qr,Xr,Zr={sync:!1,autoForward:!1};(Xr=Qr||(Qr={}))[Xr.NotStarted=0]="NotStarted",Xr[Xr.Running=1]="Running",Xr[Xr.Stopped=2]="Stopped";var en=function(){function e(t,r){void 0===r&&(r=e.defaultOptions);var n=this;this.machine=t,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,this.initialized=!1,this.status=Qr.NotStarted,this.children=new Map,this.forwardTo=new Set,this._outgoingQueue=[],this.init=this.start,this.send=function(e,t){if(er(e))return n.batch(e),n.state;var r=ar(sr(e,t));if(n.status===Qr.Stopped)return $t||Zt(!1,'Event "'.concat(r.name,'" was sent to stopped service "').concat(n.machine.id,'". This service has already reached its final state, and will not transition.\nEvent: ').concat(JSON.stringify(r.data))),n.state;if(n.status!==Qr.Running&&!n.options.deferEvents)throw new Error('Event "'.concat(r.name,'" was sent to uninitialized service "').concat(n.machine.id,'". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.\nEvent: ').concat(JSON.stringify(r.data)));return n.scheduler.schedule((function(){n.forward(r);var e=n._nextState(r);n.update(e,r)})),n._state},this.sendTo=function(e,t,r){var i,o=n.parent&&(t===dt.Parent||n.parent.id===t),s=o?n.parent:rr(t)?t===dt.Internal?n:n.children.get(t)||Kr(t):(i=t)&&"function"==typeof i.send?t:void 0;if(s)if("machine"in s){if(n.status!==Qr.Stopped||n.parent!==s||n.state.done){var a=pt(pt({},e),{name:e.name===Ot?"".concat(_r(n.id)):e.name,origin:n.sessionId});!r&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([s,a]):s.send(a)}}else!r&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([s,e.data]):s.send(e.data);else{if(!o)throw new Error("Unable to send event to child '".concat(t,"' from service '").concat(n.id,"'."));$t||Zt(!1,"Service '".concat(n.id,"' has no parent: unable to send event ").concat(e.type))}},this._exec=function(e,t,r,i){void 0===i&&(i=n.machine.options.actions);var o=e.exec||vr(e.type,i),s=tr(o)?o:o?o.exec:e.exec;if(s)try{return s(t,r.data,n.machine.config.predictableActionArguments?{action:e,_event:r}:{action:e,state:n.state,_event:r})}catch(E){throw n.parent&&n.parent.send({type:"xstate.error",data:E}),E}switch(e.type){case bt:var a=e;n.defer(a);break;case Et:var c=e;if("number"==typeof c.delay)return void n.defer(c);c.to?n.sendTo(c._event,c.to,r===fr):n.send(c._event);break;case _t:n.cancel(e.sendId);break;case yt:if(n.status!==Qr.Running)return;var l=e.activity;if(!n.machine.config.predictableActionArguments&&!n.state.activities[l.id||l.type])break;if(l.type===lt.Invoke){var u=ur(l.src),d=n.machine.options.services?n.machine.options.services[u.type]:void 0,h=l.id,p=l.data;$t||Zt(!("forward"in l),"`forward` property is deprecated (found in invocation of '".concat(l.src,"' in in machine '").concat(n.machine.id,"'). ")+"Please use `autoForward` instead.");var f="autoForward"in l?l.autoForward:!!l.forward;if(!d)return void($t||Zt(!1,"No service found for invocation '".concat(l.src,"' in machine '").concat(n.machine.id,"'.")));var v=p?Wt(p,t,r):void 0;if("string"==typeof d)return;var m=tr(d)?d(t,r.data,{data:v,src:u,meta:l.meta}):d;if(!m)return;var g=void 0;or(m)&&(m=v?m.withContext(v):m,g={autoForward:f}),n.spawn(m,h,g)}else n.spawnActivity(l);break;case wt:n.stopChild(e.activity.id);break;case St:var y=e,w=y.label,b=y.value;w?n.logger(w,b):n.logger(b);break;default:$t||Zt(!1,"No implementation found for action type '".concat(e.type,"'"))}};var i=pt(pt({},e.defaultOptions),r),o=i.clock,s=i.logger,a=i.parent,c=i.id,l=void 0!==c?c:t.id;this.id=l,this.logger=s,this.clock=o,this.parent=a,this.options=i,this.scheduler=new Fr({deferEvents:this.options.deferEvents}),this.sessionId=Br()}return Object.defineProperty(e.prototype,"initialState",{get:function(){var e=this;return this._initialState?this._initialState:xr(this,(function(){return e._initialState=e.machine.initialState,e._initialState}))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return $t||Zt(this.status!==Qr.NotStarted,"Attempted to read state from uninitialized service '".concat(this.id,"'. Make sure the service is started first.")),this._state},enumerable:!1,configurable:!0}),e.prototype.execute=function(e,t){var r,n;try{for(var i=vt(e.actions),o=i.next();!o.done;o=i.next()){var s=o.value;this.exec(s,e,t)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},e.prototype.update=function(e,t){var r,n,i,o,s,a,c,l,u=this;if(e._sessionid=this.sessionId,this._state=e,this.machine.config.predictableActionArguments&&t!==fr||!this.options.execute)for(var d=void 0;d=this._outgoingQueue.shift();)d[0].send(d[1]);else this.execute(this.state);if(this.children.forEach((function(e){u.state.children[e.id]=e})),this.devTools&&this.devTools.send(t.data,e),e.event)try{for(var h=vt(this.eventListeners),p=h.next();!p.done;p=h.next()){(0,p.value)(e.event)}}catch(_){r={error:_}}finally{try{p&&!p.done&&(n=h.return)&&n.call(h)}finally{if(r)throw r.error}}try{for(var f=vt(this.listeners),v=f.next();!v.done;v=f.next()){(0,v.value)(e,e.event)}}catch(T){i={error:T}}finally{try{v&&!v.done&&(o=f.return)&&o.call(f)}finally{if(i)throw i.error}}try{for(var m=vt(this.contextListeners),g=m.next();!g.done;g=m.next()){(0,g.value)(this.state.context,this.state.history?this.state.history.context:void 0)}}catch(x){s={error:x}}finally{try{g&&!g.done&&(a=m.return)&&a.call(m)}finally{if(s)throw s.error}}if(this.state.done){var y=e.configuration.find((function(e){return"final"===e.type&&e.parent===u.machine})),w=y&&y.doneData?Wt(y.doneData,e.context,t):void 0;this._doneEvent=Er(this.id,w);try{for(var b=vt(this.doneListeners),E=b.next();!E.done;E=b.next()){(0,E.value)(this._doneEvent)}}catch(S){c={error:S}}finally{try{E&&!E.done&&(l=b.return)&&l.call(b)}finally{if(c)throw c.error}}this._stop(),this._stopChildren(),Gr(this.sessionId)}},e.prototype.onTransition=function(e){return this.listeners.add(e),this.status===Qr.Running&&e(this.state,this.state.event),this},e.prototype.subscribe=function(e,t,r){var n=this,i=dr(e,t,r);this.listeners.add(i.next),this.status!==Qr.NotStarted&&i.next(this.state);var o=function(){n.doneListeners.delete(o),n.stopListeners.delete(o),i.complete()};return this.status===Qr.Stopped?i.complete():(this.onDone(o),this.onStop(o)),{unsubscribe:function(){n.listeners.delete(i.next),n.doneListeners.delete(o),n.stopListeners.delete(o)}}},e.prototype.onEvent=function(e){return this.eventListeners.add(e),this},e.prototype.onSend=function(e){return this.sendListeners.add(e),this},e.prototype.onChange=function(e){return this.contextListeners.add(e),this},e.prototype.onStop=function(e){return this.stopListeners.add(e),this},e.prototype.onDone=function(e){return this.status===Qr.Stopped&&this._doneEvent?e(this._doneEvent):this.doneListeners.add(e),this},e.prototype.off=function(e){return this.listeners.delete(e),this.eventListeners.delete(e),this.sendListeners.delete(e),this.stopListeners.delete(e),this.doneListeners.delete(e),this.contextListeners.delete(e),this},e.prototype.start=function(e){var t=this;if(this.status===Qr.Running)return this;this.machine._init(),Hr(this.sessionId,this),this.initialized=!0,this.status=Qr.Running;var r=void 0===e?this.initialState:xr(this,(function(){return"object"==typeof(r=e)&&null!==r&&"value"in r&&"_event"in r?t.machine.resolveState(e):t.machine.resolveState(jr.from(e,t.machine.context));var r}));return this.options.devTools&&this.attachDev(),this.scheduler.initialize((function(){t.update(r,fr)})),this},e.prototype._stopChildren=function(){this.children.forEach((function(e){tr(e.stop)&&e.stop()})),this.children.clear()},e.prototype._stop=function(){var e,t,r,n,i,o,s,a,c,l;try{for(var u=vt(this.listeners),d=u.next();!d.done;d=u.next()){var h=d.value;this.listeners.delete(h)}}catch(_){e={error:_}}finally{try{d&&!d.done&&(t=u.return)&&t.call(u)}finally{if(e)throw e.error}}try{for(var p=vt(this.stopListeners),f=p.next();!f.done;f=p.next()){(h=f.value)(),this.stopListeners.delete(h)}}catch(T){r={error:T}}finally{try{f&&!f.done&&(n=p.return)&&n.call(p)}finally{if(r)throw r.error}}try{for(var v=vt(this.contextListeners),m=v.next();!m.done;m=v.next()){h=m.value;this.contextListeners.delete(h)}}catch(x){i={error:x}}finally{try{m&&!m.done&&(o=v.return)&&o.call(v)}finally{if(i)throw i.error}}try{for(var g=vt(this.doneListeners),y=g.next();!y.done;y=g.next()){h=y.value;this.doneListeners.delete(h)}}catch(S){s={error:S}}finally{try{y&&!y.done&&(a=g.return)&&a.call(g)}finally{if(s)throw s.error}}if(!this.initialized)return this;this.initialized=!1,this.status=Qr.Stopped,this._initialState=void 0;try{for(var w=vt(Object.keys(this.delayedEventsMap)),b=w.next();!b.done;b=w.next()){var E=b.value;this.clock.clearTimeout(this.delayedEventsMap[E])}}catch(k){c={error:k}}finally{try{b&&!b.done&&(l=w.return)&&l.call(w)}finally{if(c)throw c.error}}this.scheduler.clear(),this.scheduler=new Fr({deferEvents:this.options.deferEvents})},e.prototype.stop=function(){var e=this,t=this.scheduler;return this._stop(),t.schedule((function(){var t;if(!(null===(t=e._state)||void 0===t?void 0:t.done)){var r=ar({type:"xstate.stop"}),n=xr(e,(function(){var t=Kt(gt([],mt(e.state.configuration),!1).sort((function(e,t){return t.order-e.order})).map((function(t){return gr(t.onExit,e.machine.options.actions)}))),n=mt(Tr(e.machine,e.state,e.state.context,r,[{type:"exit",actions:t}],e.machine.config.predictableActionArguments?e._exec:void 0,e.machine.config.predictableActionArguments||e.machine.config.preserveActionOrder),2),i=n[0],o=n[1],s=new jr({value:e.state.value,context:o,_event:r,_sessionid:e.sessionId,historyValue:void 0,history:e.state,actions:i.filter((function(e){return!pr(e)})),activities:{},events:[],configuration:[],transitions:[],children:{},done:e.state.done,tags:e.state.tags,machine:e.machine});return s.changed=!0,s}));e.update(n,r),e._stopChildren(),Gr(e.sessionId)}})),this},e.prototype.batch=function(e){var t=this;if(this.status===Qr.NotStarted&&this.options.deferEvents)$t||Zt(!1,"".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,'" and are deferred. Make sure .start() is called for this service.\nEvent: ').concat(JSON.stringify(event)));else if(this.status!==Qr.Running)throw new Error("".concat(e.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.'));if(e.length){var r=!!this.machine.config.predictableActionArguments&&this._exec;this.scheduler.schedule((function(){var n,i,o=t.state,s=!1,a=[],c=function(e){var n=ar(e);t.forward(n),o=xr(t,(function(){return t.machine.transition(o,n,void 0,r||void 0)})),a.push.apply(a,gt([],mt(t.machine.config.predictableActionArguments?o.actions:o.actions.map((function(e){return function(e,t){var r=e.exec;return pt(pt({},e),{exec:void 0!==r?function(){return r(t.context,t.event,{action:e,state:t,_event:t._event})}:void 0})}(e,o)}))),!1)),s=s||!!o.changed};try{for(var l=vt(e),u=l.next();!u.done;u=l.next()){c(u.value)}}catch(d){n={error:d}}finally{try{u&&!u.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}o.changed=s,o.actions=a,t.update(o,ar(e[e.length-1]))}))}},e.prototype.sender=function(e){return this.send.bind(this,e)},e.prototype._nextState=function(e,t){var r=this;void 0===t&&(t=!!this.machine.config.predictableActionArguments&&this._exec);var n=ar(e);if(0===n.name.indexOf(It)&&!this.state.nextEvents.some((function(e){return 0===e.indexOf(It)})))throw n.data.data;return xr(this,(function(){return r.machine.transition(r.state,n,void 0,t||void 0)}))},e.prototype.nextState=function(e){return this._nextState(e,!1)},e.prototype.forward=function(e){var t,r;try{for(var n=vt(this.forwardTo),i=n.next();!i.done;i=n.next()){var o=i.value,s=this.children.get(o);if(!s)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(o,"'."));s.send(e)}}catch(a){t={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}},e.prototype.defer=function(e){var t=this,r=this.clock.setTimeout((function(){"to"in e&&e.to?t.sendTo(e._event,e.to,!0):t.send(e._event)}),e.delay);e.id&&(this.delayedEventsMap[e.id]=r)},e.prototype.cancel=function(e){this.clock.clearTimeout(this.delayedEventsMap[e]),delete this.delayedEventsMap[e]},e.prototype.exec=function(e,t,r){void 0===r&&(r=this.machine.options.actions),this._exec(e,t.context,t._event,r)},e.prototype.removeChild=function(e){var t;this.children.delete(e),this.forwardTo.delete(e),null===(t=this.state)||void 0===t||delete t.children[e]},e.prototype.stopChild=function(e){var t=this.children.get(e);t&&(this.removeChild(e),tr(t.stop)&&t.stop())},e.prototype.spawn=function(e,t,r){if(this.status!==Qr.Running)return kr(e,t);if(Jt(e))return this.spawnPromise(Promise.resolve(e),t);if(tr(e))return this.spawnCallback(e,t);if(function(e){try{return"function"==typeof e.send}catch(t){return!1}}(i=e)&&"id"in i)return this.spawnActor(e,t);if(function(e){try{return"subscribe"in e&&tr(e.subscribe)}catch(t){return!1}}(e))return this.spawnObservable(e,t);if(or(e))return this.spawnMachine(e,pt(pt({},r),{id:t}));if(null!==(n=e)&&"object"==typeof n&&"transition"in n&&"function"==typeof n.transition)return this.spawnBehavior(e,t);throw new Error('Unable to spawn entity "'.concat(t,'" of type "').concat(typeof e,'".'));var n,i},e.prototype.spawnMachine=function(t,r){var n=this;void 0===r&&(r={});var i=new e(t,pt(pt({},this.options),{parent:this,id:r.id||t.id})),o=pt(pt({},Zr),r);o.sync&&i.onTransition((function(e){n.send(Nt,{state:e,id:i.id})}));var s=i;return this.children.set(i.id,s),o.autoForward&&this.forwardTo.add(i.id),i.onDone((function(e){n.removeChild(i.id),n.send(ar(e,{origin:i.id}))})).start(),s},e.prototype.spawnBehavior=function(e,t){var r=Jr(e,{id:t,parent:this});return this.children.set(t,r),r},e.prototype.spawnPromise=function(e,t){var r,n,i=this,o=!1;e.then((function(e){o||(n=e,i.removeChild(t),i.send(ar(Er(t,e),{origin:t})))}),(function(e){if(!o){i.removeChild(t);var r=_r(t,e);try{i.send(ar(r,{origin:t}))}catch(n){!function(e,t,r){if(!$t){var n=e.stack?" Stacktrace was '".concat(e.stack,"'"):"";if(e===t)console.error("Missing onError handler for invocation '".concat(r,"', error was '").concat(e,"'.").concat(n));else{var i=t.stack?" Stacktrace was '".concat(t.stack,"'"):"";console.error("Missing onError handler and/or unhandled exception/promise rejection for invocation '".concat(r,"'. ")+"Original error: '".concat(e,"'. ").concat(n," Current error is '").concat(t,"'.").concat(i))}}}(e,n,t),i.devTools&&i.devTools.send(r,i.state),i.machine.strict&&i.stop()}}}));var s=((r={id:t,send:function(){},subscribe:function(t,r,n){var i=dr(t,r,n),o=!1;return e.then((function(e){o||(i.next(e),o||i.complete())}),(function(e){o||i.error(e)})),{unsubscribe:function(){return o=!0}}},stop:function(){o=!0},toJSON:function(){return{id:t}},getSnapshot:function(){return n}})[ir]=function(){return this},r);return this.children.set(t,s),s},e.prototype.spawnCallback=function(e,t){var r,n,i,o=this,s=!1,a=new Set,c=new Set;try{i=e((function(e){n=e,c.forEach((function(t){return t(e)})),s||o.send(ar(e,{origin:t}))}),(function(e){a.add(e)}))}catch(u){this.send(_r(t,u))}if(Jt(i))return this.spawnPromise(i,t);var l=((r={id:t,send:function(e){return a.forEach((function(t){return t(e)}))},subscribe:function(e){var t=dr(e);return c.add(t.next),{unsubscribe:function(){c.delete(t.next)}}},stop:function(){s=!0,tr(i)&&i()},toJSON:function(){return{id:t}},getSnapshot:function(){return n}})[ir]=function(){return this},r);return this.children.set(t,l),l},e.prototype.spawnObservable=function(e,t){var r,n,i=this,o=e.subscribe((function(e){n=e,i.send(ar(e,{origin:t}))}),(function(e){i.removeChild(t),i.send(ar(_r(t,e),{origin:t}))}),(function(){i.removeChild(t),i.send(ar(Er(t),{origin:t}))})),s=((r={id:t,send:function(){},subscribe:function(t,r,n){return e.subscribe(t,r,n)},stop:function(){return o.unsubscribe()},getSnapshot:function(){return n},toJSON:function(){return{id:t}}})[ir]=function(){return this},r);return this.children.set(t,s),s},e.prototype.spawnActor=function(e,t){return this.children.set(t,e),e},e.prototype.spawnActivity=function(e){var t=this.machine.options&&this.machine.options.activities?this.machine.options.activities[e.type]:void 0;if(t){var r=t(this.state.context,e);this.spawnEffect(e.id,r)}else $t||Zt(!1,"No implementation found for activity '".concat(e.type,"'"))},e.prototype.spawnEffect=function(e,t){var r;this.children.set(e,((r={id:e,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},stop:t||void 0,getSnapshot:function(){},toJSON:function(){return{id:e}}})[ir]=function(){return this},r))},e.prototype.attachDev=function(){var e=Yr();if(this.options.devTools&&e){if(e.__REDUX_DEVTOOLS_EXTENSION__){var t="object"==typeof this.options.devTools?this.options.devTools:void 0;this.devTools=e.__REDUX_DEVTOOLS_EXTENSION__.connect(pt(pt({name:this.id,autoPause:!0,stateSanitizer:function(e){return{value:e.value,context:e.context,actions:e.actions}}},t),{features:pt({jump:!1,skip:!1},t?t.features:void 0)}),this.machine),this.devTools.init(this.state)}Wr(this)}},e.prototype.toJSON=function(){return{id:this.id}},e.prototype[ir]=function(){return this},e.prototype.getSnapshot=function(){return this.status===Qr.NotStarted?this.initialState:this._state},e.defaultOptions={execute:!0,deferEvents:!0,clock:{setTimeout:function(e,t){return setTimeout(e,t)},clearTimeout:function(e){return clearTimeout(e)}},logger:console.log.bind(console),devTools:!1},e.interpret=tn,e}();function tn(e,t){return new en(e,t)}function rn(e){if("string"==typeof e){var t={type:e,toString:function(){return e}};return t}return e}function nn(e){return pt(pt({type:At},e),{toJSON:function(){e.onDone,e.onError;var t=ft(e,["onDone","onError"]);return pt(pt({},t),{type:At,src:rn(e.src)})}})}var on="",sn="*",an={},cn=function(e){return"#"===e[0]},ln=function(){function e(t,r,n,i){void 0===n&&(n="context"in t?t.context:void 0);var o,s=this;this.config=t,this._context=n,this.order=-1,this.__xstatenode=!0,this.__cache={events:void 0,relativeValue:new Map,initialStateValue:void 0,initialState:void 0,on:void 0,transitions:void 0,candidates:{},delayedTransitions:void 0},this.idMap={},this.tags=[],this.options=Object.assign({actions:{},guards:{},services:{},activities:{},delays:{}},r),this.parent=null==i?void 0:i.parent,this.key=this.config.key||(null==i?void 0:i.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:"."),this.id=this.config.id||gt([this.machine.key],mt(this.path),!1).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:null!==(o=this.config.schema)&&void 0!==o?o:{},this.description=this.config.description,$t||Zt(!("parallel"in this.config),'The "parallel" property is deprecated and will be removed in version 4.1. '.concat(this.config.parallel?"Replace with `type: 'parallel'`":"Use `type: '".concat(this.type,"'`")," in the config for state node '").concat(this.id,"' instead.")),this.initial=this.config.initial,this.states=this.config.states?zt(this.config.states,(function(t,r){var n,i=new e(t,{},void 0,{parent:s,key:r});return Object.assign(s.idMap,pt(((n={})[i.id]=i,n),i.idMap)),i})):an;var a=0;!function e(t){var r,n;t.order=a++;try{for(var i=vt(Cr(t)),o=i.next();!o.done;o=i.next()){e(o.value)}}catch(s){r={error:s}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}}(this),this.history=!0===this.config.history?"shallow":this.config.history||!1,this._transient=!!this.config.always||!!this.config.on&&(Array.isArray(this.config.on)?this.config.on.some((function(e){return e.event===on})):on in this.config.on),this.strict=!!this.config.strict,this.onEntry=Yt(this.config.entry||this.config.onEntry).map((function(e){return mr(e)})),this.onExit=Yt(this.config.exit||this.config.onExit).map((function(e){return mr(e)})),this.meta=this.config.meta,this.doneData="final"===this.type?this.config.data:void 0,this.invoke=Yt(this.config.invoke).map((function(e,t){var r,n;if(or(e)){var i=hr(s.id,t);return s.machine.options.services=pt(((r={})[i]=e,r),s.machine.options.services),nn({src:i,id:i})}if(rr(e.src)){i=e.id||hr(s.id,t);return nn(pt(pt({},e),{id:i,src:e.src}))}if(or(e.src)||tr(e.src)){i=e.id||hr(s.id,t);return s.machine.options.services=pt(((n={})[i]=e.src,n),s.machine.options.services),nn(pt(pt({id:i},e),{src:i}))}var o=e.src;return nn(pt(pt({id:hr(s.id,t)},e),{src:o}))})),this.activities=Yt(this.config.activities).concat(this.invoke).map((function(e){return yr(e)})),this.transition=this.transition.bind(this),this.tags=Yt(this.config.tags)}return e.prototype._init=function(){this.__cache.transitions||Or(this).forEach((function(e){return e.on}))},e.prototype.withConfig=function(t,r){var n=this.options,i=n.actions,o=n.activities,s=n.guards,a=n.services,c=n.delays;return new e(this.config,{actions:pt(pt({},i),t.actions),activities:pt(pt({},o),t.activities),guards:pt(pt({},s),t.guards),services:pt(pt({},a),t.services),delays:pt(pt({},c),t.delays)},null!=r?r:this.context)},e.prototype.withContext=function(t){return new e(this.config,this.options,t)},Object.defineProperty(e.prototype,"context",{get:function(){return tr(this._context)?this._context():this._context},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"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:zt(this.states,(function(e){return e.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:!1,configurable:!0}),e.prototype.toJSON=function(){return this.definition},Object.defineProperty(e.prototype,"on",{get:function(){if(this.__cache.on)return this.__cache.on;var e=this.transitions;return this.__cache.on=e.reduce((function(e,t){return e[t.eventType]=e[t.eventType]||[],e[t.eventType].push(t),e}),{})},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"after",{get:function(){return this.__cache.delayedTransitions||(this.__cache.delayedTransitions=this.getDelayedTransitions(),this.__cache.delayedTransitions)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transitions",{get:function(){return this.__cache.transitions||(this.__cache.transitions=this.formatTransitions(),this.__cache.transitions)},enumerable:!1,configurable:!0}),e.prototype.getCandidates=function(e){if(this.__cache.candidates[e])return this.__cache.candidates[e];var t=e===on,r=this.transitions.filter((function(r){var n=r.eventType===e;return t?n:n||r.eventType===sn}));return this.__cache.candidates[e]=r,r},e.prototype.getDelayedTransitions=function(){var e=this,t=this.config.after;if(!t)return[];var r=function(t,r){var n=function(e,t){var r=t?"#".concat(t):"";return"".concat(lt.After,"(").concat(e,")").concat(r)}(tr(t)?"".concat(e.id,":delay[").concat(r,"]"):t,e.id);return e.onEntry.push(wr(n,{delay:t})),e.onExit.push({type:_t,sendId:n}),n};return(er(t)?t.map((function(e,t){var n=r(e.delay,t);return pt(pt({},e),{event:n})})):Kt(Object.keys(t).map((function(e,n){var i=t[e],o=rr(i)?{target:i}:i,s=isNaN(+e)?e:+e,a=r(s,n);return Yt(o).map((function(e){return pt(pt({},e),{event:a,delay:s})}))})))).map((function(t){var r=t.delay;return pt(pt({},e.formatTransition(t)),{delay:r})}))},e.prototype.getStateNodes=function(e){var t,r=this;if(!e)return[];var n=e instanceof jr?e.value:Vt(e,this.delimiter);if(rr(n)){var i=this.getStateNode(n).initial;return void 0!==i?this.getStateNodes(((t={})[n]=i,t)):[this,this.states[n]]}var o=Object.keys(n),s=[this];return s.push.apply(s,gt([],mt(Kt(o.map((function(e){return r.getStateNode(e).getStateNodes(n[e])})))),!1)),s},e.prototype.handles=function(e){var t=Mt(e);return this.events.includes(t)},e.prototype.resolveState=function(e){var t=e instanceof jr?e:jr.create(e),r=Array.from(Nr([],this.getStateNodes(t.value)));return new jr(pt(pt({},t),{value:this.resolve(t.value),configuration:r,done:$r(r,this),tags:Ur(r),machine:this.machine}))},e.prototype.transitionLeafNode=function(e,t,r){var n=this.getStateNode(e).next(t,r);return n&&n.transitions.length?n:this.next(t,r)},e.prototype.transitionCompoundNode=function(e,t,r){var n=Object.keys(e),i=this.getStateNode(n[0])._transition(e[n[0]],t,r);return i&&i.transitions.length?i:this.next(t,r)},e.prototype.transitionParallelNode=function(e,t,r){var n,i,o={};try{for(var s=vt(Object.keys(e)),a=s.next();!a.done;a=s.next()){var c=a.value,l=e[c];if(l){var u=this.getStateNode(c)._transition(l,t,r);u&&(o[c]=u)}}}catch(f){n={error:f}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}var d=Object.keys(o).map((function(e){return o[e]})),h=Kt(d.map((function(e){return e.transitions})));if(!d.some((function(e){return e.transitions.length>0})))return this.next(t,r);var p=Kt(Object.keys(o).map((function(e){return o[e].configuration})));return{transitions:h,exitSet:Kt(d.map((function(e){return e.exitSet}))),configuration:p,source:t,actions:Kt(Object.keys(o).map((function(e){return o[e].actions})))}},e.prototype._transition=function(e,t,r){return rr(e)?this.transitionLeafNode(e,t,r):1===Object.keys(e).length?this.transitionCompoundNode(e,t,r):this.transitionParallelNode(e,t,r)},e.prototype.getTransitionData=function(e,t){return this._transition(e.value,e,ar(t))},e.prototype.next=function(e,t){var r,n,i,o=this,s=t.name,a=[],c=[];try{for(var l=vt(this.getCandidates(s)),u=l.next();!u.done;u=l.next()){var d=u.value,h=d.cond,p=d.in,f=e.context,v=!p||(rr(p)&&cn(p)?e.matches(Vt(this.getStateNodeById(p).path,this.delimiter)):Ut(Vt(p,this.delimiter),Bt(this.path.slice(0,-2))(e.value))),m=!1;try{m=!h||lr(this.machine,h,f,t,e)}catch(y){throw new Error("Unable to evaluate guard '".concat(h.name||h.type,"' in transition for event '").concat(s,"' in state node '").concat(this.id,"':\n").concat(y.message))}if(m&&v){void 0!==d.target&&(c=d.target),a.push.apply(a,gt([],mt(d.actions),!1)),i=d;break}}}catch(w){r={error:w}}finally{try{u&&!u.done&&(n=l.return)&&n.call(l)}finally{if(r)throw r.error}}if(i){if(!c.length)return{transitions:[i],exitSet:[],configuration:e.value?[this]:[],source:e,actions:a};var g=Kt(c.map((function(t){return o.getRelativeStateNodes(t,e.historyValue)})));return{transitions:[i],exitSet:!!i.internal?[]:Kt(c.map((function(e){return o.getPotentiallyReenteringNodes(e)}))),configuration:g,source:e,actions:a}}},e.prototype.getPotentiallyReenteringNodes=function(e){if(this.order<e.order)return[this];for(var t=[],r=this,n=e;r&&r!==n;)t.push(r),r=r.parent;return r!==n?[]:(t.push(n),t)},e.prototype.getActions=function(e,t,r,n,i,o,s){var a,c,l,u,d=this,h=o?Nr([],this.getStateNodes(o.value)):[],p=new Set;try{for(var f=vt(Array.from(e).sort((function(e,t){return e.order-t.order}))),v=f.next();!v.done;v=f.next()){(!Dr(h,y=v.value)||Dr(r.exitSet,y)||y.parent&&p.has(y.parent))&&p.add(y)}}catch(S){a={error:S}}finally{try{v&&!v.done&&(c=f.return)&&c.call(f)}finally{if(a)throw a.error}}try{for(var m=vt(h),g=m.next();!g.done;g=m.next()){var y;Dr(e,y=g.value)&&!Dr(r.exitSet,y.parent)||r.exitSet.push(y)}}catch(k){l={error:k}}finally{try{g&&!g.done&&(u=m.return)&&u.call(m)}finally{if(l)throw l.error}}r.exitSet.sort((function(e,t){return t.order-e.order}));var w=Array.from(p).sort((function(e,t){return e.order-t.order})),b=new Set(r.exitSet),E=Kt(w.map((function(e){var t=[];if("final"!==e.type)return t;var o=e.parent;if(!o.parent)return t;t.push(br(e.id,e.doneData),br(o.id,e.doneData?Wt(e.doneData,n,i):void 0));var s=o.parent;return"parallel"===s.type&&Ir(s).every((function(e){return $r(r.configuration,e)}))&&t.push(br(s.id)),t}))),_=w.map((function(e){var t=e.onEntry,r=e.activities.map((function(e){return function(e){var t=yr(e);return{type:lt.Start,activity:t,exec:void 0}}(e)}));return{type:"entry",actions:gr(s?gt(gt([],mt(t),!1),mt(r),!1):gt(gt([],mt(r),!1),mt(t),!1),d.machine.options.actions)}})).concat({type:"state_done",actions:E.map((function(e){return function(e,t){return{type:bt,event:"function"==typeof e?e:sr(e),delay:t?t.delay:void 0,id:null==t?void 0:t.id}}(e)}))}),T=Array.from(b).map((function(e){return{type:"exit",actions:gr(gt(gt([],mt(e.onExit),!1),mt(e.activities.map((function(e){return function(e){var t=tr(e)?e:yr(e);return{type:lt.Stop,activity:t,exec:void 0}}(e)}))),!1),d.machine.options.actions)}})).concat({type:"transition",actions:gr(r.actions,this.machine.options.actions)}).concat(_);if(t){var x=gr(Kt(gt([],mt(e),!1).sort((function(e,t){return t.order-e.order})).map((function(e){return e.onExit}))),this.machine.options.actions).filter((function(e){return!pr(e)}));return T.concat({type:"stop",actions:x})}return T},e.prototype.transition=function(e,t,r,n){void 0===e&&(e=this.initialState);var i,o,s=ar(t);if(e instanceof jr)i=void 0===r?e:this.resolveState(jr.from(e,r));else{var a=rr(e)?this.resolve(Ft(this.getResolvedPath(e))):this.resolve(e),c=null!=r?r:this.machine.context;i=this.resolveState(jr.from(a,c))}if(!$t&&s.name===sn)throw new Error("An event cannot have the wildcard type ('".concat(sn,"')"));if(this.strict&&!this.events.includes(s.name)&&(o=s.name,!/^(done|error)\./.test(o)))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(s.name,"'"));var l=this._transition(i.value,i,s)||{transitions:[],configuration:[],exitSet:[],source:i,actions:[]},u=Nr([],this.getStateNodes(i.value)),d=l.configuration.length?Nr(u,l.configuration):u;return l.configuration=gt([],mt(d),!1),this.resolveTransition(l,i,i.context,n,s)},e.prototype.resolveRaisedTransition=function(e,t,r,n){var i,o=e.actions;return(e=this.transition(e,t,void 0,n))._event=r,e.event=r.data,(i=e.actions).unshift.apply(i,gt([],mt(o),!1)),e},e.prototype.resolveTransition=function(e,t,r,n,i){var o,s,a,c,l=this;void 0===i&&(i=fr);var u=e.configuration,d=!t||e.transitions.length>0,h=d?e.configuration:t?t.configuration:[],p=$r(h,this),f=d?Lr(this.machine,u):void 0,v=t?t.historyValue?t.historyValue:e.source?this.machine.historyValue(t.value):void 0:void 0,m=this.getActions(new Set(h),p,e,r,i,t,n),g=t?pt({},t.activities):{};try{for(var y=vt(m),w=y.next();!w.done;w=y.next()){var b=w.value;try{for(var E=(a=void 0,vt(b.actions)),_=E.next();!_.done;_=E.next()){var T=_.value;T.type===yt?g[T.activity.id||T.activity.type]=T:T.type===wt&&(g[T.activity.id||T.activity.type]=!1)}}catch(V){a={error:V}}finally{try{_&&!_.done&&(c=E.return)&&c.call(E)}finally{if(a)throw a.error}}}}catch(F){o={error:F}}finally{try{w&&!w.done&&(s=y.return)&&s.call(y)}finally{if(o)throw o.error}}var x,S,k=mt(Tr(this,t,r,i,m,n,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),A=k[0],C=k[1],I=mt(function(e,t){var r,n,i=mt([[],[]],2),o=i[0],s=i[1];try{for(var a=vt(e),c=a.next();!c.done;c=a.next()){var l=c.value;t(l)?o.push(l):s.push(l)}}catch(F){r={error:F}}finally{try{c&&!c.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}return[o,s]}(A,pr),2),O=I[0],N=I[1],P=A.filter((function(e){var t;return e.type===yt&&(null===(t=e.activity)||void 0===t?void 0:t.type)===At})).reduce((function(e,t){return e[t.activity.id]=function(e,t,r,n){var i,o=ur(e.src),s=null===(i=null==t?void 0:t.options.services)||void 0===i?void 0:i[o.type],a=e.data?Wt(e.data,r,n):void 0,c=s?kr(s,e.id,a):Sr(e.id);return c.meta=e,c}(t.activity,l.machine,C,i),e}),t?pt({},t.children):{}),R=new jr({value:f||t.value,context:C,_event:i,_sessionid:t?t._sessionid:null,historyValue:f?v?(x=v,S=f,{current:S,states:Qt(x,S)}):void 0:t?t.historyValue:void 0,history:!f||e.source?t:void 0,actions:f?N:[],activities:f?g:t?t.activities:{},events:[],configuration:h,transitions:e.transitions,children:P,done:p,tags:Ur(h),machine:this}),L=r!==C;R.changed=i.name===Nt||L;var D=R.history;D&&delete D.history;var $=!p&&(this._transient||u.some((function(e){return e._transient})));if(!(d||$&&i.name!==on))return R;var U=R;if(!p)for($&&(U=this.resolveRaisedTransition(U,{type:Tt},i,n));O.length;){var M=O.shift();U=this.resolveRaisedTransition(U,M._event,i,n)}var j=U.changed||(D?!!U.actions.length||L||typeof D.value!=typeof U.value||!Mr(U.value,D.value):void 0);return U.changed=j,U.history=D,U},e.prototype.getStateNode=function(e){if(cn(e))return this.machine.getStateNodeById(e);if(!this.states)throw new Error("Unable to retrieve child state '".concat(e,"' from '").concat(this.id,"'; no child states exist."));var t=this.states[e];if(!t)throw new Error("Child state '".concat(e,"' does not exist on '").concat(this.id,"'"));return t},e.prototype.getStateNodeById=function(e){var t=cn(e)?e.slice(1):e;if(t===this.id)return this;var r=this.machine.idMap[t];if(!r)throw new Error("Child state node '#".concat(t,"' does not exist on machine '").concat(this.id,"'"));return r},e.prototype.getStateNodeByPath=function(e){if("string"==typeof e&&cn(e))try{return this.getStateNodeById(e.slice(1))}catch(i){}for(var t=jt(e,this.delimiter).slice(),r=this;t.length;){var n=t.shift();if(!n.length)break;r=r.getStateNode(n)}return r},e.prototype.resolve=function(e){var t,r=this;if(!e)return this.initialStateValue||an;switch(this.type){case"parallel":return zt(this.initialStateValue,(function(t,n){return t?r.getStateNode(n).resolve(e[n]||t):an}));case"compound":if(rr(e)){var n=this.getStateNode(e);return"parallel"===n.type||"compound"===n.type?((t={})[e]=n.initialStateValue,t):e}return Object.keys(e).length?zt(e,(function(e,t){return e?r.getStateNode(t).resolve(e):an})):this.initialStateValue||{};default:return e||an}},e.prototype.getResolvedPath=function(e){if(cn(e)){var t=this.machine.idMap[e.slice(1)];if(!t)throw new Error("Unable to find state node '".concat(e,"'"));return t.path}return jt(e,this.delimiter)},Object.defineProperty(e.prototype,"initialStateValue",{get:function(){var e,t;if(this.__cache.initialStateValue)return this.__cache.initialStateValue;if("parallel"===this.type)t=qt(this.states,(function(e){return e.initialStateValue||an}),(function(e){return!("history"===e.type)}));else if(void 0!==this.initial){if(!this.states[this.initial])throw new Error("Initial state '".concat(this.initial,"' not found on '").concat(this.key,"'"));t=Ar(this.states[this.initial])?this.initial:((e={})[this.initial]=this.states[this.initial].initialStateValue,e)}else t={};return this.__cache.initialStateValue=t,this.__cache.initialStateValue},enumerable:!1,configurable:!0}),e.prototype.getInitialState=function(e,t){this._init();var r=this.getStateNodes(e);return this.resolveTransition({configuration:r,exitSet:[],transitions:[],source:void 0,actions:[]},void 0,null!=t?t:this.machine.context,void 0)},Object.defineProperty(e.prototype,"initialState",{get:function(){var e=this.initialStateValue;if(!e)throw new Error("Cannot retrieve initial state from simple state '".concat(this.id,"'."));return this.getInitialState(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"target",{get:function(){var e;if("history"===this.type){var t=this.config;e=rr(t.target)&&cn(t.target)?Ft(this.machine.getStateNodeById(t.target).path.slice(this.path.length-1)):t.target}return e},enumerable:!1,configurable:!0}),e.prototype.getRelativeStateNodes=function(e,t,r){return void 0===r&&(r=!0),r?"history"===e.type?e.resolveHistory(t):e.initialStateNodes:[e]},Object.defineProperty(e.prototype,"initialStateNodes",{get:function(){var e=this;return Ar(this)?[this]:"compound"!==this.type||this.initial?Kt(Ht(this.initialStateValue).map((function(t){return e.getFromRelativePath(t)}))):($t||Zt(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this])},enumerable:!1,configurable:!0}),e.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var t=mt(e),r=t[0],n=t.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '".concat(r,"' from node with no states"));var i=this.getStateNode(r);if("history"===i.type)return i.resolveHistory();if(!this.states[r])throw new Error("Child state '".concat(r,"' does not exist on '").concat(this.id,"'"));return this.states[r].getFromRelativePath(n)},e.prototype.historyValue=function(e){if(Object.keys(this.states).length)return{current:e||this.initialStateValue,states:qt(this.states,(function(t,r){if(!e)return t.historyValue();var n=rr(e)?void 0:e[r];return t.historyValue(n||t.initialStateValue)}),(function(e){return!e.history}))}},e.prototype.resolveHistory=function(e){var t=this;if("history"!==this.type)return[this];var r=this.parent;if(!e){var n=this.target;return n?Kt(Ht(n).map((function(e){return r.getFromRelativePath(e)}))):r.initialStateNodes}var i,o,s=(i=r.path,o="states",function(e){var t,r,n=e;try{for(var s=vt(i),a=s.next();!a.done;a=s.next()){var c=a.value;n=n[o][c]}}catch(l){t={error:l}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}return n})(e).current;return rr(s)?[r.getStateNode(s)]:Kt(Ht(s).map((function(e){return"deep"===t.history?r.getFromRelativePath(e):[r.states[e[0]]]})))},Object.defineProperty(e.prototype,"stateIds",{get:function(){var e=this,t=Kt(Object.keys(this.states).map((function(t){return e.states[t].stateIds})));return[this.id].concat(t)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"events",{get:function(){var e,t,r,n;if(this.__cache.events)return this.__cache.events;var i=this.states,o=new Set(this.ownEvents);if(i)try{for(var s=vt(Object.keys(i)),a=s.next();!a.done;a=s.next()){var c=i[a.value];if(c.states)try{for(var l=(r=void 0,vt(c.events)),u=l.next();!u.done;u=l.next()){var d=u.value;o.add("".concat(d))}}catch(h){r={error:h}}finally{try{u&&!u.done&&(n=l.return)&&n.call(l)}finally{if(r)throw r.error}}}}catch(p){e={error:p}}finally{try{a&&!a.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}return this.__cache.events=Array.from(o)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ownEvents",{get:function(){var e=new Set(this.transitions.filter((function(e){return!(!e.target&&!e.actions.length&&e.internal)})).map((function(e){return e.eventType})));return Array.from(e)},enumerable:!1,configurable:!0}),e.prototype.resolveTarget=function(e){var t=this;if(void 0!==e)return e.map((function(e){if(!rr(e))return e;var r=e[0]===t.delimiter;if(r&&!t.parent)return t.getStateNodeByPath(e.slice(1));var n=r?t.key+e:e;if(!t.parent)return t.getStateNodeByPath(n);try{return t.parent.getStateNodeByPath(n)}catch(i){throw new Error("Invalid transition definition for state node '".concat(t.id,"':\n").concat(i.message))}}))},e.prototype.formatTransition=function(e){var t=this,r=function(e){if(void 0!==e&&""!==e)return Yt(e)}(e.target),n="internal"in e?e.internal:!r||r.some((function(e){return rr(e)&&e[0]===t.delimiter})),i=this.machine.options.guards,o=this.resolveTarget(r),s=pt(pt({},e),{actions:gr(Yt(e.actions)),cond:nr(e.cond,i),target:o,source:this,internal:n,eventType:e.event,toJSON:function(){return pt(pt({},s),{target:s.target?s.target.map((function(e){return"#".concat(e.id)})):void 0,source:"#".concat(t.id)})}});return s},e.prototype.formatTransitions=function(){var e,t,r,n=this;if(this.config.on)if(Array.isArray(this.config.on))r=this.config.on;else{var i=this.config.on,o=sn,s=i[o],a=void 0===s?[]:s,c=ft(i,["*"]);r=Kt(Object.keys(c).map((function(e){$t||e!==on||Zt(!1,"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. "+'Please check the `on` configuration for "#'.concat(n.id,'".'));var t,r,i,o,s=cr(e,c[e]);return $t||(t=n,r=e,i=s.slice(0,-1).some((function(e){return!("cond"in e)&&!("in"in e)&&(rr(e.target)||or(e.target))})),o=r===on?"the transient event":"event '".concat(r,"'"),Zt(!i,"One or more transitions for ".concat(o," on state '").concat(t.id,"' are unreachable. ")+"Make sure that the default transition is the last one defined.")),s})).concat(cr(sn,a)))}else r=[];var l=this.config.always?cr("",this.config.always):[],u=this.config.onDone?cr(String(br(this.id)),this.config.onDone):[];$t||Zt(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var d=Kt(this.invoke.map((function(e){var t=[];return e.onDone&&t.push.apply(t,gt([],mt(cr(String(Er(e.id)),e.onDone)),!1)),e.onError&&t.push.apply(t,gt([],mt(cr(String(_r(e.id)),e.onError)),!1)),t}))),h=this.after,p=Kt(gt(gt(gt(gt([],mt(u),!1),mt(d),!1),mt(r),!1),mt(l),!1).map((function(e){return Yt(e).map((function(e){return n.formatTransition(e)}))})));try{for(var f=vt(h),v=f.next();!v.done;v=f.next()){var m=v.value;p.push(m)}}catch(g){e={error:g}}finally{try{v&&!v.done&&(t=f.return)&&t.call(f)}finally{if(e)throw e.error}}return p},e}(),un=!1;function dn(e,t){return $t||"predictableActionArguments"in e||un||(un=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new ln(e,t)}var hn=function(e){return{type:xt,assignment:e}},pn=wr;
|
|
973
|
-
/*! js-cookie v3.0.5 | MIT */function fn(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)e[n]=r[n]}return e}var vn=function e(t,r){function n(e,n,i){if("undefined"!=typeof document){"number"==typeof(i=fn({},r,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var s in i)i[s]&&(o+="; "+s,!0!==i[s]&&(o+="="+i[s].split(";")[0]));return document.cookie=e+"="+t.write(n,e)+o}}return Object.create({set:n,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var r=document.cookie?document.cookie.split("; "):[],n={},i=0;i<r.length;i++){var o=r[i].split("="),s=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(n[a]=t.read(s,a),e===a)break}catch(c){}}return e?n[e]:n}},remove:function(e,t){n(e,"",fn({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,fn({},this.attributes,t))},withConverter:function(t){return e(fn({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(r)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"}),mn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window||"undefined"!=typeof window?window:"undefined"!=typeof self?self:{};function gn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function yn(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})})),r}var wn,bn,En={exports:{}};wn=En.exports,bn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:mn,En.exports=function(e){var t,r=e&&e.Promise||bn.Promise,n=e&&e.XMLHttpRequest||bn.XMLHttpRequest;return t=Object.create(bn,{fetch:{value:void 0,writable:!0}}),function(e){var i=void 0!==t&&t||"undefined"!=typeof self&&self||void 0!==i&&i,o={searchParams:"URLSearchParams"in i,iterable:"Symbol"in i&&"iterator"in Symbol,blob:"FileReader"in i&&"Blob"in i&&function(){try{return new Blob,!0}catch(e){return!1}}(),formData:"FormData"in i,arrayBuffer:"ArrayBuffer"in i};function s(e){return e&&DataView.prototype.isPrototypeOf(e)}if(o.arrayBuffer)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(e){return e&&a.indexOf(Object.prototype.toString.call(e))>-1};function l(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||""===e)throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function u(e){return"string"!=typeof e&&(e=String(e)),e}function d(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return o.iterable&&(t[Symbol.iterator]=function(){return t}),t}function h(e){this.map={},e instanceof h?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function p(e){if(e.bodyUsed)return r.reject(new TypeError("Already read"));e.bodyUsed=!0}function f(e){return new r((function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}}))}function v(e){var t=new FileReader,r=f(t);return t.readAsArrayBuffer(e),r}function m(e){var t=new FileReader,r=f(t);return t.readAsText(e),r}function g(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n<t.length;n++)r[n]=String.fromCharCode(t[n]);return r.join("")}function y(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function w(){return this.bodyUsed=!1,this._initBody=function(e){this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:o.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:o.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:o.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():o.arrayBuffer&&o.blob&&s(e)?(this._bodyArrayBuffer=y(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):o.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||c(e))?this._bodyArrayBuffer=y(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):o.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o.blob&&(this.blob=function(){var e=p(this);if(e)return e;if(this._bodyBlob)return r.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return r.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return r.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?p(this)||(ArrayBuffer.isView(this._bodyArrayBuffer)?r.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):r.resolve(this._bodyArrayBuffer)):this.blob().then(v)}),this.text=function(){var e=p(this);if(e)return e;if(this._bodyBlob)return m(this._bodyBlob);if(this._bodyArrayBuffer)return r.resolve(g(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return r.resolve(this._bodyText)},o.formData&&(this.formData=function(){return this.text().then(T)}),this.json=function(){return this.text().then(JSON.parse)},this}h.prototype.append=function(e,t){e=l(e),t=u(t);var r=this.map[e];this.map[e]=r?r+", "+t:t},h.prototype.delete=function(e){delete this.map[l(e)]},h.prototype.get=function(e){return e=l(e),this.has(e)?this.map[e]:null},h.prototype.has=function(e){return this.map.hasOwnProperty(l(e))},h.prototype.set=function(e,t){this.map[l(e)]=u(t)},h.prototype.forEach=function(e,t){for(var r in this.map)this.map.hasOwnProperty(r)&&e.call(t,this.map[r],r,this)},h.prototype.keys=function(){var e=[];return this.forEach((function(t,r){e.push(r)})),d(e)},h.prototype.values=function(){var e=[];return this.forEach((function(t){e.push(t)})),d(e)},h.prototype.entries=function(){var e=[];return this.forEach((function(t,r){e.push([r,t])})),d(e)},o.iterable&&(h.prototype[Symbol.iterator]=h.prototype.entries);var b=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function E(e){var t=e.toUpperCase();return b.indexOf(t)>-1?t:e}function _(e,t){if(!(this instanceof _))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');var r=(t=t||{}).body;if(e instanceof _){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new h(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,r||null==e._bodyInit||(r=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new h(t.headers)),this.method=E(t.method||this.method||"GET"),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&r)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(r),!("GET"!==this.method&&"HEAD"!==this.method||"no-store"!==t.cache&&"no-cache"!==t.cache)){var n=/([?&])_=[^&]*/;if(n.test(this.url))this.url=this.url.replace(n,"$1_="+(new Date).getTime());else{var i=/\?/;this.url+=(i.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}}function T(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(i))}})),t}function x(e){var t=new h;return e.replace(/\r?\n[\t ]+/g," ").split("\r").map((function(e){return 0===e.indexOf("\n")?e.substr(1,e.length):e})).forEach((function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();t.append(n,i)}})),t}function S(e,t){if(!(this instanceof S))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"",this.headers=new h(t.headers),this.url=t.url||"",this._initBody(e)}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})},w.call(_.prototype),w.call(S.prototype),S.prototype.clone=function(){return new S(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new h(this.headers),url:this.url})},S.error=function(){var e=new S(null,{status:0,statusText:""});return e.type="error",e};var k=[301,302,303,307,308];S.redirect=function(e,t){if(-1===k.indexOf(t))throw new RangeError("Invalid status code");return new S(null,{status:t,headers:{location:e}})},e.DOMException=i.DOMException;try{new e.DOMException}catch(C){e.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},e.DOMException.prototype=Object.create(Error.prototype),e.DOMException.prototype.constructor=e.DOMException}function A(t,s){return new r((function(r,a){var c=new _(t,s);if(c.signal&&c.signal.aborted)return a(new e.DOMException("Aborted","AbortError"));var l=new n;function d(){l.abort()}function p(e){try{return""===e&&i.location.href?i.location.href:e}catch(t){return e}}l.onload=function(){var e={status:l.status,statusText:l.statusText,headers:x(l.getAllResponseHeaders()||"")};e.url="responseURL"in l?l.responseURL:e.headers.get("X-Request-URL");var t="response"in l?l.response:l.responseText;setTimeout((function(){r(new S(t,e))}),0)},l.onerror=function(){setTimeout((function(){a(new TypeError("Network request failed"))}),0)},l.ontimeout=function(){setTimeout((function(){a(new TypeError("Network request failed"))}),0)},l.onabort=function(){setTimeout((function(){a(new e.DOMException("Aborted","AbortError"))}),0)},l.open(c.method,p(c.url),!0),"include"===c.credentials?l.withCredentials=!0:"omit"===c.credentials&&(l.withCredentials=!1),"responseType"in l&&(o.blob?l.responseType="blob":o.arrayBuffer&&c.headers.get("Content-Type")&&-1!==c.headers.get("Content-Type").indexOf("application/octet-stream")&&(l.responseType="arraybuffer")),!s||"object"!=typeof s.headers||s.headers instanceof h?c.headers.forEach((function(e,t){l.setRequestHeader(t,e)})):Object.getOwnPropertyNames(s.headers).forEach((function(e){l.setRequestHeader(e,u(s.headers[e]))})),c.signal&&(c.signal.addEventListener("abort",d),l.onreadystatechange=function(){4===l.readyState&&c.signal.removeEventListener("abort",d)}),l.send(void 0===c._bodyInit?null:c._bodyInit)}))}A.polyfill=!0,i.fetch||(i.fetch=A,i.Headers=h,i.Request=_,i.Response=S),e.Headers=h,e.Request=_,e.Response=S,e.fetch=A,Object.defineProperty(e,"__esModule",{value:!0})}(wn),{fetch:t.fetch,Headers:t.Headers,Request:t.Request,Response:t.Response,DOMException:t.DOMException}};const _n=gn(En.exports),Tn="nhostRefreshToken",xn="nhostRefreshTokenId",Sn="nhostRefreshTokenExpiresAt",kn=10;let An=class extends Error{constructor(e){super(e.message),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:1,message:e.message}):(this.name=e.error,this.error=e)}};const Cn={status:kn,error:"invalid-email",message:"Email is incorrectly formatted"},In={status:kn,error:"invalid-password",message:"Password is incorrectly formatted"},On={status:kn,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Nn={status:kn,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},Pn={status:kn,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},Rn={status:kn,error:"no-refresh-token",message:"No refresh token has been provided"},Ln={status:20,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},Dn={status:20,error:"already-signed-in",message:"User is already signed in"},$n={status:20,error:"unauthenticated-user",message:"User is not authenticated"},Un={status:20,error:"unverified-user",message:"Email needs verification"},Mn={status:kn,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},jn={status:1,error:"invalid-sign-in-method",message:"Invalid sign-in method"},Vn={user:null,mfa:null,accessToken:{value:null,expiresAt:null,expiresInSeconds:15},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function Fn(e){return(new TextEncoder).encode(e)}function zn(e){const t=new Uint8Array(e);let r="";for(const n of t)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function qn(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=(4-t.length%4)%4,n=t.padEnd(t.length+r,"="),i=atob(n),o=new ArrayBuffer(i.length),s=new Uint8Array(o);for(let a=0;a<i.length;a++)s[a]=i.charCodeAt(a);return o}function Bn(){return void 0!==(null==window?void 0:window.PublicKeyCredential)&&"function"==typeof window.PublicKeyCredential}function Hn(e){const{id:t}=e;return{...e,id:qn(t),transports:e.transports}}function Kn(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}let Gn=class extends Error{constructor({message:e,code:t,cause:r,name:n}){super(e,{cause:r}),this.name=null!=n?n:r.name,this.code=t}};const Yn=new class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},Wn=["cross-platform","platform"];function Jn(e){if(e&&!(Wn.indexOf(e)<0))return e}async function Qn(e){var t;if(!Bn())throw new Error("WebAuthn is not supported in this browser");const r={publicKey:{...e,challenge:qn(e.challenge),user:{...e.user,id:Fn(e.user.id)},excludeCredentials:null==(t=e.excludeCredentials)?void 0:t.map(Hn)}};let n;r.signal=Yn.createNewAbortSignal();try{n=await navigator.credentials.create(r)}catch(h){throw function({error:e,options:t}){var r,n;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new Gn({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===(null==(r=i.authenticatorSelection)?void 0:r.requireResidentKey))return new Gn({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("required"===(null==(n=i.authenticatorSelection)?void 0:n.userVerification))return new Gn({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new Gn({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new Gn({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name)return 0===i.pubKeyCredParams.filter((e=>"public-key"===e.type)).length?new Gn({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new Gn({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!Kn(t))return new Gn({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(i.rp.id!==t)return new Gn({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new Gn({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new Gn({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}({error:h,options:r})}if(!n)throw new Error("Registration was not completed");const{id:i,rawId:o,response:s,type:a}=n;let c,l,u,d;if("function"==typeof s.getTransports&&(c=s.getTransports()),"function"==typeof s.getPublicKeyAlgorithm)try{l=s.getPublicKeyAlgorithm()}catch(h){Xn("getPublicKeyAlgorithm()",h)}if("function"==typeof s.getPublicKey)try{const e=s.getPublicKey();null!==e&&(u=zn(e))}catch(h){Xn("getPublicKey()",h)}if("function"==typeof s.getAuthenticatorData)try{d=zn(s.getAuthenticatorData())}catch(h){Xn("getAuthenticatorData()",h)}return{id:i,rawId:zn(o),response:{attestationObject:zn(s.attestationObject),clientDataJSON:zn(s.clientDataJSON),transports:c,publicKeyAlgorithm:l,publicKey:u,authenticatorData:d},type:a,clientExtensionResults:n.getClientExtensionResults(),authenticatorAttachment:Jn(n.authenticatorAttachment)}}function Xn(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.\n`,t)}async function Zn(e,t=!1){var r,n;if(!Bn())throw new Error("WebAuthn is not supported in this browser");let i;0!==(null==(r=e.allowCredentials)?void 0:r.length)&&(i=null==(n=e.allowCredentials)?void 0:n.map(Hn));const o={...e,challenge:qn(e.challenge),allowCredentials:i},s={};if(t){if(!(await function(){const e=window.PublicKeyCredential;return void 0===e.isConditionalMediationAvailable?new Promise((e=>e(!1))):e.isConditionalMediationAvailable()}()))throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');s.mediation="conditional",o.allowCredentials=[]}let a;s.publicKey=o,s.signal=Yn.createNewAbortSignal();try{a=await navigator.credentials.get(s)}catch(p){throw function({error:e,options:t}){const{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new Gn({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new Gn({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!Kn(t))return new Gn({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new Gn({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new Gn({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}({error:p,options:s})}if(!a)throw new Error("Authentication was not completed");const{id:c,rawId:l,response:u,type:d}=a;let h;return u.userHandle&&(h=function(e){return new TextDecoder("utf-8").decode(e)}(u.userHandle)),{id:c,rawId:zn(l),response:{authenticatorData:zn(u.authenticatorData),clientDataJSON:zn(u.clientDataJSON),signature:zn(u.signature),userHandle:h},type:d,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:Jn(a.authenticatorAttachment)}}const ei="undefined"!=typeof window,ti=new Map,ri=e=>{var t;return ei&&"undefined"!=typeof localStorage?localStorage.getItem(e):null!=(t=ti.get(e))?t:null},ni=(e,t)=>{ei&&"undefined"!=typeof localStorage?t?localStorage.setItem(e,t):localStorage.removeItem(e):t?ti.set(e,t):ti.has(e)&&ti.delete(e)},ii=e=>e&&e.accessToken.value&&e.accessToken.expiresAt&&e.user?{accessToken:e.accessToken.value,accessTokenExpiresIn:(e.accessToken.expiresAt.getTime()-Date.now())/1e3,refreshToken:e.refreshToken.value,user:e.user}:null,oi=({accessToken:e,refreshToken:t,isError:r,user:n,error:i})=>r?{session:null,error:i}:n&&e?{session:{accessToken:e,accessTokenExpiresIn:0,refreshToken:t,user:n},error:null}:{session:null,error:null},si=()=>"undefined"!=typeof window&&void 0!==window.location;let ai=globalThis.fetch;"string"!=typeof EdgeRuntime&&(ai=_n().fetch);const ci=async(e,t,r,n)=>(async(e,t,{token:r,body:n,extraHeaders:i}={})=>{const o={"Content-Type":"application/json",Accept:"*/*"};r&&(o.Authorization=`Bearer ${r}`);const s={method:t,headers:{...o,...i}};n&&(s.body=JSON.stringify(n));try{const t=await ai(e,s);if(!t.ok){const e=await t.json();return Promise.reject({error:e})}try{return{data:await t.json(),error:null}}catch{return console.warn(`Unexpected response: can't parse the response of the server at ${e}`),{data:"OK",error:null}}}catch{const e={message:"Network Error",status:0,error:"network"};return Promise.reject({error:e})}})(e,"POST",{token:r,body:t,extraHeaders:n}),li=(e,t)=>{const r=t&&Object.entries(t).map((([e,t])=>{const r=Array.isArray(t)?t.join(","):"object"==typeof t?JSON.stringify(t):t;return`${e}=${encodeURIComponent(r)}`})).join("&");return r?`${e}?${r}`:e},ui=(e,t)=>{if(null==t||!t.redirectTo)return t;const{redirectTo:r,...n}=t;if(!e)return r.startsWith("/")?n:t;const i=new URL(e),o=Object.fromEntries(new URLSearchParams(i.search)),s=new URL(r.startsWith("/")?i.origin+r:r),a=new URLSearchParams(s.search);let c=Object.fromEntries(a);r.startsWith("/")&&(c={...o,...c});let l=i.pathname;return s.pathname.length>1&&(l+=s.pathname.slice(1)),{...n,redirectTo:li(s.origin+l,c)}};function di(e,t){var r;if(!t){if("undefined"==typeof window)return;t=(null==(r=window.location)?void 0:r.href)||""}e=e.replace(/[\[\]]/g,"\\$&");const n=new RegExp("[?&#]"+e+"(=([^&#]*)|&|#|$)").exec(t);return n?n[2]?decodeURIComponent(n[2].replace(/\+/g," ")):"":null}function hi(e){var t;if("undefined"==typeof window)return;const r=null==window?void 0:window.location;if(r&&r){const n=new URLSearchParams(r.search),i=new URLSearchParams(null==(t=r.hash)?void 0:t.slice(1));n.delete(e),i.delete(e);let o=window.location.pathname;Array.from(n).length&&(o+=`?${n.toString()}`),Array.from(i).length&&(o+=`#${i.toString()}`),window.history.pushState({},"",o)}}const pi=e=>!!e&&"string"==typeof e&&!!String(e).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/),fi=e=>!!e&&"string"==typeof e&&e.length>=3,vi=e=>!!e&&"string"==typeof e,mi=({backendUrl:e,clientUrl:t,clientStorageType:r="web",clientStorage:n,refreshIntervalTime:i,autoRefreshToken:o=!0,autoSignIn:s=!0})=>{const a=((e,t)=>{if("localStorage"===e||"web"===e)return ri;if("cookie"===e)return e=>{var t;return ei&&null!=(t=vn.get(e))?t:null};if(!t)throw Error(`clientStorageType is set to '${e}' but no clientStorage has been given`);if("react-native"===e)return e=>{var r;return null==(r=t.getItem)?void 0:r.call(t,e)};if("capacitor"===e)return e=>{var r;return null==(r=t.get)?void 0:r.call(t,{key:e})};if("expo-secure-storage"===e)return e=>{var r;return null==(r=t.getItemAsync)?void 0:r.call(t,e)};if("custom"===e){if(t.getItem&&t.removeItem)return t.getItem;if(t.getItemAsync)return t.getItemAsync;throw Error('clientStorageType is set to \'custom\' but clientStorage is missing either "getItem" and "removeItem" properties or "getItemAsync" property')}throw Error(`Unknown storage type: ${e}`)})(r,n),c=((e,t)=>{if("localStorage"===e||"web"===e)return ni;if("cookie"===e)return(e,t)=>{ei&&(t?vn.set(e,t,{expires:30,sameSite:"lax",httpOnly:!1}):vn.remove(e))};if(!t)throw Error(`clientStorageType is set to '${e}' but no clienStorage has been given`);if("react-native"===e)return(e,r)=>{var n,i;return r?null==(n=t.setItem)?void 0:n.call(t,e,r):null==(i=t.removeItem)?void 0:i.call(t,e)};if("capacitor"===e)return(e,r)=>{var n,i;return r?null==(n=t.set)?void 0:n.call(t,{key:e,value:r}):null==(i=t.remove)?void 0:i.call(t,{key:e})};if("expo-secure-storage"===e)return async(e,r)=>{var n,i;return r?null==(n=t.setItemAsync)?void 0:n.call(t,e,r):null==(i=t.deleteItemAsync)?void 0:i.call(t,e)};if("custom"===e){if(!t.removeItem)throw Error("clientStorageType is set to 'custom' but clientStorage is missing a removeItem property");if(t.setItem)return(e,r)=>{var n,i;return r?null==(n=t.setItem)?void 0:n.call(t,e,r):null==(i=t.removeItem)?void 0:i.call(t,e)};if(t.setItemAsync)return async(e,r)=>{var n,i;return r?null==(n=t.setItemAsync)?void 0:n.call(t,e,r):null==(i=t.removeItem)?void 0:i.call(t,e)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${e}`)})(r,n),l=async(t,r,n,i)=>(await ci(`${e}${t}`,r,n,i)).data;return dn({schema:{context:{},events:{},services:{}},tsTypes:{},context:Vn,predictableActionArguments:!0,id:"nhost",type:"parallel",states:{authentication:{initial:"starting",on:{SESSION_UPDATE:[{cond:"hasSession",actions:["saveSession","resetTimer","reportTokenChanged"],target:".signedIn"}]},states:{starting:{tags:["loading"],always:{cond:"isSignedIn",target:"signedIn"},invoke:{id:"importRefreshToken",src:"importRefreshToken",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"signedIn"},{target:"signedOut"}],onError:[{cond:"shouldRetryImportToken",actions:"incrementTokenImportAttempts",target:"retryTokenImport"},{actions:["saveAuthenticationError"],target:"signedOut"}]}},retryTokenImport:{tags:["loading"],after:{RETRY_IMPORT_TOKEN_DELAY:"starting"}},signedOut:{initial:"noErrors",entry:"reportSignedOut",states:{noErrors:{},success:{},needsSmsOtp:{},needsMfa:{},failed:{},signingOut:{entry:["clearContextExceptTokens"],exit:["destroyAccessToken","destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_MFA_TOTP:"authenticating.mfa.totp",SIGNIN_PAT:"authenticating.pat"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},pat:{invoke:{src:"signInPAT",id:"authenticateWithPAT",onDone:{actions:["savePATSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"isRefreshTokenPAT",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{cond:"isUnauthorizedError",target:"#nhost.authentication.signedOut"},{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:pn("SIGNED_IN"),reportSignedOut:pn("SIGNED_OUT"),reportTokenChanged:pn("TOKEN_CHANGED"),incrementTokenImportAttempts:hn({importTokenAttempts:({importTokenAttempts:e})=>e+1}),clearContext:hn((()=>(c(Sn,null),c(Tn,null),c(xn,null),{...Vn}))),clearContextExceptTokens:hn((({accessToken:e,refreshToken:t})=>({...Vn,accessToken:e,refreshToken:t}))),saveSession:hn({user:(e,{data:t})=>{var r;return(null==(r=null==t?void 0:t.session)?void 0:r.user)||null},accessToken:(e,{data:t})=>{if(t.session){const{accessTokenExpiresIn:e,accessToken:r}=t.session,n=new Date(Date.now()+1e3*e);return c(Sn,n.toISOString()),{value:r,expiresAt:n,expiresInSeconds:e}}return c(Sn,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(e,{data:t})=>{var r,n;const i=(null==(r=t.session)?void 0:r.refreshToken)||null,o=(null==(n=t.session)?void 0:n.refreshTokenId)||null;return i&&c(Tn,i),o&&c(xn,o),{value:i}}}),savePATSession:hn({user:(e,{data:t})=>{var r;return(null==(r=null==t?void 0:t.session)?void 0:r.user)||null},accessToken:(e,{data:t})=>{if(t.session){const{accessTokenExpiresIn:e,accessToken:r}=t.session,n=new Date(Date.now()+1e3*e);return c(Sn,n.toISOString()),{value:r,expiresAt:n,expiresInSeconds:e}}return c(Sn,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(e,{data:t})=>{var r,n;const i=(null==(r=t.session)?void 0:r.refreshToken)||null,o=(null==(n=t.session)?void 0:n.refreshTokenId)||null;return i&&c(Tn,i),o&&c(xn,o),{value:i,isPAT:!0}}}),saveMfaTicket:hn({mfa:(e,t)=>{var r;return null==(r=t.data)?void 0:r.mfa}}),resetTimer:hn({refreshTimer:e=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:hn({refreshTimer:(e,t)=>({startedAt:e.refreshTimer.startedAt,attempts:e.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:hn({errors:({errors:e},{data:{error:t}})=>({...e,authentication:t})}),resetErrors:hn({errors:e=>({}),importTokenAttempts:e=>0}),saveRegistrationError:hn({errors:({errors:e},{data:{error:t}})=>({...e,registration:t})}),destroyRefreshToken:hn({refreshToken:e=>(c(Tn,null),c(xn,null),{value:null})}),destroyAccessToken:hn({accessToken:e=>(c(Sn,null),{value:null,expiresAt:null,expiresInSeconds:null})}),cleanUrl:()=>{s&&di("refreshToken")&&(hi("refreshToken"),hi("type"))},broadcastToken:e=>{if(s)try{new BroadcastChannel("nhost").postMessage({type:"broadcast_token",payload:{token:e.refreshToken.value}})}catch{}}},guards:{isAnonymous:(e,t)=>{var r;return!(null==(r=e.user)||!r.isAnonymous)},isSignedIn:e=>!!e.user&&!!e.accessToken.value,noToken:e=>!e.refreshToken.value,isRefreshTokenPAT:e=>{var t;return!(null==(t=e.refreshToken)||!t.isPAT)},hasRefreshToken:e=>!!e.refreshToken.value,isAutoRefreshDisabled:()=>!o,refreshTimerShouldRefresh:e=>{const{expiresAt:t}=e.accessToken;if(!t)return!1;if(e.refreshTimer.lastAttempt)return!(e.refreshTimer.attempts>5)&&Date.now()-e.refreshTimer.lastAttempt.getTime()>5e3*Math.pow(2,e.refreshTimer.attempts-1);if(t.getTime()<Date.now()||i&&Date.now()-e.refreshTimer.startedAt.getTime()>1e3*i)return!0;const r=e.accessToken.expiresInSeconds;return!!r&&t.getTime()-Date.now()-1e3*Math.min(60,.5*r)<=0},shouldRetryImportToken:(e,t)=>e.importTokenAttempts<5&&(0===t.data.error.status||t.data.error.status>=500),unverified:(e,{data:{error:t}})=>401===t.status&&("Email is not verified"===t.message||"unverified-user"===t.error),hasSession:(e,t)=>{var r;return!(null==(r=t.data)||!r.session)},hasMfaTicket:(e,t)=>{var r;return!(null==(r=t.data)||!r.mfa)},isUnauthorizedError:(e,{data:{error:t}})=>401===t.status},services:{signInPassword:(e,{email:t,password:r})=>pi(t)?fi(r)?l("/signin/email-password",{email:t,password:r}):Promise.reject({error:In}):Promise.reject({error:Cn}),signInPAT:(e,{pat:t})=>l("/signin/pat",{personalAccessToken:t}),passwordlessSms:(e,{phoneNumber:r,options:n})=>{var i;return vi(r)?null!=(i=e.user)&&i.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),l("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:r,options:ui(t,n)},e.accessToken.value)):l("/signin/passwordless/sms",{phoneNumber:r,options:ui(t,n)}):Promise.reject({error:On})},passwordlessSmsOtp:(e,{phoneNumber:t,otp:r})=>vi(t)?l("/signin/passwordless/sms/otp",{phoneNumber:t,otp:r}):Promise.reject({error:On}),passwordlessEmail:(e,{email:r,options:n})=>{var i;return pi(r)?null!=(i=e.user)&&i.isAnonymous?l("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:r,options:ui(t,n)},e.accessToken.value):l("/signin/passwordless/email",{email:r,options:ui(t,n)}):Promise.reject({error:Cn})},signInAnonymous:e=>l("/signin/anonymous"),signInMfaTotp:(e,t)=>{var r;const n=t.ticket||(null==(r=e.mfa)?void 0:r.ticket);return n?(e=>e&&"string"==typeof e&&e.match(/^mfaTotp:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i))(n)?l("/signin/mfa/totp",{ticket:n,otp:t.otp}):Promise.reject({error:Nn}):Promise.reject({error:Pn})},signInSecurityKeyEmail:async(e,{email:t})=>{if(!pi(t))throw new An(Cn);const r=await l("/signin/webauthn",{email:t});let n;try{n=await Zn(r)}catch(i){throw new An(i)}return l("/signin/webauthn/verify",{email:t,credential:n})},refreshToken:async(e,t)=>{const r="TRY_TOKEN"===t.type?t.token:e.refreshToken.value;return{session:await l("/token",{refreshToken:r}),error:null}},signout:async(e,t)=>{const r=await l("/signout",{refreshToken:e.refreshToken.value,all:!!t.all},t.all?e.accessToken.value:void 0);try{new BroadcastChannel("nhost").postMessage({type:"signout"})}catch{}return r},signUpEmailPassword:async(e,{email:r,password:n,options:i,requestOptions:o})=>{var s;return pi(r)?fi(n)?null!=(s=e.user)&&s.isAnonymous?l("/user/deanonymize",{signInMethod:"email-password",email:r,password:n,options:ui(t,i)},e.accessToken.value,null==o?void 0:o.headers):l("/signup/email-password",{email:r,password:n,options:ui(t,i)},null,null==o?void 0:o.headers):Promise.reject({error:In}):Promise.reject({error:Cn})},signUpSecurityKey:async(e,{email:t,options:r})=>{if(!pi(t))return Promise.reject({error:Cn});const n=null==r?void 0:r.nickname;n&&delete r.nickname;const i=await l("/signup/webauthn",{email:t,options:r});let o;try{o=await Qn(i)}catch(s){throw new An(s)}return l("/signup/webauthn/verify",{credential:o,options:{redirectTo:null==r?void 0:r.redirectTo,nickname:n}})},importRefreshToken:async e=>{if(e.user&&e.refreshToken.value&&e.accessToken.value&&e.accessToken.expiresAt)return{session:{accessToken:e.accessToken.value,accessTokenExpiresIn:e.accessToken.expiresAt.getTime()-Date.now(),refreshToken:e.refreshToken.value,user:e.user},error:null};let t=null;if(s){const e=di("refreshToken")||null;if(e)try{return{session:await l("/token",{refreshToken:e}),error:null}}catch(n){t=n.error}else{const e=di("error"),t=di("errorDescription");if(e&&"social user already exists"!==t)return Promise.reject({session:null,error:{status:kn,error:e,message:t||e}})}}const r=await a(Tn);if(r)try{return{session:await l("/token",{refreshToken:r}),error:null}}catch(i){t=i.error}return t?Promise.reject({error:t,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:e})=>5e3*Math.pow(2,e-1)}})};class gi{constructor({clientStorageType:e="web",autoSignIn:t=!0,autoRefreshToken:r=!0,start:n=!0,backendUrl:i,clientUrl:o,devTools:s,...a}){var c;if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=i,this.clientUrl=o,this._machine=mi({...a,backendUrl:i,clientUrl:o,clientStorageType:e,autoSignIn:t,autoRefreshToken:r}),n&&this.start({devTools:s}),"undefined"!=typeof window)try{this._channel=new BroadcastChannel("nhost"),t&&(null==(c=this._channel)||c.addEventListener("message",(e=>{var t;const{type:r,payload:n}=e.data;if("broadcast_token"===r){const e=null==(t=this.interpreter)?void 0:t.getSnapshot().context.refreshToken.value;this.interpreter&&n.token&&n.token!==e&&this.interpreter.send("TRY_TOKEN",{token:n.token})}}))),this._channel.addEventListener("message",(e=>{const{type:t}=e.data;"signout"===t&&this.interpreter&&this.interpreter.send("SIGNOUT")}))}catch{}}start({devTools:e=!1,initialSession:t,interpreter:r}={}){var n,i;const o={...this.machine.context,accessToken:{...this.machine.context.accessToken},refreshToken:{...this.machine.context.refreshToken}};t&&(o.user=t.user,o.refreshToken.value=null!=(n=t.refreshToken)?n:null,o.accessToken.value=null!=(i=t.accessToken)?i:null,o.accessToken.expiresAt=new Date(Date.now()+1e3*t.accessTokenExpiresIn));const s=this.machine.withContext(o);this._interpreter||(this._interpreter=r||tn(s,{devTools:e})),(!this._started||"undefined"==typeof window)&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach((e=>e()))),this._interpreter.start(s.initialState),this._subscriptionsQueue.forEach((e=>e(this)))),this._started=!0}get machine(){return this._machine}get interpreter(){return this._interpreter}get started(){return this._started}subscribe(e){if(this.started){const t=e(this);return this._subscriptions.add(t),t}return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}}const yi=(e,t,r)=>new Promise((n=>{const{changed:i}=e.send("PASSWORDLESS_EMAIL",{email:t,options:r});if(!i)return n({error:Dn,isError:!0,isSuccess:!1});e.onTransition((e=>{e.matches("registration.incomplete.failed")?n({error:e.context.errors.registration||null,isError:!0,isSuccess:!1}):e.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&n({error:null,isError:!1,isSuccess:!0})}))})),wi=(e,t)=>new Promise((async r=>{var n,i;const o=null==(n=e.interpreter)?void 0:n.getSnapshot(),s=null==o?void 0:o.context.accessToken.value,{data:a}=await ci(`${e.backendUrl}/elevate/webauthn`,{email:t},s);let c;try{c=await Zn(a)}catch(l){throw new An(l)}try{const{data:{session:n},error:o}=await ci(`${e.backendUrl}/elevate/webauthn/verify`,{email:t,credential:c},s);n&&!o&&(null==(i=e.interpreter)||i.send({type:"SESSION_UPDATE",data:{session:n}}),r({error:null,isError:!1,isSuccess:!0,elevated:!0}))}catch(l){const{error:e}=l;r({error:e,isError:!0,isSuccess:!1,elevated:!1})}})),bi=(e,t,r)=>new Promise((n=>{const{changed:i}=e.send("PASSWORDLESS_SMS",{phoneNumber:t,options:r});if(!i)return n({error:Dn,isError:!0,isSuccess:!1,needsOtp:!1});e.onTransition((e=>{e.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):e.matches("registration.incomplete.failed")&&n({error:e.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})}))})),Ei=(e,t,r,n,i)=>new Promise((o=>{const{changed:s,context:a}=e.send("SIGNUP_EMAIL_PASSWORD",{email:t,password:r,options:n,requestOptions:i});if(!s)return o({error:Dn,accessToken:a.accessToken.value,refreshToken:a.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:a.user});e.onTransition((e=>{e.matches("registration.incomplete.failed")?o({accessToken:null,refreshToken:null,error:e.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):e.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?o({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):e.matches({authentication:"signedIn",registration:"complete"})&&o({accessToken:e.context.accessToken.value,refreshToken:e.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:e.context.user})}))}));class _i{constructor({url:e,autoRefreshToken:t=!0,autoSignIn:r=!0,clientStorage:n,clientStorageType:i,refreshIntervalTime:o,start:s=!0}){var a;this.url=e,this._client=new gi({backendUrl:e,clientUrl:"undefined"!=typeof window&&(null==(a=window.location)?void 0:a.origin)||"",autoRefreshToken:t,autoSignIn:r,start:s,clientStorage:n,clientStorageType:i,refreshIntervalTime:o})}async signUp(e){const t=await this.waitUntilReady(),{email:r,options:n}=e;return oi("securityKey"in e?await((e,t,r)=>new Promise((n=>{const{changed:i,context:o}=e.send("SIGNUP_SECURITY_KEY",{email:t,options:r});if(!i)return n({error:Dn,accessToken:o.accessToken.value,refreshToken:o.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});e.onTransition((e=>{e.matches("registration.incomplete.failed")?n({accessToken:null,refreshToken:null,error:e.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):e.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):e.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:e.context.accessToken.value,refreshToken:e.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:e.context.user})}))})))(t,r,n):await Ei(t,r,e.password,n))}async connectProvider(e){const t=(await this.waitUntilReady()).getSnapshot().context.accessToken.value,{provider:r,options:n}=e,i=li(`${this._client.backendUrl}/signin/provider/${r}`,ui(this._client.clientUrl,{...n,connect:t}));return si()&&(window.location.href=i),{providerUrl:i}}async signIn(e){const t=await this.waitUntilReady();if(!e){const e=await(r=t,new Promise((e=>{const{changed:t}=r.send("SIGNIN_ANONYMOUS");t||e({isSuccess:!1,isError:!0,error:Dn,user:null,accessToken:null,refreshToken:null}),r.onTransition((t=>{t.matches({authentication:"signedIn"})&&e({isSuccess:!0,isError:!1,error:null,user:t.context.user,accessToken:t.context.accessToken.value,refreshToken:t.context.refreshToken.value}),t.matches({authentication:{signedOut:"failed"}})&&e({isSuccess:!1,isError:!0,error:t.context.errors.authentication||null,user:null,accessToken:null,refreshToken:null})}))})));return{...oi(e),mfa:null}}var r;if("provider"in e){const{provider:t,options:r}=e,n=li(`${this._client.backendUrl}/signin/provider/${t}`,ui(this._client.clientUrl,r));return si()&&(window.location.href=n),{providerUrl:n,provider:t,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const r=await((e,t,r)=>new Promise((n=>{const{changed:i,context:o}=e.send("SIGNIN_PASSWORD",{email:t,password:r});if(!i)return n({accessToken:o.accessToken.value,refreshToken:o.refreshToken.value,error:Dn,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.user});e.onTransition((e=>{e.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):e.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:e.context.mfa,user:null}):e.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,refreshToken:null,error:e.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):e.matches({authentication:"signedIn"})&&n({accessToken:e.context.accessToken.value,refreshToken:e.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:e.context.user})}))})))(t,e.email,e.password);return r.needsEmailVerification?{session:null,mfa:null,error:Un}:r.needsMfaOtp?{session:null,mfa:r.mfa,error:null}:{...oi(r),mfa:null}}if("email"in e&&"securityKey"in e){if(!0!==e.securityKey)throw Error("securityKey must be true");const r=await((e,t)=>new Promise((r=>{const{changed:n,context:i}=e.send({type:"SIGNIN_SECURITY_KEY_EMAIL",email:t});if(!n)return r({accessToken:i.accessToken.value,refreshToken:i.refreshToken.value,error:Dn,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});e.onTransition((e=>{e.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):e.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,refreshToken:null,error:e.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):e.matches({authentication:"signedIn"})&&r({accessToken:e.context.accessToken.value,refreshToken:e.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:e.context.user})}))})))(t,e.email);return{...oi(r),mfa:null}}if("email"in e){const{email:r,options:n}=e,{error:i}=await yi(t,r,n);return{session:null,mfa:null,error:i}}if("phoneNumber"in e&&"otp"in e){const r=await((e,t,r)=>new Promise((n=>{const{changed:i}=e.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:t,otp:r});if(!i)return n({error:Dn,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null});e.onTransition((e=>{e.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:e.context.user,accessToken:e.context.accessToken.value,refreshToken:e.context.refreshToken.value}):e.matches({registration:{incomplete:"failed"}})&&n({error:e.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null})}))})))(t,e.phoneNumber,e.otp);return{...oi(r),mfa:null}}if("phoneNumber"in e){const{error:r}=await bi(t,e.phoneNumber,e.options);return{error:r,mfa:null,session:null}}if("otp"in e){const r=await((e,t,r)=>new Promise((n=>{const{changed:i,context:o}=e.send("SIGNIN_MFA_TOTP",{otp:t,ticket:r});if(!i)return n({accessToken:o.accessToken.value,refreshToken:o.refreshToken.value,error:Dn,isError:!0,isSuccess:!1,user:o.user});e.onTransition((e=>{e.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,refreshToken:null,error:e.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):e.matches({authentication:"signedIn"})&&n({accessToken:e.context.accessToken.value,refreshToken:e.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,user:e.context.user})}))})))(t,e.otp,e.ticket);return{...oi(r),mfa:null}}return{error:jn,mfa:null,session:null}}async signInPAT(e){const t=await this.waitUntilReady(),r=await((e,t)=>new Promise((r=>{const{changed:n}=e.send("SIGNIN_PAT",{pat:t});n||r({isSuccess:!1,isError:!0,error:Dn,user:null,accessToken:null,refreshToken:null}),e.onTransition((e=>e.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,refreshToken:null,user:null,error:e.context.errors.authentication||null,isError:!0,isSuccess:!1}):e.matches({authentication:"signedIn"})?r({accessToken:e.context.accessToken.value,refreshToken:e.context.refreshToken.value,user:e.context.user,error:null,isError:!1,isSuccess:!0}):void 0))})))(t,e);return oi(r)}async signOut(e){const t=await this.waitUntilReady(),{error:r}=await(async(e,t)=>new Promise((r=>{const{event:n}=e.send("SIGNOUT",{all:t});if("SIGNED_OUT"!==n.type)return r({isSuccess:!1,isError:!0,error:$n});e.onTransition((e=>{e.matches({authentication:{signedOut:"success"}})?r({isSuccess:!0,isError:!1,error:null}):e.matches("authentication.signedOut.failed")&&r({isSuccess:!1,isError:!0,error:e.context.errors.signout||null})}))})))(t,null==e?void 0:e.all);return{error:r}}async resetPassword({email:e,options:t}){const r=tn((({backendUrl:e,clientUrl:t})=>dn({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:hn({error:e=>Cn}),saveRequestError:hn({error:(e,{data:{error:t}})=>t}),reportError:pn((e=>({type:"ERROR",error:e.error}))),reportSuccess:pn("SUCCESS")},guards:{invalidEmail:(e,{email:t})=>!pi(t)},services:{requestChange:(r,{email:n,options:i})=>ci(`${e}/user/password/reset`,{email:n,options:ui(t,i)})}}))(this._client)).start(),{error:n}=await(async(e,t,r)=>new Promise((n=>{e.send("REQUEST",{email:t,options:r}),e.onTransition((e=>{e.matches({idle:"error"})?n({error:e.context.error,isError:!0,isSent:!1}):e.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})}))})))(r,e,t);return{error:n}}async changePassword({newPassword:e,ticket:t}){const r=tn((({backendUrl:e,interpreter:t})=>dn({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidPassword",actions:"saveInvalidPasswordError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidPasswordError:hn({error:e=>In}),saveRequestError:hn({error:(e,{data:{error:t}})=>t}),reportError:pn((e=>({type:"ERROR",error:e.error}))),reportSuccess:pn("SUCCESS")},guards:{invalidPassword:(e,{password:t})=>!fi(t)},services:{requestChange:(r,{password:n,ticket:i})=>ci(`${e}/user/password`,{newPassword:n,ticket:i},null==t?void 0:t.getSnapshot().context.accessToken.value)}}))(this._client)).start(),{error:n}=await(async(e,t,r)=>new Promise((n=>{e.send("REQUEST",{password:t,ticket:r}),e.onTransition((e=>{e.matches({idle:"error"})?n({error:e.context.error,isError:!0,isSuccess:!1}):e.matches({idle:"success"})&&n({error:null,isError:!1,isSuccess:!0})}))})))(r,e,t);return{error:n}}async sendVerificationEmail({email:e,options:t}){const r=tn((({backendUrl:e,clientUrl:t})=>dn({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"sendVerificationEmail",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"request",id:"request",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:hn({error:e=>Cn}),saveRequestError:hn({error:(e,{data:{error:t}})=>t}),reportError:pn((e=>({type:"ERROR",error:e.error}))),reportSuccess:pn("SUCCESS")},guards:{invalidEmail:(e,{email:t})=>!pi(t)},services:{request:async(r,{email:n,options:i})=>(await ci(`${e}/user/email/send-verification-email`,{email:n,options:ui(t,i)})).data}}))(this._client)).start(),{error:n}=await((e,t,r)=>new Promise((n=>{e.send("REQUEST",{email:t,options:r}),e.onTransition((e=>{e.matches({idle:"error"})?n({error:e.context.error,isError:!0,isSent:!1}):e.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})}))})))(r,e,t);return{error:n}}async changeEmail({newEmail:e,options:t}){const r=tn((({backendUrl:e,clientUrl:t,interpreter:r})=>dn({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changeEmail",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:hn({error:e=>Cn}),saveRequestError:hn({error:(e,{data:{error:t}})=>t}),reportError:pn((e=>({type:"ERROR",error:e.error}))),reportSuccess:pn("SUCCESS")},guards:{invalidEmail:(e,{email:t})=>!pi(t)},services:{requestChange:async(n,{email:i,options:o})=>(await ci(`${e}/user/email/change`,{newEmail:i,options:ui(t,o)},null==r?void 0:r.getSnapshot().context.accessToken.value)).data}}))(this._client)).start(),{error:n}=await(async(e,t,r)=>new Promise((n=>{e.send("REQUEST",{email:t,options:r}),e.onTransition((e=>{e.matches({idle:"error"})?n({error:e.context.error,isError:!0,needsEmailVerification:!1}):e.matches({idle:"success"})&&n({error:null,isError:!1,needsEmailVerification:!0})}))})))(r,e,t);return{error:n}}async deanonymize(e){const t=await this.waitUntilReady();if("passwordless"===e.signInMethod){if("email"===e.connection){const{error:r}=await yi(t,e.email,e.options);return{error:r}}if("sms"===e.connection){const{error:r}=await bi(t,e.phoneNumber,e.options);return{error:r}}}if("email-password"===e.signInMethod){const{error:r}=await Ei(t,e.email,e.password,e.options);return{error:r}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:t,key:r}=await(async({backendUrl:e,interpreter:t},n)=>{try{const{data:r}=await ci(`${e}/user/webauthn/add`,{},null==t?void 0:t.getSnapshot().context.accessToken.value);let o;try{o=await Qn(r)}catch(i){throw new An(i)}const{data:s}=await ci(`${e}/user/webauthn/verify`,{credential:o,nickname:n},null==t?void 0:t.getSnapshot().context.accessToken.value);return{key:s,isError:!1,error:null,isSuccess:!0}}catch(r){const{error:t}=r;return{isError:!0,error:t,isSuccess:!1}}})(this._client,e);return{error:t,key:r}}async elevateEmailSecurityKey(e){if(!e)throw Error("A user email is required");return{...await wi(this._client,e),mfa:null}}async createPAT(e,t){return(async({backendUrl:e,interpreter:t},{expiresAt:r,metadata:n})=>{try{const{data:i}=await ci(`${e}/pat`,{expiresAt:r.toISOString(),metadata:n},null==t?void 0:t.getSnapshot().context.accessToken.value);return{data:i?{id:i.id||null,personalAccessToken:i.personalAccessToken||null}:null,isError:!1,error:null,isSuccess:!0}}catch(i){const{error:e}=i;return{isError:!0,error:e,isSuccess:!1,data:null}}})(this._client,{expiresAt:e,metadata:t})}onTokenChanged(e){return this._client.subscribe((()=>{var t;const r=null==(t=this._client.interpreter)?void 0:t.onTransition((({event:t,context:r})=>{"TOKEN_CHANGED"===t.type&&e(ii(r))}));return()=>null==r?void 0:r.stop()}))}onAuthStateChanged(e){return this._client.subscribe((()=>{var t;const r=null==(t=this._client.interpreter)?void 0:t.onTransition((({event:t,context:r})=>{("SIGNED_IN"===t.type||"SIGNED_OUT"===t.type)&&e(t.type,ii(r))}));return()=>null==r?void 0:r.stop()}))}isAuthenticated(){var e;return!(null==(e=this._client.interpreter)||!e.getSnapshot().matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).getSnapshot().matches({authentication:"signedIn"})}getAuthenticationStatus(){var e;const t=(null==(e=this.client.interpreter)?void 0:e.getSnapshot().context.importTokenAttempts)||0;return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1,connectionAttempts:t}:{isAuthenticated:!1,isLoading:!0,connectionAttempts:t}}getAccessToken(){var e,t;return null!=(t=null==(e=this._client.interpreter)?void 0:e.getSnapshot().context.accessToken.value)?t:void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?ct(e):null}getHasuraClaims(){var e;return(null==(e=this.getDecodedAccessToken())?void 0:e["https://hasura.io/jwt/claims"])||null}getHasuraClaim(e){var t;return(null==(t=this.getHasuraClaims())?void 0:t[e.startsWith("x-hasura-")?e:`x-hasura-${e}`])||null}async refreshSession(e){try{const t=await this.waitUntilReady();return new Promise((r=>{const n=e||t.getSnapshot().context.refreshToken.value;if(!n)return r({session:null,error:Rn});const{changed:i}=t.send("TRY_TOKEN",{token:n});if(!i)return r({session:null,error:Ln});t.onTransition((e=>{e.matches({token:{idle:"error"}})?r({session:null,error:Mn}):"TOKEN_CHANGED"===e.event.type&&r({session:ii(e.context),error:null})}))}))}catch(t){return{session:null,error:t.message}}}getSession(){var e,t;return ii(null==(t=null==(e=this._client.interpreter)?void 0:e.getSnapshot())?void 0:t.context)}getUser(){var e,t,r;return(null==(r=null==(t=null==(e=this._client.interpreter)?void 0:e.getSnapshot())?void 0:t.context)?void 0:r.user)||null}waitUntilReady(){const e=this._client.interpreter;if(!e)throw Error("Auth interpreter not set");return e.getSnapshot().hasTag("loading")?new Promise(((t,r)=>{let n=setTimeout((()=>r("The state machine is not yet ready after 15 seconds.")),15e3);e.onTransition((r=>{if(!r.hasTag("loading"))return clearTimeout(n),t(e)}))})):Promise.resolve(e)}isReady(){var e,t;return!(null!=(t=null==(e=this._client.interpreter)?void 0:e.getSnapshot())&&t.hasTag("loading"))}get client(){return this._client}}const Ti=gn("object"==typeof self?self.FormData:window.FormData);let xi=globalThis.fetch;const Si=async(e,t,{accessToken:r,name:n,fileId:i,bucketId:o,adminSecret:s,onUploadProgress:a,headers:c={}}={})=>{var l;const u={...c};o&&t.append("bucket-id",o),s&&(u["x-hasura-admin-secret"]=s),r&&(u.Authorization=`Bearer ${r}`);const d=`${e}/files`;if("undefined"==typeof XMLHttpRequest)try{t instanceof Ti&&(xi=_n().fetch);const e=await xi(d,{method:"POST",headers:u,body:t}),r=await e.json();return e.ok?{fileMetadata:r,error:null}:{error:{status:e.status,message:(null==(l=null==r?void 0:r.error)?void 0:l.message)||e.statusText,error:e.statusText},fileMetadata:null}}catch(h){return{error:{status:0,message:h.message,error:h.message},fileMetadata:null}}return new Promise((e=>{let r=new XMLHttpRequest;r.responseType="json",r.onload=()=>{var t,n,i,o,s;return r.status<200||r.status>=300?e({fileMetadata:null,error:{error:null!=(n=null==(t=r.response)?void 0:t.error)?n:r.response,message:null!=(s=null==(o=null==(i=r.response)?void 0:i.error)?void 0:o.message)?s:r.response,status:r.status}}):e({fileMetadata:r.response,error:null})},r.onerror=()=>e({fileMetadata:null,error:{error:r.statusText,message:r.statusText,status:r.status}}),a&&r.upload.addEventListener("progress",a,!1),r.open("POST",d,!0),Object.entries(u).forEach((([e,t])=>{r.setRequestHeader(e,t)})),r.send(t)}))};function ki(e,t){if(!t||0===Object.keys(t).length)return e;const r=new URL(e),n=Object.entries(t).reduce(((e,[t,r])=>({...e,[t.charAt(0)]:r})),{});return Object.entries(n).forEach((([e,t])=>{t&&r.searchParams.set(e,t)})),r.toString()}let Ai;void 0===Ai&&(Ai=_n().fetch);class Ci{constructor({url:e}){this.headers={},this.url=e}async uploadFormData({formData:e,bucketId:t,headers:r}){const{error:n,fileMetadata:i}=await Si(this.url,e,{bucketId:t,headers:{...this.headers,...r},accessToken:this.accessToken,adminSecret:this.adminSecret});return n?{fileMetadata:null,error:n}:i&&!("processedFiles"in i)?{fileMetadata:{processedFiles:[i]},error:null}:{fileMetadata:i,error:null}}async uploadFile({file:e,bucketId:t,id:r,name:n,headers:i}){const o="undefined"==typeof window?new Ti:new FormData;o.append("file[]",e),o.append("metadata[]",JSON.stringify({id:r,name:n}));const{error:s,fileMetadata:a}=await Si(this.url,o,{accessToken:this.accessToken,adminSecret:this.adminSecret,bucketId:t,fileId:r,name:n,headers:{...this.headers,...i}});return s?{fileMetadata:null,error:s}:a&&"processedFiles"in a?{fileMetadata:a.processedFiles[0],error:null}:{fileMetadata:a,error:null}}async downloadFile(e){try{const{fileId:t,headers:r,...n}=e,i=ki(`${this.url}/files/${t}`,n),o=await Ai(i,{method:"GET",headers:{...this.generateAuthHeaders(),...this.headers,...r}});if(!o.ok)throw new Error(await o.text());return{file:await o.blob(),error:null}}catch(t){return{file:null,error:t}}}async getPresignedUrl(e){try{const{fileId:t,headers:r}=e,n=await Ai(`${this.url}/files/${t}/presignedurl`,{method:"GET",headers:{...this.generateAuthHeaders(),...this.headers,...r}});if(!n.ok)throw new Error(await n.text());return{presignedUrl:await n.json(),error:null}}catch(t){return{presignedUrl:null,error:t}}}async delete(e){try{const{fileId:t,headers:r}=e,n=await Ai(`${this.url}/files/${t}`,{method:"DELETE",headers:{...this.generateAuthHeaders(),...this.headers,...r}});if(!n.ok)throw new Error(await n.text());return{error:null}}catch(t){return{error:t}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}getHeaders(){return this.headers}setHeaders(e){return e?(this.headers={...this.headers,...e},this):this}unsetHeaders(){const e=this.headers["x-hasura-role"];return this.headers=e?{"x-hasura-role":e}:{},this}generateAuthHeaders(){if(this.adminSecret||this.accessToken)return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}}class Ii{constructor({url:e,adminSecret:t}){this.url=e,this.api=new Ci({url:e}),this.setAdminSecret(t)}async upload(e){return"file"in e?this.api.uploadFile(e):this.api.uploadFormData(e)}getPublicUrl(e){const{fileId:t,...r}=e;return ki(`${this.url}/files/${t}`,r)}async getPresignedUrl(e){const{fileId:t,headers:r,...n}=e,{presignedUrl:i,error:o}=await this.api.getPresignedUrl(e);if(o)return{presignedUrl:null,error:o};if(!i)return{presignedUrl:null,error:new Error("Invalid file id")};const s=ki(i.url,n);return{presignedUrl:{...i,url:s},error:null}}async download(e){const{file:t,error:r}=await this.api.downloadFile(e);return r?{file:null,error:r}:t?{file:t,error:null}:{file:null,error:new Error("File does not exist")}}async delete(e){const{error:t}=await this.api.delete(e);return t?{error:t}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}getHeaders(){return this.getHeaders()}setHeaders(e){return this.api.setHeaders(e),this}unsetHeaders(){return this.api.unsetHeaders(),this}}const Oi=Object.freeze(Object.defineProperty({__proto__:null,default:function(e,t){return t=t||{},new Promise((function(r,n){var i=new XMLHttpRequest,o=[],s=[],a={},c=function(){return{ok:2==(i.status/100|0),statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:c,headers:{keys:function(){return o},entries:function(){return s},get:function(e){return a[e.toLowerCase()]},has:function(e){return e.toLowerCase()in a}}}};for(var l in i.open(t.method||"get",e,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(e,t,r){o.push(t=t.toLowerCase()),s.push([t,r]),a[t]=a[t]?a[t]+","+r:r})),r(c())},i.onerror=n,i.withCredentials="include"==t.credentials,t.headers)i.setRequestHeader(l,t.headers[l]);i.send(t.body||null)}))}},Symbol.toStringTag,{value:"Module"})),Ni=yn(Oi);const Pi=gn(self.fetch||(self.fetch=Ni.default||Ni));function Ri(e,t){if(!Boolean(e))throw new Error(t)}function Li(e,t){if(!Boolean(e))throw new Error("Unexpected invariant triggered.")}const Di=/\r\n|[\n\r]/g;function $i(e,t){let r=0,n=1;for(const i of e.body.matchAll(Di)){if("number"==typeof i.index||Li(!1),i.index>=t)break;r=i.index+i[0].length,n+=1}return{line:n,column:t+1-r}}function Ui(e,t){const r=e.locationOffset.column-1,n="".padStart(r)+e.body,i=t.line-1,o=e.locationOffset.line-1,s=t.line+o,a=1===t.line?r:0,c=t.column+a,l=`${e.name}:${s}:${c}\n`,u=n.split(/\r\n|[\n\r]/g),d=u[i];if(d.length>120){const e=Math.floor(c/80),t=c%80,r=[];for(let n=0;n<d.length;n+=80)r.push(d.slice(n,n+80));return l+Mi([[`${s} |`,r[0]],...r.slice(1,e+1).map((e=>["|",e])),["|","^".padStart(t)],["|",r[e+1]]])}return l+Mi([[s-1+" |",u[i-1]],[`${s} |`,d],["|","^".padStart(c)],[`${s+1} |`,u[i+1]]])}function Mi(e){const t=e.filter((([e,t])=>void 0!==t)),r=Math.max(...t.map((([e])=>e.length)));return t.map((([e,t])=>e.padStart(r)+(t?" "+t:""))).join("\n")}class ji extends Error{constructor(e,...t){var r,n,i;const{nodes:o,source:s,positions:a,path:c,originalError:l,extensions:u}=function(e){const t=e[0];return null==t||"kind"in t||"length"in t?{nodes:t,source:e[1],positions:e[2],path:e[3],originalError:e[4],extensions:e[5]}:t}(t);super(e),this.name="GraphQLError",this.path=null!=c?c:void 0,this.originalError=null!=l?l:void 0,this.nodes=Vi(Array.isArray(o)?o:o?[o]:void 0);const d=Vi(null===(r=this.nodes)||void 0===r?void 0:r.map((e=>e.loc)).filter((e=>null!=e)));this.source=null!=s?s:null==d||null===(n=d[0])||void 0===n?void 0:n.source,this.positions=null!=a?a:null==d?void 0:d.map((e=>e.start)),this.locations=a&&s?a.map((e=>$i(s,e))):null==d?void 0:d.map((e=>$i(e.source,e.start)));const h="object"==typeof(p=null==l?void 0:l.extensions)&&null!==p?null==l?void 0:l.extensions:void 0;var p;this.extensions=null!==(i=null!=u?u:h)&&void 0!==i?i:Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),null!=l&&l.stack?Object.defineProperty(this,"stack",{value:l.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,ji):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}get[Symbol.toStringTag](){return"GraphQLError"}toString(){let e=this.message;if(this.nodes)for(const r of this.nodes)r.loc&&(e+="\n\n"+Ui((t=r.loc).source,$i(t.source,t.start)));else if(this.source&&this.locations)for(const r of this.locations)e+="\n\n"+Ui(this.source,r);var t;return e}toJSON(){const e={message:this.message};return null!=this.locations&&(e.locations=this.locations),null!=this.path&&(e.path=this.path),null!=this.extensions&&Object.keys(this.extensions).length>0&&(e.extensions=this.extensions),e}}function Vi(e){return void 0===e||0===e.length?void 0:e}function Fi(e,t,r){return new ji(`Syntax Error: ${r}`,{source:e,positions:[t]})}class zi{constructor(e,t,r){this.start=e.start,this.end=t.end,this.startToken=e,this.endToken=t,this.source=r}get[Symbol.toStringTag](){return"Location"}toJSON(){return{start:this.start,end:this.end}}}class qi{constructor(e,t,r,n,i,o){this.kind=e,this.start=t,this.end=r,this.line=n,this.column=i,this.value=o,this.prev=null,this.next=null}get[Symbol.toStringTag](){return"Token"}toJSON(){return{kind:this.kind,value:this.value,line:this.line,column:this.column}}}const Bi={Name:[],Document:["definitions"],OperationDefinition:["name","variableDefinitions","directives","selectionSet"],VariableDefinition:["variable","type","defaultValue","directives"],Variable:["name"],SelectionSet:["selections"],Field:["alias","name","arguments","directives","selectionSet"],Argument:["name","value"],FragmentSpread:["name","directives"],InlineFragment:["typeCondition","directives","selectionSet"],FragmentDefinition:["name","variableDefinitions","typeCondition","directives","selectionSet"],IntValue:[],FloatValue:[],StringValue:[],BooleanValue:[],NullValue:[],EnumValue:[],ListValue:["values"],ObjectValue:["fields"],ObjectField:["name","value"],Directive:["name","arguments"],NamedType:["name"],ListType:["type"],NonNullType:["type"],SchemaDefinition:["description","directives","operationTypes"],OperationTypeDefinition:["type"],ScalarTypeDefinition:["description","name","directives"],ObjectTypeDefinition:["description","name","interfaces","directives","fields"],FieldDefinition:["description","name","arguments","type","directives"],InputValueDefinition:["description","name","type","defaultValue","directives"],InterfaceTypeDefinition:["description","name","interfaces","directives","fields"],UnionTypeDefinition:["description","name","directives","types"],EnumTypeDefinition:["description","name","directives","values"],EnumValueDefinition:["description","name","directives"],InputObjectTypeDefinition:["description","name","directives","fields"],DirectiveDefinition:["description","name","arguments","locations"],SchemaExtension:["directives","operationTypes"],ScalarTypeExtension:["name","directives"],ObjectTypeExtension:["name","interfaces","directives","fields"],InterfaceTypeExtension:["name","interfaces","directives","fields"],UnionTypeExtension:["name","directives","types"],EnumTypeExtension:["name","directives","values"],InputObjectTypeExtension:["name","directives","fields"]},Hi=new Set(Object.keys(Bi));function Ki(e){const t=null==e?void 0:e.kind;return"string"==typeof t&&Hi.has(t)}var Gi,Yi,Wi,Ji,Qi,Xi,Zi,eo;function to(e){return 9===e||32===e}function ro(e){return e>=48&&e<=57}function no(e){return e>=97&&e<=122||e>=65&&e<=90}function io(e){return no(e)||95===e}function oo(e){return no(e)||ro(e)||95===e}function so(e){var t;let r=Number.MAX_SAFE_INTEGER,n=null,i=-1;for(let s=0;s<e.length;++s){var o;const t=e[s],a=ao(t);a!==t.length&&(n=null!==(o=n)&&void 0!==o?o:s,i=s,0!==s&&a<r&&(r=a))}return e.map(((e,t)=>0===t?e:e.slice(r))).slice(null!==(t=n)&&void 0!==t?t:0,i+1)}function ao(e){let t=0;for(;t<e.length&&to(e.charCodeAt(t));)++t;return t}(Yi=Gi||(Gi={})).QUERY="query",Yi.MUTATION="mutation",Yi.SUBSCRIPTION="subscription",(Ji=Wi||(Wi={})).QUERY="QUERY",Ji.MUTATION="MUTATION",Ji.SUBSCRIPTION="SUBSCRIPTION",Ji.FIELD="FIELD",Ji.FRAGMENT_DEFINITION="FRAGMENT_DEFINITION",Ji.FRAGMENT_SPREAD="FRAGMENT_SPREAD",Ji.INLINE_FRAGMENT="INLINE_FRAGMENT",Ji.VARIABLE_DEFINITION="VARIABLE_DEFINITION",Ji.SCHEMA="SCHEMA",Ji.SCALAR="SCALAR",Ji.OBJECT="OBJECT",Ji.FIELD_DEFINITION="FIELD_DEFINITION",Ji.ARGUMENT_DEFINITION="ARGUMENT_DEFINITION",Ji.INTERFACE="INTERFACE",Ji.UNION="UNION",Ji.ENUM="ENUM",Ji.ENUM_VALUE="ENUM_VALUE",Ji.INPUT_OBJECT="INPUT_OBJECT",Ji.INPUT_FIELD_DEFINITION="INPUT_FIELD_DEFINITION",(Xi=Qi||(Qi={})).NAME="Name",Xi.DOCUMENT="Document",Xi.OPERATION_DEFINITION="OperationDefinition",Xi.VARIABLE_DEFINITION="VariableDefinition",Xi.SELECTION_SET="SelectionSet",Xi.FIELD="Field",Xi.ARGUMENT="Argument",Xi.FRAGMENT_SPREAD="FragmentSpread",Xi.INLINE_FRAGMENT="InlineFragment",Xi.FRAGMENT_DEFINITION="FragmentDefinition",Xi.VARIABLE="Variable",Xi.INT="IntValue",Xi.FLOAT="FloatValue",Xi.STRING="StringValue",Xi.BOOLEAN="BooleanValue",Xi.NULL="NullValue",Xi.ENUM="EnumValue",Xi.LIST="ListValue",Xi.OBJECT="ObjectValue",Xi.OBJECT_FIELD="ObjectField",Xi.DIRECTIVE="Directive",Xi.NAMED_TYPE="NamedType",Xi.LIST_TYPE="ListType",Xi.NON_NULL_TYPE="NonNullType",Xi.SCHEMA_DEFINITION="SchemaDefinition",Xi.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",Xi.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",Xi.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",Xi.FIELD_DEFINITION="FieldDefinition",Xi.INPUT_VALUE_DEFINITION="InputValueDefinition",Xi.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",Xi.UNION_TYPE_DEFINITION="UnionTypeDefinition",Xi.ENUM_TYPE_DEFINITION="EnumTypeDefinition",Xi.ENUM_VALUE_DEFINITION="EnumValueDefinition",Xi.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",Xi.DIRECTIVE_DEFINITION="DirectiveDefinition",Xi.SCHEMA_EXTENSION="SchemaExtension",Xi.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",Xi.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",Xi.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",Xi.UNION_TYPE_EXTENSION="UnionTypeExtension",Xi.ENUM_TYPE_EXTENSION="EnumTypeExtension",Xi.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension",(eo=Zi||(Zi={})).SOF="<SOF>",eo.EOF="<EOF>",eo.BANG="!",eo.DOLLAR="$",eo.AMP="&",eo.PAREN_L="(",eo.PAREN_R=")",eo.SPREAD="...",eo.COLON=":",eo.EQUALS="=",eo.AT="@",eo.BRACKET_L="[",eo.BRACKET_R="]",eo.BRACE_L="{",eo.PIPE="|",eo.BRACE_R="}",eo.NAME="Name",eo.INT="Int",eo.FLOAT="Float",eo.STRING="String",eo.BLOCK_STRING="BlockString",eo.COMMENT="Comment";class co{constructor(e){const t=new qi(Zi.SOF,0,0,0,0);this.source=e,this.lastToken=t,this.token=t,this.line=1,this.lineStart=0}get[Symbol.toStringTag](){return"Lexer"}advance(){this.lastToken=this.token;return this.token=this.lookahead()}lookahead(){let e=this.token;if(e.kind!==Zi.EOF)do{if(e.next)e=e.next;else{const t=mo(this,e.end);e.next=t,t.prev=e,e=t}}while(e.kind===Zi.COMMENT);return e}}function lo(e){return e>=0&&e<=55295||e>=57344&&e<=1114111}function uo(e,t){return ho(e.charCodeAt(t))&&po(e.charCodeAt(t+1))}function ho(e){return e>=55296&&e<=56319}function po(e){return e>=56320&&e<=57343}function fo(e,t){const r=e.source.body.codePointAt(t);if(void 0===r)return Zi.EOF;if(r>=32&&r<=126){const e=String.fromCodePoint(r);return'"'===e?"'\"'":`"${e}"`}return"U+"+r.toString(16).toUpperCase().padStart(4,"0")}function vo(e,t,r,n,i){const o=e.line,s=1+r-e.lineStart;return new qi(t,r,n,o,s,i)}function mo(e,t){const r=e.source.body,n=r.length;let i=t;for(;i<n;){const t=r.charCodeAt(i);switch(t){case 65279:case 9:case 32:case 44:++i;continue;case 10:++i,++e.line,e.lineStart=i;continue;case 13:10===r.charCodeAt(i+1)?i+=2:++i,++e.line,e.lineStart=i;continue;case 35:return go(e,i);case 33:return vo(e,Zi.BANG,i,i+1);case 36:return vo(e,Zi.DOLLAR,i,i+1);case 38:return vo(e,Zi.AMP,i,i+1);case 40:return vo(e,Zi.PAREN_L,i,i+1);case 41:return vo(e,Zi.PAREN_R,i,i+1);case 46:if(46===r.charCodeAt(i+1)&&46===r.charCodeAt(i+2))return vo(e,Zi.SPREAD,i,i+3);break;case 58:return vo(e,Zi.COLON,i,i+1);case 61:return vo(e,Zi.EQUALS,i,i+1);case 64:return vo(e,Zi.AT,i,i+1);case 91:return vo(e,Zi.BRACKET_L,i,i+1);case 93:return vo(e,Zi.BRACKET_R,i,i+1);case 123:return vo(e,Zi.BRACE_L,i,i+1);case 124:return vo(e,Zi.PIPE,i,i+1);case 125:return vo(e,Zi.BRACE_R,i,i+1);case 34:return 34===r.charCodeAt(i+1)&&34===r.charCodeAt(i+2)?ko(e,i):bo(e,i)}if(ro(t)||45===t)return yo(e,i,t);if(io(t))return Ao(e,i);throw Fi(e.source,i,39===t?"Unexpected single quote character ('), did you mean to use a double quote (\")?":lo(t)||uo(r,i)?`Unexpected character: ${fo(e,i)}.`:`Invalid character: ${fo(e,i)}.`)}return vo(e,Zi.EOF,n,n)}function go(e,t){const r=e.source.body,n=r.length;let i=t+1;for(;i<n;){const e=r.charCodeAt(i);if(10===e||13===e)break;if(lo(e))++i;else{if(!uo(r,i))break;i+=2}}return vo(e,Zi.COMMENT,t,i,r.slice(t+1,i))}function yo(e,t,r){const n=e.source.body;let i=t,o=r,s=!1;if(45===o&&(o=n.charCodeAt(++i)),48===o){if(o=n.charCodeAt(++i),ro(o))throw Fi(e.source,i,`Invalid number, unexpected digit after 0: ${fo(e,i)}.`)}else i=wo(e,i,o),o=n.charCodeAt(i);if(46===o&&(s=!0,o=n.charCodeAt(++i),i=wo(e,i,o),o=n.charCodeAt(i)),69!==o&&101!==o||(s=!0,o=n.charCodeAt(++i),43!==o&&45!==o||(o=n.charCodeAt(++i)),i=wo(e,i,o),o=n.charCodeAt(i)),46===o||io(o))throw Fi(e.source,i,`Invalid number, expected digit but got: ${fo(e,i)}.`);return vo(e,s?Zi.FLOAT:Zi.INT,t,i,n.slice(t,i))}function wo(e,t,r){if(!ro(r))throw Fi(e.source,t,`Invalid number, expected digit but got: ${fo(e,t)}.`);const n=e.source.body;let i=t+1;for(;ro(n.charCodeAt(i));)++i;return i}function bo(e,t){const r=e.source.body,n=r.length;let i=t+1,o=i,s="";for(;i<n;){const n=r.charCodeAt(i);if(34===n)return s+=r.slice(o,i),vo(e,Zi.STRING,t,i+1,s);if(92!==n){if(10===n||13===n)break;if(lo(n))++i;else{if(!uo(r,i))throw Fi(e.source,i,`Invalid character within String: ${fo(e,i)}.`);i+=2}}else{s+=r.slice(o,i);const t=117===r.charCodeAt(i+1)?123===r.charCodeAt(i+2)?Eo(e,i):_o(e,i):So(e,i);s+=t.value,i+=t.size,o=i}}throw Fi(e.source,i,"Unterminated string.")}function Eo(e,t){const r=e.source.body;let n=0,i=3;for(;i<12;){const e=r.charCodeAt(t+i++);if(125===e){if(i<5||!lo(n))break;return{value:String.fromCodePoint(n),size:i}}if(n=n<<4|xo(e),n<0)break}throw Fi(e.source,t,`Invalid Unicode escape sequence: "${r.slice(t,t+i)}".`)}function _o(e,t){const r=e.source.body,n=To(r,t+2);if(lo(n))return{value:String.fromCodePoint(n),size:6};if(ho(n)&&92===r.charCodeAt(t+6)&&117===r.charCodeAt(t+7)){const e=To(r,t+8);if(po(e))return{value:String.fromCodePoint(n,e),size:12}}throw Fi(e.source,t,`Invalid Unicode escape sequence: "${r.slice(t,t+6)}".`)}function To(e,t){return xo(e.charCodeAt(t))<<12|xo(e.charCodeAt(t+1))<<8|xo(e.charCodeAt(t+2))<<4|xo(e.charCodeAt(t+3))}function xo(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:-1}function So(e,t){const r=e.source.body;switch(r.charCodeAt(t+1)){case 34:return{value:'"',size:2};case 92:return{value:"\\",size:2};case 47:return{value:"/",size:2};case 98:return{value:"\b",size:2};case 102:return{value:"\f",size:2};case 110:return{value:"\n",size:2};case 114:return{value:"\r",size:2};case 116:return{value:"\t",size:2}}throw Fi(e.source,t,`Invalid character escape sequence: "${r.slice(t,t+2)}".`)}function ko(e,t){const r=e.source.body,n=r.length;let i=e.lineStart,o=t+3,s=o,a="";const c=[];for(;o<n;){const n=r.charCodeAt(o);if(34===n&&34===r.charCodeAt(o+1)&&34===r.charCodeAt(o+2)){a+=r.slice(s,o),c.push(a);const n=vo(e,Zi.BLOCK_STRING,t,o+3,so(c).join("\n"));return e.line+=c.length-1,e.lineStart=i,n}if(92!==n||34!==r.charCodeAt(o+1)||34!==r.charCodeAt(o+2)||34!==r.charCodeAt(o+3))if(10!==n&&13!==n)if(lo(n))++o;else{if(!uo(r,o))throw Fi(e.source,o,`Invalid character within String: ${fo(e,o)}.`);o+=2}else a+=r.slice(s,o),c.push(a),13===n&&10===r.charCodeAt(o+1)?o+=2:++o,a="",s=o,i=o;else a+=r.slice(s,o),s=o+1,o+=4}throw Fi(e.source,o,"Unterminated string.")}function Ao(e,t){const r=e.source.body,n=r.length;let i=t+1;for(;i<n;){if(!oo(r.charCodeAt(i)))break;++i}return vo(e,Zi.NAME,t,i,r.slice(t,i))}const Co=10,Io=2;function Oo(e){return No(e,[])}function No(e,t){switch(typeof e){case"string":return JSON.stringify(e);case"function":return e.name?`[function ${e.name}]`:"[function]";case"object":return function(e,t){if(null===e)return"null";if(t.includes(e))return"[Circular]";const r=[...t,e];if(function(e){return"function"==typeof e.toJSON}(e)){const t=e.toJSON();if(t!==e)return"string"==typeof t?t:No(t,r)}else if(Array.isArray(e))return function(e,t){if(0===e.length)return"[]";if(t.length>Io)return"[Array]";const r=Math.min(Co,e.length),n=e.length-r,i=[];for(let o=0;o<r;++o)i.push(No(e[o],t));1===n?i.push("... 1 more item"):n>1&&i.push(`... ${n} more items`);return"["+i.join(", ")+"]"}(e,r);return function(e,t){const r=Object.entries(e);if(0===r.length)return"{}";if(t.length>Io)return"["+function(e){const t=Object.prototype.toString.call(e).replace(/^\[object /,"").replace(/]$/,"");if("Object"===t&&"function"==typeof e.constructor){const t=e.constructor.name;if("string"==typeof t&&""!==t)return t}return t}(e)+"]";const n=r.map((([e,r])=>e+": "+No(r,t)));return"{ "+n.join(", ")+" }"}(e,r)}(e,t);default:return String(e)}}const Po=globalThis.process&&"production"===process.env.NODE_ENV?function(e,t){return e instanceof t}:function(e,t){if(e instanceof t)return!0;if("object"==typeof e&&null!==e){var r;const n=t.prototype[Symbol.toStringTag];if(n===(Symbol.toStringTag in e?e[Symbol.toStringTag]:null===(r=e.constructor)||void 0===r?void 0:r.name)){const t=Oo(e);throw new Error(`Cannot use ${n} "${t}" from another module or realm.\n\nEnsure that there is only one instance of "graphql" in the node_modules\ndirectory. If different versions of "graphql" are the dependencies of other\nrelied on modules, use "resolutions" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate "graphql" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results.`)}}return!1};class Ro{constructor(e,t="GraphQL request",r={line:1,column:1}){"string"==typeof e||Ri(!1,`Body must be a string. Received: ${Oo(e)}.`),this.body=e,this.name=t,this.locationOffset=r,this.locationOffset.line>0||Ri(!1,"line in locationOffset is 1-indexed and must be positive."),this.locationOffset.column>0||Ri(!1,"column in locationOffset is 1-indexed and must be positive.")}get[Symbol.toStringTag](){return"Source"}}class Lo{constructor(e,t={}){const r=function(e){return Po(e,Ro)}(e)?e:new Ro(e);this._lexer=new co(r),this._options=t,this._tokenCounter=0}parseName(){const e=this.expectToken(Zi.NAME);return this.node(e,{kind:Qi.NAME,value:e.value})}parseDocument(){return this.node(this._lexer.token,{kind:Qi.DOCUMENT,definitions:this.many(Zi.SOF,this.parseDefinition,Zi.EOF)})}parseDefinition(){if(this.peek(Zi.BRACE_L))return this.parseOperationDefinition();const e=this.peekDescription(),t=e?this._lexer.lookahead():this._lexer.token;if(t.kind===Zi.NAME){switch(t.value){case"schema":return this.parseSchemaDefinition();case"scalar":return this.parseScalarTypeDefinition();case"type":return this.parseObjectTypeDefinition();case"interface":return this.parseInterfaceTypeDefinition();case"union":return this.parseUnionTypeDefinition();case"enum":return this.parseEnumTypeDefinition();case"input":return this.parseInputObjectTypeDefinition();case"directive":return this.parseDirectiveDefinition()}if(e)throw Fi(this._lexer.source,this._lexer.token.start,"Unexpected description, descriptions are supported only on type definitions.");switch(t.value){case"query":case"mutation":case"subscription":return this.parseOperationDefinition();case"fragment":return this.parseFragmentDefinition();case"extend":return this.parseTypeSystemExtension()}}throw this.unexpected(t)}parseOperationDefinition(){const e=this._lexer.token;if(this.peek(Zi.BRACE_L))return this.node(e,{kind:Qi.OPERATION_DEFINITION,operation:Gi.QUERY,name:void 0,variableDefinitions:[],directives:[],selectionSet:this.parseSelectionSet()});const t=this.parseOperationType();let r;return this.peek(Zi.NAME)&&(r=this.parseName()),this.node(e,{kind:Qi.OPERATION_DEFINITION,operation:t,name:r,variableDefinitions:this.parseVariableDefinitions(),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseOperationType(){const e=this.expectToken(Zi.NAME);switch(e.value){case"query":return Gi.QUERY;case"mutation":return Gi.MUTATION;case"subscription":return Gi.SUBSCRIPTION}throw this.unexpected(e)}parseVariableDefinitions(){return this.optionalMany(Zi.PAREN_L,this.parseVariableDefinition,Zi.PAREN_R)}parseVariableDefinition(){return this.node(this._lexer.token,{kind:Qi.VARIABLE_DEFINITION,variable:this.parseVariable(),type:(this.expectToken(Zi.COLON),this.parseTypeReference()),defaultValue:this.expectOptionalToken(Zi.EQUALS)?this.parseConstValueLiteral():void 0,directives:this.parseConstDirectives()})}parseVariable(){const e=this._lexer.token;return this.expectToken(Zi.DOLLAR),this.node(e,{kind:Qi.VARIABLE,name:this.parseName()})}parseSelectionSet(){return this.node(this._lexer.token,{kind:Qi.SELECTION_SET,selections:this.many(Zi.BRACE_L,this.parseSelection,Zi.BRACE_R)})}parseSelection(){return this.peek(Zi.SPREAD)?this.parseFragment():this.parseField()}parseField(){const e=this._lexer.token,t=this.parseName();let r,n;return this.expectOptionalToken(Zi.COLON)?(r=t,n=this.parseName()):n=t,this.node(e,{kind:Qi.FIELD,alias:r,name:n,arguments:this.parseArguments(!1),directives:this.parseDirectives(!1),selectionSet:this.peek(Zi.BRACE_L)?this.parseSelectionSet():void 0})}parseArguments(e){const t=e?this.parseConstArgument:this.parseArgument;return this.optionalMany(Zi.PAREN_L,t,Zi.PAREN_R)}parseArgument(e=!1){const t=this._lexer.token,r=this.parseName();return this.expectToken(Zi.COLON),this.node(t,{kind:Qi.ARGUMENT,name:r,value:this.parseValueLiteral(e)})}parseConstArgument(){return this.parseArgument(!0)}parseFragment(){const e=this._lexer.token;this.expectToken(Zi.SPREAD);const t=this.expectOptionalKeyword("on");return!t&&this.peek(Zi.NAME)?this.node(e,{kind:Qi.FRAGMENT_SPREAD,name:this.parseFragmentName(),directives:this.parseDirectives(!1)}):this.node(e,{kind:Qi.INLINE_FRAGMENT,typeCondition:t?this.parseNamedType():void 0,directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseFragmentDefinition(){const e=this._lexer.token;return this.expectKeyword("fragment"),!0===this._options.allowLegacyFragmentVariables?this.node(e,{kind:Qi.FRAGMENT_DEFINITION,name:this.parseFragmentName(),variableDefinitions:this.parseVariableDefinitions(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()}):this.node(e,{kind:Qi.FRAGMENT_DEFINITION,name:this.parseFragmentName(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseFragmentName(){if("on"===this._lexer.token.value)throw this.unexpected();return this.parseName()}parseValueLiteral(e){const t=this._lexer.token;switch(t.kind){case Zi.BRACKET_L:return this.parseList(e);case Zi.BRACE_L:return this.parseObject(e);case Zi.INT:return this.advanceLexer(),this.node(t,{kind:Qi.INT,value:t.value});case Zi.FLOAT:return this.advanceLexer(),this.node(t,{kind:Qi.FLOAT,value:t.value});case Zi.STRING:case Zi.BLOCK_STRING:return this.parseStringLiteral();case Zi.NAME:switch(this.advanceLexer(),t.value){case"true":return this.node(t,{kind:Qi.BOOLEAN,value:!0});case"false":return this.node(t,{kind:Qi.BOOLEAN,value:!1});case"null":return this.node(t,{kind:Qi.NULL});default:return this.node(t,{kind:Qi.ENUM,value:t.value})}case Zi.DOLLAR:if(e){if(this.expectToken(Zi.DOLLAR),this._lexer.token.kind===Zi.NAME){const e=this._lexer.token.value;throw Fi(this._lexer.source,t.start,`Unexpected variable "$${e}" in constant value.`)}throw this.unexpected(t)}return this.parseVariable();default:throw this.unexpected()}}parseConstValueLiteral(){return this.parseValueLiteral(!0)}parseStringLiteral(){const e=this._lexer.token;return this.advanceLexer(),this.node(e,{kind:Qi.STRING,value:e.value,block:e.kind===Zi.BLOCK_STRING})}parseList(e){return this.node(this._lexer.token,{kind:Qi.LIST,values:this.any(Zi.BRACKET_L,(()=>this.parseValueLiteral(e)),Zi.BRACKET_R)})}parseObject(e){return this.node(this._lexer.token,{kind:Qi.OBJECT,fields:this.any(Zi.BRACE_L,(()=>this.parseObjectField(e)),Zi.BRACE_R)})}parseObjectField(e){const t=this._lexer.token,r=this.parseName();return this.expectToken(Zi.COLON),this.node(t,{kind:Qi.OBJECT_FIELD,name:r,value:this.parseValueLiteral(e)})}parseDirectives(e){const t=[];for(;this.peek(Zi.AT);)t.push(this.parseDirective(e));return t}parseConstDirectives(){return this.parseDirectives(!0)}parseDirective(e){const t=this._lexer.token;return this.expectToken(Zi.AT),this.node(t,{kind:Qi.DIRECTIVE,name:this.parseName(),arguments:this.parseArguments(e)})}parseTypeReference(){const e=this._lexer.token;let t;if(this.expectOptionalToken(Zi.BRACKET_L)){const r=this.parseTypeReference();this.expectToken(Zi.BRACKET_R),t=this.node(e,{kind:Qi.LIST_TYPE,type:r})}else t=this.parseNamedType();return this.expectOptionalToken(Zi.BANG)?this.node(e,{kind:Qi.NON_NULL_TYPE,type:t}):t}parseNamedType(){return this.node(this._lexer.token,{kind:Qi.NAMED_TYPE,name:this.parseName()})}peekDescription(){return this.peek(Zi.STRING)||this.peek(Zi.BLOCK_STRING)}parseDescription(){if(this.peekDescription())return this.parseStringLiteral()}parseSchemaDefinition(){const e=this._lexer.token,t=this.parseDescription();this.expectKeyword("schema");const r=this.parseConstDirectives(),n=this.many(Zi.BRACE_L,this.parseOperationTypeDefinition,Zi.BRACE_R);return this.node(e,{kind:Qi.SCHEMA_DEFINITION,description:t,directives:r,operationTypes:n})}parseOperationTypeDefinition(){const e=this._lexer.token,t=this.parseOperationType();this.expectToken(Zi.COLON);const r=this.parseNamedType();return this.node(e,{kind:Qi.OPERATION_TYPE_DEFINITION,operation:t,type:r})}parseScalarTypeDefinition(){const e=this._lexer.token,t=this.parseDescription();this.expectKeyword("scalar");const r=this.parseName(),n=this.parseConstDirectives();return this.node(e,{kind:Qi.SCALAR_TYPE_DEFINITION,description:t,name:r,directives:n})}parseObjectTypeDefinition(){const e=this._lexer.token,t=this.parseDescription();this.expectKeyword("type");const r=this.parseName(),n=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),o=this.parseFieldsDefinition();return this.node(e,{kind:Qi.OBJECT_TYPE_DEFINITION,description:t,name:r,interfaces:n,directives:i,fields:o})}parseImplementsInterfaces(){return this.expectOptionalKeyword("implements")?this.delimitedMany(Zi.AMP,this.parseNamedType):[]}parseFieldsDefinition(){return this.optionalMany(Zi.BRACE_L,this.parseFieldDefinition,Zi.BRACE_R)}parseFieldDefinition(){const e=this._lexer.token,t=this.parseDescription(),r=this.parseName(),n=this.parseArgumentDefs();this.expectToken(Zi.COLON);const i=this.parseTypeReference(),o=this.parseConstDirectives();return this.node(e,{kind:Qi.FIELD_DEFINITION,description:t,name:r,arguments:n,type:i,directives:o})}parseArgumentDefs(){return this.optionalMany(Zi.PAREN_L,this.parseInputValueDef,Zi.PAREN_R)}parseInputValueDef(){const e=this._lexer.token,t=this.parseDescription(),r=this.parseName();this.expectToken(Zi.COLON);const n=this.parseTypeReference();let i;this.expectOptionalToken(Zi.EQUALS)&&(i=this.parseConstValueLiteral());const o=this.parseConstDirectives();return this.node(e,{kind:Qi.INPUT_VALUE_DEFINITION,description:t,name:r,type:n,defaultValue:i,directives:o})}parseInterfaceTypeDefinition(){const e=this._lexer.token,t=this.parseDescription();this.expectKeyword("interface");const r=this.parseName(),n=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),o=this.parseFieldsDefinition();return this.node(e,{kind:Qi.INTERFACE_TYPE_DEFINITION,description:t,name:r,interfaces:n,directives:i,fields:o})}parseUnionTypeDefinition(){const e=this._lexer.token,t=this.parseDescription();this.expectKeyword("union");const r=this.parseName(),n=this.parseConstDirectives(),i=this.parseUnionMemberTypes();return this.node(e,{kind:Qi.UNION_TYPE_DEFINITION,description:t,name:r,directives:n,types:i})}parseUnionMemberTypes(){return this.expectOptionalToken(Zi.EQUALS)?this.delimitedMany(Zi.PIPE,this.parseNamedType):[]}parseEnumTypeDefinition(){const e=this._lexer.token,t=this.parseDescription();this.expectKeyword("enum");const r=this.parseName(),n=this.parseConstDirectives(),i=this.parseEnumValuesDefinition();return this.node(e,{kind:Qi.ENUM_TYPE_DEFINITION,description:t,name:r,directives:n,values:i})}parseEnumValuesDefinition(){return this.optionalMany(Zi.BRACE_L,this.parseEnumValueDefinition,Zi.BRACE_R)}parseEnumValueDefinition(){const e=this._lexer.token,t=this.parseDescription(),r=this.parseEnumValueName(),n=this.parseConstDirectives();return this.node(e,{kind:Qi.ENUM_VALUE_DEFINITION,description:t,name:r,directives:n})}parseEnumValueName(){if("true"===this._lexer.token.value||"false"===this._lexer.token.value||"null"===this._lexer.token.value)throw Fi(this._lexer.source,this._lexer.token.start,`${Do(this._lexer.token)} is reserved and cannot be used for an enum value.`);return this.parseName()}parseInputObjectTypeDefinition(){const e=this._lexer.token,t=this.parseDescription();this.expectKeyword("input");const r=this.parseName(),n=this.parseConstDirectives(),i=this.parseInputFieldsDefinition();return this.node(e,{kind:Qi.INPUT_OBJECT_TYPE_DEFINITION,description:t,name:r,directives:n,fields:i})}parseInputFieldsDefinition(){return this.optionalMany(Zi.BRACE_L,this.parseInputValueDef,Zi.BRACE_R)}parseTypeSystemExtension(){const e=this._lexer.lookahead();if(e.kind===Zi.NAME)switch(e.value){case"schema":return this.parseSchemaExtension();case"scalar":return this.parseScalarTypeExtension();case"type":return this.parseObjectTypeExtension();case"interface":return this.parseInterfaceTypeExtension();case"union":return this.parseUnionTypeExtension();case"enum":return this.parseEnumTypeExtension();case"input":return this.parseInputObjectTypeExtension()}throw this.unexpected(e)}parseSchemaExtension(){const e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("schema");const t=this.parseConstDirectives(),r=this.optionalMany(Zi.BRACE_L,this.parseOperationTypeDefinition,Zi.BRACE_R);if(0===t.length&&0===r.length)throw this.unexpected();return this.node(e,{kind:Qi.SCHEMA_EXTENSION,directives:t,operationTypes:r})}parseScalarTypeExtension(){const e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("scalar");const t=this.parseName(),r=this.parseConstDirectives();if(0===r.length)throw this.unexpected();return this.node(e,{kind:Qi.SCALAR_TYPE_EXTENSION,name:t,directives:r})}parseObjectTypeExtension(){const e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("type");const t=this.parseName(),r=this.parseImplementsInterfaces(),n=this.parseConstDirectives(),i=this.parseFieldsDefinition();if(0===r.length&&0===n.length&&0===i.length)throw this.unexpected();return this.node(e,{kind:Qi.OBJECT_TYPE_EXTENSION,name:t,interfaces:r,directives:n,fields:i})}parseInterfaceTypeExtension(){const e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("interface");const t=this.parseName(),r=this.parseImplementsInterfaces(),n=this.parseConstDirectives(),i=this.parseFieldsDefinition();if(0===r.length&&0===n.length&&0===i.length)throw this.unexpected();return this.node(e,{kind:Qi.INTERFACE_TYPE_EXTENSION,name:t,interfaces:r,directives:n,fields:i})}parseUnionTypeExtension(){const e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("union");const t=this.parseName(),r=this.parseConstDirectives(),n=this.parseUnionMemberTypes();if(0===r.length&&0===n.length)throw this.unexpected();return this.node(e,{kind:Qi.UNION_TYPE_EXTENSION,name:t,directives:r,types:n})}parseEnumTypeExtension(){const e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("enum");const t=this.parseName(),r=this.parseConstDirectives(),n=this.parseEnumValuesDefinition();if(0===r.length&&0===n.length)throw this.unexpected();return this.node(e,{kind:Qi.ENUM_TYPE_EXTENSION,name:t,directives:r,values:n})}parseInputObjectTypeExtension(){const e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("input");const t=this.parseName(),r=this.parseConstDirectives(),n=this.parseInputFieldsDefinition();if(0===r.length&&0===n.length)throw this.unexpected();return this.node(e,{kind:Qi.INPUT_OBJECT_TYPE_EXTENSION,name:t,directives:r,fields:n})}parseDirectiveDefinition(){const e=this._lexer.token,t=this.parseDescription();this.expectKeyword("directive"),this.expectToken(Zi.AT);const r=this.parseName(),n=this.parseArgumentDefs(),i=this.expectOptionalKeyword("repeatable");this.expectKeyword("on");const o=this.parseDirectiveLocations();return this.node(e,{kind:Qi.DIRECTIVE_DEFINITION,description:t,name:r,arguments:n,repeatable:i,locations:o})}parseDirectiveLocations(){return this.delimitedMany(Zi.PIPE,this.parseDirectiveLocation)}parseDirectiveLocation(){const e=this._lexer.token,t=this.parseName();if(Object.prototype.hasOwnProperty.call(Wi,t.value))return t;throw this.unexpected(e)}node(e,t){return!0!==this._options.noLocation&&(t.loc=new zi(e,this._lexer.lastToken,this._lexer.source)),t}peek(e){return this._lexer.token.kind===e}expectToken(e){const t=this._lexer.token;if(t.kind===e)return this.advanceLexer(),t;throw Fi(this._lexer.source,t.start,`Expected ${$o(e)}, found ${Do(t)}.`)}expectOptionalToken(e){return this._lexer.token.kind===e&&(this.advanceLexer(),!0)}expectKeyword(e){const t=this._lexer.token;if(t.kind!==Zi.NAME||t.value!==e)throw Fi(this._lexer.source,t.start,`Expected "${e}", found ${Do(t)}.`);this.advanceLexer()}expectOptionalKeyword(e){const t=this._lexer.token;return t.kind===Zi.NAME&&t.value===e&&(this.advanceLexer(),!0)}unexpected(e){const t=null!=e?e:this._lexer.token;return Fi(this._lexer.source,t.start,`Unexpected ${Do(t)}.`)}any(e,t,r){this.expectToken(e);const n=[];for(;!this.expectOptionalToken(r);)n.push(t.call(this));return n}optionalMany(e,t,r){if(this.expectOptionalToken(e)){const e=[];do{e.push(t.call(this))}while(!this.expectOptionalToken(r));return e}return[]}many(e,t,r){this.expectToken(e);const n=[];do{n.push(t.call(this))}while(!this.expectOptionalToken(r));return n}delimitedMany(e,t){this.expectOptionalToken(e);const r=[];do{r.push(t.call(this))}while(this.expectOptionalToken(e));return r}advanceLexer(){const{maxTokens:e}=this._options,t=this._lexer.advance();if(void 0!==e&&t.kind!==Zi.EOF&&(++this._tokenCounter,this._tokenCounter>e))throw Fi(this._lexer.source,t.start,`Document contains more that ${e} tokens. Parsing aborted.`)}}function Do(e){const t=e.value;return $o(e.kind)+(null!=t?` "${t}"`:"")}function $o(e){return function(e){return e===Zi.BANG||e===Zi.DOLLAR||e===Zi.AMP||e===Zi.PAREN_L||e===Zi.PAREN_R||e===Zi.SPREAD||e===Zi.COLON||e===Zi.EQUALS||e===Zi.AT||e===Zi.BRACKET_L||e===Zi.BRACKET_R||e===Zi.BRACE_L||e===Zi.PIPE||e===Zi.BRACE_R}(e)?`"${e}"`:e}const Uo=/[\x00-\x1f\x22\x5c\x7f-\x9f]/g;function Mo(e){return jo[e.charCodeAt(0)]}const jo=["\\u0000","\\u0001","\\u0002","\\u0003","\\u0004","\\u0005","\\u0006","\\u0007","\\b","\\t","\\n","\\u000B","\\f","\\r","\\u000E","\\u000F","\\u0010","\\u0011","\\u0012","\\u0013","\\u0014","\\u0015","\\u0016","\\u0017","\\u0018","\\u0019","\\u001A","\\u001B","\\u001C","\\u001D","\\u001E","\\u001F","","",'\\"',"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\\\","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\u007F","\\u0080","\\u0081","\\u0082","\\u0083","\\u0084","\\u0085","\\u0086","\\u0087","\\u0088","\\u0089","\\u008A","\\u008B","\\u008C","\\u008D","\\u008E","\\u008F","\\u0090","\\u0091","\\u0092","\\u0093","\\u0094","\\u0095","\\u0096","\\u0097","\\u0098","\\u0099","\\u009A","\\u009B","\\u009C","\\u009D","\\u009E","\\u009F"],Vo=Object.freeze({});function Fo(e,t){const r=e[t];return"object"==typeof r?r:"function"==typeof r?{enter:r,leave:void 0}:{enter:e.enter,leave:e.leave}}function zo(e){return function(e,t,r=Bi){const n=new Map;for(const g of Object.values(Qi))n.set(g,Fo(t,g));let i,o,s,a=Array.isArray(e),c=[e],l=-1,u=[],d=e;const h=[],p=[];do{l++;const e=l===c.length,g=e&&0!==u.length;if(e){if(o=0===p.length?void 0:h[h.length-1],d=s,s=p.pop(),g)if(a){d=d.slice();let e=0;for(const[t,r]of u){const n=t-e;null===r?(d.splice(n,1),e++):d[n]=r}}else{d=Object.defineProperties({},Object.getOwnPropertyDescriptors(d));for(const[e,t]of u)d[e]=t}l=i.index,c=i.keys,u=i.edits,a=i.inArray,i=i.prev}else if(s){if(o=a?l:c[l],d=s[o],null==d)continue;h.push(o)}let y;if(!Array.isArray(d)){var f,v;Ki(d)||Ri(!1,`Invalid AST Node: ${Oo(d)}.`);const r=e?null===(f=n.get(d.kind))||void 0===f?void 0:f.leave:null===(v=n.get(d.kind))||void 0===v?void 0:v.enter;if(y=null==r?void 0:r.call(t,d,o,s,h,p),y===Vo)break;if(!1===y){if(!e){h.pop();continue}}else if(void 0!==y&&(u.push([o,y]),!e)){if(!Ki(y)){h.pop();continue}d=y}}var m;void 0===y&&g&&u.push([o,d]),e?h.pop():(i={inArray:a,index:l,keys:c,edits:u,prev:i},a=Array.isArray(d),c=a?d:null!==(m=r[d.kind])&&void 0!==m?m:[],l=-1,u=[],s&&p.push(s),s=d)}while(void 0!==i);return 0!==u.length?u[u.length-1][1]:e}(e,qo)}const qo={Name:{leave:e=>e.value},Variable:{leave:e=>"$"+e.name},Document:{leave:e=>Bo(e.definitions,"\n\n")},OperationDefinition:{leave(e){const t=Ko("(",Bo(e.variableDefinitions,", "),")"),r=Bo([e.operation,Bo([e.name,t]),Bo(e.directives," ")]," ");return("query"===r?"":r+" ")+e.selectionSet}},VariableDefinition:{leave:({variable:e,type:t,defaultValue:r,directives:n})=>e+": "+t+Ko(" = ",r)+Ko(" ",Bo(n," "))},SelectionSet:{leave:({selections:e})=>Ho(e)},Field:{leave({alias:e,name:t,arguments:r,directives:n,selectionSet:i}){const o=Ko("",e,": ")+t;let s=o+Ko("(",Bo(r,", "),")");return s.length>80&&(s=o+Ko("(\n",Go(Bo(r,"\n")),"\n)")),Bo([s,Bo(n," "),i]," ")}},Argument:{leave:({name:e,value:t})=>e+": "+t},FragmentSpread:{leave:({name:e,directives:t})=>"..."+e+Ko(" ",Bo(t," "))},InlineFragment:{leave:({typeCondition:e,directives:t,selectionSet:r})=>Bo(["...",Ko("on ",e),Bo(t," "),r]," ")},FragmentDefinition:{leave:({name:e,typeCondition:t,variableDefinitions:r,directives:n,selectionSet:i})=>`fragment ${e}${Ko("(",Bo(r,", "),")")} on ${t} ${Ko("",Bo(n," ")," ")}`+i},IntValue:{leave:({value:e})=>e},FloatValue:{leave:({value:e})=>e},StringValue:{leave:({value:e,block:t})=>t?function(e,t){const r=e.replace(/"""/g,'\\"""'),n=r.split(/\r\n|[\n\r]/g),i=1===n.length,o=n.length>1&&n.slice(1).every((e=>0===e.length||to(e.charCodeAt(0)))),s=r.endsWith('\\"""'),a=e.endsWith('"')&&!s,c=e.endsWith("\\"),l=a||c,u=!i||e.length>70||l||o||s;let d="";const h=i&&to(e.charCodeAt(0));return(u&&!h||o)&&(d+="\n"),d+=r,(u||l)&&(d+="\n"),'"""'+d+'"""'}(e):`"${e.replace(Uo,Mo)}"`},BooleanValue:{leave:({value:e})=>e?"true":"false"},NullValue:{leave:()=>"null"},EnumValue:{leave:({value:e})=>e},ListValue:{leave:({values:e})=>"["+Bo(e,", ")+"]"},ObjectValue:{leave:({fields:e})=>"{"+Bo(e,", ")+"}"},ObjectField:{leave:({name:e,value:t})=>e+": "+t},Directive:{leave:({name:e,arguments:t})=>"@"+e+Ko("(",Bo(t,", "),")")},NamedType:{leave:({name:e})=>e},ListType:{leave:({type:e})=>"["+e+"]"},NonNullType:{leave:({type:e})=>e+"!"},SchemaDefinition:{leave:({description:e,directives:t,operationTypes:r})=>Ko("",e,"\n")+Bo(["schema",Bo(t," "),Ho(r)]," ")},OperationTypeDefinition:{leave:({operation:e,type:t})=>e+": "+t},ScalarTypeDefinition:{leave:({description:e,name:t,directives:r})=>Ko("",e,"\n")+Bo(["scalar",t,Bo(r," ")]," ")},ObjectTypeDefinition:{leave:({description:e,name:t,interfaces:r,directives:n,fields:i})=>Ko("",e,"\n")+Bo(["type",t,Ko("implements ",Bo(r," & ")),Bo(n," "),Ho(i)]," ")},FieldDefinition:{leave:({description:e,name:t,arguments:r,type:n,directives:i})=>Ko("",e,"\n")+t+(Yo(r)?Ko("(\n",Go(Bo(r,"\n")),"\n)"):Ko("(",Bo(r,", "),")"))+": "+n+Ko(" ",Bo(i," "))},InputValueDefinition:{leave:({description:e,name:t,type:r,defaultValue:n,directives:i})=>Ko("",e,"\n")+Bo([t+": "+r,Ko("= ",n),Bo(i," ")]," ")},InterfaceTypeDefinition:{leave:({description:e,name:t,interfaces:r,directives:n,fields:i})=>Ko("",e,"\n")+Bo(["interface",t,Ko("implements ",Bo(r," & ")),Bo(n," "),Ho(i)]," ")},UnionTypeDefinition:{leave:({description:e,name:t,directives:r,types:n})=>Ko("",e,"\n")+Bo(["union",t,Bo(r," "),Ko("= ",Bo(n," | "))]," ")},EnumTypeDefinition:{leave:({description:e,name:t,directives:r,values:n})=>Ko("",e,"\n")+Bo(["enum",t,Bo(r," "),Ho(n)]," ")},EnumValueDefinition:{leave:({description:e,name:t,directives:r})=>Ko("",e,"\n")+Bo([t,Bo(r," ")]," ")},InputObjectTypeDefinition:{leave:({description:e,name:t,directives:r,fields:n})=>Ko("",e,"\n")+Bo(["input",t,Bo(r," "),Ho(n)]," ")},DirectiveDefinition:{leave:({description:e,name:t,arguments:r,repeatable:n,locations:i})=>Ko("",e,"\n")+"directive @"+t+(Yo(r)?Ko("(\n",Go(Bo(r,"\n")),"\n)"):Ko("(",Bo(r,", "),")"))+(n?" repeatable":"")+" on "+Bo(i," | ")},SchemaExtension:{leave:({directives:e,operationTypes:t})=>Bo(["extend schema",Bo(e," "),Ho(t)]," ")},ScalarTypeExtension:{leave:({name:e,directives:t})=>Bo(["extend scalar",e,Bo(t," ")]," ")},ObjectTypeExtension:{leave:({name:e,interfaces:t,directives:r,fields:n})=>Bo(["extend type",e,Ko("implements ",Bo(t," & ")),Bo(r," "),Ho(n)]," ")},InterfaceTypeExtension:{leave:({name:e,interfaces:t,directives:r,fields:n})=>Bo(["extend interface",e,Ko("implements ",Bo(t," & ")),Bo(r," "),Ho(n)]," ")},UnionTypeExtension:{leave:({name:e,directives:t,types:r})=>Bo(["extend union",e,Bo(t," "),Ko("= ",Bo(r," | "))]," ")},EnumTypeExtension:{leave:({name:e,directives:t,values:r})=>Bo(["extend enum",e,Bo(t," "),Ho(r)]," ")},InputObjectTypeExtension:{leave:({name:e,directives:t,fields:r})=>Bo(["extend input",e,Bo(t," "),Ho(r)]," ")}};function Bo(e,t=""){var r;return null!==(r=null==e?void 0:e.filter((e=>e)).join(t))&&void 0!==r?r:""}function Ho(e){return Ko("{\n",Go(Bo(e,"\n")),"\n}")}function Ko(e,t,r=""){return null!=t&&""!==t?e+t+r:""}function Go(e){return Ko(" ",e.replace(/\n/g,"\n "))}function Yo(e){var t;return null!==(t=null==e?void 0:e.some((e=>e.includes("\n"))))&&void 0!==t&&t}function Wo(e){var t;let r;const n=e.definitions.filter((e=>"OperationDefinition"===e.kind));return 1===n.length&&(r=null==(t=n[0].name)?void 0:t.value),r}function Jo(e){if("string"==typeof e){let r;try{r=Wo(new Lo(e,t).parseDocument())}catch{}return{query:e,operationName:r}}var t;const r=Wo(e);return{query:zo(e),operationName:r}}const Qo=/^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;function Xo(e,t){const{subdomain:r,region:n}=e;if(!r)throw new Error("A `subdomain` must be set.");const i=r.match(Qo);if(null!=i&&i.groups){const{protocol:e,host:r,port:n}=i.groups,o=function(e){return"undefined"==typeof window&&"undefined"!=typeof process&&process.env?process.env[`NHOST_${e.toUpperCase()}_URL`]:null}(t);return o||("localhost"===r?(console.warn('The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.'),`${e||"http"}://localhost:${n||1337}/v1/${t}`):n?`${e||"https"}://local.${t}.nhost.run:${n}/v1`:`${e||"https"}://local.${t}.nhost.run/v1`)}if(!n)throw new Error('`region` must be set when using a `subdomain` other than "local".');return`https://${r}.${t}.${n}.nhost.run/v1`}class Zo{constructor(e){this.headers={};const{url:t,adminSecret:r}=e;this.url=t,this.accessToken=null,this.adminSecret=r}async call(e,t,r){var n,i;const o={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...null==r?void 0:r.headers,...this.headers},s=function(e,t){return e+(t.startsWith("/")?t:`/${t}`)}(this.url,e);try{const e=await Pi(s,{body:t?JSON.stringify(t):null,headers:o,method:"POST"});if(!e.ok){let t;return t=null!=(n=e.headers.get("content-type"))&&n.includes("application/json")?await e.json():await e.text(),{res:null,error:{message:t,error:e.statusText,status:e.status}}}let r;return r=null!=(i=e.headers.get("content-type"))&&i.includes("application/json")?await e.json():await e.text(),{res:{data:r,status:e.status,statusText:e.statusText},error:null}}catch(a){const e=a;return{res:null,error:{message:e.message,status:"AbortError"===e.name?0:500,error:"AbortError"===e.name?"abort-error":"unknown"}}}}setAccessToken(e){this.accessToken=e||null}getHeaders(){return this.headers}setHeaders(e){e&&(this.headers={...this.headers,...e})}unsetHeaders(){const e=this.headers["x-hasura-role"];this.headers=e?{"x-hasura-role":e}:{}}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function es(e){const t="subdomain"in e?Xo(e,"graphql"):e.graphqlUrl;if(!t)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new class{constructor(e){this.headers={},this.isAccessTokenValidOrNull=()=>{if(!this.accessToken)return!0;try{const e=ct(this.accessToken);return null!=e.exp&&1e3*e.exp>Date.now()}catch(t){return console.error("Error decoding token:",t),!1}},this.awaitForValidAccessTokenOrNull=async()=>{if(this.isAccessTokenValidOrNull())return!0;const e=()=>this.isAccessTokenValidOrNull()?Promise.resolve(!0):new Promise((t=>{setTimeout((()=>e().then(t)),100)}));return e()};const{url:r,adminSecret:n}=e;this._url=r,this.accessToken=null,this.adminSecret=n}async request(e,...t){const[r,n]=t,i=function(e,t,r){return e.document?e:{document:e,variables:t,config:r}}(e,r,n),{headers:o,...s}=n||{},{query:a,operationName:c}=Jo(i.document);"undefined"!=typeof process&&!process.env.TEST_MODE&&await this.awaitForValidAccessTokenOrNull();try{const e=await Pi(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:c,query:a,variables:r}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...this.headers,...o},...s});if(!e.ok)return{data:null,error:{error:e.statusText,message:e.statusText,status:e.status}};const{data:t,errors:n}=await e.json();return n?{data:null,error:n}:"object"!=typeof t||Array.isArray(t)||null===t?{data:null,error:{error:"invalid-response",message:"incorrect response data from GraphQL server",status:0}}:{data:t,error:null}}catch(l){const e=l;return{data:null,error:{message:e.message,status:"AbortError"===e.name?0:500,error:"AbortError"===e.name?"abort-error":"unknown"}}}}get httpUrl(){return this._url}get wsUrl(){return this._url.replace(/^(http)(s?):\/\//,"ws$2://")}get url(){return this._url}getUrl(){return this._url}setAccessToken(e){this.accessToken=e||null}getHeaders(){return this.headers}setHeaders(e){e&&(this.headers={...this.headers,...e})}unsetHeaders(){const e=this.headers["x-hasura-role"];this.headers=e?{"x-hasura-role":e}:{}}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}({url:t,...e})}class ts{constructor({refreshIntervalTime:e,clientStorage:t,clientStorageType:r,autoRefreshToken:n,autoSignIn:i,adminSecret:o,devTools:s,start:a=!0,...c}){this.auth=function(e){const t="subdomain"in e?Xo(e,"auth"):e.authUrl;if(!t)throw new Error("Please provide `subdomain` or `authUrl`.");return new _i({url:t,...e})}({refreshIntervalTime:e,clientStorage:t,clientStorageType:r,autoRefreshToken:n,autoSignIn:i,start:a,...c}),this.storage=function(e){const t="subdomain"in e?Xo(e,"storage"):e.storageUrl;if(!t)throw new Error("Please provide `subdomain` or `storageUrl`.");return new Ii({url:t,...e})}({adminSecret:o,...c}),this.functions=function(e){const t="subdomain"in e?Xo(e,"functions"):e.functionsUrl;if(!t)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new Zo({url:t,...e})}({adminSecret:o,...c}),this.graphql=es({adminSecret:o,...c}),this.auth.onAuthStateChanged(((e,t)=>{if("SIGNED_OUT"===e)return this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),void this.graphql.setAccessToken(void 0);const r=null==t?void 0:t.accessToken;this.storage.setAccessToken(r),this.functions.setAccessToken(r),this.graphql.setAccessToken(r)})),this.auth.onTokenChanged((e=>{const t=null==e?void 0:e.accessToken;this.storage.setAccessToken(t),this.functions.setAccessToken(t),this.graphql.setAccessToken(t)})),this._adminSecret=o,this.devTools=s}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}setRole(e){this.graphql.setHeaders({"x-hasura-role":e}),this.storage.setHeaders({"x-hasura-role":e}),this.functions.setHeaders({"x-hasura-role":e})}unsetRole(){this.graphql.setHeaders((({"x-hasura-role":e,...t})=>t)(this.graphql.getHeaders())),this.storage.setHeaders((({"x-hasura-role":e,...t})=>t)(this.storage.getHeaders())),this.functions.setHeaders((({"x-hasura-role":e,...t})=>t)(this.functions.getHeaders()))}}var rs=Object.defineProperty,ns=(e,t,r,n)=>{for(var i,o=void 0,s=e.length-1;s>=0;s--)(i=e[s])&&(o=i(t,r,o)||o);return o&&rs(t,r,o),o};const is=e=>({items:e.lines.edges.map((({node:e})=>({id:e.id,key:e.id,variant_id:e.merchandise.id,sku:e.merchandise.sku,final_line_price:parseFloat(e.cost.totalAmount.amount),quantity:e.quantity}))),total_price:parseFloat(e.cost.totalAmount.amount),item_count:e.lines.edges.length}),os=async(e,t)=>{try{const r=await fetch(e,t);if(!r.ok)throw new Error(await r.text());return await r.json()}catch(r){throw console.error(r),new Error("Failed to complete fetch request.")}},ss=e=>console.warn(`[ShipAid] ${e}`),as=e=>console.error(`[ShipAid] ${e}`),cs="shipaid-protection",ls="shipaid-protection-popup-show",us="query StoreByDomain ($store: String!) {\n store: storeByDomain (input: {store: $store}) {\n currency\n planActive\n store\n widgetAutoOptIn\n widgetPollProtection\n widgetShowCart\n excludedProductSkus\n excludedCustomersIdsAutoOptIn\n protectionSettings\n widgetConfigurations\n }\n}",ds=Object.assign({"./lang/de.json":()=>Promise.resolve().then((()=>Es)).then((e=>e.default)),"./lang/en.json":()=>Promise.resolve().then((()=>nt)).then((e=>e.default)),"./lang/es.json":()=>Promise.resolve().then((()=>Cs)).then((e=>e.default)),"./lang/fr.json":()=>Promise.resolve().then((()=>Ds)).then((e=>e.default)),"./lang/it.json":()=>Promise.resolve().then((()=>zs)).then((e=>e.default)),"./lang/pt.json":()=>Promise.resolve().then((()=>Ws)).then((e=>e.default))});var hs;hs={loader:async e=>{if("en"===e)return rt;const t=Reflect.get(ds,`./lang/${e}.json`);return t?await t():rt}},ge=Object.assign(Object.assign({},ge),hs);const ps=class extends de{constructor(){var e,t,r;super(...arguments),this.env="prod",this.useCustomStoreFront=!1,this.storeDomain="",this.storeAccessToken="",this.cartId="",this.disablePolling=!1,this.disableActions=!1,this.pollingInterval=2500,this.disableRefresh=!1,this.refreshCart=!1,this.persistPopup=!1,this.defaultToggleButton=!1,this.lang="en",this.currency=void 0,this.customerId=void 0,this.supportSubscriptions=!1,this._apiEndpoint="/apps/shipaid",this._storeDomain=(null==(e=window.Shopify)?void 0:e.shop)??(null==(r=null==(t=window.Shopify)?void 0:t.Checkout)?void 0:r.apiHost),this._hasFinishedSetup=!1,this._shouldShowWidget=!1,this._hasProtectionInCart=!1,this.hasLoadedStrings=!1,this.fetchInterceptorCleanup=()=>{},this.intervalId=null,this._state={loading:!1,success:null,error:!1},this._popup=null,this._fetch={get:e=>os(e),post:(e,t)=>os(e,{method:"POST",headers:{"Content-Type":"application/json","X-ShipAid":"1"},body:JSON.stringify(t)})}}shouldUpdate(e){return this.hasLoadedStrings&&super.shouldUpdate(e)}shouldPersistPopup(){return"true"===localStorage.getItem(`${ls}`)?"learn-more":null}setPopupKey(){this.persistPopup&&localStorage.setItem(`${ls}`,"true")}get nhost(){return new ts({subdomain:"prod"===this.env?"gjiyysyzjwuculcymsvb":"staging"===this.env?"xfnjpunvafvudwuzwjlm":"local",region:"us-east-1"})}async runStoreFrontQuery(e,t){try{const r=new Headers;r.append("Content-Type","application/json"),r.append("X-Shopify-Storefront-Access-Token",this.storeAccessToken);const n={method:"POST",headers:r,body:JSON.stringify({query:e,variables:t})},i=await fetch(`https://${this.storeDomain}/api/2021-07/graphql.json`,n);if(!i.ok)throw new Error(`GraphQL request failed: ${i.statusText}`);const o=await i.json();if(o.errors)throw new Error(o.errors[0].message);return o.data}catch(r){throw console.error("GraphQL query error:",r),new Error("Failed to execute GraphQL query")}}get shouldRefreshOnUpdate(){return!this.disablePolling&&!this.disableRefresh}get planActive(){var e,t;const{searchParams:r}=new URL(window.location.href);return(null==(e=window.Shopify)?void 0:e.designMode)||r.has("shipaid-test")?(ss("Currently in preview mode."),!0):!!(null==(t=this._store)?void 0:t.planActive)}_currencyFormat(e){var t,r,n,i,o,s;const a=this.currency||(null==(r=null==(t=window.Shopify)?void 0:t.currency)?void 0:r.active)||(null==(n=this._store)?void 0:n.currency)||"USD";if(null==(s=null==(o=null==(i=this._store)?void 0:i.widgetConfigurations)?void 0:o.widget)?void 0:s.currencyFormat){return this._store.widgetConfigurations.widget.currencyFormat.replace("_value_",Number(e)).replace("_currency_",a)}return new Intl.NumberFormat(void 0,{currency:a,style:"currency"}).format(Number(e))}_dispatchEvent(e,t={}){this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:t}))}_handleRefreshCart(){if(this.refreshCart)return window.location.reload()}async _handleRefresh(e){const t=Reflect.has(e,"items");if(this.shouldRefreshOnUpdate)return window.location.reload();t||await this.updateCart(),this._dispatchEvent(ot.STATUS_UPDATE,{protection:this._hasProtectionInCart,cart:t?e:this._cart,lineItem:t?this._protectionCartItem:e})}async calculateProtectionTotal(e){if(e||(e=await this._fetchCart()),!e)throw new Error("Could not fetch cart.");if(!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return r.calculateProtectionTotal(this._store,this._protectionProduct,e)}_findProtectionVariant(e){if(!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return r.findProtectionVariant(this._store,this._protectionProduct,e)}_setState(e,t){this._state={loading:"loading"===e,success:"success"===e,error:"error"===e&&(t||!0)}}_handleConfirmationPopup(){"confirmation"!==this._popup&&(this._popup="confirmation")}_updateProtection(){var e,t,r;const n=null==(r=null==(t=null==(e=this._store)?void 0:e.widgetConfigurations)?void 0:t.widget)?void 0:r.removeWithConfirmation;return this._hasProtectionInCart?n?this._handleConfirmationPopup():this.removeProtection():this.addProtection()}async _fetchShipAidData(){var e,t,r,n,i;let o;if(o=this.storeDomain?this.storeDomain:(null==(e=window.Shopify)?void 0:e.shop)??(null==(r=null==(t=window.Shopify)?void 0:t.Checkout)?void 0:r.apiHost),!o)throw new Error("No shop found in Shopify object.");try{let e,t;if(this.useCustomStoreFront)t=await this.nhost.graphql.request(us,{store:o});else{e=new URL(window.location.href),e.pathname=this._apiEndpoint;const r={query:us,variables:{store:o}};t=await this._fetch.post(e.toString(),r)}if(!t)throw new Error("Missing response for store query.");if(null==(n=t.errors)?void 0:n.length)throw new Error(t.errors[0].message);if(!(null==(i=t.data)?void 0:i.store))throw new Error("Missing store from store query response.");return t.data.store}catch(s){throw console.error(s),new Error(`Could not find a store for ${this._storeDomain}`)}}_findSellingPlanByName(e,t){for(const r of e){const e=r.node;for(const r of e.sellingPlans.edges){const e=r.node;if(t===e.name)return e}}return null}async _fetchSellingPlanFromVariant(e){var t,r,n,i,o,s,a,c,l,u,d,h,p;const f=(null==(t=window.Shopify)?void 0:t.shop)??(null==(n=null==(r=window.Shopify)?void 0:r.Checkout)?void 0:n.apiHost);if(!f)throw new Error("No shop found in Shopify object.");try{const t=new URL(window.location.href);t.pathname=this._apiEndpoint;const r={query:"query SellingPlanFromVariant($store: String!, $variantId: String!){\n sellingPlanFromVariant(input: {store: $store, variantId: $variantId })\n}",variables:{store:f,variantId:`gid://shopify/ProductVariant/${null==(i=this._protectionVariant)?void 0:i.id}`}},n=await this._fetch.post(t.toString(),r);if(!n)throw new Error("Missing response for selling plan query.");if(null==(o=n.errors)?void 0:o.length)throw new Error(n.errors[0].message);if(!(null==(s=n.data)?void 0:s.sellingPlanFromVariant))throw new Error("Missing variant from selling plan query response.");const v=(null==(c=null==(a=n.data.sellingPlanFromVariant)?void 0:a.sellingPlanGroups)?void 0:c.edges)||[],m=(null==(p=null==(h=null==(d=null==(u=null==(l=v[0])?void 0:l.node)?void 0:u.sellingPlans)?void 0:d.edges)?void 0:h[0])?void 0:p.node)||null;return this._findSellingPlanByName(v,e.name)||m}catch(v){console.error("Error during the query ====>",v)}}async _fetchCart(){try{if(this.useCustomStoreFront&&this.cartId){const e=await this.runStoreFrontQuery("query getCart($cartId: ID!){ cart( id: $cartId ) { id createdAt updatedAt lines(first: 10) { edges { node { id quantity merchandise { ... on ProductVariant { id sku } } cost{ totalAmount{ amount currencyCode } } } } } cost { totalAmount { amount currencyCode } subtotalAmount { amount currencyCode } } } }",{cartId:this.cartId});return is(e.cart)}return await this._fetch.get("/cart.js")}catch(e){throw as(e.message),new Error("Could not fetch cart for current domain.")}}async _fetchProduct(){var e,t;try{let r;if(this.useCustomStoreFront){const n=await this.runStoreFrontQuery("query searchProducts($query: String!, $first: Int) { search(query: $query, first: $first, types: PRODUCT) { edges { node { ... on Product { id title handle variants(first: 1) { edges { node { id title price { amount } } } } } } } } }",{query:"ShipAid Delivery Guarantee",first:1});if(null==(t=null==(e=null==n?void 0:n.search)?void 0:e.edges)?void 0:t.length){const e=n.search.edges[0];r={id:e.node.id,variants:e.node.variants.edges.map((e=>({id:e.node.id,price:e.node.price.amount})))}}}else r=(await this._fetch.get("/products/shipaid-protection.json")).product;return r}catch(r){throw as(r.message),new Error("Could not fetch protection product for current domain.")}}hasProtection(){return this._hasProtectionInCart}async updateCart(e){e||(e=await this._fetchCart()),this._cart=e}async addCartProtectionVariant(){var e,r,n,i;let o,s;if(this.supportSubscriptions){const n=null==(r=null==(e=this._cart)?void 0:e.items)?void 0:r.find((e=>{var t;return e.id!==(null==(t=this._protectionVariant)?void 0:t.id)&&!!(null==e?void 0:e.selling_plan_allocation)}));if(n){const e=await this._fetchSellingPlanFromVariant(n.selling_plan_allocation.selling_plan);s=e?t(e.id):null}}if(this.useCustomStoreFront){const e=await this.runStoreFrontQuery("mutation AddItemToCart($cartId: ID!, $lines: [CartLineInput!]!) { cartLinesAdd(cartId: $cartId, lines: $lines) { cart { id lines(first: 10) { edges { node { id quantity merchandise { ... on ProductVariant { id sku } } cost{ totalAmount{ amount currencyCode } } } } } cost { totalAmount { amount currencyCode } subtotalAmount { amount currencyCode } } } } }",{cartId:this.cartId,lines:[{merchandiseId:String(null==(n=this._protectionVariant)?void 0:n.id),quantity:1,sellingPlanId:s}]});o=is(e.cartLinesAdd.cart)}else{const e={quantity:1,id:String(null==(i=this._protectionVariant)?void 0:i.id),selling_plan:s};o=await this._fetch.post("/cart/add.js",e)}return o}async updateCartProtectionVariant(e,t=null,r=null){var n,i;let o;if(this.useCustomStoreFront){const i=await this.runStoreFrontQuery("mutation RemoveItemToCart($cartId: ID!, $lines: [CartLineUpdateInput!]!) { cartLinesUpdate(cartId: $cartId, lines: $lines) { cart { id lines(first: 10) { edges { node { id quantity merchandise { ... on ProductVariant { id sku } } cost{ totalAmount{ amount currencyCode } } } } } cost { totalAmount { amount currencyCode } subtotalAmount { amount currencyCode } } } } }",{cartId:this.cartId,lines:[{id:String(t?t.key:null==(n=this._protectionCartItem)?void 0:n.key),quantity:e,sellingPlanId:r}]});o=is(i.cartLinesUpdate.cart)}else{const n={quantity:e,id:String(t?t.key:null==(i=this._protectionCartItem)?void 0:i.key),selling_plan:r};o=await this._fetch.post("/cart/change.js",n)}return o}async addProtection(){var e,t;try{if(!this._store)throw new Error("Store has not been loaded.");if(!(null==(e=this._cart)?void 0:e.items))throw new Error("Cart has not been loaded.");if(!(null==(t=this._protectionVariant)?void 0:t.id))throw new Error("No protection variant found.");this._setState("loading");const r=await this.addCartProtectionVariant();await this._handleRefresh(r),this._setState("success")}catch(r){as(r.message)}finally{this._cart=await this._fetchCart(),this._setState("success")}}async removeProtection(){try{if(!this._store)throw new Error("Store has not been loaded.");if(!this._protectionCartItem)throw new Error("Protection product not found.");this._setState("loading");const e=await this.updateCartProtectionVariant(0,this._protectionCartItem);await this._handleRefresh(e),this._cart=e,this._setState("success")}catch(e){as(e.message)}finally{this._cart=await this._fetchCart(),this._setState("success")}}async attemptAddProtection(){var e,t,r,n,i,o;if(!(null==(e=this._store)?void 0:e.widgetAutoOptIn))return;if(!(null==(t=this._cart)?void 0:t.items)||!(null==(r=this._cart)?void 0:r.item_count))return;const s=null==(n=this._cart.items)?void 0:n.findIndex((e=>{var t,r;return null==(r=null==(t=this._protectionProduct)?void 0:t.variants)?void 0:r.some((t=>t.id===e.variant_id))})),a=null==(i=this._cart)?void 0:i.items[s];if(this._hasProtectionInCart=!!a,1===this._cart.item_count&&a)return;!!sessionStorage.getItem(cs)||!this._hasProtectionInCart&&(null==(o=this._cart)?void 0:o.item_count)&&this._store.widgetShowCart&&(await this.addProtection(),sessionStorage.setItem(cs,JSON.stringify({loaded:!0})))}async handleMultipleProtectionVariants(){var e,t,r,n,i;if(!(null==(e=this._cart)?void 0:e.items)||!(null==(t=this._cart)?void 0:t.item_count))return;let o=0;if(null==(r=this._cart.items)||r.forEach((e=>{var t,r;(null==(r=null==(t=this._protectionProduct)?void 0:t.variants)?void 0:r.some((t=>t.id===e.variant_id)))&&o++})),o>1){const e=null==(n=this._cart.items)?void 0:n.findIndex((e=>{var t,r;return null==(r=null==(t=this._protectionProduct)?void 0:t.variants)?void 0:r.some((t=>t.id===e.variant_id))})),t=null==(i=this._cart)?void 0:i.items[e],r=await this.updateCartProtectionVariant(0,t);return await this._handleRefresh(r)}}learnMorePopupTemplate(){return H`
|
|
958
|
+
`;var ne=(t=>(t.LOADED="shipaid-loaded",t.STATUS_UPDATE="shipaid-protection-status",t))(ne||{});var ae=Object.defineProperty,pe=(t,e,i,o)=>{for(var r,s=void 0,n=t.length-1;n>=0;n--)(r=t[n])&&(s=r(e,i,s)||s);return s&&ae(e,i,s),s};const de=async(t,e)=>{try{const i=await fetch(t,e);if(!i.ok)throw new Error(await i.text());return await i.json()}catch(i){throw console.error(i),new Error("Failed to complete fetch request.")}},le=t=>console.warn(`[ShipAid] ${t}`),ce=t=>console.error(`[ShipAid] ${t}`),he="shipaid-protection",ue="shipaid-protection-popup-show",fe=Object.assign({"./lang/de.json":()=>Promise.resolve().then((()=>$e)).then((t=>t.default)),"./lang/en.json":()=>Promise.resolve().then((()=>re)).then((t=>t.default)),"./lang/es.json":()=>Promise.resolve().then((()=>Ee)).then((t=>t.default)),"./lang/fr.json":()=>Promise.resolve().then((()=>je)).then((t=>t.default)),"./lang/it.json":()=>Promise.resolve().then((()=>Fe)).then((t=>t.default)),"./lang/pt.json":()=>Promise.resolve().then((()=>Xe)).then((t=>t.default))});var me;me={loader:async t=>{if("en"===t)return oe;const e=Reflect.get(fe,`./lang/${t}.json`);return e?await e():oe}},bt=Object.assign(Object.assign({},bt),me);const ge=class extends ht{constructor(){var t,e,i;super(...arguments),this.disablePolling=!1,this.disableActions=!1,this.pollingInterval=2500,this.disableRefresh=!1,this.refreshCart=!1,this.persistPopup=!1,this.defaultToggleButton=!1,this.lang="en",this.currency=void 0,this.customerId=void 0,this.supportSubscriptions=!1,this._apiEndpoint="/apps/shipaid",this._storeDomain=(null==(t=window.Shopify)?void 0:t.shop)??(null==(i=null==(e=window.Shopify)?void 0:e.Checkout)?void 0:i.apiHost),this._hasFinishedSetup=!1,this._shouldShowWidget=!1,this._hasProtectionInCart=!1,this.hasLoadedStrings=!1,this.fetchInterceptorCleanup=()=>{},this.intervalId=0,this._state={loading:!1,success:null,error:!1},this._popup=null,this._fetch={get:t=>de(t),post:(t,e)=>de(t,{method:"POST",headers:{"Content-Type":"application/json","X-ShipAid":"1"},body:JSON.stringify(e)})}}shouldUpdate(t){return this.hasLoadedStrings&&super.shouldUpdate(t)}shouldPersistPopup(){return"true"===localStorage.getItem(`${ue}`)?"learn-more":null}setPopupKey(){this.persistPopup&&localStorage.setItem(`${ue}`,"true")}get shouldRefreshOnUpdate(){return!this.disablePolling&&!this.disableRefresh}get planActive(){var t,e;const{searchParams:i}=new URL(window.location.href);return(null==(t=window.Shopify)?void 0:t.designMode)||i.has("shipaid-test")?(le("Currently in preview mode."),!0):!!(null==(e=this._store)?void 0:e.planActive)}_currencyFormat(t){var e,i,o,r,s,n;const a=this.currency||(null==(i=null==(e=window.Shopify)?void 0:e.currency)?void 0:i.active)||(null==(o=this._store)?void 0:o.currency)||"USD";if(null==(n=null==(s=null==(r=this._store)?void 0:r.widgetConfigurations)?void 0:s.widget)?void 0:n.currencyFormat){return this._store.widgetConfigurations.widget.currencyFormat.replace("_value_",Number(t)).replace("_currency_",a)}return new Intl.NumberFormat(void 0,{currency:a,style:"currency"}).format(Number(t))}_dispatchEvent(t,e={}){this.dispatchEvent(new CustomEvent(t,{bubbles:!0,composed:!0,detail:e}))}_handleRefreshCart(){if(this.refreshCart)return window.location.reload()}async _handleRefresh(t){const e=Reflect.has(t,"items");if(this.shouldRefreshOnUpdate)return window.location.reload();e||await this.updateCart(),this._dispatchEvent(ne.STATUS_UPDATE,{protection:this._hasProtectionInCart,cart:e?t:this._cart,lineItem:e?this._protectionCartItem:t})}async calculateProtectionTotal(t){if(t||(t=await this._fetchCart()),!t)throw new Error("Could not fetch cart.");if(!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return i.calculateProtectionTotal(this._store,this._protectionProduct,t)}_findProtectionVariant(t){if(!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return i.findProtectionVariant(this._store,this._protectionProduct,t)}_setState(t,e){this._state={loading:"loading"===t,success:"success"===t,error:"error"===t&&(e||!0)}}_handleConfirmationPopup(){"confirmation"!==this._popup&&(this._popup="confirmation")}_updateProtection(){var t,e,i;const o=null==(i=null==(e=null==(t=this._store)?void 0:t.widgetConfigurations)?void 0:e.widget)?void 0:i.removeWithConfirmation;return this._hasProtectionInCart?o?this._handleConfirmationPopup():this.removeProtection():this.addProtection()}async _fetchShipAidData(){var t,e,i,o,r;const s=(null==(t=window.Shopify)?void 0:t.shop)??(null==(i=null==(e=window.Shopify)?void 0:e.Checkout)?void 0:i.apiHost);if(!s)throw new Error("No shop found in Shopify object.");try{const t=new URL(window.location.href);t.pathname=this._apiEndpoint;const e={query:"query StoreByDomain ($store: String!) {\n store: storeByDomain (input: {store: $store}) {\n currency\n planActive\n store\n widgetAutoOptIn\n widgetPollProtection\n widgetShowCart\n excludedProductSkus\n excludedCustomersIdsAutoOptIn\n protectionSettings\n widgetConfigurations\n }\n}",variables:{store:s}},i=await this._fetch.post(t.toString(),e);if(!i)throw new Error("Missing response for store query.");if(null==(o=i.errors)?void 0:o.length)throw new Error(i.errors[0].message);if(!(null==(r=i.data)?void 0:r.store))throw new Error("Missing store from store query response.");return i.data.store}catch(n){throw console.error(n),new Error(`Could not find a store for ${this._storeDomain}`)}}_findSellingPlanByName(t,e){for(const i of t){const t=i.node;for(const i of t.sellingPlans.edges){const t=i.node;if(e===t.name)return t}}return null}async _fetchSellingPlanFromVariant(t){var e,i,o,r,s,n,a,p,d,l,c,h,u;const f=(null==(e=window.Shopify)?void 0:e.shop)??(null==(o=null==(i=window.Shopify)?void 0:i.Checkout)?void 0:o.apiHost);if(!f)throw new Error("No shop found in Shopify object.");try{const e=new URL(window.location.href);e.pathname=this._apiEndpoint;const i={query:"query SellingPlanFromVariant($store: String!, $variantId: String!){\n sellingPlanFromVariant(input: {store: $store, variantId: $variantId })\n}",variables:{store:f,variantId:`gid://shopify/ProductVariant/${null==(r=this._protectionVariant)?void 0:r.id}`}},o=await this._fetch.post(e.toString(),i);if(!o)throw new Error("Missing response for selling plan query.");if(null==(s=o.errors)?void 0:s.length)throw new Error(o.errors[0].message);if(!(null==(n=o.data)?void 0:n.sellingPlanFromVariant))throw new Error("Missing variant from selling plan query response.");const m=(null==(p=null==(a=o.data.sellingPlanFromVariant)?void 0:a.sellingPlanGroups)?void 0:p.edges)||[],g=(null==(u=null==(h=null==(c=null==(l=null==(d=m[0])?void 0:d.node)?void 0:l.sellingPlans)?void 0:c.edges)?void 0:h[0])?void 0:u.node)||null;return this._findSellingPlanByName(m,t.name)||g}catch(m){console.error("Error during the query ====>",m)}}async _fetchCart(){try{return await this._fetch.get("/cart.js")}catch(t){throw ce(t.message),new Error("Could not fetch cart for current domain.")}}async _fetchProduct(){try{const{product:t}=await this._fetch.get("/products/shipaid-protection.json");return t}catch(t){throw ce(t.message),new Error("Could not fetch protection product for current domain.")}}hasProtection(){return this._hasProtectionInCart}async updateCart(t){t||(t=await this._fetchCart()),this._cart=t}async addProtection(){var t,i;try{if(!this._store)throw new Error("Store has not been loaded.");if(!(null==(t=this._cart)?void 0:t.items))throw new Error("Cart has not been loaded.");if(!(null==(i=this._protectionVariant)?void 0:i.id))throw new Error("No protection variant found.");this._setState("loading");const o={quantity:1,id:this._protectionVariant.id};if(this.supportSubscriptions){const t=this._cart.items.find((t=>{var e;return t.id!==(null==(e=this._protectionVariant)?void 0:e.id)&&!!(null==t?void 0:t.selling_plan_allocation)}));if(t){const i=await this._fetchSellingPlanFromVariant(t.selling_plan_allocation.selling_plan),r=i?e(i.id):null;o.selling_plan=r}}const r=await this._fetch.post("/cart/add.js",o);await this._handleRefresh(r),this._setState("success")}catch(o){ce(o.message)}finally{this._cart=await this._fetchCart(),this._setState("success")}}async removeProtection(){try{if(!this._store)throw new Error("Store has not been loaded.");if(!this._protectionCartItem)throw new Error("Protection product not found.");this._setState("loading");const t={quantity:0,id:this._protectionCartItem.key},e=await this._fetch.post("/cart/change.js",t);await this._handleRefresh(e),this._cart=e,this._setState("success")}catch(t){ce(t.message)}finally{this._cart=await this._fetchCart(),this._setState("success")}}async attemptAddProtection(){var t,e,i,o,r,s;if(!(null==(t=this._store)?void 0:t.widgetAutoOptIn))return;if(!(null==(e=this._cart)?void 0:e.items)||!(null==(i=this._cart)?void 0:i.item_count))return;const n=null==(o=this._cart.items)?void 0:o.findIndex((t=>{var e,i;return null==(i=null==(e=this._protectionProduct)?void 0:e.variants)?void 0:i.some((e=>e.id===t.variant_id))})),a=null==(r=this._cart)?void 0:r.items[n];if(this._hasProtectionInCart=!!a,1===this._cart.item_count&&a)return;!!sessionStorage.getItem(he)||!this._hasProtectionInCart&&(null==(s=this._cart)?void 0:s.item_count)&&this._store.widgetShowCart&&(await this.addProtection(),sessionStorage.setItem(he,JSON.stringify({loaded:!0})))}async handleMultipleProtectionVariants(){var t,e,i,o,r;if(!(null==(t=this._cart)?void 0:t.items)||!(null==(e=this._cart)?void 0:e.item_count))return;let s=0;if(null==(i=this._cart.items)||i.forEach((t=>{var e,i;(null==(i=null==(e=this._protectionProduct)?void 0:e.variants)?void 0:i.some((e=>e.id===t.variant_id)))&&s++})),s>1){const t=null==(o=this._cart.items)?void 0:o.findIndex((t=>{var e,i;return null==(i=null==(e=this._protectionProduct)?void 0:e.variants)?void 0:i.some((e=>e.id===t.variant_id))})),e={id:(null==(r=this._cart)?void 0:r.items[t]).key,quantity:0},i=await this._fetch.post("/cart/change.js",e);return await this._handleRefresh(i)}}learnMorePopupTemplate(){return F`
|
|
974
959
|
<shipaid-popup-learn-more
|
|
975
960
|
?active=${"learn-more"===this._popup}
|
|
976
|
-
@close=${()=>{this.persistPopup&&localStorage.removeItem(`${
|
|
961
|
+
@close=${()=>{this.persistPopup&&localStorage.removeItem(`${ue}`),this._popup=null}}
|
|
977
962
|
></shipaid-popup-learn-more>
|
|
978
|
-
`}confirmationPopupTemplate(){return
|
|
963
|
+
`}confirmationPopupTemplate(){return F`
|
|
979
964
|
<shipaid-popup-confirmation
|
|
980
965
|
?active=${"confirmation"===this._popup}
|
|
981
|
-
@close=${()=>{this.persistPopup&&localStorage.removeItem(`${
|
|
982
|
-
@remove-protection=${()=>{this.removeProtection(),this.persistPopup&&localStorage.removeItem(`${
|
|
966
|
+
@close=${()=>{this.persistPopup&&localStorage.removeItem(`${ue}`),this._popup=null}}
|
|
967
|
+
@remove-protection=${()=>{this.removeProtection(),this.persistPopup&&localStorage.removeItem(`${ue}`),this._popup=null}}
|
|
983
968
|
></shipaid-popup-confirmation>
|
|
984
|
-
`}renderPopups(){switch(this.persistPopup&&(this._popup=this.shouldPersistPopup()),this._popup){case"confirmation":return this.confirmationPopupTemplate();case"learn-more":return this.learnMorePopupTemplate();default:return null}}promptTemplate(){var e,
|
|
969
|
+
`}renderPopups(){switch(this.persistPopup&&(this._popup=this.shouldPersistPopup()),this._popup){case"confirmation":return this.confirmationPopupTemplate();case"learn-more":return this.learnMorePopupTemplate();default:return null}}promptTemplate(){var t,e,i;const{useToggle:o,useCheckbox:r,leftCheckbox:s}=(null==(e=null==(t=this._store)?void 0:t.widgetConfigurations)?void 0:e.widget)||{useToggle:!1,useCheckbox:!1,leftCheckbox:!1};return F`
|
|
985
970
|
<div class="shipaid-prompt">
|
|
986
971
|
<div class="prompt-product">
|
|
987
|
-
${
|
|
972
|
+
${Tt(!this.disableActions&&s,(()=>F`
|
|
988
973
|
<label class="shipaid-checkbox">
|
|
989
|
-
${this._hasProtectionInCart||!this._hasFinishedSetup?
|
|
974
|
+
${this._hasProtectionInCart||!this._hasFinishedSetup?F`<input type="checkbox" checked @click=${this._updateProtection} ?disabled=${this._state.loading}>`:F`<input type="checkbox" @click=${this._updateProtection} ?disabled=${this._state.loading}>`}
|
|
990
975
|
<span class="shipaid-checkMark left"></span>
|
|
991
976
|
</label>
|
|
992
977
|
`))}
|
|
993
978
|
<div class="prompt-product-image">
|
|
994
|
-
${
|
|
979
|
+
${Tt(this._hasProtectionInCart,(()=>jt),(()=>Ot))}
|
|
995
980
|
</div>
|
|
996
981
|
<div class="prompt-product-details">
|
|
997
982
|
<p class="prompt-product-details-title">
|
|
998
|
-
<slot name="title">${
|
|
983
|
+
<slot name="title">${zt("title")}</slot>
|
|
999
984
|
</p>
|
|
1000
985
|
<p class="prompt-product-details-description">
|
|
1001
|
-
<slot name="subtitle">${
|
|
986
|
+
<slot name="subtitle">${zt("description")}</slot>
|
|
1002
987
|
</p>
|
|
1003
988
|
</div>
|
|
1004
989
|
<div class="prompt-product-actions">
|
|
1005
990
|
<p class="prompt-product-actions-price">
|
|
1006
|
-
${(null==(
|
|
991
|
+
${(null==(i=this._protectionVariant)?void 0:i.price)&&this._currencyFormat(this._protectionVariant.price)}
|
|
1007
992
|
</p>
|
|
1008
|
-
${
|
|
1009
|
-
<label class="shipaid-${
|
|
1010
|
-
${this._hasProtectionInCart||!this._hasFinishedSetup?
|
|
1011
|
-
<span class="shipaid-${
|
|
993
|
+
${o||r||this.defaultToggleButton?Tt(!this.disableActions&&!s,(()=>F`
|
|
994
|
+
<label class="shipaid-${o?"toggle":r?"checkbox":""}">
|
|
995
|
+
${this._hasProtectionInCart||!this._hasFinishedSetup?F`<input type="checkbox" checked @click=${this._updateProtection} ?disabled=${this._state.loading}>`:F`<input type="checkbox" @click=${this._updateProtection} ?disabled=${this._state.loading}>`}
|
|
996
|
+
<span class="shipaid-${o?"slider":r?"checkMark":""}"></span>
|
|
1012
997
|
</label>
|
|
1013
|
-
`)):
|
|
998
|
+
`)):Tt(!this.disableActions,(()=>F`
|
|
1014
999
|
<button
|
|
1015
1000
|
class="prompt-product-actions-button"
|
|
1016
1001
|
@click=${this._updateProtection}
|
|
1017
1002
|
?disabled=${this._state.loading}
|
|
1018
1003
|
>
|
|
1019
|
-
${this._state.loading?
|
|
1004
|
+
${this._state.loading?zt("actions.loading"):this._hasProtectionInCart?zt("actions.remove"):F`+ ${zt("actions.add")}`}
|
|
1020
1005
|
</button>
|
|
1021
1006
|
`))}
|
|
1022
1007
|
</div>
|
|
1023
1008
|
</div>
|
|
1024
|
-
${
|
|
1009
|
+
${Tt(this._state.error,(()=>F`<p class="error">${this._state.error}</p>`))}
|
|
1025
1010
|
<div class="prompt-footer">
|
|
1026
1011
|
<a
|
|
1027
1012
|
class="prompt-footer-badge"
|
|
1028
1013
|
@click=${()=>{this._popup="learn-more",this.persistPopup&&this.setPopupKey()}}
|
|
1029
1014
|
>
|
|
1030
|
-
<span>${
|
|
1031
|
-
${
|
|
1015
|
+
<span>${zt("footer.button")}</span>
|
|
1016
|
+
${Rt}
|
|
1032
1017
|
<button
|
|
1033
1018
|
class="prompt-footer-about"
|
|
1034
1019
|
@click=${()=>{this._popup="learn-more",this.persistPopup&&this.setPopupKey()}}
|
|
@@ -1038,7 +1023,7 @@ function Le(e,t,r){return e?t():null==r?void 0:r()}const De=p`
|
|
|
1038
1023
|
</a>
|
|
1039
1024
|
</div>
|
|
1040
1025
|
</div>
|
|
1041
|
-
`}async connectedCallback(){super.connectedCallback(),await async function(e
|
|
1026
|
+
`}async connectedCallback(){super.connectedCallback(),await async function(t,e=bt){const i=await e.loader(t,e);e.translationCache={},_t(t,i,e)}(this.lang),this.hasLoadedStrings=!0,this.fetchInterceptorCleanup=function(t){const e=window.fetch;let i=!0;const o=async(o,r)=>{const s=e(o,r);if(i)try{await t([o,r],s)}catch(n){console.warn(n)}return await s};return window.fetch=o,()=>{window.fetch===o?window.fetch=e:i=!1}}((async(t,e)=>{var i,o,r,s;if(null==(o=null==(i=t[1])?void 0:i.headers)?void 0:o["X-ShipAid"])return;if(!t[0].startsWith("/cart/change")&&!t[0].startsWith("/cart/update"))return;const n=(null==(s=null==(r=this._store)?void 0:r.widgetConfigurations)?void 0:s.checkoutButtonSelector)||'button[type="submit"][name="checkout"][form="cart"]',a=document.querySelector(n);if(console.log("q",a),a){a.setAttribute("disabled","true"),console.debug("button","t");try{await e,await this.updateCart(),await this.updateProtection()}finally{a.removeAttribute("disabled"),console.debug("button","f")}}}))}disconnectedCallback(){var t;super.disconnectedCallback(),null==(t=this.fetchInterceptorCleanup)||t.call(this)}async updateProtection(){var t,i,o,r;if(this._cartLastUpdated=new Date,!(null==(t=this._cart)?void 0:t.items))return;const s=null==(i=this._cart.items)?void 0:i.findIndex((t=>{var e,i;return null==(i=null==(e=this._protectionProduct)?void 0:e.variants)?void 0:i.some((e=>e.id===t.variant_id))})),n=null==(o=this._cart)?void 0:o.items[s];if(this._hasProtectionInCart=!!n,!this._store)return;const a=await this.calculateProtectionTotal(this._cart);if(this._cart.item_count>0&&n&&(this._cart.total_price===(null==n?void 0:n.final_line_price)||!a)){const t={id:n.key,quantity:0},e=await this._fetch.post("/cart/change.js",t);return sessionStorage.removeItem(he),await this._handleRefresh(e)}const p=this._findProtectionVariant(a);if(a?(this._protectionVariant=p,this._shouldShowWidget=!0):this._protectionVariant={id:0,price:"0"},!(null==p?void 0:p.id))return this._shouldShowWidget=!1,void ce("No matching protection variant found.");if(!(null==(r=this._protectionVariant)?void 0:r.id))return void(this._shouldShowWidget=!1);if(!n)return;if(this.supportSubscriptions){const t=this._cart.items.find((t=>{var e;return t.id!==(null==(e=this._protectionVariant)?void 0:e.id)&&!!(null==t?void 0:t.selling_plan_allocation)}));let i=null;if(!t&&(null==n?void 0:n.selling_plan_allocation))i={id:n.key,quantity:1,selling_plan:null};else if(t&&!(null==n?void 0:n.selling_plan_allocation)){const o=await this._fetchSellingPlanFromVariant(t.selling_plan_allocation.selling_plan),r=o?e(o.id):null;i={id:n.key,quantity:1,selling_plan:r}}if(i){const t=await this._fetch.post("/cart/change.js",i);await this._handleRefresh(t)}}if(p.id===n.variant_id){if(this._protectionCartItem={...n,index:s,position:s+1},1===n.quantity)return;const t={id:n.key,quantity:1},e=await this._fetch.post("/cart/change.js",t);return this._handleRefreshCart(),await this._handleRefresh(e)}const d={updates:{[n.variant_id]:0,[p.id]:1}},l=await this._fetch.post("/cart/update.js",d);await this._handleRefresh(l)}render(){return It(this,(async()=>{var t,e,i,o,r,s;const n=document.createElement("link");n.setAttribute("href","https://fonts.googleapis.com/css2?family=Lato&display=swap"),n.setAttribute("rel","stylesheet"),document.head.appendChild(n);try{const[t,e,i]=await Promise.all([this._fetchShipAidData(),this._fetchCart(),this._fetchProduct()]);this._store=t,this._cart=e,this._protectionProduct=i}catch(a){return ce(a.message),this._hasFinishedSetup=!0,void(this._shouldShowWidget=!1)}return this.planActive?(null==(e=null==(t=this._store)?void 0:t.protectionSettings)?void 0:e.protectionType)?this._protectionProduct?(this._hasFinishedSetup=!0,this._dispatchEvent(ne.LOADED,this._store),setTimeout((async()=>{var t,e,i,o;(null==(t=this._store)?void 0:t.widgetAutoOptIn)&&(null==(e=this._cart)?void 0:e.item_count)&&(this.customerId&&this._store.excludedCustomersIdsAutoOptIn&&(null==(i=this._store.excludedCustomersIdsAutoOptIn)?void 0:i.length)&&this._store.excludedCustomersIdsAutoOptIn.includes(`gid://shopify/Customer/${this.customerId}`)||sessionStorage.getItem(he)||!this._hasProtectionInCart&&(null==(o=this._cart)?void 0:o.item_count)&&this._store.widgetShowCart&&(await this.addProtection(),sessionStorage.setItem(he,JSON.stringify({loaded:!0}))))}),500),void(this.disablePolling||(setInterval((async()=>{const t=this._cartLastUpdated;t&&(new Date).getTime()-t.getTime()<this.pollingInterval||await this.updateCart()}),this.pollingInterval),(null==(i=this._store)?void 0:i.widgetPollProtection)&&!this.intervalId&&(this.intervalId=setInterval((async()=>{await this.attemptAddProtection()}),400),localStorage.setItem(`polling-shipaid-protection_${this.intervalId}`,`${this.intervalId}`)),(null==(s=null==(r=null==(o=this._store)?void 0:o.widgetConfigurations)?void 0:r.widget)?void 0:s.pollVariantsCheck)&&setInterval((async()=>{await this.handleMultipleProtectionVariants()}),400)))):(le("No protection settings product for this store - skipping setup."),this._hasFinishedSetup=!0,void(this._shouldShowWidget=!1)):(le("No protection settings for this store - skipping setup."),this._hasFinishedSetup=!0,void(this._shouldShowWidget=!1)):(le("No plan is active for this store - skipping setup."),this._hasFinishedSetup=!0,void(this._shouldShowWidget=!1))}),[]),It(this,(async()=>{await this.updateProtection()}),[this._store,this._cart]),dt(this.renderPopups(),document.body),F`
|
|
1042
1027
|
<style>
|
|
1043
1028
|
:host {
|
|
1044
1029
|
--shipaid-primary: #002bd6;
|
|
@@ -1305,6 +1290,6 @@ function Le(e,t,r){return e?t():null==r?void 0:r()}const De=p`
|
|
|
1305
1290
|
}
|
|
1306
1291
|
</style>
|
|
1307
1292
|
<div class="shipaid">
|
|
1308
|
-
${
|
|
1293
|
+
${Tt(this._hasFinishedSetup,(()=>{var t;return Tt(this._shouldShowWidget&&this.planActive&&(null==(t=this._store)?void 0:t.widgetShowCart),(()=>this.promptTemplate()),(()=>Z))}),(()=>this.promptTemplate()))}
|
|
1309
1294
|
</div>
|
|
1310
|
-
`}};ps.styles=it;let fs=ps;ns([o({type:String,attribute:!0})],fs.prototype,"env"),ns([o({type:Boolean,attribute:!0})],fs.prototype,"useCustomStoreFront"),ns([o({type:String,attribute:!0})],fs.prototype,"storeDomain"),ns([o({type:String,attribute:!0})],fs.prototype,"storeAccessToken"),ns([o({type:String,attribute:!0})],fs.prototype,"cartId"),ns([o({type:Boolean,attribute:!0})],fs.prototype,"disablePolling"),ns([o({type:Boolean,attribute:!0})],fs.prototype,"disableActions"),ns([o({type:Number,attribute:!0})],fs.prototype,"pollingInterval"),ns([o({type:Boolean,attribute:!0})],fs.prototype,"disableRefresh"),ns([o({type:Boolean,attribute:!0})],fs.prototype,"refreshCart"),ns([o({type:Boolean,attribute:!0})],fs.prototype,"persistPopup"),ns([o({type:Boolean,attribute:!0})],fs.prototype,"defaultToggleButton"),ns([o({type:String,attribute:!0})],fs.prototype,"lang"),ns([o({type:String,attribute:!0})],fs.prototype,"currency"),ns([o({type:String,attribute:!0})],fs.prototype,"customerId"),ns([o({type:Boolean,attribute:!0})],fs.prototype,"supportSubscriptions"),ns([s()],fs.prototype,"_storeDomain"),ns([s()],fs.prototype,"_store"),ns([s()],fs.prototype,"_cart"),ns([s()],fs.prototype,"_protectionProduct"),ns([s()],fs.prototype,"_cartLastUpdated"),ns([s()],fs.prototype,"_hasFinishedSetup"),ns([s()],fs.prototype,"_shouldShowWidget"),ns([s()],fs.prototype,"_hasProtectionInCart"),ns([s()],fs.prototype,"_protectionCartItem"),ns([s()],fs.prototype,"_protectionVariant"),ns([s()],fs.prototype,"hasLoadedStrings"),ns([s()],fs.prototype,"fetchInterceptorCleanup"),ns([s()],fs.prototype,"intervalId"),ns([s()],fs.prototype,"_state"),ns([s()],fs.prototype,"_popup"),customElements.get("shipaid-widget")||customElements.define("shipaid-widget",fs);const vs="Laden des ShipAid-Widgets...",ms="Liefergarantie",gs="im Falle von Verlust, Beschädigung oder Diebstahl",ys={button:"Bereitgestellt von"},ws={add:"Hinzufügen",remove:"Entfernen",loading:"Lädt..."},bs={loading:vs,title:ms,description:gs,footer:ys,actions:ws,"learn-more-popup":{close:"Schließen",title:"Liefergarantie",subtitle:"Wir ermöglichen es Ihren Lieblingsmarken, eine Liefergarantie anzubieten, weil jede Bestellung wertvoll ist!",disclaimer:{"subtitle-enable":"Wir ermöglichen es Ihren Lieblingsmarken, eine Liefergarantie zu bieten, denn wir wissen, dass jede Bestellung wertvoll ist und Dinge passieren können!","subtitle-monitor":"Wir überwachen Ihr Paket kontinuierlich und bieten ein praktisches Portal, damit Sie den Fortschritt Ihrer Bestellung jederzeit verfolgen können!","subtitle-notify":"Sie werden während des gesamten Versandprozesses benachrichtigt, um sicherzustellen, dass Sie auf dem Laufenden bleiben.","subtitle-resolution":"Sie werden während des gesamten Versandprozesses benachrichtigt, um sicherzustellen, dass Sie auf dem Laufenden bleiben.",text:"Durch den Erwerb dieser Liefergarantie stimmen Sie unseren Servicebedingungen und Datenschutzrichtlinien zu. Diese Garantie ist nicht verpflichtend, IST KEINE Versicherung und bietet keine Entschädigung für Verluste, Schäden oder Haftungen, die aus einem zufälligen oder unbekannten Ereignis resultieren. Sollte das Produkt nicht in zufriedenstellendem Zustand geliefert werden, kann die Marke, bei der Sie gekauft haben, dieses kostenlos ersetzen. ShipAid liefert keine Produkte oder Dienstleistungen direkt an Verbraucher, sondern bietet einen Dienst an, der Marken ermöglicht, den Produktersatz für ihre Kunden zu erleichtern. Der Erwerb dieser Garantie bedeutet nicht, dass Sie automatisch eine Rückerstattung für irgendwelche Produkte oder Versandkosten erhalten, da der Lösungsprozess und die Entscheidung über eine Kompensation strikt von der Marke, bei der Sie kaufen, entschieden werden. Die Marke wird einen Nachweis für Beschädigungen oder die Nichtlieferung des Produkts verlangen."},links:{terms:"Servicebedingungen",privacy:"Datenschutzrichtlinie"}}},Es=Object.freeze(Object.defineProperty({__proto__:null,actions:ws,default:bs,description:gs,footer:ys,loading:vs,title:ms},Symbol.toStringTag,{value:"Module"})),_s="Cargando el widget ShipAid...",Ts="Garantía de entrega",xs="en caso de Pérdida, Daño o Robo",Ss={button:"Energizado por"},ks={add:"Agregar",remove:"Eliminar",loading:"Cargando..."},As={loading:_s,title:Ts,description:xs,footer:Ss,actions:ks,"learn-more-popup":{close:"Cerca",title:"Garantía de entrega",disclaimer:{"subtitle-enable":"Permitimos que sus marcas favoritas brinden una garantía de entrega porque sabemos que cada pedido es valioso y las cosas suceden!","subtitle-monitor":"Supervisamos continuamente su paquete y le ofrecemos un portal conveniente para que pueda realizar un seguimiento del progreso de su pedido en cualquier momento.","subtitle-notify":"Se le notificará durante todo el proceso de envío, asegurándose de que esté actualizado en cada paso del camino.","subtitle-resolution":"En caso de cualquier problema durante el tránsito, ofrecemos un método rápido y fácil para informar el problema directamente a la marca, para una resolución rápida.",text:"Al comprar esta garantía de entrega, acepta nuestros Términos de servicio y Política de privacidad. Usted no está obligado a comprar esta garantía. Esta garantía NO es un seguro y no brinda indemnización por pérdida, daño o responsabilidad que surja de un evento contingente o desconocido, sino que, a través de las marcas de ShipAid, brinda una garantía de entrega mediante la cual, si el producto que ordenó no se entrega en condiciones satisfactorias, la marca desde el que ordenó el producto puede reemplazar el producto sin cargo. ShipAid no proporciona ningún producto o servicio directamente a los consumidores, sino que proporciona un servicio que permite a las marcas facilitar el reemplazo de productos a sus clientes. La compra de esta garantía no significa que se le reembolsará automáticamente cualquier producto o costo de envío porque el proceso de resolución y la decisión de compensación lo decide estrictamente la marca a la que le compra. La marca requerirá prueba de daño o producto no entregado."},links:{terms:"Términos de servicio",privacy:"Política de Privacidad"}}},Cs=Object.freeze(Object.defineProperty({__proto__:null,actions:ks,default:As,description:xs,footer:Ss,loading:_s,title:Ts},Symbol.toStringTag,{value:"Module"})),Is="Chargement du widget ShipAid...",Os="Garantie de livraison",Ns="en cas de Perte, Dommages ou Vol",Ps={button:"Propulsé par"},Rs={add:"Ajouter",remove:"Retirer",loading:"Chargement..."},Ls={loading:Is,title:Os,description:Ns,footer:Ps,actions:Rs,"learn-more-popup":{close:"Fermer",title:"Garantie de livraison",subtitle:"Nous permettons à vos marques préférées d'offrir une garantie de livraison car chaque commande est précieuse !",disclaimer:{"subtitle-enable":"Nous permettons à vos marques préférées de fournir une garantie de livraison car nous savons que chaque commande est précieuse et que des incidents peuvent survenir !","subtitle-monitor":"Nous surveillons continuellement votre colis et offrons un portail pratique pour vous permettre de suivre l'avancement de votre commande à tout moment !","subtitle-notify":"Vous serez notifié tout au long du processus d'expédition, vous assurant que vous restez informé à chaque étape du parcours.","subtitle-resolution":"Vous serez notifié tout au long du processus d'expédition, vous assurant que vous restez informé à chaque étape du parcours.",text:"En acquérant cette garantie de livraison, vous acceptez nos Conditions de Service et notre Politique de Confidentialité. Cette garantie n'est pas obligatoire, N'EST PAS une assurance et ne fournit pas d'indemnisation pour les pertes, dommages ou responsabilités résultant d'un événement contingent ou inconnu. Si le produit n'est pas livré dans des conditions satisfaisantes, la marque auprès de laquelle vous avez acheté peut le remplacer gratuitement. ShipAid ne fournit aucun produit ou service directement aux consommateurs, mais offre un service permettant aux marques de faciliter le remplacement du produit pour leurs clients. L'achat de cette garantie ne signifie pas que vous serez automatiquement remboursé pour tout produit ou frais de port, car le processus de résolution et la décision de compensation sont strictement décidés par la marque que vous achetez. La marque exigera une preuve de dommage ou de produit non livré."},links:{terms:"Conditions de service",privacy:"Politique de Confidentialité"}}},Ds=Object.freeze(Object.defineProperty({__proto__:null,actions:Rs,default:Ls,description:Ns,footer:Ps,loading:Is,title:Os},Symbol.toStringTag,{value:"Module"})),$s="Caricamento del widget ShipAid...",Us="Garanzia di consegna",Ms="in caso di Perdita, Danno o Furto",js={button:"Offerto da"},Vs={add:"Aggiungere",remove:"Rimuovere",loading:"Caricamento ..."},Fs={loading:$s,title:Us,description:Ms,footer:js,actions:Vs,"learn-more-popup":{close:"Vicina",title:"Garanzia di consegna",subtitle:"Consentiamo ai tuoi marchi preferiti di offrire una garanzia di consegna perché ogni ordine è prezioso!",disclaimer:{"subtitle-enable":"Consentiamo ai tuoi marchi preferiti di fornire una garanzia di consegna perché sappiamo che ogni ordine è prezioso e le cose accadono!","subtitle-monitor":"Monitoriamo continuamente il tuo pacco e ti offriamo un comodo portale per monitorare lo stato di avanzamento del tuo ordine in qualsiasi momento!","subtitle-notify":"Riceverai una notifica durante l'intero processo di spedizione, assicurandoti di rimanere aggiornato in ogni fase del processo.","subtitle-resolution":"Você será notificado durante todo o processo de envio, garantindo que você fique atualizado a cada passo do caminho.",text:"Acquistando questa garanzia di consegna, accetti i nostri Termini di servizio e l'Informativa sulla privacy. Non sei obbligato ad acquistare questa garanzia. Questa garanzia NON è un'assicurazione e non fornisce un indennizzo contro perdite, danni o responsabilità derivanti da un evento contingente o sconosciuto, ma piuttosto, attraverso ShipAid i marchi forniscono una garanzia di consegna in base alla quale se il prodotto ordinato non viene consegnato in condizioni soddisfacenti, il marchio da cui hai ordinato il prodotto può sostituire il prodotto gratuitamente. ShipAid non fornisce alcun prodotto o servizio direttamente ai consumatori, ma fornisce invece un servizio che consente ai marchi di facilitare la sostituzione del prodotto ai propri clienti. L'acquisto di questa garanzia non significa che verrai automaticamente rimborsato per qualsiasi prodotto o costo di spedizione perché il processo di risoluzione e la decisione per il risarcimento sono rigorosamente decisi dal marchio da cui stai acquistando. Il marchio richiederà la prova del danno o del prodotto non consegnato."},links:{terms:"Termini di servizio",privacy:"Politica sulla riservatezza"}}},zs=Object.freeze(Object.defineProperty({__proto__:null,actions:Vs,default:Fs,description:Ms,footer:js,loading:$s,title:Us},Symbol.toStringTag,{value:"Module"})),qs="Carregando o widget ShipAid...",Bs="Garantia de entrega",Hs="em caso de Perda, Danos ou Roubo",Ks={button:"Distribuído por"},Gs={add:"Adicionar",remove:"Remover",loading:"Carregando..."},Ys={loading:qs,title:Bs,description:Hs,footer:Ks,actions:Gs,"learn-more-popup":{close:"Fechar",title:"Garantia de entrega",subtitle:"Capacitamos suas marcas favoritas para oferecer uma garantia de entrega porque cada pedido é precioso!",disclaimer:{"subtitle-enable":"Permitimos que suas marcas favoritas forneçam uma garantia de entrega porque sabemos que cada pedido é precioso e as coisas acontecem!","subtitle-monitor":"Monitoramos continuamente o seu pacote e oferecemos um portal conveniente para você acompanhar o andamento do seu pedido a qualquer momento!","subtitle-notify":"Você será notificado durante todo o processo de envio, garantindo que você fique atualizado a cada passo do caminho.","subtitle-resolution":"Você será notificado durante todo o processo de envio, garantindo que você fique atualizado a cada passo do caminho.",text:"Ao adquirir esta garantia de entrega, você concorda com nossos Termos de Serviço e Política de Privacidade. Esta garantia não é obrigatória, NÃO é um seguro e não fornece indenização contra perdas, danos ou responsabilidade decorrentes de um contingente ou desconhecido. Caso o produto não seja entregue em condições satisfatórias, a marca da qual você comprou pode substituí-lo gratuitamente. A ShipAid não fornece nenhum produto ou serviço diretamente aos consumidores, mas sim presta um serviço que permite às marcas facilitar a substituição do produto aos seus clientes. Adquirir esta garantia não significa que você será automaticamente reembolsado por qualquer produto ou custos de envio porque o processo de resolução e decisão de compensação é estritamente decidido pela marca que você está comprando. A marca exigirá prova de danos ou produto não entregue."},links:{terms:"Termos de serviço",privacy:"Política de Privacidade"}}},Ws=Object.freeze(Object.defineProperty({__proto__:null,actions:Gs,default:Ys,description:Hs,footer:Ks,loading:qs,title:Bs},Symbol.toStringTag,{value:"Module"}));return e.ShipAidWidget=fs,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});
|
|
1295
|
+
`}};ge.styles=se;let ve=ge;pe([s({type:Boolean,attribute:!0})],ve.prototype,"disablePolling"),pe([s({type:Boolean,attribute:!0})],ve.prototype,"disableActions"),pe([s({type:Number,attribute:!0})],ve.prototype,"pollingInterval"),pe([s({type:Boolean,attribute:!0})],ve.prototype,"disableRefresh"),pe([s({type:Boolean,attribute:!0})],ve.prototype,"refreshCart"),pe([s({type:Boolean,attribute:!0})],ve.prototype,"persistPopup"),pe([s({type:Boolean,attribute:!0})],ve.prototype,"defaultToggleButton"),pe([s({type:String,attribute:!0})],ve.prototype,"lang"),pe([s({type:String,attribute:!0})],ve.prototype,"currency"),pe([s({type:String,attribute:!0})],ve.prototype,"customerId"),pe([s({type:Boolean,attribute:!0})],ve.prototype,"supportSubscriptions"),pe([n()],ve.prototype,"_storeDomain"),pe([n()],ve.prototype,"_store"),pe([n()],ve.prototype,"_cart"),pe([n()],ve.prototype,"_protectionProduct"),pe([n()],ve.prototype,"_cartLastUpdated"),pe([n()],ve.prototype,"_hasFinishedSetup"),pe([n()],ve.prototype,"_shouldShowWidget"),pe([n()],ve.prototype,"_hasProtectionInCart"),pe([n()],ve.prototype,"_protectionCartItem"),pe([n()],ve.prototype,"_protectionVariant"),pe([n()],ve.prototype,"hasLoadedStrings"),pe([n()],ve.prototype,"fetchInterceptorCleanup"),pe([n()],ve.prototype,"intervalId"),pe([n()],ve.prototype,"_state"),pe([n()],ve.prototype,"_popup"),customElements.get("shipaid-widget")||customElements.define("shipaid-widget",ve);const be="Laden des ShipAid-Widgets...",_e="Liefergarantie",ye="im Falle von Verlust, Beschädigung oder Diebstahl",Ce={button:"Bereitgestellt von"},we={add:"Hinzufügen",remove:"Entfernen",loading:"Lädt..."},xe={loading:be,title:_e,description:ye,footer:Ce,actions:we,"learn-more-popup":{close:"Schließen",title:"Liefergarantie",subtitle:"Wir ermöglichen es Ihren Lieblingsmarken, eine Liefergarantie anzubieten, weil jede Bestellung wertvoll ist!",disclaimer:{"subtitle-enable":"Wir ermöglichen es Ihren Lieblingsmarken, eine Liefergarantie zu bieten, denn wir wissen, dass jede Bestellung wertvoll ist und Dinge passieren können!","subtitle-monitor":"Wir überwachen Ihr Paket kontinuierlich und bieten ein praktisches Portal, damit Sie den Fortschritt Ihrer Bestellung jederzeit verfolgen können!","subtitle-notify":"Sie werden während des gesamten Versandprozesses benachrichtigt, um sicherzustellen, dass Sie auf dem Laufenden bleiben.","subtitle-resolution":"Sie werden während des gesamten Versandprozesses benachrichtigt, um sicherzustellen, dass Sie auf dem Laufenden bleiben.",text:"Durch den Erwerb dieser Liefergarantie stimmen Sie unseren Servicebedingungen und Datenschutzrichtlinien zu. Diese Garantie ist nicht verpflichtend, IST KEINE Versicherung und bietet keine Entschädigung für Verluste, Schäden oder Haftungen, die aus einem zufälligen oder unbekannten Ereignis resultieren. Sollte das Produkt nicht in zufriedenstellendem Zustand geliefert werden, kann die Marke, bei der Sie gekauft haben, dieses kostenlos ersetzen. ShipAid liefert keine Produkte oder Dienstleistungen direkt an Verbraucher, sondern bietet einen Dienst an, der Marken ermöglicht, den Produktersatz für ihre Kunden zu erleichtern. Der Erwerb dieser Garantie bedeutet nicht, dass Sie automatisch eine Rückerstattung für irgendwelche Produkte oder Versandkosten erhalten, da der Lösungsprozess und die Entscheidung über eine Kompensation strikt von der Marke, bei der Sie kaufen, entschieden werden. Die Marke wird einen Nachweis für Beschädigungen oder die Nichtlieferung des Produkts verlangen."},links:{terms:"Servicebedingungen",privacy:"Datenschutzrichtlinie"}}},$e=Object.freeze(Object.defineProperty({__proto__:null,actions:we,default:xe,description:ye,footer:Ce,loading:be,title:_e},Symbol.toStringTag,{value:"Module"})),Se="Cargando el widget ShipAid...",Ae="Garantía de entrega",Le="en caso de Pérdida, Daño o Robo",Pe={button:"Energizado por"},ke={add:"Agregar",remove:"Eliminar",loading:"Cargando..."},ze={loading:Se,title:Ae,description:Le,footer:Pe,actions:ke,"learn-more-popup":{close:"Cerca",title:"Garantía de entrega",disclaimer:{"subtitle-enable":"Permitimos que sus marcas favoritas brinden una garantía de entrega porque sabemos que cada pedido es valioso y las cosas suceden!","subtitle-monitor":"Supervisamos continuamente su paquete y le ofrecemos un portal conveniente para que pueda realizar un seguimiento del progreso de su pedido en cualquier momento.","subtitle-notify":"Se le notificará durante todo el proceso de envío, asegurándose de que esté actualizado en cada paso del camino.","subtitle-resolution":"En caso de cualquier problema durante el tránsito, ofrecemos un método rápido y fácil para informar el problema directamente a la marca, para una resolución rápida.",text:"Al comprar esta garantía de entrega, acepta nuestros Términos de servicio y Política de privacidad. Usted no está obligado a comprar esta garantía. Esta garantía NO es un seguro y no brinda indemnización por pérdida, daño o responsabilidad que surja de un evento contingente o desconocido, sino que, a través de las marcas de ShipAid, brinda una garantía de entrega mediante la cual, si el producto que ordenó no se entrega en condiciones satisfactorias, la marca desde el que ordenó el producto puede reemplazar el producto sin cargo. ShipAid no proporciona ningún producto o servicio directamente a los consumidores, sino que proporciona un servicio que permite a las marcas facilitar el reemplazo de productos a sus clientes. La compra de esta garantía no significa que se le reembolsará automáticamente cualquier producto o costo de envío porque el proceso de resolución y la decisión de compensación lo decide estrictamente la marca a la que le compra. La marca requerirá prueba de daño o producto no entregado."},links:{terms:"Términos de servicio",privacy:"Política de Privacidad"}}},Ee=Object.freeze(Object.defineProperty({__proto__:null,actions:ke,default:ze,description:Le,footer:Pe,loading:Se,title:Ae},Symbol.toStringTag,{value:"Module"})),Me="Chargement du widget ShipAid...",qe="Garantie de livraison",Ie="en cas de Perte, Dommages ou Vol",Te={button:"Propulsé par"},Ne={add:"Ajouter",remove:"Retirer",loading:"Chargement..."},Oe={loading:Me,title:qe,description:Ie,footer:Te,actions:Ne,"learn-more-popup":{close:"Fermer",title:"Garantie de livraison",subtitle:"Nous permettons à vos marques préférées d'offrir une garantie de livraison car chaque commande est précieuse !",disclaimer:{"subtitle-enable":"Nous permettons à vos marques préférées de fournir une garantie de livraison car nous savons que chaque commande est précieuse et que des incidents peuvent survenir !","subtitle-monitor":"Nous surveillons continuellement votre colis et offrons un portail pratique pour vous permettre de suivre l'avancement de votre commande à tout moment !","subtitle-notify":"Vous serez notifié tout au long du processus d'expédition, vous assurant que vous restez informé à chaque étape du parcours.","subtitle-resolution":"Vous serez notifié tout au long du processus d'expédition, vous assurant que vous restez informé à chaque étape du parcours.",text:"En acquérant cette garantie de livraison, vous acceptez nos Conditions de Service et notre Politique de Confidentialité. Cette garantie n'est pas obligatoire, N'EST PAS une assurance et ne fournit pas d'indemnisation pour les pertes, dommages ou responsabilités résultant d'un événement contingent ou inconnu. Si le produit n'est pas livré dans des conditions satisfaisantes, la marque auprès de laquelle vous avez acheté peut le remplacer gratuitement. ShipAid ne fournit aucun produit ou service directement aux consommateurs, mais offre un service permettant aux marques de faciliter le remplacement du produit pour leurs clients. L'achat de cette garantie ne signifie pas que vous serez automatiquement remboursé pour tout produit ou frais de port, car le processus de résolution et la décision de compensation sont strictement décidés par la marque que vous achetez. La marque exigera une preuve de dommage ou de produit non livré."},links:{terms:"Conditions de service",privacy:"Politique de Confidentialité"}}},je=Object.freeze(Object.defineProperty({__proto__:null,actions:Ne,default:Oe,description:Ie,footer:Te,loading:Me,title:qe},Symbol.toStringTag,{value:"Module"})),Re="Caricamento del widget ShipAid...",Ue="Garanzia di consegna",Ve="in caso di Perdita, Danno o Furto",De={button:"Offerto da"},Be={add:"Aggiungere",remove:"Rimuovere",loading:"Caricamento ..."},He={loading:Re,title:Ue,description:Ve,footer:De,actions:Be,"learn-more-popup":{close:"Vicina",title:"Garanzia di consegna",subtitle:"Consentiamo ai tuoi marchi preferiti di offrire una garanzia di consegna perché ogni ordine è prezioso!",disclaimer:{"subtitle-enable":"Consentiamo ai tuoi marchi preferiti di fornire una garanzia di consegna perché sappiamo che ogni ordine è prezioso e le cose accadono!","subtitle-monitor":"Monitoriamo continuamente il tuo pacco e ti offriamo un comodo portale per monitorare lo stato di avanzamento del tuo ordine in qualsiasi momento!","subtitle-notify":"Riceverai una notifica durante l'intero processo di spedizione, assicurandoti di rimanere aggiornato in ogni fase del processo.","subtitle-resolution":"Você será notificado durante todo o processo de envio, garantindo que você fique atualizado a cada passo do caminho.",text:"Acquistando questa garanzia di consegna, accetti i nostri Termini di servizio e l'Informativa sulla privacy. Non sei obbligato ad acquistare questa garanzia. Questa garanzia NON è un'assicurazione e non fornisce un indennizzo contro perdite, danni o responsabilità derivanti da un evento contingente o sconosciuto, ma piuttosto, attraverso ShipAid i marchi forniscono una garanzia di consegna in base alla quale se il prodotto ordinato non viene consegnato in condizioni soddisfacenti, il marchio da cui hai ordinato il prodotto può sostituire il prodotto gratuitamente. ShipAid non fornisce alcun prodotto o servizio direttamente ai consumatori, ma fornisce invece un servizio che consente ai marchi di facilitare la sostituzione del prodotto ai propri clienti. L'acquisto di questa garanzia non significa che verrai automaticamente rimborsato per qualsiasi prodotto o costo di spedizione perché il processo di risoluzione e la decisione per il risarcimento sono rigorosamente decisi dal marchio da cui stai acquistando. Il marchio richiederà la prova del danno o del prodotto non consegnato."},links:{terms:"Termini di servizio",privacy:"Politica sulla riservatezza"}}},Fe=Object.freeze(Object.defineProperty({__proto__:null,actions:Be,default:He,description:Ve,footer:De,loading:Re,title:Ue},Symbol.toStringTag,{value:"Module"})),We="Carregando o widget ShipAid...",Ze="Garantia de entrega",Ge="em caso de Perda, Danos ou Roubo",Ke={button:"Distribuído por"},Ye={add:"Adicionar",remove:"Remover",loading:"Carregando..."},Je={loading:We,title:Ze,description:Ge,footer:Ke,actions:Ye,"learn-more-popup":{close:"Fechar",title:"Garantia de entrega",subtitle:"Capacitamos suas marcas favoritas para oferecer uma garantia de entrega porque cada pedido é precioso!",disclaimer:{"subtitle-enable":"Permitimos que suas marcas favoritas forneçam uma garantia de entrega porque sabemos que cada pedido é precioso e as coisas acontecem!","subtitle-monitor":"Monitoramos continuamente o seu pacote e oferecemos um portal conveniente para você acompanhar o andamento do seu pedido a qualquer momento!","subtitle-notify":"Você será notificado durante todo o processo de envio, garantindo que você fique atualizado a cada passo do caminho.","subtitle-resolution":"Você será notificado durante todo o processo de envio, garantindo que você fique atualizado a cada passo do caminho.",text:"Ao adquirir esta garantia de entrega, você concorda com nossos Termos de Serviço e Política de Privacidade. Esta garantia não é obrigatória, NÃO é um seguro e não fornece indenização contra perdas, danos ou responsabilidade decorrentes de um contingente ou desconhecido. Caso o produto não seja entregue em condições satisfatórias, a marca da qual você comprou pode substituí-lo gratuitamente. A ShipAid não fornece nenhum produto ou serviço diretamente aos consumidores, mas sim presta um serviço que permite às marcas facilitar a substituição do produto aos seus clientes. Adquirir esta garantia não significa que você será automaticamente reembolsado por qualquer produto ou custos de envio porque o processo de resolução e decisão de compensação é estritamente decidido pela marca que você está comprando. A marca exigirá prova de danos ou produto não entregue."},links:{terms:"Termos de serviço",privacy:"Política de Privacidade"}}},Xe=Object.freeze(Object.defineProperty({__proto__:null,actions:Ye,default:Je,description:Ge,footer:Ke,loading:We,title:Ze},Symbol.toStringTag,{value:"Module"}));return t.ShipAidWidget=ve,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),t}({});
|