@clicktap/state 0.14.8 → 0.15.0

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/index.js CHANGED
@@ -1,16 +1,16 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ce=require("react/jsx-runtime"),N=require("react");function _n(e,t){for(var n=0;n<t.length;n++){const s=t[n];if(typeof s!="string"&&!Array.isArray(s)){for(const r in s)if(r!=="default"&&!(r in e)){const i=Object.getOwnPropertyDescriptor(s,r);i&&Object.defineProperty(e,r,i.get?i:{enumerable:!0,get:()=>s[r]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}function In(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function An(){const e=In();if(e.__xstate__)return e.__xstate__}const wn=e=>{if(typeof window>"u")return;const t=An();t&&t.register(e)};class gt{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const n={value:t,next:null};if(this._current){this._last.next=n,this._last=n;return}this._current=n,this._last=n,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const Bt=".",xn="",jt="",bn="#",Cn="*",$t="xstate.init",On="xstate.error",de="xstate.stop";function Nn(e,t){return{type:`xstate.after.${e}.${t}`}}function $e(e,t){return{type:`xstate.done.state.${e}`,output:t}}function kn(e,t){return{type:`xstate.done.actor.${e}`,output:t}}function Vt(e,t){return{type:`xstate.error.actor.${e}`,error:t}}function Ht(e){return{type:$t,input:e}}function B(e){setTimeout(()=>{throw e})}const Dn=(()=>typeof Symbol=="function"&&Symbol.observable||"@@observable")();function Et(e,t){return`${e.sessionId}.${t}`}let Rn=0;function qn(e,t){const n=new Map,s=new Map,r=new WeakMap,i=new Set,o={},{clock:a,logger:c}=t,u={schedule:(f,m,y,v,_=Math.random().toString(36).slice(2))=>{const w={source:f,target:m,event:y,delay:v,id:_,startedAt:Date.now()},q=Et(f,_);d._snapshot._scheduledEvents[q]=w;const D=a.setTimeout(()=>{delete o[q],delete d._snapshot._scheduledEvents[q],d._relay(f,m,y)},v);o[q]=D},cancel:(f,m)=>{const y=Et(f,m),v=o[y];delete o[y],delete d._snapshot._scheduledEvents[y],a.clearTimeout(v)},cancelAll:f=>{for(const m in d._snapshot._scheduledEvents){const y=d._snapshot._scheduledEvents[m];y.source===f&&u.cancel(f,y.id)}}},h=f=>{if(!i.size)return;const m={...f,rootId:e.sessionId};i.forEach(y=>{var v;return(v=y.next)==null?void 0:v.call(y,m)})},d={_snapshot:{_scheduledEvents:((t==null?void 0:t.snapshot)&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${Rn++}`,_register:(f,m)=>(n.set(f,m),f),_unregister:f=>{n.delete(f.sessionId);const m=r.get(f);m!==void 0&&(s.delete(m),r.delete(f))},get:f=>s.get(f),_set:(f,m)=>{const y=s.get(f);if(y&&y!==m)throw new Error(`Actor with system ID '${f}' already exists.`);s.set(f,m),r.set(m,f)},inspect:f=>{i.add(f)},_sendInspectionEvent:h,_relay:(f,m,y)=>{d._sendInspectionEvent({type:"@xstate.event",sourceRef:f,actorRef:m,event:y}),m._send(y)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...d._snapshot._scheduledEvents}}),start:()=>{const f=d._snapshot._scheduledEvents;d._snapshot._scheduledEvents={};for(const m in f){const{source:y,target:v,event:_,delay:w,id:q}=f[m];u.schedule(y,v,_,w,q)}},_clock:a,_logger:c};return d}function zt(e,t){const n=vt(e),s=vt(t);return typeof s=="string"?typeof n=="string"?s===n:!1:typeof n=="string"?n in s:Object.keys(n).every(r=>r in s?zt(n[r],s[r]):!1)}function et(e){if(Jt(e))return e;let t=[],n="";for(let s=0;s<e.length;s++){switch(e.charCodeAt(s)){case 92:n+=e[s+1],s++;continue;case 46:t.push(n),n="";continue}n+=e[s]}return t.push(n),t}function vt(e){if(ls(e))return e.value;if(typeof e!="string")return e;const t=et(e);return Mn(t)}function Mn(e){if(e.length===1)return e[0];const t={};let n=t;for(let s=0;s<e.length-1;s++)if(s===e.length-2)n[e[s]]=e[s+1];else{const r=n;n={},r[e[s]]=n}return t}function Tt(e,t){const n={},s=Object.keys(e);for(let r=0;r<s.length;r++){const i=s[r];n[i]=t(e[i],i,e,r)}return n}function Gt(e){return Jt(e)?e:[e]}function j(e){return e===void 0?[]:Gt(e)}function Ve(e,t,n,s){return typeof e=="function"?e({context:t,event:n,self:s}):e}function Jt(e){return Array.isArray(e)}function Ln(e){return e.type.startsWith("xstate.error.actor")}function Z(e){return Gt(e).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function Yt(e){if(!(e===void 0||e===xn))return j(e)}function St(e,t,n){var i,o,a;const s=typeof e=="object",r=s?e:void 0;return{next:(i=s?e.next:e)==null?void 0:i.bind(r),error:(o=s?e.error:t)==null?void 0:o.bind(r),complete:(a=s?e.complete:n)==null?void 0:a.bind(r)}}function _t(e,t){return`${t}.${e}`}function tt(e,t){const n=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return e.implementations.actors[t];const[,s,r]=n,o=e.getStateNodeById(r).config.invoke;return(Array.isArray(o)?o[s]:o).src}const nt=1;let R=function(e){return e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped",e}({});const Pn={clock:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},logger:console.log.bind(console),devTools:!1};class Un{constructor(t,n){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new gt(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=R.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const s={...Pn,...n},{clock:r,logger:i,parent:o,syncSnapshot:a,id:c,systemId:u,inspect:h}=s;this.system=o?o.system:qn(this,{clock:r,logger:i}),h&&!o&&this.system.inspect(St(h)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=(n==null?void 0:n.logger)??this.system._logger,this.clock=(n==null?void 0:n.clock)??this.system._clock,this._parent=o,this._syncSnapshot=a,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:d=>{this._deferred.push(d)},system:this.system,stopChild:d=>{if(d._parent!==this)throw new Error(`Cannot stop child actor ${d.id} of ${this.id} because it is not a child`);d._stop()},emit:d=>{const f=this.eventListeners.get(d.type);if(f)for(const m of Array.from(f))m(d)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),u&&(this._systemId=u,this.system._set(u,this)),this._initState((n==null?void 0:n.snapshot)??(n==null?void 0:n.state)),u&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(t){var n;try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,(n=this.options)==null?void 0:n.input)}catch(s){this._snapshot={status:"error",output:void 0,error:s}}}update(t,n){var r,i;this._snapshot=t;let s;for(;s=this._deferred.shift();)try{s()}catch(o){this._deferred.length=0,this._snapshot={...t,status:"error",error:o}}switch(this._snapshot.status){case"active":for(const o of this.observers)try{(r=o.next)==null||r.call(o,t)}catch(a){B(a)}break;case"done":for(const o of this.observers)try{(i=o.next)==null||i.call(o,t)}catch(a){B(a)}this._stopProcedure(),this._complete(),this._doneEvent=kn(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:n,snapshot:t})}subscribe(t,n,s){var i;const r=St(t,n,s);if(this._processingStatus!==R.Stopped)this.observers.add(r);else switch(this._snapshot.status){case"done":try{(i=r.complete)==null||i.call(r)}catch(o){B(o)}break;case"error":{const o=this._snapshot.error;if(!r.error)B(o);else try{r.error(o)}catch(a){B(a)}break}}return{unsubscribe:()=>{this.observers.delete(r)}}}on(t,n){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const r=n.bind(void 0);return s.add(r),{unsubscribe:()=>{s.delete(r)}}}start(){if(this._processingStatus===R.Running)return this;this._syncSnapshot&&this.subscribe({next:s=>{s.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:s})},error:()=>{}}),this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this._processingStatus=R.Running;const t=Ht(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t}),this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(s){return this._snapshot={...this._snapshot,status:"error",error:s},this._error(s),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let n,s;try{n=this.logic.transition(this._snapshot,t,this._actorScope)}catch(r){s={err:r}}if(s){const{err:r}=s;this._snapshot={...this._snapshot,status:"error",error:r},this._error(r);return}this.update(n,t),t.type===de&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===R.Stopped?this:(this.mailbox.clear(),this._processingStatus===R.NotStarted?(this._processingStatus=R.Stopped,this):(this.mailbox.enqueue({type:de}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){var t;for(const n of this.observers)try{(t=n.complete)==null||t.call(n)}catch(s){B(s)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||B(t);return}let n=!1;for(const s of this.observers){const r=s.error;n||(n=!r);try{r==null||r(t)}catch(i){B(i)}}this.observers.clear(),n&&B(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,Vt(this.id,t))}_stopProcedure(){return this._processingStatus!==R.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new gt(this._process.bind(this)),this._processingStatus=R.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==R.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;t&&(typeof t=="function"?t:wn)(this)}toJSON(){return{xstate$$type:nt,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[Dn](){return this}getSnapshot(){return this._snapshot}}function $(e,...[t]){return new Un(e,t)}function Fn(e,t,n,s,{sendId:r}){const i=typeof r=="function"?r(n,s):r;return[t,i]}function Bn(e,t){e.defer(()=>{e.system.scheduler.cancel(e.self,t)})}function jn(e){function t(n,s){}return t.type="xstate.cancel",t.sendId=e,t.resolve=Fn,t.execute=Bn,t}function $n(e,t,n,s,{id:r,systemId:i,src:o,input:a,syncSnapshot:c}){const u=typeof o=="string"?tt(t.machine,o):o,h=typeof r=="function"?r(n):r;let d;return u&&(d=$(u,{id:h,src:o,parent:e.self,syncSnapshot:c,systemId:i,input:typeof a=="function"?a({context:t.context,event:n.event,self:e.self}):a})),[Q(t,{children:{...t.children,[h]:d}}),{id:r,actorRef:d}]}function Vn(e,{id:t,actorRef:n}){n&&e.defer(()=>{n._processingStatus!==R.Stopped&&n.start()})}function Hn(...[e,{id:t,systemId:n,input:s,syncSnapshot:r=!1}={}]){function i(o,a){}return i.type="snapshot.spawnChild",i.id=t,i.systemId=n,i.src=e,i.input=s,i.syncSnapshot=r,i.resolve=$n,i.execute=Vn,i}function zn(e,t,n,s,{actorRef:r}){const i=typeof r=="function"?r(n,s):r,o=typeof i=="string"?t.children[i]:i;let a=t.children;return o&&(a={...a},delete a[o.id]),[Q(t,{children:a}),o]}function Gn(e,t){if(t){if(e.system._unregister(t),t._processingStatus!==R.Running){e.stopChild(t);return}e.defer(()=>{e.stopChild(t)})}}function Qt(e){function t(n,s){}return t.type="xstate.stopChild",t.actorRef=e,t.resolve=zn,t.execute=Gn,t}function st(e,t,n,s){const{machine:r}=s,i=typeof e=="function",o=i?e:r.implementations.guards[typeof e=="string"?e:e.type];if(!i&&!o)throw new Error(`Guard '${typeof e=="string"?e:e.type}' is not implemented.'.`);if(typeof o!="function")return st(o,t,n,s);const a={context:t,event:n},c=i||typeof e=="string"?void 0:"params"in e?typeof e.params=="function"?e.params({context:t,event:n}):e.params:void 0;return"check"in o?o.check(s,a,o):o(a,c)}const rt=e=>e.type==="atomic"||e.type==="final";function ne(e){return Object.values(e.states).filter(t=>t.type!=="history")}function he(e,t){const n=[];if(t===e)return n;let s=e.parent;for(;s&&s!==t;)n.push(s),s=s.parent;return n}function Ae(e){const t=new Set(e),n=Wt(t);for(const s of t)if(s.type==="compound"&&(!n.get(s)||!n.get(s).length))It(s).forEach(r=>t.add(r));else if(s.type==="parallel"){for(const r of ne(s))if(r.type!=="history"&&!t.has(r)){const i=It(r);for(const o of i)t.add(o)}}for(const s of t){let r=s.parent;for(;r;)t.add(r),r=r.parent}return t}function Xt(e,t){const n=t.get(e);if(!n)return{};if(e.type==="compound"){const r=n[0];if(r){if(rt(r))return r.key}else return{}}const s={};for(const r of n)s[r.key]=Xt(r,t);return s}function Wt(e){const t=new Map;for(const n of e)t.has(n)||t.set(n,[]),n.parent&&(t.has(n.parent)||t.set(n.parent,[]),t.get(n.parent).push(n));return t}function Kt(e,t){const n=Ae(t);return Xt(e,Wt(n))}function it(e,t){return t.type==="compound"?ne(t).some(n=>n.type==="final"&&e.has(n)):t.type==="parallel"?ne(t).every(n=>it(e,n)):t.type==="final"}const Oe=e=>e[0]===bn;function Jn(e,t){return e.transitions.get(t)||[...e.transitions.keys()].filter(s=>{if(s===Cn)return!0;if(!s.endsWith(".*"))return!1;const r=s.split("."),i=t.split(".");for(let o=0;o<r.length;o++){const a=r[o],c=i[o];if(a==="*")return o===r.length-1;if(a!==c)return!1}return!0}).sort((s,r)=>r.length-s.length).flatMap(s=>e.transitions.get(s))}function Yn(e){const t=e.config.after;if(!t)return[];const n=(r,i)=>{const o=Nn(r,e.id),a=o.type;return e.entry.push(Ts(o,{id:a,delay:r})),e.exit.push(jn(a)),a};return Object.keys(t).flatMap((r,i)=>{const o=t[r],a=typeof o=="string"?{target:o}:o,c=Number.isNaN(+r)?r:+r,u=n(c);return j(a).map(h=>({...h,event:u,delay:c}))}).map(r=>{const{delay:i}=r;return{...J(e,r.event,r),delay:i}})}function J(e,t,n){const s=Yt(n.target),r=n.reenter??!1,i=Wn(e,s),o={...n,actions:j(n.actions),guard:n.guard,target:i,source:e,reenter:r,eventType:t,toJSON:()=>({...o,source:`#${e.id}`,target:i?i.map(a=>`#${a.id}`):void 0})};return o}function Qn(e){const t=new Map;if(e.config.on)for(const n of Object.keys(e.config.on)){if(n===jt)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const s=e.config.on[n];t.set(n,Z(s).map(r=>J(e,n,r)))}if(e.config.onDone){const n=`xstate.done.state.${e.id}`;t.set(n,Z(e.config.onDone).map(s=>J(e,n,s)))}for(const n of e.invoke){if(n.onDone){const s=`xstate.done.actor.${n.id}`;t.set(s,Z(n.onDone).map(r=>J(e,s,r)))}if(n.onError){const s=`xstate.error.actor.${n.id}`;t.set(s,Z(n.onError).map(r=>J(e,s,r)))}if(n.onSnapshot){const s=`xstate.snapshot.${n.id}`;t.set(s,Z(n.onSnapshot).map(r=>J(e,s,r)))}}for(const n of e.after){let s=t.get(n.eventType);s||(s=[],t.set(n.eventType,s)),s.push(n)}return t}function Xn(e,t){const n=typeof t=="string"?e.states[t]:t?e.states[t.target]:void 0;if(!n&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${e.id}`);const s={source:e,actions:!t||typeof t=="string"?[]:j(t.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...s,source:`#${e.id}`,target:n?[`#${n.id}`]:[]})};return s}function Wn(e,t){if(t!==void 0)return t.map(n=>{if(typeof n!="string")return n;if(Oe(n))return e.machine.getStateNodeById(n);const s=n[0]===Bt;if(s&&!e.parent)return we(e,n.slice(1));const r=s?e.key+n:n;if(e.parent)try{return we(e.parent,r)}catch(i){throw new Error(`Invalid transition definition for state node '${e.id}':
2
- ${i.message}`)}else throw new Error(`Invalid target: "${n}" is not a valid target from the root node. Did you mean ".${n}"?`)})}function Zt(e){const t=Yt(e.config.target);return t?{target:t.map(n=>typeof n=="string"?we(e.parent,n):n)}:e.parent.initial}function Y(e){return e.type==="history"}function It(e){const t=en(e);for(const n of t)for(const s of he(n,e))t.add(s);return t}function en(e){const t=new Set;function n(s){if(!t.has(s)){if(t.add(s),s.type==="compound")n(s.initial.target[0]);else if(s.type==="parallel")for(const r of ne(s))n(r)}}return n(e),t}function se(e,t){if(Oe(t))return e.machine.getStateNodeById(t);if(!e.states)throw new Error(`Unable to retrieve child state '${t}' from '${e.id}'; no child states exist.`);const n=e.states[t];if(!n)throw new Error(`Child state '${t}' does not exist on '${e.id}'`);return n}function we(e,t){if(typeof t=="string"&&Oe(t))try{return e.machine.getStateNodeById(t)}catch{}const n=et(t).slice();let s=e;for(;n.length;){const r=n.shift();if(!r.length)break;s=se(s,r)}return s}function xe(e,t){if(typeof t=="string"){const r=e.states[t];if(!r)throw new Error(`State '${t}' does not exist on '${e.id}'`);return[e,r]}const n=Object.keys(t),s=n.map(r=>se(e,r)).filter(Boolean);return[e.machine.root,e].concat(s,n.reduce((r,i)=>{const o=se(e,i);if(!o)return r;const a=xe(o,t[i]);return r.concat(a)},[]))}function Kn(e,t,n,s){const i=se(e,t).next(n,s);return!i||!i.length?e.next(n,s):i}function Zn(e,t,n,s){const r=Object.keys(t),i=se(e,r[0]),o=ot(i,t[r[0]],n,s);return!o||!o.length?e.next(n,s):o}function es(e,t,n,s){const r=[];for(const i of Object.keys(t)){const o=t[i];if(!o)continue;const a=se(e,i),c=ot(a,o,n,s);c&&r.push(...c)}return r.length?r:e.next(n,s)}function ot(e,t,n,s){return typeof t=="string"?Kn(e,t,n,s):Object.keys(t).length===1?Zn(e,t,n,s):es(e,t,n,s)}function ts(e){return Object.keys(e.states).map(t=>e.states[t]).filter(t=>t.type==="history")}function H(e,t){let n=e;for(;n.parent&&n.parent!==t;)n=n.parent;return n.parent===t}function ns(e,t){const n=new Set(e),s=new Set(t);for(const r of n)if(s.has(r))return!0;for(const r of s)if(n.has(r))return!0;return!1}function tn(e,t,n){const s=new Set;for(const r of e){let i=!1;const o=new Set;for(const a of s)if(ns(He([r],t,n),He([a],t,n)))if(H(r.source,a.source))o.add(a);else{i=!0;break}if(!i){for(const a of o)s.delete(a);s.add(r)}}return Array.from(s)}function ss(e){const[t,...n]=e;for(const s of he(t,void 0))if(n.every(r=>H(r,s)))return s}function at(e,t){if(!e.target)return[];const n=new Set;for(const s of e.target)if(Y(s))if(t[s.id])for(const r of t[s.id])n.add(r);else for(const r of at(Zt(s),t))n.add(r);else n.add(s);return[...n]}function nn(e,t){const n=at(e,t);if(!n)return;if(!e.reenter&&n.every(r=>r===e.source||H(r,e.source)))return e.source;const s=ss(n.concat(e.source));if(s)return s;if(!e.reenter)return e.source.machine.root}function He(e,t,n){var r;const s=new Set;for(const i of e)if((r=i.target)!=null&&r.length){const o=nn(i,n);i.reenter&&i.source===o&&s.add(o);for(const a of t)H(a,o)&&s.add(a)}return[...s]}function rs(e,t){if(e.length!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function ze(e,t,n,s,r,i){if(!e.length)return t;const o=new Set(t._nodes);let a=t.historyValue;const c=tn(e,o,a);let u=t;r||([u,a]=cs(u,s,n,c,o,a,i)),u=re(u,s,n,c.flatMap(d=>d.actions),i),u=os(u,s,n,c,o,i,a,r);const h=[...o];u.status==="done"&&(u=re(u,s,n,h.sort((d,f)=>f.order-d.order).flatMap(d=>d.exit),i));try{return a===t.historyValue&&rs(t._nodes,o)?u:Q(u,{_nodes:h,historyValue:a})}catch(d){throw d}}function is(e,t,n,s,r){if(s.output===void 0)return;const i=$e(r.id,r.output!==void 0&&r.parent?Ve(r.output,e.context,t,n.self):void 0);return Ve(s.output,e.context,i,n.self)}function os(e,t,n,s,r,i,o,a){let c=e;const u=new Set,h=new Set;as(s,o,h,u),a&&h.add(e.machine.root);const d=new Set;for(const f of[...u].sort((m,y)=>m.order-y.order)){r.add(f);const m=[];m.push(...f.entry);for(const y of f.invoke)m.push(Hn(y.src,{...y,syncSnapshot:!!y.onSnapshot}));if(h.has(f)){const y=f.initial.actions;m.push(...y)}if(c=re(c,t,n,m,i,f.invoke.map(y=>y.id)),f.type==="final"){const y=f.parent;let v=(y==null?void 0:y.type)==="parallel"?y:y==null?void 0:y.parent,_=v||f;for((y==null?void 0:y.type)==="compound"&&i.push($e(y.id,f.output!==void 0?Ve(f.output,c.context,t,n.self):void 0));(v==null?void 0:v.type)==="parallel"&&!d.has(v)&&it(r,v);)d.add(v),i.push($e(v.id)),_=v,v=v.parent;if(v)continue;c=Q(c,{status:"done",output:is(c,t,n,c.machine.root,_)})}}return c}function as(e,t,n,s){for(const r of e){const i=nn(r,t);for(const a of r.target||[])!Y(a)&&(r.source!==a||r.source!==i||r.reenter)&&(s.add(a),n.add(a)),ee(a,t,n,s);const o=at(r,t);for(const a of o){const c=he(a,i);(i==null?void 0:i.type)==="parallel"&&c.push(i),sn(s,t,n,c,!r.source.parent&&r.reenter?void 0:i)}}}function ee(e,t,n,s){var r;if(Y(e))if(t[e.id]){const i=t[e.id];for(const o of i)s.add(o),ee(o,t,n,s);for(const o of i)qe(o,e.parent,s,t,n)}else{const i=Zt(e);for(const o of i.target)s.add(o),i===((r=e.parent)==null?void 0:r.initial)&&n.add(e.parent),ee(o,t,n,s);for(const o of i.target)qe(o,e.parent,s,t,n)}else if(e.type==="compound"){const[i]=e.initial.target;Y(i)||(s.add(i),n.add(i)),ee(i,t,n,s),qe(i,e,s,t,n)}else if(e.type==="parallel")for(const i of ne(e).filter(o=>!Y(o)))[...s].some(o=>H(o,i))||(Y(i)||(s.add(i),n.add(i)),ee(i,t,n,s))}function sn(e,t,n,s,r){for(const i of s)if((!r||H(i,r))&&e.add(i),i.type==="parallel")for(const o of ne(i).filter(a=>!Y(a)))[...e].some(a=>H(a,o))||(e.add(o),ee(o,t,n,e))}function qe(e,t,n,s,r){sn(n,s,r,he(e,t))}function cs(e,t,n,s,r,i,o){let a=e;const c=He(s,r,i);c.sort((h,d)=>d.order-h.order);let u;for(const h of c)for(const d of ts(h)){let f;d.history==="deep"?f=m=>rt(m)&&H(m,h):f=m=>m.parent===h,u??(u={...i}),u[d.id]=Array.from(r).filter(f)}for(const h of c)a=re(a,t,n,[...h.exit,...h.invoke.map(d=>Qt(d.id))],o),r.delete(h);return[a,u||i]}let At=!1;function rn(e,t,n,s,r,i){const{machine:o}=e;let a=e;for(const c of s){let m=function(){n.system._sendInspectionEvent({type:"@xstate.action",actorRef:n.self,action:{type:typeof c=="string"?c:typeof c=="object"?c.type:c.name||"(anonymous)",params:f}});try{At=h,h(d,f)}finally{At=!1}};const u=typeof c=="function",h=u?c:o.implementations.actions[typeof c=="string"?c:c.type];if(!h)continue;const d={context:a.context,event:t,self:n.self,system:n.system},f=u||typeof c=="string"?void 0:"params"in c?typeof c.params=="function"?c.params({context:a.context,event:t}):c.params:void 0;if(!("resolve"in h)){n.self._processingStatus===R.Running?m():n.defer(()=>{m()});continue}const y=h,[v,_,w]=y.resolve(n,a,d,f,h,r);a=v,"retryResolve"in y&&(i==null||i.push([y,_])),"execute"in y&&(n.self._processingStatus===R.Running?y.execute(n,_):n.defer(y.execute.bind(null,n,_))),w&&(a=rn(a,t,n,w,r,i))}return a}function re(e,t,n,s,r,i){const o=i?[]:void 0,a=rn(e,t,n,s,{internalQueue:r,deferredActorIds:i},o);return o==null||o.forEach(([c,u])=>{c.retryResolve(n,a,u)}),a}function Me(e,t,n,s=[]){let r=e;const i=[];function o(u,h,d){n.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:n.self,event:h,snapshot:u,_transitions:d}),i.push(u)}if(t.type===de)return r=Q(wt(r,t,n),{status:"stopped"}),o(r,t,[]),{snapshot:r,microstates:i};let a=t;if(a.type!==$t){const u=a,h=Ln(u),d=xt(u,r);if(h&&!d.length)return r=Q(e,{status:"error",error:u.error}),o(r,u,[]),{snapshot:r,microstates:i};r=ze(d,e,n,a,!1,s),o(r,u,d)}let c=!0;for(;r.status==="active";){let u=c?us(r,a):[];const h=u.length?r:void 0;if(!u.length){if(!s.length)break;a=s.shift(),u=xt(a,r)}r=ze(u,r,n,a,!1,s),c=r!==h,o(r,a,u)}return r.status!=="active"&&wt(r,a,n),{snapshot:r,microstates:i}}function wt(e,t,n){return re(e,t,n,Object.values(e.children).map(s=>Qt(s)),[])}function xt(e,t){return t.machine.getTransitionData(t,e)}function us(e,t){const n=new Set,s=e._nodes.filter(rt);for(const r of s)e:for(const i of[r].concat(he(r,void 0)))if(i.always){for(const o of i.always)if(o.guard===void 0||st(o.guard,e.context,t,e)){n.add(o);break e}}return tn(Array.from(n),new Set(e._nodes),e.historyValue)}function ds(e,t){const n=Ae(xe(e,t));return Kt(e,[...n])}function ls(e){return!!e&&typeof e=="object"&&"machine"in e&&"value"in e}const hs=function(t){return zt(t,this.value)},fs=function(t){return this.tags.has(t)},ps=function(t){const n=this.machine.getTransitionData(this,t);return!!(n!=null&&n.length)&&n.some(s=>s.target!==void 0||s.actions.length)},ys=function(){const{_nodes:t,tags:n,machine:s,getMeta:r,toJSON:i,can:o,hasTag:a,matches:c,...u}=this;return{...u,tags:Array.from(n)}},ms=function(){return this._nodes.reduce((t,n)=>(n.meta!==void 0&&(t[n.id]=n.meta),t),{})};function Te(e,t){return{status:e.status,output:e.output,error:e.error,machine:t,context:e.context,_nodes:e._nodes,value:Kt(t.root,e._nodes),tags:new Set(e._nodes.flatMap(n=>n.tags)),children:e.children,historyValue:e.historyValue||{},matches:hs,hasTag:fs,can:ps,getMeta:ms,toJSON:ys}}function Q(e,t={}){return Te({...e,...t},e.machine)}function gs(e,t){const{_nodes:n,tags:s,machine:r,children:i,context:o,can:a,hasTag:c,matches:u,getMeta:h,toJSON:d,...f}=e,m={};for(const v in i){const _=i[v];m[v]={snapshot:_.getPersistedSnapshot(t),src:_.src,systemId:_._systemId,syncSnapshot:_._syncSnapshot}}return{...f,context:on(o),children:m}}function on(e){let t;for(const n in e){const s=e[n];if(s&&typeof s=="object")if("sessionId"in s&&"send"in s&&"ref"in s)t??(t=Array.isArray(e)?e.slice():{...e}),t[n]={xstate$$type:nt,id:s.id};else{const r=on(s);r!==s&&(t??(t=Array.isArray(e)?e.slice():{...e}),t[n]=r)}}return t??e}function Es(e,t,n,s,{event:r,id:i,delay:o},{internalQueue:a}){const c=t.machine.implementations.delays;if(typeof r=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${r}" }) instead`);const u=typeof r=="function"?r(n,s):r;let h;if(typeof o=="string"){const d=c&&c[o];h=typeof d=="function"?d(n,s):d}else h=typeof o=="function"?o(n,s):o;return typeof h!="number"&&a.push(u),[t,{event:u,id:i,delay:h}]}function vs(e,t){const{event:n,delay:s,id:r}=t;if(typeof s=="number"){e.defer(()=>{const i=e.self;e.system.scheduler.schedule(i,i,n,s,r)});return}}function Ts(e,t){function n(s,r){}return n.type="xstate.raise",n.event=e,n.id=t==null?void 0:t.id,n.delay=t==null?void 0:t.delay,n.resolve=Es,n.execute=vs,n}const bt=new WeakMap;function Ss(e){return{config:e,start:(n,s)=>{const{self:r,system:i}=s,o={receivers:void 0,dispose:void 0};bt.set(r,o),o.dispose=e({input:n.input,system:i,self:r,sendBack:a=>{r.getSnapshot().status!=="stopped"&&r._parent&&i._relay(r,r._parent,a)},receive:a=>{o.receivers??(o.receivers=new Set),o.receivers.add(a)}})},transition:(n,s,r)=>{var o,a;const i=bt.get(r.self);return s.type===de?(n={...n,status:"stopped",error:void 0},(o=i.dispose)==null||o.call(i),n):((a=i.receivers)==null||a.forEach(c=>c(s)),n)},getInitialSnapshot:(n,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedSnapshot:n=>n,restoreSnapshot:n=>n}}const Ct="xstate.promise.resolve",Ot="xstate.promise.reject",Ee=new WeakMap;function V(e){return{config:e,transition:(n,s,r)=>{var i;if(n.status!=="active")return n;switch(s.type){case Ct:{const o=s.data;return{...n,status:"done",output:o,input:void 0}}case Ot:return{...n,status:"error",error:s.data,input:void 0};case de:return(i=Ee.get(r.self))==null||i.abort(),{...n,status:"stopped",input:void 0};default:return n}},start:(n,{self:s,system:r})=>{if(n.status!=="active")return;const i=new AbortController;Ee.set(s,i),Promise.resolve(e({input:n.input,system:r,self:s,signal:i.signal})).then(a=>{s.getSnapshot().status==="active"&&(Ee.delete(s),r._relay(s,s,{type:Ct,data:a}))},a=>{s.getSnapshot().status==="active"&&(Ee.delete(s),r._relay(s,s,{type:Ot,data:a}))})},getInitialSnapshot:(n,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedSnapshot:n=>n,restoreSnapshot:n=>n}}function _s(e,{machine:t,context:n},s,r){const i=(o,a={})=>{const{systemId:c,input:u}=a;if(typeof o=="string"){const h=tt(t,o);if(!h)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const d=$(h,{id:a.id,parent:e.self,syncSnapshot:a.syncSnapshot,input:typeof u=="function"?u({context:n,event:s,self:e.self}):u,src:o,systemId:c});return r[d.id]=d,d}else return $(o,{id:a.id,parent:e.self,syncSnapshot:a.syncSnapshot,input:a.input,src:o,systemId:c})};return(o,a)=>{const c=i(o,a);return r[c.id]=c,e.defer(()=>{c._processingStatus!==R.Stopped&&c.start()}),c}}function Is(e,t,n,s,{assignment:r}){if(!t.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},o={context:t.context,event:n.event,spawn:_s(e,t,n.event,i),self:e.self,system:e.system};let a={};if(typeof r=="function")a=r(o,s);else for(const u of Object.keys(r)){const h=r[u];a[u]=typeof h=="function"?h(o,s):h}const c=Object.assign({},t.context,a);return[Q(t,{context:c,children:Object.keys(i).length?{...t.children,...i}:t.children})]}function x(e){function t(n,s){}return t.type="xstate.assign",t.assignment=e,t.resolve=Is,t}function As(e,t,n,s,{event:r}){const i=typeof r=="function"?r(n,s):r;return[t,{event:i}]}function ws(e,{event:t}){e.defer(()=>e.emit(t))}function Le(e){function t(n,s){}return t.type="xstate.emit",t.event=e,t.resolve=As,t.execute=ws,t}let Nt=function(e){return e.Parent="#_parent",e.Internal="#_internal",e}({});function xs(e,t,n,s,{to:r,event:i,id:o,delay:a},c){var y;const u=t.machine.implementations.delays;if(typeof i=="string")throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${i}" }) instead`);const h=typeof i=="function"?i(n,s):i;let d;if(typeof a=="string"){const v=u&&u[a];d=typeof v=="function"?v(n,s):v}else d=typeof a=="function"?a(n,s):a;const f=typeof r=="function"?r(n,s):r;let m;if(typeof f=="string"){if(f===Nt.Parent?m=e.self._parent:f===Nt.Internal?m=e.self:f.startsWith("#_")?m=t.children[f.slice(2)]:m=(y=c.deferredActorIds)!=null&&y.includes(f)?f:t.children[f],!m)throw new Error(`Unable to send event to actor '${f}' from machine '${t.machine.id}'.`)}else m=f||e.self;return[t,{to:m,event:h,id:o,delay:d}]}function bs(e,t,n){typeof n.to=="string"&&(n.to=t.children[n.to])}function Cs(e,t){e.defer(()=>{const{to:n,event:s,delay:r,id:i}=t;if(typeof r=="number"){e.system.scheduler.schedule(e.self,n,s,r,i);return}e.system._relay(e.self,n,s.type===On?Vt(e.self.id,s.data):s)})}function kt(e,t,n){function s(r,i){}return s.type="xsnapshot.sendTo",s.to=e,s.event=t,s.id=n==null?void 0:n.id,s.delay=n==null?void 0:n.delay,s.resolve=xs,s.retryResolve=bs,s.execute=Cs,s}const Dt=new WeakMap;function W(e,t,n){let s=Dt.get(e);return s?t in s||(s[t]=n()):(s={[t]:n()},Dt.set(e,s)),s[t]}const Os={},ae=e=>typeof e=="string"?{type:e}:typeof e=="function"?"resolve"in e?{type:e.type}:{type:e.name}:e;class ct{constructor(t,n){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=n._parent,this.key=n._key,this.machine=n._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(Bt),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?Tt(this.config.states,(s,r)=>new ct(s,{_parent:this,_key:r,_machine:this.machine})):Os,this.type==="compound"&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?"shallow":this.config.history||!1,this.entry=j(this.config.entry).slice(),this.exit=j(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=j(t.tags).slice()}_initialize(){this.transitions=Qn(this),this.config.always&&(this.always=Z(this.config.always).map(t=>J(this,jt,t))),Object.keys(this.states).forEach(t=>{this.states[t]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(ae),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(ae),eventType:null})}:void 0,history:this.history,states:Tt(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(ae)})),entry:this.entry.map(ae),exit:this.exit.map(ae),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return W(this,"invoke",()=>j(this.config.invoke).map((t,n)=>{const{src:s,systemId:r}=t,i=t.id??_t(this.id,n),o=typeof s=="string"?s:`xstate.invoke.${_t(this.id,n)}`;return{...t,src:o,id:i,systemId:r,toJSON(){const{onDone:a,onError:c,...u}=t;return{...u,type:"xstate.invoke",src:o,id:i}}}}))}get on(){return W(this,"on",()=>[...this.transitions].flatMap(([n,s])=>s.map(r=>[n,r])).reduce((n,[s,r])=>(n[s]=n[s]||[],n[s].push(r),n),{}))}get after(){return W(this,"delayedTransitions",()=>Yn(this))}get initial(){return W(this,"initial",()=>Xn(this,this.config.initial))}next(t,n){const s=n.type,r=[];let i;const o=W(this,`candidates-${s}`,()=>Jn(this,s));for(const a of o){const{guard:c}=a,u=t.context;let h=!1;try{h=!c||st(c,u,n,t)}catch(d){const f=typeof c=="string"?c:typeof c=="object"?c.type:void 0;throw new Error(`Unable to evaluate guard ${f?`'${f}' `:""}in transition for event '${s}' in state node '${this.id}':
3
- ${d.message}`)}if(h){r.push(...a.actions),i=a;break}}return i?[i]:void 0}get events(){return W(this,"events",()=>{const{states:t}=this,n=new Set(this.ownEvents);if(t)for(const s of Object.keys(t)){const r=t[s];if(r.states)for(const i of r.events)n.add(`${i}`)}return Array.from(n)})}get ownEvents(){const t=new Set([...this.transitions.keys()].filter(n=>this.transitions.get(n).some(s=>!(!s.target&&!s.actions.length&&!s.reenter))));return Array.from(t)}}const Ns="#";class ut{constructor(t,n){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.__TResolvedTypesMeta=void 0,this.id=t.id||"(machine)",this.implementations={actors:(n==null?void 0:n.actors)??{},actions:(n==null?void 0:n.actions)??{},delays:(n==null?void 0:n.delays)??{},guards:(n==null?void 0:n.guards)??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new ct(t,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:n,guards:s,actors:r,delays:i}=this.implementations;return new ut(this.config,{actions:{...n,...t.actions},guards:{...s,...t.guards},actors:{...r,...t.actors},delays:{...i,...t.delays}})}resolveState(t){const n=ds(this.root,t.value),s=Ae(xe(this.root,n));return Te({_nodes:[...s],context:t.context||{},children:{},status:it(s,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,n,s){return Me(t,n,s).snapshot}microstep(t,n,s){return Me(t,n,s).microstates}getTransitionData(t,n){return ot(this.root,t.value,t,n)||[]}getPreInitialState(t,n,s){const{context:r}=this.config,i=Te({context:typeof r!="function"&&r?r:{},_nodes:[this.root],children:{},status:"active"},this);return typeof r=="function"?re(i,n,t,[x(({spawn:a,event:c,self:u})=>r({spawn:a,input:c.input,self:u}))],s):i}getInitialSnapshot(t,n){const s=Ht(n),r=[],i=this.getPreInitialState(t,s,r),o=ze([{target:[...en(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],i,t,s,!0,r),{snapshot:a}=Me(o,s,t,r);return a}start(t){Object.values(t.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(t){const n=et(t),s=n.slice(1),r=Oe(n[0])?n[0].slice(Ns.length):n[0],i=this.idMap.get(r);if(!i)throw new Error(`Child state node '#${r}' does not exist on machine '${this.id}'`);return we(i,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,n){return gs(t,n)}restoreSnapshot(t,n){const s={},r=t.children;Object.keys(r).forEach(c=>{const u=r[c],h=u.snapshot,d=u.src,f=typeof d=="string"?tt(this,d):d;if(!f)return;const m=$(f,{id:c,parent:n.self,syncSnapshot:u.syncSnapshot,snapshot:h,src:d,systemId:u.systemId});s[c]=m});const i=Te({...t,children:s,_nodes:Array.from(Ae(xe(this.root,t.value)))},this);let o=new Set;function a(c,u){if(!o.has(c)){o.add(c);for(let h in c){const d=c[h];if(d&&typeof d=="object"){if("xstate$$type"in d&&d.xstate$$type===nt){c[h]=u[d.id];continue}a(d,u)}}}}return a(i.context,s),i}}function ks(e,t){return new ut(e,t)}function fe({schemas:e,actors:t,actions:n,guards:s,delays:r}){return{createMachine:i=>ks({...i,schemas:e},{actors:t,actions:n,guards:s,delays:r})}}function Ge(e,t){const n=j(t);if(!n.includes(e.type)){const s=n.length===1?`type "${n[0]}"`:`one of types "${n.join('", "')}"`;throw new Error(`Expected event ${JSON.stringify(e)} to have ${s}`)}}function Ds({context:e,event:t}){if(!t.type.includes("xstate.error.actor"))return e;const n=t;return{errors:[...e.errors,String(n.error).replace("Error: ","")]}}function Rs(){return{errors:[]}}function qs({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="REFRESH_TOKEN_SUCCESS"?e:{accessToken:n.output.accessToken,ignoreRefreshToken:!1}}function Ms(){return{ignoreRefreshToken:!0}}function Ls({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="AUTHENTICATE_SUCCESS"?e:{accessToken:n.output.accessToken,ignoreRefreshToken:!1}}function Ps(){return{refreshToken:""}}function Us(){return{user:null,accessToken:"",refreshToken:"",ignoreRefreshToken:!1}}async function Je(e,t){const n=await fetch(e,t);return n.status===200?n.json():Promise.resolve({message:n.statusText,success:!1})}const Fs=V(async({input:e})=>{var t;if(!e.endpoint.client||e.endpoint.client==="")throw console.log("refreshAccessToken: No client endpoint provided."),new Error("No client endpoint provided.");try{const n=await Je(e.endpoint.client,{method:"POST",mode:"cors",credentials:"include",headers:{"Content-Type":"application/json","clicktap-scope":"view","clicktap-scope-id":"default"},body:JSON.stringify({username:e.username,password:e.password}).toString()});if(!n.success)throw new Error(((t=n.message)==null?void 0:t.toString())??"Sign in failed. Please try again.");return{type:"AUTHENTICATE_SUCCESS",user:null,accessToken:n.accessToken??""}}catch(n){throw console.log(n),new Error("Could not complete authenticate request (server)")}}),Bs=typeof window>"u",js=V(async({input:e})=>{if(!e.endpoint.client||e.endpoint.client==="")throw console.log("refreshAccessToken: No client endpoint provided."),new Error("No client endpoint provided.");if(!e.endpoint.server||e.endpoint.server==="")throw console.log("refreshAccessToken: No server endpoint provided."),new Error("No server endpoint provided.");let t;if(Bs){if(e.refreshToken==="")throw new Error("Unauthorized.");try{if(t=await Je(e.endpoint.server,{method:"POST",mode:"cors",credentials:"include",headers:{Cookie:`refresh_token=${e.refreshToken}`,"Content-Type":"application/json","clicktap-scope":"view","clicktap-scope-id":"default"}}),typeof t.accessToken>"u")throw new Error("Unauthorized.");return{type:"REFRESH_TOKEN_SUCCESS",accessToken:t.accessToken}}catch(n){throw console.log(n),new Error("Could not complete refresh request (server)")}}else{if(t=await Je(e.endpoint.client,{method:"POST",mode:"cors",credentials:"include",headers:{"Content-Type":"application/json","clicktap-scope":"view","clicktap-scope-id":"default"},body:JSON.stringify({grant_type:"refresh_token"}).toString()}),typeof t.accessToken>"u")throw new Error("Unauthorized.");return{type:"REFRESH_TOKEN_SUCCESS",accessToken:t.accessToken}}}),$s=V(async({input:e})=>{if(!e.endpoint.client||e.endpoint.client==="")throw console.log("unauthenticate: No client endpoint provided."),new Error("No client endpoint provided.");try{return await fetch(e.endpoint.client,{method:"POST",mode:"cors",credentials:"include",headers:{"clicktap-scope":"view","clicktap-scope-id":"default"}}),{type:"UNAUTHENTICATE_SUCCESS"}}catch(t){throw console.log(t),new Error("Could not complete unauthenticate request (server)")}}),an=fe({types:{context:{},events:{},input:{}},actions:{addError:x(Ds),clearErrors:x(Rs),setAccessToken:x(qs),setIgnoreRefreshToken:x(Ms),setUserContext:x(Ls),unsetRefreshToken:x(Ps),unsetUserContext:x(Us)},actors:{authenticate:Fs,refreshAccessToken:js,unauthenticate:$s}}).createMachine({id:"auth",context:({input:e})=>{var t,n;return{user:null,accessToken:"",refreshToken:((t=e==null?void 0:e.initialContext)==null?void 0:t.refreshToken)??"",ignoreRefreshToken:!1,endpoints:((n=e==null?void 0:e.initialContext)==null?void 0:n.endpoints)??{login:"",logout:"",refresh:"",ssrRefresh:""},errors:[]}},initial:"refreshing",states:{authenticating:{invoke:{src:"authenticate",input:({context:e,event:t})=>(Ge(t,"LOGIN"),{endpoint:{client:e.endpoints.login},username:t.username,password:t.password}),onDone:[{actions:"setUserContext",target:"loggedIn"}],onError:[{actions:"addError",target:"loggedOut"}]}},unauthenticating:{invoke:{src:"unauthenticate",input:({context:e})=>({endpoint:{client:e.endpoints.logout}}),onDone:[{actions:"unsetUserContext",target:"loggedOut"}],onError:[{actions:["unsetUserContext","setIgnoreRefreshToken"],target:"loggedOut"}]}},refreshing:{invoke:{src:"refreshAccessToken",input:({context:e})=>({accessToken:e.accessToken,endpoint:{client:e.endpoints.refresh,server:e.endpoints.ssrRefresh},refreshToken:e.refreshToken}),onDone:[{actions:["unsetRefreshToken","setAccessToken"],target:"loggedIn"}],onError:[{actions:"unsetRefreshToken",target:"unauthenticating",guard:()=>typeof window<"u"},{actions:"unsetRefreshToken",target:"loggedOut"}]}},loggedOut:{on:{LOGIN:{target:"authenticating"},CLEAR_ERRORS:{actions:"clearErrors"}}},loggedIn:{after:{84e4:{guard:()=>typeof window<"u",target:"refreshing"}},on:{LOGOUT:{target:"unauthenticating"},CLEAR_ERRORS:{actions:"clearErrors"}}}}}),dt=N.createContext({}),Vs=()=>{const e=N.useContext(dt),[t,n]=N.useState(typeof window<"u"&&e.getSnapshot().value==="loggedIn");return N.useEffect(()=>{if(typeof window>"u")return;const s=e.subscribe(r=>{(r.value==="loggedIn"||r.value==="loggedOut")&&n(r.value==="loggedIn")});return()=>{s.unsubscribe()}},[e]),{authActor:e,isLoggedIn:t}},Hs=async(e="",t={inspect:void 0,endpoints:{login:"",logout:"",refresh:"",ssrRefresh:""}})=>$(an,{input:{initialContext:{endpoints:t.endpoints,refreshToken:e}},inspect:t.inspect}).start();function zs({actor:e,children:t}){return Ce.jsx(dt.Provider,{value:e,children:t})}function Gs({context:e,event:t}){if(t.type!=="CHANGE_STEP")return e;const n=e.quote.checkoutSteps,s=n==null?void 0:n.find(r=>r.code===t.step);return!s||!s.isAvailable?e:{currentStep:s.code??e.currentStep}}function Js({context:e,event:t}){var r,i;if(!t.type.includes("xstate.done.actor")||t.output.type!=="SUBMIT_STEP_DATA_SUCCESS")return e;const s=(i=(r=e.steps)==null?void 0:r.find(o=>o.code===e.currentStep))==null?void 0:i.next;return s?{currentStep:s??e.currentStep}:e}function Ys({context:e,event:t}){return t.type!=="RESET_CHECKOUT"?e:{currentStep:t.data.currentStep,errors:[],steps:t.data.steps,successId:"",quote:t.data.quote}}function Qs({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="SUBMIT_STEP_DATA_SUCCESS"?e:{quote:{...e.quote,...n.output.quote}}}function Xs({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="PLACE_ORDER_SUCCESS"?e:{successId:n.output.successId}}const lt=JSON,Ws=e=>e.toUpperCase(),Ks=e=>{const t={};return e.forEach((n,s)=>{t[s]=n}),t},Zs=(e,t,n)=>e.document?e:{document:e,variables:t,requestHeaders:n,signal:void 0},er=(e,t,n)=>e.query?e:{query:e,variables:t,requestHeaders:n,signal:void 0},tr=(e,t)=>e.documents?e:{documents:e,requestHeaders:t,signal:void 0},nr=(e,t,...n)=>{const[s,r]=n;return e.document?e:{url:e,document:t,variables:s,requestHeaders:r,signal:void 0}};function Se(e,t){if(!!!e)throw new Error(t)}function sr(e){return typeof e=="object"&&e!==null}function rr(e,t){if(!!!e)throw new Error(t??"Unexpected invariant triggered.")}const ir=/\r\n|[\n\r]/g;function Ye(e,t){let n=0,s=1;for(const r of e.body.matchAll(ir)){if(typeof r.index=="number"||rr(!1),r.index>=t)break;n=r.index+r[0].length,s+=1}return{line:s,column:t+1-n}}function or(e){return cn(e.source,Ye(e.source,e.start))}function cn(e,t){const n=e.locationOffset.column-1,s="".padStart(n)+e.body,r=t.line-1,i=e.locationOffset.line-1,o=t.line+i,a=t.line===1?n:0,c=t.column+a,u=`${e.name}:${o}:${c}
4
- `,h=s.split(/\r\n|[\n\r]/g),d=h[r];if(d.length>120){const f=Math.floor(c/80),m=c%80,y=[];for(let v=0;v<d.length;v+=80)y.push(d.slice(v,v+80));return u+Rt([[`${o} |`,y[0]],...y.slice(1,f+1).map(v=>["|",v]),["|","^".padStart(m)],["|",y[f+1]]])}return u+Rt([[`${o-1} |`,h[r-1]],[`${o} |`,d],["|","^".padStart(c)],[`${o+1} |`,h[r+1]]])}function Rt(e){const t=e.filter(([s,r])=>r!==void 0),n=Math.max(...t.map(([s])=>s.length));return t.map(([s,r])=>s.padStart(n)+(r?" "+r:"")).join(`
5
- `)}function ar(e){const t=e[0];return t==null||"kind"in t||"length"in t?{nodes:t,source:e[1],positions:e[2],path:e[3],originalError:e[4],extensions:e[5]}:t}class ht extends Error{constructor(t,...n){var s,r,i;const{nodes:o,source:a,positions:c,path:u,originalError:h,extensions:d}=ar(n);super(t),this.name="GraphQLError",this.path=u??void 0,this.originalError=h??void 0,this.nodes=qt(Array.isArray(o)?o:o?[o]:void 0);const f=qt((s=this.nodes)===null||s===void 0?void 0:s.map(y=>y.loc).filter(y=>y!=null));this.source=a??(f==null||(r=f[0])===null||r===void 0?void 0:r.source),this.positions=c??(f==null?void 0:f.map(y=>y.start)),this.locations=c&&a?c.map(y=>Ye(a,y)):f==null?void 0:f.map(y=>Ye(y.source,y.start));const m=sr(h==null?void 0:h.extensions)?h==null?void 0:h.extensions:void 0;this.extensions=(i=d??m)!==null&&i!==void 0?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}}),h!=null&&h.stack?Object.defineProperty(this,"stack",{value:h.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,ht):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}get[Symbol.toStringTag](){return"GraphQLError"}toString(){let t=this.message;if(this.nodes)for(const n of this.nodes)n.loc&&(t+=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ke=require("react/jsx-runtime"),N=require("react");function _n(e,t){for(var n=0;n<t.length;n++){const s=t[n];if(typeof s!="string"&&!Array.isArray(s)){for(const r in s)if(r!=="default"&&!(r in e)){const i=Object.getOwnPropertyDescriptor(s,r);i&&Object.defineProperty(e,r,i.get?i:{enumerable:!0,get:()=>s[r]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}function In(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function An(){const e=In();if(e.__xstate__)return e.__xstate__}const wn=e=>{if(typeof window>"u")return;const t=An();t&&t.register(e)};class gt{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const n={value:t,next:null};if(this._current){this._last.next=n,this._last=n;return}this._current=n,this._last=n,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const Bt=".",xn="",jt="",bn="#",Cn="*",$t="xstate.init",kn="xstate.error",de="xstate.stop";function Nn(e,t){return{type:`xstate.after.${e}.${t}`}}function $e(e,t){return{type:`xstate.done.state.${e}`,output:t}}function On(e,t){return{type:`xstate.done.actor.${e}`,output:t}}function Vt(e,t){return{type:`xstate.error.actor.${e}`,error:t}}function Ht(e){return{type:$t,input:e}}function B(e){setTimeout(()=>{throw e})}const Dn=(()=>typeof Symbol=="function"&&Symbol.observable||"@@observable")();function Et(e,t){return`${e.sessionId}.${t}`}let Rn=0;function qn(e,t){const n=new Map,s=new Map,r=new WeakMap,i=new Set,o={},{clock:a,logger:c}=t,u={schedule:(h,m,y,T,_=Math.random().toString(36).slice(2))=>{const w={source:h,target:m,event:y,delay:T,id:_,startedAt:Date.now()},q=Et(h,_);l._snapshot._scheduledEvents[q]=w;const D=a.setTimeout(()=>{delete o[q],delete l._snapshot._scheduledEvents[q],l._relay(h,m,y)},T);o[q]=D},cancel:(h,m)=>{const y=Et(h,m),T=o[y];delete o[y],delete l._snapshot._scheduledEvents[y],a.clearTimeout(T)},cancelAll:h=>{for(const m in l._snapshot._scheduledEvents){const y=l._snapshot._scheduledEvents[m];y.source===h&&u.cancel(h,y.id)}}},f=h=>{if(!i.size)return;const m={...h,rootId:e.sessionId};i.forEach(y=>{var T;return(T=y.next)==null?void 0:T.call(y,m)})},l={_snapshot:{_scheduledEvents:((t==null?void 0:t.snapshot)&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${Rn++}`,_register:(h,m)=>(n.set(h,m),h),_unregister:h=>{n.delete(h.sessionId);const m=r.get(h);m!==void 0&&(s.delete(m),r.delete(h))},get:h=>s.get(h),_set:(h,m)=>{const y=s.get(h);if(y&&y!==m)throw new Error(`Actor with system ID '${h}' already exists.`);s.set(h,m),r.set(m,h)},inspect:h=>{i.add(h)},_sendInspectionEvent:f,_relay:(h,m,y)=>{l._sendInspectionEvent({type:"@xstate.event",sourceRef:h,actorRef:m,event:y}),m._send(y)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...l._snapshot._scheduledEvents}}),start:()=>{const h=l._snapshot._scheduledEvents;l._snapshot._scheduledEvents={};for(const m in h){const{source:y,target:T,event:_,delay:w,id:q}=h[m];u.schedule(y,T,_,w,q)}},_clock:a,_logger:c};return l}function zt(e,t){const n=Tt(e),s=Tt(t);return typeof s=="string"?typeof n=="string"?s===n:!1:typeof n=="string"?n in s:Object.keys(n).every(r=>r in s?zt(n[r],s[r]):!1)}function et(e){if(Jt(e))return e;let t=[],n="";for(let s=0;s<e.length;s++){switch(e.charCodeAt(s)){case 92:n+=e[s+1],s++;continue;case 46:t.push(n),n="";continue}n+=e[s]}return t.push(n),t}function Tt(e){if(ls(e))return e.value;if(typeof e!="string")return e;const t=et(e);return Mn(t)}function Mn(e){if(e.length===1)return e[0];const t={};let n=t;for(let s=0;s<e.length-1;s++)if(s===e.length-2)n[e[s]]=e[s+1];else{const r=n;n={},r[e[s]]=n}return t}function vt(e,t){const n={},s=Object.keys(e);for(let r=0;r<s.length;r++){const i=s[r];n[i]=t(e[i],i,e,r)}return n}function Gt(e){return Jt(e)?e:[e]}function j(e){return e===void 0?[]:Gt(e)}function Ve(e,t,n,s){return typeof e=="function"?e({context:t,event:n,self:s}):e}function Jt(e){return Array.isArray(e)}function Ln(e){return e.type.startsWith("xstate.error.actor")}function Z(e){return Gt(e).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function Yt(e){if(!(e===void 0||e===xn))return j(e)}function St(e,t,n){var i,o,a;const s=typeof e=="object",r=s?e:void 0;return{next:(i=s?e.next:e)==null?void 0:i.bind(r),error:(o=s?e.error:t)==null?void 0:o.bind(r),complete:(a=s?e.complete:n)==null?void 0:a.bind(r)}}function _t(e,t){return`${t}.${e}`}function tt(e,t){const n=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return e.implementations.actors[t];const[,s,r]=n,o=e.getStateNodeById(r).config.invoke;return(Array.isArray(o)?o[s]:o).src}const nt=1;let R=function(e){return e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped",e}({});const Un={clock:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},logger:console.log.bind(console),devTools:!1};class Pn{constructor(t,n){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new gt(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=R.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const s={...Un,...n},{clock:r,logger:i,parent:o,syncSnapshot:a,id:c,systemId:u,inspect:f}=s;this.system=o?o.system:qn(this,{clock:r,logger:i}),f&&!o&&this.system.inspect(St(f)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=(n==null?void 0:n.logger)??this.system._logger,this.clock=(n==null?void 0:n.clock)??this.system._clock,this._parent=o,this._syncSnapshot=a,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:l=>{this._deferred.push(l)},system:this.system,stopChild:l=>{if(l._parent!==this)throw new Error(`Cannot stop child actor ${l.id} of ${this.id} because it is not a child`);l._stop()},emit:l=>{const h=this.eventListeners.get(l.type);if(h)for(const m of Array.from(h))m(l)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),u&&(this._systemId=u,this.system._set(u,this)),this._initState((n==null?void 0:n.snapshot)??(n==null?void 0:n.state)),u&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(t){var n;try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,(n=this.options)==null?void 0:n.input)}catch(s){this._snapshot={status:"error",output:void 0,error:s}}}update(t,n){var r,i;this._snapshot=t;let s;for(;s=this._deferred.shift();)try{s()}catch(o){this._deferred.length=0,this._snapshot={...t,status:"error",error:o}}switch(this._snapshot.status){case"active":for(const o of this.observers)try{(r=o.next)==null||r.call(o,t)}catch(a){B(a)}break;case"done":for(const o of this.observers)try{(i=o.next)==null||i.call(o,t)}catch(a){B(a)}this._stopProcedure(),this._complete(),this._doneEvent=On(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:n,snapshot:t})}subscribe(t,n,s){var i;const r=St(t,n,s);if(this._processingStatus!==R.Stopped)this.observers.add(r);else switch(this._snapshot.status){case"done":try{(i=r.complete)==null||i.call(r)}catch(o){B(o)}break;case"error":{const o=this._snapshot.error;if(!r.error)B(o);else try{r.error(o)}catch(a){B(a)}break}}return{unsubscribe:()=>{this.observers.delete(r)}}}on(t,n){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const r=n.bind(void 0);return s.add(r),{unsubscribe:()=>{s.delete(r)}}}start(){if(this._processingStatus===R.Running)return this;this._syncSnapshot&&this.subscribe({next:s=>{s.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:s})},error:()=>{}}),this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this._processingStatus=R.Running;const t=Ht(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t}),this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(s){return this._snapshot={...this._snapshot,status:"error",error:s},this._error(s),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let n,s;try{n=this.logic.transition(this._snapshot,t,this._actorScope)}catch(r){s={err:r}}if(s){const{err:r}=s;this._snapshot={...this._snapshot,status:"error",error:r},this._error(r);return}this.update(n,t),t.type===de&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===R.Stopped?this:(this.mailbox.clear(),this._processingStatus===R.NotStarted?(this._processingStatus=R.Stopped,this):(this.mailbox.enqueue({type:de}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){var t;for(const n of this.observers)try{(t=n.complete)==null||t.call(n)}catch(s){B(s)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||B(t);return}let n=!1;for(const s of this.observers){const r=s.error;n||(n=!r);try{r==null||r(t)}catch(i){B(i)}}this.observers.clear(),n&&B(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,Vt(this.id,t))}_stopProcedure(){return this._processingStatus!==R.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new gt(this._process.bind(this)),this._processingStatus=R.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==R.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;t&&(typeof t=="function"?t:wn)(this)}toJSON(){return{xstate$$type:nt,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[Dn](){return this}getSnapshot(){return this._snapshot}}function $(e,...[t]){return new Pn(e,t)}function Fn(e,t,n,s,{sendId:r}){const i=typeof r=="function"?r(n,s):r;return[t,i]}function Bn(e,t){e.defer(()=>{e.system.scheduler.cancel(e.self,t)})}function jn(e){function t(n,s){}return t.type="xstate.cancel",t.sendId=e,t.resolve=Fn,t.execute=Bn,t}function $n(e,t,n,s,{id:r,systemId:i,src:o,input:a,syncSnapshot:c}){const u=typeof o=="string"?tt(t.machine,o):o,f=typeof r=="function"?r(n):r;let l;return u&&(l=$(u,{id:f,src:o,parent:e.self,syncSnapshot:c,systemId:i,input:typeof a=="function"?a({context:t.context,event:n.event,self:e.self}):a})),[Q(t,{children:{...t.children,[f]:l}}),{id:r,actorRef:l}]}function Vn(e,{id:t,actorRef:n}){n&&e.defer(()=>{n._processingStatus!==R.Stopped&&n.start()})}function Hn(...[e,{id:t,systemId:n,input:s,syncSnapshot:r=!1}={}]){function i(o,a){}return i.type="snapshot.spawnChild",i.id=t,i.systemId=n,i.src=e,i.input=s,i.syncSnapshot=r,i.resolve=$n,i.execute=Vn,i}function zn(e,t,n,s,{actorRef:r}){const i=typeof r=="function"?r(n,s):r,o=typeof i=="string"?t.children[i]:i;let a=t.children;return o&&(a={...a},delete a[o.id]),[Q(t,{children:a}),o]}function Gn(e,t){if(t){if(e.system._unregister(t),t._processingStatus!==R.Running){e.stopChild(t);return}e.defer(()=>{e.stopChild(t)})}}function Qt(e){function t(n,s){}return t.type="xstate.stopChild",t.actorRef=e,t.resolve=zn,t.execute=Gn,t}function st(e,t,n,s){const{machine:r}=s,i=typeof e=="function",o=i?e:r.implementations.guards[typeof e=="string"?e:e.type];if(!i&&!o)throw new Error(`Guard '${typeof e=="string"?e:e.type}' is not implemented.'.`);if(typeof o!="function")return st(o,t,n,s);const a={context:t,event:n},c=i||typeof e=="string"?void 0:"params"in e?typeof e.params=="function"?e.params({context:t,event:n}):e.params:void 0;return"check"in o?o.check(s,a,o):o(a,c)}const rt=e=>e.type==="atomic"||e.type==="final";function ne(e){return Object.values(e.states).filter(t=>t.type!=="history")}function he(e,t){const n=[];if(t===e)return n;let s=e.parent;for(;s&&s!==t;)n.push(s),s=s.parent;return n}function we(e){const t=new Set(e),n=Wt(t);for(const s of t)if(s.type==="compound"&&(!n.get(s)||!n.get(s).length))It(s).forEach(r=>t.add(r));else if(s.type==="parallel"){for(const r of ne(s))if(r.type!=="history"&&!t.has(r)){const i=It(r);for(const o of i)t.add(o)}}for(const s of t){let r=s.parent;for(;r;)t.add(r),r=r.parent}return t}function Xt(e,t){const n=t.get(e);if(!n)return{};if(e.type==="compound"){const r=n[0];if(r){if(rt(r))return r.key}else return{}}const s={};for(const r of n)s[r.key]=Xt(r,t);return s}function Wt(e){const t=new Map;for(const n of e)t.has(n)||t.set(n,[]),n.parent&&(t.has(n.parent)||t.set(n.parent,[]),t.get(n.parent).push(n));return t}function Kt(e,t){const n=we(t);return Xt(e,Wt(n))}function it(e,t){return t.type==="compound"?ne(t).some(n=>n.type==="final"&&e.has(n)):t.type==="parallel"?ne(t).every(n=>it(e,n)):t.type==="final"}const Ne=e=>e[0]===bn;function Jn(e,t){return e.transitions.get(t)||[...e.transitions.keys()].filter(s=>{if(s===Cn)return!0;if(!s.endsWith(".*"))return!1;const r=s.split("."),i=t.split(".");for(let o=0;o<r.length;o++){const a=r[o],c=i[o];if(a==="*")return o===r.length-1;if(a!==c)return!1}return!0}).sort((s,r)=>r.length-s.length).flatMap(s=>e.transitions.get(s))}function Yn(e){const t=e.config.after;if(!t)return[];const n=(r,i)=>{const o=Nn(r,e.id),a=o.type;return e.entry.push(vs(o,{id:a,delay:r})),e.exit.push(jn(a)),a};return Object.keys(t).flatMap((r,i)=>{const o=t[r],a=typeof o=="string"?{target:o}:o,c=Number.isNaN(+r)?r:+r,u=n(c);return j(a).map(f=>({...f,event:u,delay:c}))}).map(r=>{const{delay:i}=r;return{...J(e,r.event,r),delay:i}})}function J(e,t,n){const s=Yt(n.target),r=n.reenter??!1,i=Wn(e,s),o={...n,actions:j(n.actions),guard:n.guard,target:i,source:e,reenter:r,eventType:t,toJSON:()=>({...o,source:`#${e.id}`,target:i?i.map(a=>`#${a.id}`):void 0})};return o}function Qn(e){const t=new Map;if(e.config.on)for(const n of Object.keys(e.config.on)){if(n===jt)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const s=e.config.on[n];t.set(n,Z(s).map(r=>J(e,n,r)))}if(e.config.onDone){const n=`xstate.done.state.${e.id}`;t.set(n,Z(e.config.onDone).map(s=>J(e,n,s)))}for(const n of e.invoke){if(n.onDone){const s=`xstate.done.actor.${n.id}`;t.set(s,Z(n.onDone).map(r=>J(e,s,r)))}if(n.onError){const s=`xstate.error.actor.${n.id}`;t.set(s,Z(n.onError).map(r=>J(e,s,r)))}if(n.onSnapshot){const s=`xstate.snapshot.${n.id}`;t.set(s,Z(n.onSnapshot).map(r=>J(e,s,r)))}}for(const n of e.after){let s=t.get(n.eventType);s||(s=[],t.set(n.eventType,s)),s.push(n)}return t}function Xn(e,t){const n=typeof t=="string"?e.states[t]:t?e.states[t.target]:void 0;if(!n&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${e.id}`);const s={source:e,actions:!t||typeof t=="string"?[]:j(t.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...s,source:`#${e.id}`,target:n?[`#${n.id}`]:[]})};return s}function Wn(e,t){if(t!==void 0)return t.map(n=>{if(typeof n!="string")return n;if(Ne(n))return e.machine.getStateNodeById(n);const s=n[0]===Bt;if(s&&!e.parent)return xe(e,n.slice(1));const r=s?e.key+n:n;if(e.parent)try{return xe(e.parent,r)}catch(i){throw new Error(`Invalid transition definition for state node '${e.id}':
2
+ ${i.message}`)}else throw new Error(`Invalid target: "${n}" is not a valid target from the root node. Did you mean ".${n}"?`)})}function Zt(e){const t=Yt(e.config.target);return t?{target:t.map(n=>typeof n=="string"?xe(e.parent,n):n)}:e.parent.initial}function Y(e){return e.type==="history"}function It(e){const t=en(e);for(const n of t)for(const s of he(n,e))t.add(s);return t}function en(e){const t=new Set;function n(s){if(!t.has(s)){if(t.add(s),s.type==="compound")n(s.initial.target[0]);else if(s.type==="parallel")for(const r of ne(s))n(r)}}return n(e),t}function se(e,t){if(Ne(t))return e.machine.getStateNodeById(t);if(!e.states)throw new Error(`Unable to retrieve child state '${t}' from '${e.id}'; no child states exist.`);const n=e.states[t];if(!n)throw new Error(`Child state '${t}' does not exist on '${e.id}'`);return n}function xe(e,t){if(typeof t=="string"&&Ne(t))try{return e.machine.getStateNodeById(t)}catch{}const n=et(t).slice();let s=e;for(;n.length;){const r=n.shift();if(!r.length)break;s=se(s,r)}return s}function be(e,t){if(typeof t=="string"){const r=e.states[t];if(!r)throw new Error(`State '${t}' does not exist on '${e.id}'`);return[e,r]}const n=Object.keys(t),s=n.map(r=>se(e,r)).filter(Boolean);return[e.machine.root,e].concat(s,n.reduce((r,i)=>{const o=se(e,i);if(!o)return r;const a=be(o,t[i]);return r.concat(a)},[]))}function Kn(e,t,n,s){const i=se(e,t).next(n,s);return!i||!i.length?e.next(n,s):i}function Zn(e,t,n,s){const r=Object.keys(t),i=se(e,r[0]),o=ot(i,t[r[0]],n,s);return!o||!o.length?e.next(n,s):o}function es(e,t,n,s){const r=[];for(const i of Object.keys(t)){const o=t[i];if(!o)continue;const a=se(e,i),c=ot(a,o,n,s);c&&r.push(...c)}return r.length?r:e.next(n,s)}function ot(e,t,n,s){return typeof t=="string"?Kn(e,t,n,s):Object.keys(t).length===1?Zn(e,t,n,s):es(e,t,n,s)}function ts(e){return Object.keys(e.states).map(t=>e.states[t]).filter(t=>t.type==="history")}function H(e,t){let n=e;for(;n.parent&&n.parent!==t;)n=n.parent;return n.parent===t}function ns(e,t){const n=new Set(e),s=new Set(t);for(const r of n)if(s.has(r))return!0;for(const r of s)if(n.has(r))return!0;return!1}function tn(e,t,n){const s=new Set;for(const r of e){let i=!1;const o=new Set;for(const a of s)if(ns(He([r],t,n),He([a],t,n)))if(H(r.source,a.source))o.add(a);else{i=!0;break}if(!i){for(const a of o)s.delete(a);s.add(r)}}return Array.from(s)}function ss(e){const[t,...n]=e;for(const s of he(t,void 0))if(n.every(r=>H(r,s)))return s}function at(e,t){if(!e.target)return[];const n=new Set;for(const s of e.target)if(Y(s))if(t[s.id])for(const r of t[s.id])n.add(r);else for(const r of at(Zt(s),t))n.add(r);else n.add(s);return[...n]}function nn(e,t){const n=at(e,t);if(!n)return;if(!e.reenter&&n.every(r=>r===e.source||H(r,e.source)))return e.source;const s=ss(n.concat(e.source));if(s)return s;if(!e.reenter)return e.source.machine.root}function He(e,t,n){var r;const s=new Set;for(const i of e)if((r=i.target)!=null&&r.length){const o=nn(i,n);i.reenter&&i.source===o&&s.add(o);for(const a of t)H(a,o)&&s.add(a)}return[...s]}function rs(e,t){if(e.length!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function ze(e,t,n,s,r,i){if(!e.length)return t;const o=new Set(t._nodes);let a=t.historyValue;const c=tn(e,o,a);let u=t;r||([u,a]=cs(u,s,n,c,o,a,i)),u=re(u,s,n,c.flatMap(l=>l.actions),i),u=os(u,s,n,c,o,i,a,r);const f=[...o];u.status==="done"&&(u=re(u,s,n,f.sort((l,h)=>h.order-l.order).flatMap(l=>l.exit),i));try{return a===t.historyValue&&rs(t._nodes,o)?u:Q(u,{_nodes:f,historyValue:a})}catch(l){throw l}}function is(e,t,n,s,r){if(s.output===void 0)return;const i=$e(r.id,r.output!==void 0&&r.parent?Ve(r.output,e.context,t,n.self):void 0);return Ve(s.output,e.context,i,n.self)}function os(e,t,n,s,r,i,o,a){let c=e;const u=new Set,f=new Set;as(s,o,f,u),a&&f.add(e.machine.root);const l=new Set;for(const h of[...u].sort((m,y)=>m.order-y.order)){r.add(h);const m=[];m.push(...h.entry);for(const y of h.invoke)m.push(Hn(y.src,{...y,syncSnapshot:!!y.onSnapshot}));if(f.has(h)){const y=h.initial.actions;m.push(...y)}if(c=re(c,t,n,m,i,h.invoke.map(y=>y.id)),h.type==="final"){const y=h.parent;let T=(y==null?void 0:y.type)==="parallel"?y:y==null?void 0:y.parent,_=T||h;for((y==null?void 0:y.type)==="compound"&&i.push($e(y.id,h.output!==void 0?Ve(h.output,c.context,t,n.self):void 0));(T==null?void 0:T.type)==="parallel"&&!l.has(T)&&it(r,T);)l.add(T),i.push($e(T.id)),_=T,T=T.parent;if(T)continue;c=Q(c,{status:"done",output:is(c,t,n,c.machine.root,_)})}}return c}function as(e,t,n,s){for(const r of e){const i=nn(r,t);for(const a of r.target||[])!Y(a)&&(r.source!==a||r.source!==i||r.reenter)&&(s.add(a),n.add(a)),ee(a,t,n,s);const o=at(r,t);for(const a of o){const c=he(a,i);(i==null?void 0:i.type)==="parallel"&&c.push(i),sn(s,t,n,c,!r.source.parent&&r.reenter?void 0:i)}}}function ee(e,t,n,s){var r;if(Y(e))if(t[e.id]){const i=t[e.id];for(const o of i)s.add(o),ee(o,t,n,s);for(const o of i)Me(o,e.parent,s,t,n)}else{const i=Zt(e);for(const o of i.target)s.add(o),i===((r=e.parent)==null?void 0:r.initial)&&n.add(e.parent),ee(o,t,n,s);for(const o of i.target)Me(o,e.parent,s,t,n)}else if(e.type==="compound"){const[i]=e.initial.target;Y(i)||(s.add(i),n.add(i)),ee(i,t,n,s),Me(i,e,s,t,n)}else if(e.type==="parallel")for(const i of ne(e).filter(o=>!Y(o)))[...s].some(o=>H(o,i))||(Y(i)||(s.add(i),n.add(i)),ee(i,t,n,s))}function sn(e,t,n,s,r){for(const i of s)if((!r||H(i,r))&&e.add(i),i.type==="parallel")for(const o of ne(i).filter(a=>!Y(a)))[...e].some(a=>H(a,o))||(e.add(o),ee(o,t,n,e))}function Me(e,t,n,s,r){sn(n,s,r,he(e,t))}function cs(e,t,n,s,r,i,o){let a=e;const c=He(s,r,i);c.sort((f,l)=>l.order-f.order);let u;for(const f of c)for(const l of ts(f)){let h;l.history==="deep"?h=m=>rt(m)&&H(m,f):h=m=>m.parent===f,u??(u={...i}),u[l.id]=Array.from(r).filter(h)}for(const f of c)a=re(a,t,n,[...f.exit,...f.invoke.map(l=>Qt(l.id))],o),r.delete(f);return[a,u||i]}let At=!1;function rn(e,t,n,s,r,i){const{machine:o}=e;let a=e;for(const c of s){let m=function(){n.system._sendInspectionEvent({type:"@xstate.action",actorRef:n.self,action:{type:typeof c=="string"?c:typeof c=="object"?c.type:c.name||"(anonymous)",params:h}});try{At=f,f(l,h)}finally{At=!1}};const u=typeof c=="function",f=u?c:o.implementations.actions[typeof c=="string"?c:c.type];if(!f)continue;const l={context:a.context,event:t,self:n.self,system:n.system},h=u||typeof c=="string"?void 0:"params"in c?typeof c.params=="function"?c.params({context:a.context,event:t}):c.params:void 0;if(!("resolve"in f)){n.self._processingStatus===R.Running?m():n.defer(()=>{m()});continue}const y=f,[T,_,w]=y.resolve(n,a,l,h,f,r);a=T,"retryResolve"in y&&(i==null||i.push([y,_])),"execute"in y&&(n.self._processingStatus===R.Running?y.execute(n,_):n.defer(y.execute.bind(null,n,_))),w&&(a=rn(a,t,n,w,r,i))}return a}function re(e,t,n,s,r,i){const o=i?[]:void 0,a=rn(e,t,n,s,{internalQueue:r,deferredActorIds:i},o);return o==null||o.forEach(([c,u])=>{c.retryResolve(n,a,u)}),a}function Le(e,t,n,s=[]){let r=e;const i=[];function o(u,f,l){n.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:n.self,event:f,snapshot:u,_transitions:l}),i.push(u)}if(t.type===de)return r=Q(wt(r,t,n),{status:"stopped"}),o(r,t,[]),{snapshot:r,microstates:i};let a=t;if(a.type!==$t){const u=a,f=Ln(u),l=xt(u,r);if(f&&!l.length)return r=Q(e,{status:"error",error:u.error}),o(r,u,[]),{snapshot:r,microstates:i};r=ze(l,e,n,a,!1,s),o(r,u,l)}let c=!0;for(;r.status==="active";){let u=c?us(r,a):[];const f=u.length?r:void 0;if(!u.length){if(!s.length)break;a=s.shift(),u=xt(a,r)}r=ze(u,r,n,a,!1,s),c=r!==f,o(r,a,u)}return r.status!=="active"&&wt(r,a,n),{snapshot:r,microstates:i}}function wt(e,t,n){return re(e,t,n,Object.values(e.children).map(s=>Qt(s)),[])}function xt(e,t){return t.machine.getTransitionData(t,e)}function us(e,t){const n=new Set,s=e._nodes.filter(rt);for(const r of s)e:for(const i of[r].concat(he(r,void 0)))if(i.always){for(const o of i.always)if(o.guard===void 0||st(o.guard,e.context,t,e)){n.add(o);break e}}return tn(Array.from(n),new Set(e._nodes),e.historyValue)}function ds(e,t){const n=we(be(e,t));return Kt(e,[...n])}function ls(e){return!!e&&typeof e=="object"&&"machine"in e&&"value"in e}const hs=function(t){return zt(t,this.value)},fs=function(t){return this.tags.has(t)},ps=function(t){const n=this.machine.getTransitionData(this,t);return!!(n!=null&&n.length)&&n.some(s=>s.target!==void 0||s.actions.length)},ys=function(){const{_nodes:t,tags:n,machine:s,getMeta:r,toJSON:i,can:o,hasTag:a,matches:c,...u}=this;return{...u,tags:Array.from(n)}},ms=function(){return this._nodes.reduce((t,n)=>(n.meta!==void 0&&(t[n.id]=n.meta),t),{})};function ve(e,t){return{status:e.status,output:e.output,error:e.error,machine:t,context:e.context,_nodes:e._nodes,value:Kt(t.root,e._nodes),tags:new Set(e._nodes.flatMap(n=>n.tags)),children:e.children,historyValue:e.historyValue||{},matches:hs,hasTag:fs,can:ps,getMeta:ms,toJSON:ys}}function Q(e,t={}){return ve({...e,...t},e.machine)}function gs(e,t){const{_nodes:n,tags:s,machine:r,children:i,context:o,can:a,hasTag:c,matches:u,getMeta:f,toJSON:l,...h}=e,m={};for(const T in i){const _=i[T];m[T]={snapshot:_.getPersistedSnapshot(t),src:_.src,systemId:_._systemId,syncSnapshot:_._syncSnapshot}}return{...h,context:on(o),children:m}}function on(e){let t;for(const n in e){const s=e[n];if(s&&typeof s=="object")if("sessionId"in s&&"send"in s&&"ref"in s)t??(t=Array.isArray(e)?e.slice():{...e}),t[n]={xstate$$type:nt,id:s.id};else{const r=on(s);r!==s&&(t??(t=Array.isArray(e)?e.slice():{...e}),t[n]=r)}}return t??e}function Es(e,t,n,s,{event:r,id:i,delay:o},{internalQueue:a}){const c=t.machine.implementations.delays;if(typeof r=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${r}" }) instead`);const u=typeof r=="function"?r(n,s):r;let f;if(typeof o=="string"){const l=c&&c[o];f=typeof l=="function"?l(n,s):l}else f=typeof o=="function"?o(n,s):o;return typeof f!="number"&&a.push(u),[t,{event:u,id:i,delay:f}]}function Ts(e,t){const{event:n,delay:s,id:r}=t;if(typeof s=="number"){e.defer(()=>{const i=e.self;e.system.scheduler.schedule(i,i,n,s,r)});return}}function vs(e,t){function n(s,r){}return n.type="xstate.raise",n.event=e,n.id=t==null?void 0:t.id,n.delay=t==null?void 0:t.delay,n.resolve=Es,n.execute=Ts,n}const bt=new WeakMap;function Ss(e){return{config:e,start:(n,s)=>{const{self:r,system:i}=s,o={receivers:void 0,dispose:void 0};bt.set(r,o),o.dispose=e({input:n.input,system:i,self:r,sendBack:a=>{r.getSnapshot().status!=="stopped"&&r._parent&&i._relay(r,r._parent,a)},receive:a=>{o.receivers??(o.receivers=new Set),o.receivers.add(a)}})},transition:(n,s,r)=>{var o,a;const i=bt.get(r.self);return s.type===de?(n={...n,status:"stopped",error:void 0},(o=i.dispose)==null||o.call(i),n):((a=i.receivers)==null||a.forEach(c=>c(s)),n)},getInitialSnapshot:(n,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedSnapshot:n=>n,restoreSnapshot:n=>n}}const Ct="xstate.promise.resolve",kt="xstate.promise.reject",Ee=new WeakMap;function V(e){return{config:e,transition:(n,s,r)=>{var i;if(n.status!=="active")return n;switch(s.type){case Ct:{const o=s.data;return{...n,status:"done",output:o,input:void 0}}case kt:return{...n,status:"error",error:s.data,input:void 0};case de:return(i=Ee.get(r.self))==null||i.abort(),{...n,status:"stopped",input:void 0};default:return n}},start:(n,{self:s,system:r})=>{if(n.status!=="active")return;const i=new AbortController;Ee.set(s,i),Promise.resolve(e({input:n.input,system:r,self:s,signal:i.signal})).then(a=>{s.getSnapshot().status==="active"&&(Ee.delete(s),r._relay(s,s,{type:Ct,data:a}))},a=>{s.getSnapshot().status==="active"&&(Ee.delete(s),r._relay(s,s,{type:kt,data:a}))})},getInitialSnapshot:(n,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedSnapshot:n=>n,restoreSnapshot:n=>n}}function _s(e,{machine:t,context:n},s,r){const i=(o,a={})=>{const{systemId:c,input:u}=a;if(typeof o=="string"){const f=tt(t,o);if(!f)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const l=$(f,{id:a.id,parent:e.self,syncSnapshot:a.syncSnapshot,input:typeof u=="function"?u({context:n,event:s,self:e.self}):u,src:o,systemId:c});return r[l.id]=l,l}else return $(o,{id:a.id,parent:e.self,syncSnapshot:a.syncSnapshot,input:a.input,src:o,systemId:c})};return(o,a)=>{const c=i(o,a);return r[c.id]=c,e.defer(()=>{c._processingStatus!==R.Stopped&&c.start()}),c}}function Is(e,t,n,s,{assignment:r}){if(!t.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},o={context:t.context,event:n.event,spawn:_s(e,t,n.event,i),self:e.self,system:e.system};let a={};if(typeof r=="function")a=r(o,s);else for(const u of Object.keys(r)){const f=r[u];a[u]=typeof f=="function"?f(o,s):f}const c=Object.assign({},t.context,a);return[Q(t,{context:c,children:Object.keys(i).length?{...t.children,...i}:t.children})]}function x(e){function t(n,s){}return t.type="xstate.assign",t.assignment=e,t.resolve=Is,t}function As(e,t,n,s,{event:r}){const i=typeof r=="function"?r(n,s):r;return[t,{event:i}]}function ws(e,{event:t}){e.defer(()=>e.emit(t))}function Se(e){function t(n,s){}return t.type="xstate.emit",t.event=e,t.resolve=As,t.execute=ws,t}let Nt=function(e){return e.Parent="#_parent",e.Internal="#_internal",e}({});function xs(e,t,n,s,{to:r,event:i,id:o,delay:a},c){var y;const u=t.machine.implementations.delays;if(typeof i=="string")throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${i}" }) instead`);const f=typeof i=="function"?i(n,s):i;let l;if(typeof a=="string"){const T=u&&u[a];l=typeof T=="function"?T(n,s):T}else l=typeof a=="function"?a(n,s):a;const h=typeof r=="function"?r(n,s):r;let m;if(typeof h=="string"){if(h===Nt.Parent?m=e.self._parent:h===Nt.Internal?m=e.self:h.startsWith("#_")?m=t.children[h.slice(2)]:m=(y=c.deferredActorIds)!=null&&y.includes(h)?h:t.children[h],!m)throw new Error(`Unable to send event to actor '${h}' from machine '${t.machine.id}'.`)}else m=h||e.self;return[t,{to:m,event:f,id:o,delay:l}]}function bs(e,t,n){typeof n.to=="string"&&(n.to=t.children[n.to])}function Cs(e,t){e.defer(()=>{const{to:n,event:s,delay:r,id:i}=t;if(typeof r=="number"){e.system.scheduler.schedule(e.self,n,s,r,i);return}e.system._relay(e.self,n,s.type===kn?Vt(e.self.id,s.data):s)})}function Ot(e,t,n){function s(r,i){}return s.type="xsnapshot.sendTo",s.to=e,s.event=t,s.id=n==null?void 0:n.id,s.delay=n==null?void 0:n.delay,s.resolve=xs,s.retryResolve=bs,s.execute=Cs,s}const Dt=new WeakMap;function W(e,t,n){let s=Dt.get(e);return s?t in s||(s[t]=n()):(s={[t]:n()},Dt.set(e,s)),s[t]}const ks={},ae=e=>typeof e=="string"?{type:e}:typeof e=="function"?"resolve"in e?{type:e.type}:{type:e.name}:e;class ct{constructor(t,n){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=n._parent,this.key=n._key,this.machine=n._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(Bt),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?vt(this.config.states,(s,r)=>new ct(s,{_parent:this,_key:r,_machine:this.machine})):ks,this.type==="compound"&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?"shallow":this.config.history||!1,this.entry=j(this.config.entry).slice(),this.exit=j(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=j(t.tags).slice()}_initialize(){this.transitions=Qn(this),this.config.always&&(this.always=Z(this.config.always).map(t=>J(this,jt,t))),Object.keys(this.states).forEach(t=>{this.states[t]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(ae),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(ae),eventType:null})}:void 0,history:this.history,states:vt(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(ae)})),entry:this.entry.map(ae),exit:this.exit.map(ae),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return W(this,"invoke",()=>j(this.config.invoke).map((t,n)=>{const{src:s,systemId:r}=t,i=t.id??_t(this.id,n),o=typeof s=="string"?s:`xstate.invoke.${_t(this.id,n)}`;return{...t,src:o,id:i,systemId:r,toJSON(){const{onDone:a,onError:c,...u}=t;return{...u,type:"xstate.invoke",src:o,id:i}}}}))}get on(){return W(this,"on",()=>[...this.transitions].flatMap(([n,s])=>s.map(r=>[n,r])).reduce((n,[s,r])=>(n[s]=n[s]||[],n[s].push(r),n),{}))}get after(){return W(this,"delayedTransitions",()=>Yn(this))}get initial(){return W(this,"initial",()=>Xn(this,this.config.initial))}next(t,n){const s=n.type,r=[];let i;const o=W(this,`candidates-${s}`,()=>Jn(this,s));for(const a of o){const{guard:c}=a,u=t.context;let f=!1;try{f=!c||st(c,u,n,t)}catch(l){const h=typeof c=="string"?c:typeof c=="object"?c.type:void 0;throw new Error(`Unable to evaluate guard ${h?`'${h}' `:""}in transition for event '${s}' in state node '${this.id}':
3
+ ${l.message}`)}if(f){r.push(...a.actions),i=a;break}}return i?[i]:void 0}get events(){return W(this,"events",()=>{const{states:t}=this,n=new Set(this.ownEvents);if(t)for(const s of Object.keys(t)){const r=t[s];if(r.states)for(const i of r.events)n.add(`${i}`)}return Array.from(n)})}get ownEvents(){const t=new Set([...this.transitions.keys()].filter(n=>this.transitions.get(n).some(s=>!(!s.target&&!s.actions.length&&!s.reenter))));return Array.from(t)}}const Ns="#";class ut{constructor(t,n){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.__TResolvedTypesMeta=void 0,this.id=t.id||"(machine)",this.implementations={actors:(n==null?void 0:n.actors)??{},actions:(n==null?void 0:n.actions)??{},delays:(n==null?void 0:n.delays)??{},guards:(n==null?void 0:n.guards)??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new ct(t,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:n,guards:s,actors:r,delays:i}=this.implementations;return new ut(this.config,{actions:{...n,...t.actions},guards:{...s,...t.guards},actors:{...r,...t.actors},delays:{...i,...t.delays}})}resolveState(t){const n=ds(this.root,t.value),s=we(be(this.root,n));return ve({_nodes:[...s],context:t.context||{},children:{},status:it(s,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,n,s){return Le(t,n,s).snapshot}microstep(t,n,s){return Le(t,n,s).microstates}getTransitionData(t,n){return ot(this.root,t.value,t,n)||[]}getPreInitialState(t,n,s){const{context:r}=this.config,i=ve({context:typeof r!="function"&&r?r:{},_nodes:[this.root],children:{},status:"active"},this);return typeof r=="function"?re(i,n,t,[x(({spawn:a,event:c,self:u})=>r({spawn:a,input:c.input,self:u}))],s):i}getInitialSnapshot(t,n){const s=Ht(n),r=[],i=this.getPreInitialState(t,s,r),o=ze([{target:[...en(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],i,t,s,!0,r),{snapshot:a}=Le(o,s,t,r);return a}start(t){Object.values(t.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(t){const n=et(t),s=n.slice(1),r=Ne(n[0])?n[0].slice(Ns.length):n[0],i=this.idMap.get(r);if(!i)throw new Error(`Child state node '#${r}' does not exist on machine '${this.id}'`);return xe(i,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,n){return gs(t,n)}restoreSnapshot(t,n){const s={},r=t.children;Object.keys(r).forEach(c=>{const u=r[c],f=u.snapshot,l=u.src,h=typeof l=="string"?tt(this,l):l;if(!h)return;const m=$(h,{id:c,parent:n.self,syncSnapshot:u.syncSnapshot,snapshot:f,src:l,systemId:u.systemId});s[c]=m});const i=ve({...t,children:s,_nodes:Array.from(we(be(this.root,t.value)))},this);let o=new Set;function a(c,u){if(!o.has(c)){o.add(c);for(let f in c){const l=c[f];if(l&&typeof l=="object"){if("xstate$$type"in l&&l.xstate$$type===nt){c[f]=u[l.id];continue}a(l,u)}}}}return a(i.context,s),i}}function Os(e,t){return new ut(e,t)}function fe({schemas:e,actors:t,actions:n,guards:s,delays:r}){return{createMachine:i=>Os({...i,schemas:e},{actors:t,actions:n,guards:s,delays:r})}}function Ge(e,t){const n=j(t);if(!n.includes(e.type)){const s=n.length===1?`type "${n[0]}"`:`one of types "${n.join('", "')}"`;throw new Error(`Expected event ${JSON.stringify(e)} to have ${s}`)}}function Ds({context:e,event:t}){if(!t.type.includes("xstate.error.actor"))return e;const n=t;return{errors:[...e.errors,String(n.error).replace("Error: ","")]}}function Rs(){return{errors:[]}}function qs({event:e}){if(!e.type.includes("xstate.done.actor"))return{type:"EMIT_AUTHENTICATED",accessToken:""};const t=e;return t.output.type!=="REFRESH_TOKEN_SUCCESS"?{type:"EMIT_AUTHENTICATED",accessToken:""}:{type:"EMIT_AUTHENTICATED",accessToken:t.output.accessToken}}function Ms({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="REFRESH_TOKEN_SUCCESS"?e:{accessToken:n.output.accessToken,ignoreRefreshToken:!1}}function Ls(){return{ignoreRefreshToken:!0}}function Us({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="AUTHENTICATE_SUCCESS"?e:{accessToken:n.output.accessToken,ignoreRefreshToken:!1}}function Ps(){return{refreshToken:""}}function Fs(){return{user:null,accessToken:"",refreshToken:"",ignoreRefreshToken:!1}}async function Je(e,t){const n=await fetch(e,t);return n.status===200?n.json():Promise.resolve({message:n.statusText,success:!1})}const Bs=V(async({input:e})=>{var t;if(!e.endpoint.client||e.endpoint.client==="")throw console.log("refreshAccessToken: No client endpoint provided."),new Error("No client endpoint provided.");try{const n=await Je(e.endpoint.client,{method:"POST",mode:"cors",credentials:"include",headers:{"Content-Type":"application/json","clicktap-scope":"view","clicktap-scope-id":"default"},body:JSON.stringify({username:e.username,password:e.password}).toString()});if(!n.success)throw new Error(((t=n.message)==null?void 0:t.toString())??"Sign in failed. Please try again.");return{type:"AUTHENTICATE_SUCCESS",user:null,accessToken:n.accessToken??""}}catch(n){throw console.log(n),new Error("Could not complete authenticate request (server)")}}),js=typeof window>"u",$s=V(async({input:e})=>{if(!e.endpoint.client||e.endpoint.client==="")throw console.log("refreshAccessToken: No client endpoint provided."),new Error("No client endpoint provided.");if(!e.endpoint.server||e.endpoint.server==="")throw console.log("refreshAccessToken: No server endpoint provided."),new Error("No server endpoint provided.");let t;if(js){if(e.refreshToken==="")throw new Error("Unauthorized.");try{if(t=await Je(e.endpoint.server,{method:"POST",mode:"cors",credentials:"include",headers:{Cookie:`refresh_token=${e.refreshToken}`,"Content-Type":"application/json","clicktap-scope":"view","clicktap-scope-id":"default"}}),typeof t.accessToken>"u")throw new Error("Unauthorized.");return{type:"REFRESH_TOKEN_SUCCESS",accessToken:t.accessToken}}catch(n){throw console.log(n),new Error("Could not complete refresh request (server)")}}else{if(t=await Je(e.endpoint.client,{method:"POST",mode:"cors",credentials:"include",headers:{"Content-Type":"application/json","clicktap-scope":"view","clicktap-scope-id":"default"},body:JSON.stringify({grant_type:"refresh_token"}).toString()}),typeof t.accessToken>"u")throw new Error("Unauthorized.");return{type:"REFRESH_TOKEN_SUCCESS",accessToken:t.accessToken}}}),Vs=V(async({input:e})=>{if(!e.endpoint.client||e.endpoint.client==="")throw console.log("unauthenticate: No client endpoint provided."),new Error("No client endpoint provided.");try{return await fetch(e.endpoint.client,{method:"POST",mode:"cors",credentials:"include",headers:{"clicktap-scope":"view","clicktap-scope-id":"default"}}),{type:"UNAUTHENTICATE_SUCCESS"}}catch(t){throw console.log(t),new Error("Could not complete unauthenticate request (server)")}}),an=fe({types:{context:{},emitted:{},events:{},input:{}},actions:{addError:x(Ds),clearErrors:x(Rs),notifyAuthenticated:Se(qs),setAccessToken:x(Ms),setIgnoreRefreshToken:x(Ls),setUserContext:x(Us),unsetRefreshToken:x(Ps),unsetUserContext:x(Fs)},actors:{authenticate:Bs,refreshAccessToken:$s,unauthenticate:Vs},delays:{refresh:84e4}}).createMachine({id:"auth",context:({input:e})=>({user:null,accessToken:"",refreshToken:"",ignoreRefreshToken:!1,endpoints:{login:"",logout:"",refresh:"",ssrRefresh:""},errors:[],...e==null?void 0:e.initialContext}),initial:"refreshing",states:{authenticating:{invoke:{src:"authenticate",input:({context:e,event:t})=>(Ge(t,"LOGIN"),{endpoint:{client:e.endpoints.login},username:t.username,password:t.password}),onDone:[{actions:["setUserContext"],target:"loggedIn"}],onError:[{actions:"addError",target:"loggedOut"}]}},unauthenticating:{invoke:{src:"unauthenticate",input:({context:e})=>({endpoint:{client:e.endpoints.logout}}),onDone:[{actions:"unsetUserContext",target:"loggedOut"}],onError:[{actions:["unsetUserContext","setIgnoreRefreshToken"],target:"loggedOut"}]}},refreshing:{invoke:{src:"refreshAccessToken",input:({context:e})=>({accessToken:e.accessToken,endpoint:{client:e.endpoints.refresh,server:e.endpoints.ssrRefresh},refreshToken:e.refreshToken}),onDone:[{actions:["unsetRefreshToken","setAccessToken","notifyAuthenticated"],guard:()=>typeof window<"u",target:"loggedIn"},{actions:["unsetRefreshToken","setAccessToken"],target:"loggedInReady"}],onError:[{actions:"unsetRefreshToken",target:"unauthenticating",guard:()=>typeof window<"u"},{actions:"unsetRefreshToken",target:"loggedOut"}]}},loggedOut:{on:{LOGIN:{target:"authenticating"},CLEAR_ERRORS:{actions:"clearErrors"}}},loggedInReady:{on:{RESTORE:{guard:()=>typeof window<"u",target:"loggedIn"}}},loggedIn:{after:{refresh:{guard:()=>typeof window<"u",target:"refreshing"}},on:{LOGOUT:{target:"unauthenticating"},CLEAR_ERRORS:{actions:"clearErrors"}}}}}),dt=N.createContext({}),Hs=()=>{const e=N.useContext(dt),[t,n]=N.useState(["loggedIn","loggedInReady"].includes(e.getSnapshot().value));return N.useEffect(()=>{const s=e.subscribe(r=>{switch(r.value){case"loggedIn":case"loggedInReady":n(!0);break;case"loggedOut":n(!1);break}});return()=>{s.unsubscribe()}},[e]),{authActor:e,isLoggedIn:t}},zs=async(e="",t={inspect:void 0,endpoints:{login:"",logout:"",refresh:"",ssrRefresh:""}})=>$(an,{input:{initialContext:{endpoints:t.endpoints,refreshToken:e}},inspect:t.inspect}).start();function Gs({actor:e,children:t}){return ke.jsx(dt.Provider,{value:e,children:t})}function Js({context:e,event:t}){if(t.type!=="CHANGE_STEP")return e;const n=e.quote.checkoutSteps,s=n==null?void 0:n.find(r=>r.code===t.step);return!s||!s.isAvailable?e:{currentStep:s.code??e.currentStep}}function Ys({context:e,event:t}){var r,i;if(!t.type.includes("xstate.done.actor")||t.output.type!=="SUBMIT_STEP_DATA_SUCCESS")return e;const s=(i=(r=e.steps)==null?void 0:r.find(o=>o.code===e.currentStep))==null?void 0:i.next;return s?{currentStep:s??e.currentStep}:e}function Qs({context:e,event:t}){return t.type!=="RESET_CHECKOUT"?e:{currentStep:t.data.currentStep,errors:[],steps:t.data.steps,successId:"",quote:t.data.quote}}function Xs({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="SUBMIT_STEP_DATA_SUCCESS"?e:{quote:{...e.quote,...n.output.quote}}}function Ws({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="PLACE_ORDER_SUCCESS"?e:{successId:n.output.successId}}const lt=JSON,Ks=e=>e.toUpperCase(),Zs=e=>{const t={};return e.forEach((n,s)=>{t[s]=n}),t},er=(e,t,n)=>e.document?e:{document:e,variables:t,requestHeaders:n,signal:void 0},tr=(e,t,n)=>e.query?e:{query:e,variables:t,requestHeaders:n,signal:void 0},nr=(e,t)=>e.documents?e:{documents:e,requestHeaders:t,signal:void 0},sr=(e,t,...n)=>{const[s,r]=n;return e.document?e:{url:e,document:t,variables:s,requestHeaders:r,signal:void 0}};function _e(e,t){if(!!!e)throw new Error(t)}function rr(e){return typeof e=="object"&&e!==null}function ir(e,t){if(!!!e)throw new Error(t??"Unexpected invariant triggered.")}const or=/\r\n|[\n\r]/g;function Ye(e,t){let n=0,s=1;for(const r of e.body.matchAll(or)){if(typeof r.index=="number"||ir(!1),r.index>=t)break;n=r.index+r[0].length,s+=1}return{line:s,column:t+1-n}}function ar(e){return cn(e.source,Ye(e.source,e.start))}function cn(e,t){const n=e.locationOffset.column-1,s="".padStart(n)+e.body,r=t.line-1,i=e.locationOffset.line-1,o=t.line+i,a=t.line===1?n:0,c=t.column+a,u=`${e.name}:${o}:${c}
4
+ `,f=s.split(/\r\n|[\n\r]/g),l=f[r];if(l.length>120){const h=Math.floor(c/80),m=c%80,y=[];for(let T=0;T<l.length;T+=80)y.push(l.slice(T,T+80));return u+Rt([[`${o} |`,y[0]],...y.slice(1,h+1).map(T=>["|",T]),["|","^".padStart(m)],["|",y[h+1]]])}return u+Rt([[`${o-1} |`,f[r-1]],[`${o} |`,l],["|","^".padStart(c)],[`${o+1} |`,f[r+1]]])}function Rt(e){const t=e.filter(([s,r])=>r!==void 0),n=Math.max(...t.map(([s])=>s.length));return t.map(([s,r])=>s.padStart(n)+(r?" "+r:"")).join(`
5
+ `)}function cr(e){const t=e[0];return t==null||"kind"in t||"length"in t?{nodes:t,source:e[1],positions:e[2],path:e[3],originalError:e[4],extensions:e[5]}:t}class ht extends Error{constructor(t,...n){var s,r,i;const{nodes:o,source:a,positions:c,path:u,originalError:f,extensions:l}=cr(n);super(t),this.name="GraphQLError",this.path=u??void 0,this.originalError=f??void 0,this.nodes=qt(Array.isArray(o)?o:o?[o]:void 0);const h=qt((s=this.nodes)===null||s===void 0?void 0:s.map(y=>y.loc).filter(y=>y!=null));this.source=a??(h==null||(r=h[0])===null||r===void 0?void 0:r.source),this.positions=c??(h==null?void 0:h.map(y=>y.start)),this.locations=c&&a?c.map(y=>Ye(a,y)):h==null?void 0:h.map(y=>Ye(y.source,y.start));const m=rr(f==null?void 0:f.extensions)?f==null?void 0:f.extensions:void 0;this.extensions=(i=l??m)!==null&&i!==void 0?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}}),f!=null&&f.stack?Object.defineProperty(this,"stack",{value:f.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,ht):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}get[Symbol.toStringTag](){return"GraphQLError"}toString(){let t=this.message;if(this.nodes)for(const n of this.nodes)n.loc&&(t+=`
6
6
 
7
- `+or(n.loc));else if(this.source&&this.locations)for(const n of this.locations)t+=`
7
+ `+ar(n.loc));else if(this.source&&this.locations)for(const n of this.locations)t+=`
8
8
 
9
- `+cn(this.source,n);return t}toJSON(){const t={message:this.message};return this.locations!=null&&(t.locations=this.locations),this.path!=null&&(t.path=this.path),this.extensions!=null&&Object.keys(this.extensions).length>0&&(t.extensions=this.extensions),t}}function qt(e){return e===void 0||e.length===0?void 0:e}function C(e,t,n){return new ht(`Syntax Error: ${n}`,{source:e,positions:[t]})}class cr{constructor(t,n,s){this.start=t.start,this.end=n.end,this.startToken=t,this.endToken=n,this.source=s}get[Symbol.toStringTag](){return"Location"}toJSON(){return{start:this.start,end:this.end}}}class un{constructor(t,n,s,r,i,o){this.kind=t,this.start=n,this.end=s,this.line=r,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 dn={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"]},ur=new Set(Object.keys(dn));function Mt(e){const t=e==null?void 0:e.kind;return typeof t=="string"&&ur.has(t)}var te;(function(e){e.QUERY="query",e.MUTATION="mutation",e.SUBSCRIPTION="subscription"})(te||(te={}));var Qe;(function(e){e.QUERY="QUERY",e.MUTATION="MUTATION",e.SUBSCRIPTION="SUBSCRIPTION",e.FIELD="FIELD",e.FRAGMENT_DEFINITION="FRAGMENT_DEFINITION",e.FRAGMENT_SPREAD="FRAGMENT_SPREAD",e.INLINE_FRAGMENT="INLINE_FRAGMENT",e.VARIABLE_DEFINITION="VARIABLE_DEFINITION",e.SCHEMA="SCHEMA",e.SCALAR="SCALAR",e.OBJECT="OBJECT",e.FIELD_DEFINITION="FIELD_DEFINITION",e.ARGUMENT_DEFINITION="ARGUMENT_DEFINITION",e.INTERFACE="INTERFACE",e.UNION="UNION",e.ENUM="ENUM",e.ENUM_VALUE="ENUM_VALUE",e.INPUT_OBJECT="INPUT_OBJECT",e.INPUT_FIELD_DEFINITION="INPUT_FIELD_DEFINITION"})(Qe||(Qe={}));var T;(function(e){e.NAME="Name",e.DOCUMENT="Document",e.OPERATION_DEFINITION="OperationDefinition",e.VARIABLE_DEFINITION="VariableDefinition",e.SELECTION_SET="SelectionSet",e.FIELD="Field",e.ARGUMENT="Argument",e.FRAGMENT_SPREAD="FragmentSpread",e.INLINE_FRAGMENT="InlineFragment",e.FRAGMENT_DEFINITION="FragmentDefinition",e.VARIABLE="Variable",e.INT="IntValue",e.FLOAT="FloatValue",e.STRING="StringValue",e.BOOLEAN="BooleanValue",e.NULL="NullValue",e.ENUM="EnumValue",e.LIST="ListValue",e.OBJECT="ObjectValue",e.OBJECT_FIELD="ObjectField",e.DIRECTIVE="Directive",e.NAMED_TYPE="NamedType",e.LIST_TYPE="ListType",e.NON_NULL_TYPE="NonNullType",e.SCHEMA_DEFINITION="SchemaDefinition",e.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",e.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",e.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",e.FIELD_DEFINITION="FieldDefinition",e.INPUT_VALUE_DEFINITION="InputValueDefinition",e.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",e.UNION_TYPE_DEFINITION="UnionTypeDefinition",e.ENUM_TYPE_DEFINITION="EnumTypeDefinition",e.ENUM_VALUE_DEFINITION="EnumValueDefinition",e.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",e.DIRECTIVE_DEFINITION="DirectiveDefinition",e.SCHEMA_EXTENSION="SchemaExtension",e.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",e.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",e.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",e.UNION_TYPE_EXTENSION="UnionTypeExtension",e.ENUM_TYPE_EXTENSION="EnumTypeExtension",e.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension"})(T||(T={}));function Xe(e){return e===9||e===32}function le(e){return e>=48&&e<=57}function ln(e){return e>=97&&e<=122||e>=65&&e<=90}function hn(e){return ln(e)||e===95}function dr(e){return ln(e)||le(e)||e===95}function lr(e){var t;let n=Number.MAX_SAFE_INTEGER,s=null,r=-1;for(let o=0;o<e.length;++o){var i;const a=e[o],c=hr(a);c!==a.length&&(s=(i=s)!==null&&i!==void 0?i:o,r=o,o!==0&&c<n&&(n=c))}return e.map((o,a)=>a===0?o:o.slice(n)).slice((t=s)!==null&&t!==void 0?t:0,r+1)}function hr(e){let t=0;for(;t<e.length&&Xe(e.charCodeAt(t));)++t;return t}function fr(e,t){const n=e.replace(/"""/g,'\\"""'),s=n.split(/\r\n|[\n\r]/g),r=s.length===1,i=s.length>1&&s.slice(1).every(m=>m.length===0||Xe(m.charCodeAt(0))),o=n.endsWith('\\"""'),a=e.endsWith('"')&&!o,c=e.endsWith("\\"),u=a||c,h=!(t!=null&&t.minimize)&&(!r||e.length>70||u||i||o);let d="";const f=r&&Xe(e.charCodeAt(0));return(h&&!f||i)&&(d+=`
10
- `),d+=n,(h||u)&&(d+=`
11
- `),'"""'+d+'"""'}var p;(function(e){e.SOF="<SOF>",e.EOF="<EOF>",e.BANG="!",e.DOLLAR="$",e.AMP="&",e.PAREN_L="(",e.PAREN_R=")",e.SPREAD="...",e.COLON=":",e.EQUALS="=",e.AT="@",e.BRACKET_L="[",e.BRACKET_R="]",e.BRACE_L="{",e.PIPE="|",e.BRACE_R="}",e.NAME="Name",e.INT="Int",e.FLOAT="Float",e.STRING="String",e.BLOCK_STRING="BlockString",e.COMMENT="Comment"})(p||(p={}));class pr{constructor(t){const n=new un(p.SOF,0,0,0,0);this.source=t,this.lastToken=n,this.token=n,this.line=1,this.lineStart=0}get[Symbol.toStringTag](){return"Lexer"}advance(){return this.lastToken=this.token,this.token=this.lookahead()}lookahead(){let t=this.token;if(t.kind!==p.EOF)do if(t.next)t=t.next;else{const n=mr(this,t.end);t.next=n,n.prev=t,t=n}while(t.kind===p.COMMENT);return t}}function yr(e){return e===p.BANG||e===p.DOLLAR||e===p.AMP||e===p.PAREN_L||e===p.PAREN_R||e===p.SPREAD||e===p.COLON||e===p.EQUALS||e===p.AT||e===p.BRACKET_L||e===p.BRACKET_R||e===p.BRACE_L||e===p.PIPE||e===p.BRACE_R}function ie(e){return e>=0&&e<=55295||e>=57344&&e<=1114111}function Ne(e,t){return fn(e.charCodeAt(t))&&pn(e.charCodeAt(t+1))}function fn(e){return e>=55296&&e<=56319}function pn(e){return e>=56320&&e<=57343}function X(e,t){const n=e.source.body.codePointAt(t);if(n===void 0)return p.EOF;if(n>=32&&n<=126){const s=String.fromCodePoint(n);return s==='"'?`'"'`:`"${s}"`}return"U+"+n.toString(16).toUpperCase().padStart(4,"0")}function b(e,t,n,s,r){const i=e.line,o=1+n-e.lineStart;return new un(t,n,s,i,o,r)}function mr(e,t){const n=e.source.body,s=n.length;let r=t;for(;r<s;){const i=n.charCodeAt(r);switch(i){case 65279:case 9:case 32:case 44:++r;continue;case 10:++r,++e.line,e.lineStart=r;continue;case 13:n.charCodeAt(r+1)===10?r+=2:++r,++e.line,e.lineStart=r;continue;case 35:return gr(e,r);case 33:return b(e,p.BANG,r,r+1);case 36:return b(e,p.DOLLAR,r,r+1);case 38:return b(e,p.AMP,r,r+1);case 40:return b(e,p.PAREN_L,r,r+1);case 41:return b(e,p.PAREN_R,r,r+1);case 46:if(n.charCodeAt(r+1)===46&&n.charCodeAt(r+2)===46)return b(e,p.SPREAD,r,r+3);break;case 58:return b(e,p.COLON,r,r+1);case 61:return b(e,p.EQUALS,r,r+1);case 64:return b(e,p.AT,r,r+1);case 91:return b(e,p.BRACKET_L,r,r+1);case 93:return b(e,p.BRACKET_R,r,r+1);case 123:return b(e,p.BRACE_L,r,r+1);case 124:return b(e,p.PIPE,r,r+1);case 125:return b(e,p.BRACE_R,r,r+1);case 34:return n.charCodeAt(r+1)===34&&n.charCodeAt(r+2)===34?Ir(e,r):vr(e,r)}if(le(i)||i===45)return Er(e,r,i);if(hn(i))return Ar(e,r);throw C(e.source,r,i===39?`Unexpected single quote character ('), did you mean to use a double quote (")?`:ie(i)||Ne(n,r)?`Unexpected character: ${X(e,r)}.`:`Invalid character: ${X(e,r)}.`)}return b(e,p.EOF,s,s)}function gr(e,t){const n=e.source.body,s=n.length;let r=t+1;for(;r<s;){const i=n.charCodeAt(r);if(i===10||i===13)break;if(ie(i))++r;else if(Ne(n,r))r+=2;else break}return b(e,p.COMMENT,t,r,n.slice(t+1,r))}function Er(e,t,n){const s=e.source.body;let r=t,i=n,o=!1;if(i===45&&(i=s.charCodeAt(++r)),i===48){if(i=s.charCodeAt(++r),le(i))throw C(e.source,r,`Invalid number, unexpected digit after 0: ${X(e,r)}.`)}else r=Pe(e,r,i),i=s.charCodeAt(r);if(i===46&&(o=!0,i=s.charCodeAt(++r),r=Pe(e,r,i),i=s.charCodeAt(r)),(i===69||i===101)&&(o=!0,i=s.charCodeAt(++r),(i===43||i===45)&&(i=s.charCodeAt(++r)),r=Pe(e,r,i),i=s.charCodeAt(r)),i===46||hn(i))throw C(e.source,r,`Invalid number, expected digit but got: ${X(e,r)}.`);return b(e,o?p.FLOAT:p.INT,t,r,s.slice(t,r))}function Pe(e,t,n){if(!le(n))throw C(e.source,t,`Invalid number, expected digit but got: ${X(e,t)}.`);const s=e.source.body;let r=t+1;for(;le(s.charCodeAt(r));)++r;return r}function vr(e,t){const n=e.source.body,s=n.length;let r=t+1,i=r,o="";for(;r<s;){const a=n.charCodeAt(r);if(a===34)return o+=n.slice(i,r),b(e,p.STRING,t,r+1,o);if(a===92){o+=n.slice(i,r);const c=n.charCodeAt(r+1)===117?n.charCodeAt(r+2)===123?Tr(e,r):Sr(e,r):_r(e,r);o+=c.value,r+=c.size,i=r;continue}if(a===10||a===13)break;if(ie(a))++r;else if(Ne(n,r))r+=2;else throw C(e.source,r,`Invalid character within String: ${X(e,r)}.`)}throw C(e.source,r,"Unterminated string.")}function Tr(e,t){const n=e.source.body;let s=0,r=3;for(;r<12;){const i=n.charCodeAt(t+r++);if(i===125){if(r<5||!ie(s))break;return{value:String.fromCodePoint(s),size:r}}if(s=s<<4|ce(i),s<0)break}throw C(e.source,t,`Invalid Unicode escape sequence: "${n.slice(t,t+r)}".`)}function Sr(e,t){const n=e.source.body,s=Lt(n,t+2);if(ie(s))return{value:String.fromCodePoint(s),size:6};if(fn(s)&&n.charCodeAt(t+6)===92&&n.charCodeAt(t+7)===117){const r=Lt(n,t+8);if(pn(r))return{value:String.fromCodePoint(s,r),size:12}}throw C(e.source,t,`Invalid Unicode escape sequence: "${n.slice(t,t+6)}".`)}function Lt(e,t){return ce(e.charCodeAt(t))<<12|ce(e.charCodeAt(t+1))<<8|ce(e.charCodeAt(t+2))<<4|ce(e.charCodeAt(t+3))}function ce(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:-1}function _r(e,t){const n=e.source.body;switch(n.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:`
12
- `,size:2};case 114:return{value:"\r",size:2};case 116:return{value:" ",size:2}}throw C(e.source,t,`Invalid character escape sequence: "${n.slice(t,t+2)}".`)}function Ir(e,t){const n=e.source.body,s=n.length;let r=e.lineStart,i=t+3,o=i,a="";const c=[];for(;i<s;){const u=n.charCodeAt(i);if(u===34&&n.charCodeAt(i+1)===34&&n.charCodeAt(i+2)===34){a+=n.slice(o,i),c.push(a);const h=b(e,p.BLOCK_STRING,t,i+3,lr(c).join(`
13
- `));return e.line+=c.length-1,e.lineStart=r,h}if(u===92&&n.charCodeAt(i+1)===34&&n.charCodeAt(i+2)===34&&n.charCodeAt(i+3)===34){a+=n.slice(o,i),o=i+1,i+=4;continue}if(u===10||u===13){a+=n.slice(o,i),c.push(a),u===13&&n.charCodeAt(i+1)===10?i+=2:++i,a="",o=i,r=i;continue}if(ie(u))++i;else if(Ne(n,i))i+=2;else throw C(e.source,i,`Invalid character within String: ${X(e,i)}.`)}throw C(e.source,i,"Unterminated string.")}function Ar(e,t){const n=e.source.body,s=n.length;let r=t+1;for(;r<s;){const i=n.charCodeAt(r);if(dr(i))++r;else break}return b(e,p.NAME,t,r,n.slice(t,r))}const wr=10,yn=2;function ft(e){return ke(e,[])}function ke(e,t){switch(typeof e){case"string":return JSON.stringify(e);case"function":return e.name?`[function ${e.name}]`:"[function]";case"object":return xr(e,t);default:return String(e)}}function xr(e,t){if(e===null)return"null";if(t.includes(e))return"[Circular]";const n=[...t,e];if(br(e)){const s=e.toJSON();if(s!==e)return typeof s=="string"?s:ke(s,n)}else if(Array.isArray(e))return Or(e,n);return Cr(e,n)}function br(e){return typeof e.toJSON=="function"}function Cr(e,t){const n=Object.entries(e);return n.length===0?"{}":t.length>yn?"["+Nr(e)+"]":"{ "+n.map(([r,i])=>r+": "+ke(i,t)).join(", ")+" }"}function Or(e,t){if(e.length===0)return"[]";if(t.length>yn)return"[Array]";const n=Math.min(wr,e.length),s=e.length-n,r=[];for(let i=0;i<n;++i)r.push(ke(e[i],t));return s===1?r.push("... 1 more item"):s>1&&r.push(`... ${s} more items`),"["+r.join(", ")+"]"}function Nr(e){const t=Object.prototype.toString.call(e).replace(/^\[object /,"").replace(/]$/,"");if(t==="Object"&&typeof e.constructor=="function"){const n=e.constructor.name;if(typeof n=="string"&&n!=="")return n}return t}const kr=globalThis.process&&process.env.NODE_ENV==="production",Dr=kr?function(t,n){return t instanceof n}:function(t,n){if(t instanceof n)return!0;if(typeof t=="object"&&t!==null){var s;const r=n.prototype[Symbol.toStringTag],i=Symbol.toStringTag in t?t[Symbol.toStringTag]:(s=t.constructor)===null||s===void 0?void 0:s.name;if(r===i){const o=ft(t);throw new Error(`Cannot use ${r} "${o}" from another module or realm.
9
+ `+cn(this.source,n);return t}toJSON(){const t={message:this.message};return this.locations!=null&&(t.locations=this.locations),this.path!=null&&(t.path=this.path),this.extensions!=null&&Object.keys(this.extensions).length>0&&(t.extensions=this.extensions),t}}function qt(e){return e===void 0||e.length===0?void 0:e}function C(e,t,n){return new ht(`Syntax Error: ${n}`,{source:e,positions:[t]})}class ur{constructor(t,n,s){this.start=t.start,this.end=n.end,this.startToken=t,this.endToken=n,this.source=s}get[Symbol.toStringTag](){return"Location"}toJSON(){return{start:this.start,end:this.end}}}class un{constructor(t,n,s,r,i,o){this.kind=t,this.start=n,this.end=s,this.line=r,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 dn={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"]},dr=new Set(Object.keys(dn));function Mt(e){const t=e==null?void 0:e.kind;return typeof t=="string"&&dr.has(t)}var te;(function(e){e.QUERY="query",e.MUTATION="mutation",e.SUBSCRIPTION="subscription"})(te||(te={}));var Qe;(function(e){e.QUERY="QUERY",e.MUTATION="MUTATION",e.SUBSCRIPTION="SUBSCRIPTION",e.FIELD="FIELD",e.FRAGMENT_DEFINITION="FRAGMENT_DEFINITION",e.FRAGMENT_SPREAD="FRAGMENT_SPREAD",e.INLINE_FRAGMENT="INLINE_FRAGMENT",e.VARIABLE_DEFINITION="VARIABLE_DEFINITION",e.SCHEMA="SCHEMA",e.SCALAR="SCALAR",e.OBJECT="OBJECT",e.FIELD_DEFINITION="FIELD_DEFINITION",e.ARGUMENT_DEFINITION="ARGUMENT_DEFINITION",e.INTERFACE="INTERFACE",e.UNION="UNION",e.ENUM="ENUM",e.ENUM_VALUE="ENUM_VALUE",e.INPUT_OBJECT="INPUT_OBJECT",e.INPUT_FIELD_DEFINITION="INPUT_FIELD_DEFINITION"})(Qe||(Qe={}));var v;(function(e){e.NAME="Name",e.DOCUMENT="Document",e.OPERATION_DEFINITION="OperationDefinition",e.VARIABLE_DEFINITION="VariableDefinition",e.SELECTION_SET="SelectionSet",e.FIELD="Field",e.ARGUMENT="Argument",e.FRAGMENT_SPREAD="FragmentSpread",e.INLINE_FRAGMENT="InlineFragment",e.FRAGMENT_DEFINITION="FragmentDefinition",e.VARIABLE="Variable",e.INT="IntValue",e.FLOAT="FloatValue",e.STRING="StringValue",e.BOOLEAN="BooleanValue",e.NULL="NullValue",e.ENUM="EnumValue",e.LIST="ListValue",e.OBJECT="ObjectValue",e.OBJECT_FIELD="ObjectField",e.DIRECTIVE="Directive",e.NAMED_TYPE="NamedType",e.LIST_TYPE="ListType",e.NON_NULL_TYPE="NonNullType",e.SCHEMA_DEFINITION="SchemaDefinition",e.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",e.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",e.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",e.FIELD_DEFINITION="FieldDefinition",e.INPUT_VALUE_DEFINITION="InputValueDefinition",e.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",e.UNION_TYPE_DEFINITION="UnionTypeDefinition",e.ENUM_TYPE_DEFINITION="EnumTypeDefinition",e.ENUM_VALUE_DEFINITION="EnumValueDefinition",e.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",e.DIRECTIVE_DEFINITION="DirectiveDefinition",e.SCHEMA_EXTENSION="SchemaExtension",e.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",e.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",e.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",e.UNION_TYPE_EXTENSION="UnionTypeExtension",e.ENUM_TYPE_EXTENSION="EnumTypeExtension",e.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension"})(v||(v={}));function Xe(e){return e===9||e===32}function le(e){return e>=48&&e<=57}function ln(e){return e>=97&&e<=122||e>=65&&e<=90}function hn(e){return ln(e)||e===95}function lr(e){return ln(e)||le(e)||e===95}function hr(e){var t;let n=Number.MAX_SAFE_INTEGER,s=null,r=-1;for(let o=0;o<e.length;++o){var i;const a=e[o],c=fr(a);c!==a.length&&(s=(i=s)!==null&&i!==void 0?i:o,r=o,o!==0&&c<n&&(n=c))}return e.map((o,a)=>a===0?o:o.slice(n)).slice((t=s)!==null&&t!==void 0?t:0,r+1)}function fr(e){let t=0;for(;t<e.length&&Xe(e.charCodeAt(t));)++t;return t}function pr(e,t){const n=e.replace(/"""/g,'\\"""'),s=n.split(/\r\n|[\n\r]/g),r=s.length===1,i=s.length>1&&s.slice(1).every(m=>m.length===0||Xe(m.charCodeAt(0))),o=n.endsWith('\\"""'),a=e.endsWith('"')&&!o,c=e.endsWith("\\"),u=a||c,f=!(t!=null&&t.minimize)&&(!r||e.length>70||u||i||o);let l="";const h=r&&Xe(e.charCodeAt(0));return(f&&!h||i)&&(l+=`
10
+ `),l+=n,(f||u)&&(l+=`
11
+ `),'"""'+l+'"""'}var p;(function(e){e.SOF="<SOF>",e.EOF="<EOF>",e.BANG="!",e.DOLLAR="$",e.AMP="&",e.PAREN_L="(",e.PAREN_R=")",e.SPREAD="...",e.COLON=":",e.EQUALS="=",e.AT="@",e.BRACKET_L="[",e.BRACKET_R="]",e.BRACE_L="{",e.PIPE="|",e.BRACE_R="}",e.NAME="Name",e.INT="Int",e.FLOAT="Float",e.STRING="String",e.BLOCK_STRING="BlockString",e.COMMENT="Comment"})(p||(p={}));class yr{constructor(t){const n=new un(p.SOF,0,0,0,0);this.source=t,this.lastToken=n,this.token=n,this.line=1,this.lineStart=0}get[Symbol.toStringTag](){return"Lexer"}advance(){return this.lastToken=this.token,this.token=this.lookahead()}lookahead(){let t=this.token;if(t.kind!==p.EOF)do if(t.next)t=t.next;else{const n=gr(this,t.end);t.next=n,n.prev=t,t=n}while(t.kind===p.COMMENT);return t}}function mr(e){return e===p.BANG||e===p.DOLLAR||e===p.AMP||e===p.PAREN_L||e===p.PAREN_R||e===p.SPREAD||e===p.COLON||e===p.EQUALS||e===p.AT||e===p.BRACKET_L||e===p.BRACKET_R||e===p.BRACE_L||e===p.PIPE||e===p.BRACE_R}function ie(e){return e>=0&&e<=55295||e>=57344&&e<=1114111}function Oe(e,t){return fn(e.charCodeAt(t))&&pn(e.charCodeAt(t+1))}function fn(e){return e>=55296&&e<=56319}function pn(e){return e>=56320&&e<=57343}function X(e,t){const n=e.source.body.codePointAt(t);if(n===void 0)return p.EOF;if(n>=32&&n<=126){const s=String.fromCodePoint(n);return s==='"'?`'"'`:`"${s}"`}return"U+"+n.toString(16).toUpperCase().padStart(4,"0")}function b(e,t,n,s,r){const i=e.line,o=1+n-e.lineStart;return new un(t,n,s,i,o,r)}function gr(e,t){const n=e.source.body,s=n.length;let r=t;for(;r<s;){const i=n.charCodeAt(r);switch(i){case 65279:case 9:case 32:case 44:++r;continue;case 10:++r,++e.line,e.lineStart=r;continue;case 13:n.charCodeAt(r+1)===10?r+=2:++r,++e.line,e.lineStart=r;continue;case 35:return Er(e,r);case 33:return b(e,p.BANG,r,r+1);case 36:return b(e,p.DOLLAR,r,r+1);case 38:return b(e,p.AMP,r,r+1);case 40:return b(e,p.PAREN_L,r,r+1);case 41:return b(e,p.PAREN_R,r,r+1);case 46:if(n.charCodeAt(r+1)===46&&n.charCodeAt(r+2)===46)return b(e,p.SPREAD,r,r+3);break;case 58:return b(e,p.COLON,r,r+1);case 61:return b(e,p.EQUALS,r,r+1);case 64:return b(e,p.AT,r,r+1);case 91:return b(e,p.BRACKET_L,r,r+1);case 93:return b(e,p.BRACKET_R,r,r+1);case 123:return b(e,p.BRACE_L,r,r+1);case 124:return b(e,p.PIPE,r,r+1);case 125:return b(e,p.BRACE_R,r,r+1);case 34:return n.charCodeAt(r+1)===34&&n.charCodeAt(r+2)===34?Ar(e,r):vr(e,r)}if(le(i)||i===45)return Tr(e,r,i);if(hn(i))return wr(e,r);throw C(e.source,r,i===39?`Unexpected single quote character ('), did you mean to use a double quote (")?`:ie(i)||Oe(n,r)?`Unexpected character: ${X(e,r)}.`:`Invalid character: ${X(e,r)}.`)}return b(e,p.EOF,s,s)}function Er(e,t){const n=e.source.body,s=n.length;let r=t+1;for(;r<s;){const i=n.charCodeAt(r);if(i===10||i===13)break;if(ie(i))++r;else if(Oe(n,r))r+=2;else break}return b(e,p.COMMENT,t,r,n.slice(t+1,r))}function Tr(e,t,n){const s=e.source.body;let r=t,i=n,o=!1;if(i===45&&(i=s.charCodeAt(++r)),i===48){if(i=s.charCodeAt(++r),le(i))throw C(e.source,r,`Invalid number, unexpected digit after 0: ${X(e,r)}.`)}else r=Ue(e,r,i),i=s.charCodeAt(r);if(i===46&&(o=!0,i=s.charCodeAt(++r),r=Ue(e,r,i),i=s.charCodeAt(r)),(i===69||i===101)&&(o=!0,i=s.charCodeAt(++r),(i===43||i===45)&&(i=s.charCodeAt(++r)),r=Ue(e,r,i),i=s.charCodeAt(r)),i===46||hn(i))throw C(e.source,r,`Invalid number, expected digit but got: ${X(e,r)}.`);return b(e,o?p.FLOAT:p.INT,t,r,s.slice(t,r))}function Ue(e,t,n){if(!le(n))throw C(e.source,t,`Invalid number, expected digit but got: ${X(e,t)}.`);const s=e.source.body;let r=t+1;for(;le(s.charCodeAt(r));)++r;return r}function vr(e,t){const n=e.source.body,s=n.length;let r=t+1,i=r,o="";for(;r<s;){const a=n.charCodeAt(r);if(a===34)return o+=n.slice(i,r),b(e,p.STRING,t,r+1,o);if(a===92){o+=n.slice(i,r);const c=n.charCodeAt(r+1)===117?n.charCodeAt(r+2)===123?Sr(e,r):_r(e,r):Ir(e,r);o+=c.value,r+=c.size,i=r;continue}if(a===10||a===13)break;if(ie(a))++r;else if(Oe(n,r))r+=2;else throw C(e.source,r,`Invalid character within String: ${X(e,r)}.`)}throw C(e.source,r,"Unterminated string.")}function Sr(e,t){const n=e.source.body;let s=0,r=3;for(;r<12;){const i=n.charCodeAt(t+r++);if(i===125){if(r<5||!ie(s))break;return{value:String.fromCodePoint(s),size:r}}if(s=s<<4|ce(i),s<0)break}throw C(e.source,t,`Invalid Unicode escape sequence: "${n.slice(t,t+r)}".`)}function _r(e,t){const n=e.source.body,s=Lt(n,t+2);if(ie(s))return{value:String.fromCodePoint(s),size:6};if(fn(s)&&n.charCodeAt(t+6)===92&&n.charCodeAt(t+7)===117){const r=Lt(n,t+8);if(pn(r))return{value:String.fromCodePoint(s,r),size:12}}throw C(e.source,t,`Invalid Unicode escape sequence: "${n.slice(t,t+6)}".`)}function Lt(e,t){return ce(e.charCodeAt(t))<<12|ce(e.charCodeAt(t+1))<<8|ce(e.charCodeAt(t+2))<<4|ce(e.charCodeAt(t+3))}function ce(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:-1}function Ir(e,t){const n=e.source.body;switch(n.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:`
12
+ `,size:2};case 114:return{value:"\r",size:2};case 116:return{value:" ",size:2}}throw C(e.source,t,`Invalid character escape sequence: "${n.slice(t,t+2)}".`)}function Ar(e,t){const n=e.source.body,s=n.length;let r=e.lineStart,i=t+3,o=i,a="";const c=[];for(;i<s;){const u=n.charCodeAt(i);if(u===34&&n.charCodeAt(i+1)===34&&n.charCodeAt(i+2)===34){a+=n.slice(o,i),c.push(a);const f=b(e,p.BLOCK_STRING,t,i+3,hr(c).join(`
13
+ `));return e.line+=c.length-1,e.lineStart=r,f}if(u===92&&n.charCodeAt(i+1)===34&&n.charCodeAt(i+2)===34&&n.charCodeAt(i+3)===34){a+=n.slice(o,i),o=i+1,i+=4;continue}if(u===10||u===13){a+=n.slice(o,i),c.push(a),u===13&&n.charCodeAt(i+1)===10?i+=2:++i,a="",o=i,r=i;continue}if(ie(u))++i;else if(Oe(n,i))i+=2;else throw C(e.source,i,`Invalid character within String: ${X(e,i)}.`)}throw C(e.source,i,"Unterminated string.")}function wr(e,t){const n=e.source.body,s=n.length;let r=t+1;for(;r<s;){const i=n.charCodeAt(r);if(lr(i))++r;else break}return b(e,p.NAME,t,r,n.slice(t,r))}const xr=10,yn=2;function ft(e){return De(e,[])}function De(e,t){switch(typeof e){case"string":return JSON.stringify(e);case"function":return e.name?`[function ${e.name}]`:"[function]";case"object":return br(e,t);default:return String(e)}}function br(e,t){if(e===null)return"null";if(t.includes(e))return"[Circular]";const n=[...t,e];if(Cr(e)){const s=e.toJSON();if(s!==e)return typeof s=="string"?s:De(s,n)}else if(Array.isArray(e))return Nr(e,n);return kr(e,n)}function Cr(e){return typeof e.toJSON=="function"}function kr(e,t){const n=Object.entries(e);return n.length===0?"{}":t.length>yn?"["+Or(e)+"]":"{ "+n.map(([r,i])=>r+": "+De(i,t)).join(", ")+" }"}function Nr(e,t){if(e.length===0)return"[]";if(t.length>yn)return"[Array]";const n=Math.min(xr,e.length),s=e.length-n,r=[];for(let i=0;i<n;++i)r.push(De(e[i],t));return s===1?r.push("... 1 more item"):s>1&&r.push(`... ${s} more items`),"["+r.join(", ")+"]"}function Or(e){const t=Object.prototype.toString.call(e).replace(/^\[object /,"").replace(/]$/,"");if(t==="Object"&&typeof e.constructor=="function"){const n=e.constructor.name;if(typeof n=="string"&&n!=="")return n}return t}const Dr=globalThis.process&&process.env.NODE_ENV==="production",Rr=Dr?function(t,n){return t instanceof n}:function(t,n){if(t instanceof n)return!0;if(typeof t=="object"&&t!==null){var s;const r=n.prototype[Symbol.toStringTag],i=Symbol.toStringTag in t?t[Symbol.toStringTag]:(s=t.constructor)===null||s===void 0?void 0:s.name;if(r===i){const o=ft(t);throw new Error(`Cannot use ${r} "${o}" from another module or realm.
14
14
 
15
15
  Ensure that there is only one instance of "graphql" in the node_modules
16
16
  directory. If different versions of "graphql" are the dependencies of other
@@ -21,17 +21,17 @@ https://yarnpkg.com/en/docs/selective-version-resolutions
21
21
  Duplicate "graphql" modules cannot be used at the same time since different
22
22
  versions may have different capabilities and behavior. The data from one
23
23
  version used in the function from another could produce confusing and
24
- spurious results.`)}}return!1};class mn{constructor(t,n="GraphQL request",s={line:1,column:1}){typeof t=="string"||Se(!1,`Body must be a string. Received: ${ft(t)}.`),this.body=t,this.name=n,this.locationOffset=s,this.locationOffset.line>0||Se(!1,"line in locationOffset is 1-indexed and must be positive."),this.locationOffset.column>0||Se(!1,"column in locationOffset is 1-indexed and must be positive.")}get[Symbol.toStringTag](){return"Source"}}function Rr(e){return Dr(e,mn)}function qr(e,t){return new Mr(e,t).parseDocument()}class Mr{constructor(t,n={}){const s=Rr(t)?t:new mn(t);this._lexer=new pr(s),this._options=n,this._tokenCounter=0}parseName(){const t=this.expectToken(p.NAME);return this.node(t,{kind:T.NAME,value:t.value})}parseDocument(){return this.node(this._lexer.token,{kind:T.DOCUMENT,definitions:this.many(p.SOF,this.parseDefinition,p.EOF)})}parseDefinition(){if(this.peek(p.BRACE_L))return this.parseOperationDefinition();const t=this.peekDescription(),n=t?this._lexer.lookahead():this._lexer.token;if(n.kind===p.NAME){switch(n.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(t)throw C(this._lexer.source,this._lexer.token.start,"Unexpected description, descriptions are supported only on type definitions.");switch(n.value){case"query":case"mutation":case"subscription":return this.parseOperationDefinition();case"fragment":return this.parseFragmentDefinition();case"extend":return this.parseTypeSystemExtension()}}throw this.unexpected(n)}parseOperationDefinition(){const t=this._lexer.token;if(this.peek(p.BRACE_L))return this.node(t,{kind:T.OPERATION_DEFINITION,operation:te.QUERY,name:void 0,variableDefinitions:[],directives:[],selectionSet:this.parseSelectionSet()});const n=this.parseOperationType();let s;return this.peek(p.NAME)&&(s=this.parseName()),this.node(t,{kind:T.OPERATION_DEFINITION,operation:n,name:s,variableDefinitions:this.parseVariableDefinitions(),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseOperationType(){const t=this.expectToken(p.NAME);switch(t.value){case"query":return te.QUERY;case"mutation":return te.MUTATION;case"subscription":return te.SUBSCRIPTION}throw this.unexpected(t)}parseVariableDefinitions(){return this.optionalMany(p.PAREN_L,this.parseVariableDefinition,p.PAREN_R)}parseVariableDefinition(){return this.node(this._lexer.token,{kind:T.VARIABLE_DEFINITION,variable:this.parseVariable(),type:(this.expectToken(p.COLON),this.parseTypeReference()),defaultValue:this.expectOptionalToken(p.EQUALS)?this.parseConstValueLiteral():void 0,directives:this.parseConstDirectives()})}parseVariable(){const t=this._lexer.token;return this.expectToken(p.DOLLAR),this.node(t,{kind:T.VARIABLE,name:this.parseName()})}parseSelectionSet(){return this.node(this._lexer.token,{kind:T.SELECTION_SET,selections:this.many(p.BRACE_L,this.parseSelection,p.BRACE_R)})}parseSelection(){return this.peek(p.SPREAD)?this.parseFragment():this.parseField()}parseField(){const t=this._lexer.token,n=this.parseName();let s,r;return this.expectOptionalToken(p.COLON)?(s=n,r=this.parseName()):r=n,this.node(t,{kind:T.FIELD,alias:s,name:r,arguments:this.parseArguments(!1),directives:this.parseDirectives(!1),selectionSet:this.peek(p.BRACE_L)?this.parseSelectionSet():void 0})}parseArguments(t){const n=t?this.parseConstArgument:this.parseArgument;return this.optionalMany(p.PAREN_L,n,p.PAREN_R)}parseArgument(t=!1){const n=this._lexer.token,s=this.parseName();return this.expectToken(p.COLON),this.node(n,{kind:T.ARGUMENT,name:s,value:this.parseValueLiteral(t)})}parseConstArgument(){return this.parseArgument(!0)}parseFragment(){const t=this._lexer.token;this.expectToken(p.SPREAD);const n=this.expectOptionalKeyword("on");return!n&&this.peek(p.NAME)?this.node(t,{kind:T.FRAGMENT_SPREAD,name:this.parseFragmentName(),directives:this.parseDirectives(!1)}):this.node(t,{kind:T.INLINE_FRAGMENT,typeCondition:n?this.parseNamedType():void 0,directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseFragmentDefinition(){const t=this._lexer.token;return this.expectKeyword("fragment"),this._options.allowLegacyFragmentVariables===!0?this.node(t,{kind:T.FRAGMENT_DEFINITION,name:this.parseFragmentName(),variableDefinitions:this.parseVariableDefinitions(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()}):this.node(t,{kind:T.FRAGMENT_DEFINITION,name:this.parseFragmentName(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseFragmentName(){if(this._lexer.token.value==="on")throw this.unexpected();return this.parseName()}parseValueLiteral(t){const n=this._lexer.token;switch(n.kind){case p.BRACKET_L:return this.parseList(t);case p.BRACE_L:return this.parseObject(t);case p.INT:return this.advanceLexer(),this.node(n,{kind:T.INT,value:n.value});case p.FLOAT:return this.advanceLexer(),this.node(n,{kind:T.FLOAT,value:n.value});case p.STRING:case p.BLOCK_STRING:return this.parseStringLiteral();case p.NAME:switch(this.advanceLexer(),n.value){case"true":return this.node(n,{kind:T.BOOLEAN,value:!0});case"false":return this.node(n,{kind:T.BOOLEAN,value:!1});case"null":return this.node(n,{kind:T.NULL});default:return this.node(n,{kind:T.ENUM,value:n.value})}case p.DOLLAR:if(t)if(this.expectToken(p.DOLLAR),this._lexer.token.kind===p.NAME){const s=this._lexer.token.value;throw C(this._lexer.source,n.start,`Unexpected variable "$${s}" in constant value.`)}else throw this.unexpected(n);return this.parseVariable();default:throw this.unexpected()}}parseConstValueLiteral(){return this.parseValueLiteral(!0)}parseStringLiteral(){const t=this._lexer.token;return this.advanceLexer(),this.node(t,{kind:T.STRING,value:t.value,block:t.kind===p.BLOCK_STRING})}parseList(t){const n=()=>this.parseValueLiteral(t);return this.node(this._lexer.token,{kind:T.LIST,values:this.any(p.BRACKET_L,n,p.BRACKET_R)})}parseObject(t){const n=()=>this.parseObjectField(t);return this.node(this._lexer.token,{kind:T.OBJECT,fields:this.any(p.BRACE_L,n,p.BRACE_R)})}parseObjectField(t){const n=this._lexer.token,s=this.parseName();return this.expectToken(p.COLON),this.node(n,{kind:T.OBJECT_FIELD,name:s,value:this.parseValueLiteral(t)})}parseDirectives(t){const n=[];for(;this.peek(p.AT);)n.push(this.parseDirective(t));return n}parseConstDirectives(){return this.parseDirectives(!0)}parseDirective(t){const n=this._lexer.token;return this.expectToken(p.AT),this.node(n,{kind:T.DIRECTIVE,name:this.parseName(),arguments:this.parseArguments(t)})}parseTypeReference(){const t=this._lexer.token;let n;if(this.expectOptionalToken(p.BRACKET_L)){const s=this.parseTypeReference();this.expectToken(p.BRACKET_R),n=this.node(t,{kind:T.LIST_TYPE,type:s})}else n=this.parseNamedType();return this.expectOptionalToken(p.BANG)?this.node(t,{kind:T.NON_NULL_TYPE,type:n}):n}parseNamedType(){return this.node(this._lexer.token,{kind:T.NAMED_TYPE,name:this.parseName()})}peekDescription(){return this.peek(p.STRING)||this.peek(p.BLOCK_STRING)}parseDescription(){if(this.peekDescription())return this.parseStringLiteral()}parseSchemaDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("schema");const s=this.parseConstDirectives(),r=this.many(p.BRACE_L,this.parseOperationTypeDefinition,p.BRACE_R);return this.node(t,{kind:T.SCHEMA_DEFINITION,description:n,directives:s,operationTypes:r})}parseOperationTypeDefinition(){const t=this._lexer.token,n=this.parseOperationType();this.expectToken(p.COLON);const s=this.parseNamedType();return this.node(t,{kind:T.OPERATION_TYPE_DEFINITION,operation:n,type:s})}parseScalarTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("scalar");const s=this.parseName(),r=this.parseConstDirectives();return this.node(t,{kind:T.SCALAR_TYPE_DEFINITION,description:n,name:s,directives:r})}parseObjectTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("type");const s=this.parseName(),r=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),o=this.parseFieldsDefinition();return this.node(t,{kind:T.OBJECT_TYPE_DEFINITION,description:n,name:s,interfaces:r,directives:i,fields:o})}parseImplementsInterfaces(){return this.expectOptionalKeyword("implements")?this.delimitedMany(p.AMP,this.parseNamedType):[]}parseFieldsDefinition(){return this.optionalMany(p.BRACE_L,this.parseFieldDefinition,p.BRACE_R)}parseFieldDefinition(){const t=this._lexer.token,n=this.parseDescription(),s=this.parseName(),r=this.parseArgumentDefs();this.expectToken(p.COLON);const i=this.parseTypeReference(),o=this.parseConstDirectives();return this.node(t,{kind:T.FIELD_DEFINITION,description:n,name:s,arguments:r,type:i,directives:o})}parseArgumentDefs(){return this.optionalMany(p.PAREN_L,this.parseInputValueDef,p.PAREN_R)}parseInputValueDef(){const t=this._lexer.token,n=this.parseDescription(),s=this.parseName();this.expectToken(p.COLON);const r=this.parseTypeReference();let i;this.expectOptionalToken(p.EQUALS)&&(i=this.parseConstValueLiteral());const o=this.parseConstDirectives();return this.node(t,{kind:T.INPUT_VALUE_DEFINITION,description:n,name:s,type:r,defaultValue:i,directives:o})}parseInterfaceTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("interface");const s=this.parseName(),r=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),o=this.parseFieldsDefinition();return this.node(t,{kind:T.INTERFACE_TYPE_DEFINITION,description:n,name:s,interfaces:r,directives:i,fields:o})}parseUnionTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("union");const s=this.parseName(),r=this.parseConstDirectives(),i=this.parseUnionMemberTypes();return this.node(t,{kind:T.UNION_TYPE_DEFINITION,description:n,name:s,directives:r,types:i})}parseUnionMemberTypes(){return this.expectOptionalToken(p.EQUALS)?this.delimitedMany(p.PIPE,this.parseNamedType):[]}parseEnumTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("enum");const s=this.parseName(),r=this.parseConstDirectives(),i=this.parseEnumValuesDefinition();return this.node(t,{kind:T.ENUM_TYPE_DEFINITION,description:n,name:s,directives:r,values:i})}parseEnumValuesDefinition(){return this.optionalMany(p.BRACE_L,this.parseEnumValueDefinition,p.BRACE_R)}parseEnumValueDefinition(){const t=this._lexer.token,n=this.parseDescription(),s=this.parseEnumValueName(),r=this.parseConstDirectives();return this.node(t,{kind:T.ENUM_VALUE_DEFINITION,description:n,name:s,directives:r})}parseEnumValueName(){if(this._lexer.token.value==="true"||this._lexer.token.value==="false"||this._lexer.token.value==="null")throw C(this._lexer.source,this._lexer.token.start,`${ve(this._lexer.token)} is reserved and cannot be used for an enum value.`);return this.parseName()}parseInputObjectTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("input");const s=this.parseName(),r=this.parseConstDirectives(),i=this.parseInputFieldsDefinition();return this.node(t,{kind:T.INPUT_OBJECT_TYPE_DEFINITION,description:n,name:s,directives:r,fields:i})}parseInputFieldsDefinition(){return this.optionalMany(p.BRACE_L,this.parseInputValueDef,p.BRACE_R)}parseTypeSystemExtension(){const t=this._lexer.lookahead();if(t.kind===p.NAME)switch(t.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(t)}parseSchemaExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("schema");const n=this.parseConstDirectives(),s=this.optionalMany(p.BRACE_L,this.parseOperationTypeDefinition,p.BRACE_R);if(n.length===0&&s.length===0)throw this.unexpected();return this.node(t,{kind:T.SCHEMA_EXTENSION,directives:n,operationTypes:s})}parseScalarTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("scalar");const n=this.parseName(),s=this.parseConstDirectives();if(s.length===0)throw this.unexpected();return this.node(t,{kind:T.SCALAR_TYPE_EXTENSION,name:n,directives:s})}parseObjectTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("type");const n=this.parseName(),s=this.parseImplementsInterfaces(),r=this.parseConstDirectives(),i=this.parseFieldsDefinition();if(s.length===0&&r.length===0&&i.length===0)throw this.unexpected();return this.node(t,{kind:T.OBJECT_TYPE_EXTENSION,name:n,interfaces:s,directives:r,fields:i})}parseInterfaceTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("interface");const n=this.parseName(),s=this.parseImplementsInterfaces(),r=this.parseConstDirectives(),i=this.parseFieldsDefinition();if(s.length===0&&r.length===0&&i.length===0)throw this.unexpected();return this.node(t,{kind:T.INTERFACE_TYPE_EXTENSION,name:n,interfaces:s,directives:r,fields:i})}parseUnionTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("union");const n=this.parseName(),s=this.parseConstDirectives(),r=this.parseUnionMemberTypes();if(s.length===0&&r.length===0)throw this.unexpected();return this.node(t,{kind:T.UNION_TYPE_EXTENSION,name:n,directives:s,types:r})}parseEnumTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("enum");const n=this.parseName(),s=this.parseConstDirectives(),r=this.parseEnumValuesDefinition();if(s.length===0&&r.length===0)throw this.unexpected();return this.node(t,{kind:T.ENUM_TYPE_EXTENSION,name:n,directives:s,values:r})}parseInputObjectTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("input");const n=this.parseName(),s=this.parseConstDirectives(),r=this.parseInputFieldsDefinition();if(s.length===0&&r.length===0)throw this.unexpected();return this.node(t,{kind:T.INPUT_OBJECT_TYPE_EXTENSION,name:n,directives:s,fields:r})}parseDirectiveDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("directive"),this.expectToken(p.AT);const s=this.parseName(),r=this.parseArgumentDefs(),i=this.expectOptionalKeyword("repeatable");this.expectKeyword("on");const o=this.parseDirectiveLocations();return this.node(t,{kind:T.DIRECTIVE_DEFINITION,description:n,name:s,arguments:r,repeatable:i,locations:o})}parseDirectiveLocations(){return this.delimitedMany(p.PIPE,this.parseDirectiveLocation)}parseDirectiveLocation(){const t=this._lexer.token,n=this.parseName();if(Object.prototype.hasOwnProperty.call(Qe,n.value))return n;throw this.unexpected(t)}node(t,n){return this._options.noLocation!==!0&&(n.loc=new cr(t,this._lexer.lastToken,this._lexer.source)),n}peek(t){return this._lexer.token.kind===t}expectToken(t){const n=this._lexer.token;if(n.kind===t)return this.advanceLexer(),n;throw C(this._lexer.source,n.start,`Expected ${gn(t)}, found ${ve(n)}.`)}expectOptionalToken(t){return this._lexer.token.kind===t?(this.advanceLexer(),!0):!1}expectKeyword(t){const n=this._lexer.token;if(n.kind===p.NAME&&n.value===t)this.advanceLexer();else throw C(this._lexer.source,n.start,`Expected "${t}", found ${ve(n)}.`)}expectOptionalKeyword(t){const n=this._lexer.token;return n.kind===p.NAME&&n.value===t?(this.advanceLexer(),!0):!1}unexpected(t){const n=t??this._lexer.token;return C(this._lexer.source,n.start,`Unexpected ${ve(n)}.`)}any(t,n,s){this.expectToken(t);const r=[];for(;!this.expectOptionalToken(s);)r.push(n.call(this));return r}optionalMany(t,n,s){if(this.expectOptionalToken(t)){const r=[];do r.push(n.call(this));while(!this.expectOptionalToken(s));return r}return[]}many(t,n,s){this.expectToken(t);const r=[];do r.push(n.call(this));while(!this.expectOptionalToken(s));return r}delimitedMany(t,n){this.expectOptionalToken(t);const s=[];do s.push(n.call(this));while(this.expectOptionalToken(t));return s}advanceLexer(){const{maxTokens:t}=this._options,n=this._lexer.advance();if(t!==void 0&&n.kind!==p.EOF&&(++this._tokenCounter,this._tokenCounter>t))throw C(this._lexer.source,n.start,`Document contains more that ${t} tokens. Parsing aborted.`)}}function ve(e){const t=e.value;return gn(e.kind)+(t!=null?` "${t}"`:"")}function gn(e){return yr(e)?`"${e}"`:e}function Lr(e){return`"${e.replace(Pr,Ur)}"`}const Pr=/[\x00-\x1f\x22\x5c\x7f-\x9f]/g;function Ur(e){return Fr[e.charCodeAt(0)]}const Fr=["\\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"],Br=Object.freeze({});function jr(e,t,n=dn){const s=new Map;for(const w of Object.values(T))s.set(w,$r(t,w));let r,i=Array.isArray(e),o=[e],a=-1,c=[],u=e,h,d;const f=[],m=[];do{a++;const w=a===o.length,q=w&&c.length!==0;if(w){if(h=m.length===0?void 0:f[f.length-1],u=d,d=m.pop(),q)if(i){u=u.slice();let M=0;for(const[F,z]of c){const G=F-M;z===null?(u.splice(G,1),M++):u[G]=z}}else{u=Object.defineProperties({},Object.getOwnPropertyDescriptors(u));for(const[M,F]of c)u[M]=F}a=r.index,o=r.keys,c=r.edits,i=r.inArray,r=r.prev}else if(d){if(h=i?a:o[a],u=d[h],u==null)continue;f.push(h)}let D;if(!Array.isArray(u)){var y,v;Mt(u)||Se(!1,`Invalid AST Node: ${ft(u)}.`);const M=w?(y=s.get(u.kind))===null||y===void 0?void 0:y.leave:(v=s.get(u.kind))===null||v===void 0?void 0:v.enter;if(D=M==null?void 0:M.call(t,u,h,d,f,m),D===Br)break;if(D===!1){if(!w){f.pop();continue}}else if(D!==void 0&&(c.push([h,D]),!w))if(Mt(D))u=D;else{f.pop();continue}}if(D===void 0&&q&&c.push([h,u]),w)f.pop();else{var _;r={inArray:i,index:a,keys:o,edits:c,prev:r},i=Array.isArray(u),o=i?u:(_=n[u.kind])!==null&&_!==void 0?_:[],a=-1,c=[],d&&m.push(d),d=u}}while(r!==void 0);return c.length!==0?c[c.length-1][1]:e}function $r(e,t){const n=e[t];return typeof n=="object"?n:typeof n=="function"?{enter:n,leave:void 0}:{enter:e.enter,leave:e.leave}}function En(e){return jr(e,Hr)}const Vr=80,Hr={Name:{leave:e=>e.value},Variable:{leave:e=>"$"+e.name},Document:{leave:e=>E(e.definitions,`
24
+ spurious results.`)}}return!1};class mn{constructor(t,n="GraphQL request",s={line:1,column:1}){typeof t=="string"||_e(!1,`Body must be a string. Received: ${ft(t)}.`),this.body=t,this.name=n,this.locationOffset=s,this.locationOffset.line>0||_e(!1,"line in locationOffset is 1-indexed and must be positive."),this.locationOffset.column>0||_e(!1,"column in locationOffset is 1-indexed and must be positive.")}get[Symbol.toStringTag](){return"Source"}}function qr(e){return Rr(e,mn)}function Mr(e,t){return new Lr(e,t).parseDocument()}class Lr{constructor(t,n={}){const s=qr(t)?t:new mn(t);this._lexer=new yr(s),this._options=n,this._tokenCounter=0}parseName(){const t=this.expectToken(p.NAME);return this.node(t,{kind:v.NAME,value:t.value})}parseDocument(){return this.node(this._lexer.token,{kind:v.DOCUMENT,definitions:this.many(p.SOF,this.parseDefinition,p.EOF)})}parseDefinition(){if(this.peek(p.BRACE_L))return this.parseOperationDefinition();const t=this.peekDescription(),n=t?this._lexer.lookahead():this._lexer.token;if(n.kind===p.NAME){switch(n.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(t)throw C(this._lexer.source,this._lexer.token.start,"Unexpected description, descriptions are supported only on type definitions.");switch(n.value){case"query":case"mutation":case"subscription":return this.parseOperationDefinition();case"fragment":return this.parseFragmentDefinition();case"extend":return this.parseTypeSystemExtension()}}throw this.unexpected(n)}parseOperationDefinition(){const t=this._lexer.token;if(this.peek(p.BRACE_L))return this.node(t,{kind:v.OPERATION_DEFINITION,operation:te.QUERY,name:void 0,variableDefinitions:[],directives:[],selectionSet:this.parseSelectionSet()});const n=this.parseOperationType();let s;return this.peek(p.NAME)&&(s=this.parseName()),this.node(t,{kind:v.OPERATION_DEFINITION,operation:n,name:s,variableDefinitions:this.parseVariableDefinitions(),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseOperationType(){const t=this.expectToken(p.NAME);switch(t.value){case"query":return te.QUERY;case"mutation":return te.MUTATION;case"subscription":return te.SUBSCRIPTION}throw this.unexpected(t)}parseVariableDefinitions(){return this.optionalMany(p.PAREN_L,this.parseVariableDefinition,p.PAREN_R)}parseVariableDefinition(){return this.node(this._lexer.token,{kind:v.VARIABLE_DEFINITION,variable:this.parseVariable(),type:(this.expectToken(p.COLON),this.parseTypeReference()),defaultValue:this.expectOptionalToken(p.EQUALS)?this.parseConstValueLiteral():void 0,directives:this.parseConstDirectives()})}parseVariable(){const t=this._lexer.token;return this.expectToken(p.DOLLAR),this.node(t,{kind:v.VARIABLE,name:this.parseName()})}parseSelectionSet(){return this.node(this._lexer.token,{kind:v.SELECTION_SET,selections:this.many(p.BRACE_L,this.parseSelection,p.BRACE_R)})}parseSelection(){return this.peek(p.SPREAD)?this.parseFragment():this.parseField()}parseField(){const t=this._lexer.token,n=this.parseName();let s,r;return this.expectOptionalToken(p.COLON)?(s=n,r=this.parseName()):r=n,this.node(t,{kind:v.FIELD,alias:s,name:r,arguments:this.parseArguments(!1),directives:this.parseDirectives(!1),selectionSet:this.peek(p.BRACE_L)?this.parseSelectionSet():void 0})}parseArguments(t){const n=t?this.parseConstArgument:this.parseArgument;return this.optionalMany(p.PAREN_L,n,p.PAREN_R)}parseArgument(t=!1){const n=this._lexer.token,s=this.parseName();return this.expectToken(p.COLON),this.node(n,{kind:v.ARGUMENT,name:s,value:this.parseValueLiteral(t)})}parseConstArgument(){return this.parseArgument(!0)}parseFragment(){const t=this._lexer.token;this.expectToken(p.SPREAD);const n=this.expectOptionalKeyword("on");return!n&&this.peek(p.NAME)?this.node(t,{kind:v.FRAGMENT_SPREAD,name:this.parseFragmentName(),directives:this.parseDirectives(!1)}):this.node(t,{kind:v.INLINE_FRAGMENT,typeCondition:n?this.parseNamedType():void 0,directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseFragmentDefinition(){const t=this._lexer.token;return this.expectKeyword("fragment"),this._options.allowLegacyFragmentVariables===!0?this.node(t,{kind:v.FRAGMENT_DEFINITION,name:this.parseFragmentName(),variableDefinitions:this.parseVariableDefinitions(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()}):this.node(t,{kind:v.FRAGMENT_DEFINITION,name:this.parseFragmentName(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseFragmentName(){if(this._lexer.token.value==="on")throw this.unexpected();return this.parseName()}parseValueLiteral(t){const n=this._lexer.token;switch(n.kind){case p.BRACKET_L:return this.parseList(t);case p.BRACE_L:return this.parseObject(t);case p.INT:return this.advanceLexer(),this.node(n,{kind:v.INT,value:n.value});case p.FLOAT:return this.advanceLexer(),this.node(n,{kind:v.FLOAT,value:n.value});case p.STRING:case p.BLOCK_STRING:return this.parseStringLiteral();case p.NAME:switch(this.advanceLexer(),n.value){case"true":return this.node(n,{kind:v.BOOLEAN,value:!0});case"false":return this.node(n,{kind:v.BOOLEAN,value:!1});case"null":return this.node(n,{kind:v.NULL});default:return this.node(n,{kind:v.ENUM,value:n.value})}case p.DOLLAR:if(t)if(this.expectToken(p.DOLLAR),this._lexer.token.kind===p.NAME){const s=this._lexer.token.value;throw C(this._lexer.source,n.start,`Unexpected variable "$${s}" in constant value.`)}else throw this.unexpected(n);return this.parseVariable();default:throw this.unexpected()}}parseConstValueLiteral(){return this.parseValueLiteral(!0)}parseStringLiteral(){const t=this._lexer.token;return this.advanceLexer(),this.node(t,{kind:v.STRING,value:t.value,block:t.kind===p.BLOCK_STRING})}parseList(t){const n=()=>this.parseValueLiteral(t);return this.node(this._lexer.token,{kind:v.LIST,values:this.any(p.BRACKET_L,n,p.BRACKET_R)})}parseObject(t){const n=()=>this.parseObjectField(t);return this.node(this._lexer.token,{kind:v.OBJECT,fields:this.any(p.BRACE_L,n,p.BRACE_R)})}parseObjectField(t){const n=this._lexer.token,s=this.parseName();return this.expectToken(p.COLON),this.node(n,{kind:v.OBJECT_FIELD,name:s,value:this.parseValueLiteral(t)})}parseDirectives(t){const n=[];for(;this.peek(p.AT);)n.push(this.parseDirective(t));return n}parseConstDirectives(){return this.parseDirectives(!0)}parseDirective(t){const n=this._lexer.token;return this.expectToken(p.AT),this.node(n,{kind:v.DIRECTIVE,name:this.parseName(),arguments:this.parseArguments(t)})}parseTypeReference(){const t=this._lexer.token;let n;if(this.expectOptionalToken(p.BRACKET_L)){const s=this.parseTypeReference();this.expectToken(p.BRACKET_R),n=this.node(t,{kind:v.LIST_TYPE,type:s})}else n=this.parseNamedType();return this.expectOptionalToken(p.BANG)?this.node(t,{kind:v.NON_NULL_TYPE,type:n}):n}parseNamedType(){return this.node(this._lexer.token,{kind:v.NAMED_TYPE,name:this.parseName()})}peekDescription(){return this.peek(p.STRING)||this.peek(p.BLOCK_STRING)}parseDescription(){if(this.peekDescription())return this.parseStringLiteral()}parseSchemaDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("schema");const s=this.parseConstDirectives(),r=this.many(p.BRACE_L,this.parseOperationTypeDefinition,p.BRACE_R);return this.node(t,{kind:v.SCHEMA_DEFINITION,description:n,directives:s,operationTypes:r})}parseOperationTypeDefinition(){const t=this._lexer.token,n=this.parseOperationType();this.expectToken(p.COLON);const s=this.parseNamedType();return this.node(t,{kind:v.OPERATION_TYPE_DEFINITION,operation:n,type:s})}parseScalarTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("scalar");const s=this.parseName(),r=this.parseConstDirectives();return this.node(t,{kind:v.SCALAR_TYPE_DEFINITION,description:n,name:s,directives:r})}parseObjectTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("type");const s=this.parseName(),r=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),o=this.parseFieldsDefinition();return this.node(t,{kind:v.OBJECT_TYPE_DEFINITION,description:n,name:s,interfaces:r,directives:i,fields:o})}parseImplementsInterfaces(){return this.expectOptionalKeyword("implements")?this.delimitedMany(p.AMP,this.parseNamedType):[]}parseFieldsDefinition(){return this.optionalMany(p.BRACE_L,this.parseFieldDefinition,p.BRACE_R)}parseFieldDefinition(){const t=this._lexer.token,n=this.parseDescription(),s=this.parseName(),r=this.parseArgumentDefs();this.expectToken(p.COLON);const i=this.parseTypeReference(),o=this.parseConstDirectives();return this.node(t,{kind:v.FIELD_DEFINITION,description:n,name:s,arguments:r,type:i,directives:o})}parseArgumentDefs(){return this.optionalMany(p.PAREN_L,this.parseInputValueDef,p.PAREN_R)}parseInputValueDef(){const t=this._lexer.token,n=this.parseDescription(),s=this.parseName();this.expectToken(p.COLON);const r=this.parseTypeReference();let i;this.expectOptionalToken(p.EQUALS)&&(i=this.parseConstValueLiteral());const o=this.parseConstDirectives();return this.node(t,{kind:v.INPUT_VALUE_DEFINITION,description:n,name:s,type:r,defaultValue:i,directives:o})}parseInterfaceTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("interface");const s=this.parseName(),r=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),o=this.parseFieldsDefinition();return this.node(t,{kind:v.INTERFACE_TYPE_DEFINITION,description:n,name:s,interfaces:r,directives:i,fields:o})}parseUnionTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("union");const s=this.parseName(),r=this.parseConstDirectives(),i=this.parseUnionMemberTypes();return this.node(t,{kind:v.UNION_TYPE_DEFINITION,description:n,name:s,directives:r,types:i})}parseUnionMemberTypes(){return this.expectOptionalToken(p.EQUALS)?this.delimitedMany(p.PIPE,this.parseNamedType):[]}parseEnumTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("enum");const s=this.parseName(),r=this.parseConstDirectives(),i=this.parseEnumValuesDefinition();return this.node(t,{kind:v.ENUM_TYPE_DEFINITION,description:n,name:s,directives:r,values:i})}parseEnumValuesDefinition(){return this.optionalMany(p.BRACE_L,this.parseEnumValueDefinition,p.BRACE_R)}parseEnumValueDefinition(){const t=this._lexer.token,n=this.parseDescription(),s=this.parseEnumValueName(),r=this.parseConstDirectives();return this.node(t,{kind:v.ENUM_VALUE_DEFINITION,description:n,name:s,directives:r})}parseEnumValueName(){if(this._lexer.token.value==="true"||this._lexer.token.value==="false"||this._lexer.token.value==="null")throw C(this._lexer.source,this._lexer.token.start,`${Te(this._lexer.token)} is reserved and cannot be used for an enum value.`);return this.parseName()}parseInputObjectTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("input");const s=this.parseName(),r=this.parseConstDirectives(),i=this.parseInputFieldsDefinition();return this.node(t,{kind:v.INPUT_OBJECT_TYPE_DEFINITION,description:n,name:s,directives:r,fields:i})}parseInputFieldsDefinition(){return this.optionalMany(p.BRACE_L,this.parseInputValueDef,p.BRACE_R)}parseTypeSystemExtension(){const t=this._lexer.lookahead();if(t.kind===p.NAME)switch(t.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(t)}parseSchemaExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("schema");const n=this.parseConstDirectives(),s=this.optionalMany(p.BRACE_L,this.parseOperationTypeDefinition,p.BRACE_R);if(n.length===0&&s.length===0)throw this.unexpected();return this.node(t,{kind:v.SCHEMA_EXTENSION,directives:n,operationTypes:s})}parseScalarTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("scalar");const n=this.parseName(),s=this.parseConstDirectives();if(s.length===0)throw this.unexpected();return this.node(t,{kind:v.SCALAR_TYPE_EXTENSION,name:n,directives:s})}parseObjectTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("type");const n=this.parseName(),s=this.parseImplementsInterfaces(),r=this.parseConstDirectives(),i=this.parseFieldsDefinition();if(s.length===0&&r.length===0&&i.length===0)throw this.unexpected();return this.node(t,{kind:v.OBJECT_TYPE_EXTENSION,name:n,interfaces:s,directives:r,fields:i})}parseInterfaceTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("interface");const n=this.parseName(),s=this.parseImplementsInterfaces(),r=this.parseConstDirectives(),i=this.parseFieldsDefinition();if(s.length===0&&r.length===0&&i.length===0)throw this.unexpected();return this.node(t,{kind:v.INTERFACE_TYPE_EXTENSION,name:n,interfaces:s,directives:r,fields:i})}parseUnionTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("union");const n=this.parseName(),s=this.parseConstDirectives(),r=this.parseUnionMemberTypes();if(s.length===0&&r.length===0)throw this.unexpected();return this.node(t,{kind:v.UNION_TYPE_EXTENSION,name:n,directives:s,types:r})}parseEnumTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("enum");const n=this.parseName(),s=this.parseConstDirectives(),r=this.parseEnumValuesDefinition();if(s.length===0&&r.length===0)throw this.unexpected();return this.node(t,{kind:v.ENUM_TYPE_EXTENSION,name:n,directives:s,values:r})}parseInputObjectTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("input");const n=this.parseName(),s=this.parseConstDirectives(),r=this.parseInputFieldsDefinition();if(s.length===0&&r.length===0)throw this.unexpected();return this.node(t,{kind:v.INPUT_OBJECT_TYPE_EXTENSION,name:n,directives:s,fields:r})}parseDirectiveDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("directive"),this.expectToken(p.AT);const s=this.parseName(),r=this.parseArgumentDefs(),i=this.expectOptionalKeyword("repeatable");this.expectKeyword("on");const o=this.parseDirectiveLocations();return this.node(t,{kind:v.DIRECTIVE_DEFINITION,description:n,name:s,arguments:r,repeatable:i,locations:o})}parseDirectiveLocations(){return this.delimitedMany(p.PIPE,this.parseDirectiveLocation)}parseDirectiveLocation(){const t=this._lexer.token,n=this.parseName();if(Object.prototype.hasOwnProperty.call(Qe,n.value))return n;throw this.unexpected(t)}node(t,n){return this._options.noLocation!==!0&&(n.loc=new ur(t,this._lexer.lastToken,this._lexer.source)),n}peek(t){return this._lexer.token.kind===t}expectToken(t){const n=this._lexer.token;if(n.kind===t)return this.advanceLexer(),n;throw C(this._lexer.source,n.start,`Expected ${gn(t)}, found ${Te(n)}.`)}expectOptionalToken(t){return this._lexer.token.kind===t?(this.advanceLexer(),!0):!1}expectKeyword(t){const n=this._lexer.token;if(n.kind===p.NAME&&n.value===t)this.advanceLexer();else throw C(this._lexer.source,n.start,`Expected "${t}", found ${Te(n)}.`)}expectOptionalKeyword(t){const n=this._lexer.token;return n.kind===p.NAME&&n.value===t?(this.advanceLexer(),!0):!1}unexpected(t){const n=t??this._lexer.token;return C(this._lexer.source,n.start,`Unexpected ${Te(n)}.`)}any(t,n,s){this.expectToken(t);const r=[];for(;!this.expectOptionalToken(s);)r.push(n.call(this));return r}optionalMany(t,n,s){if(this.expectOptionalToken(t)){const r=[];do r.push(n.call(this));while(!this.expectOptionalToken(s));return r}return[]}many(t,n,s){this.expectToken(t);const r=[];do r.push(n.call(this));while(!this.expectOptionalToken(s));return r}delimitedMany(t,n){this.expectOptionalToken(t);const s=[];do s.push(n.call(this));while(this.expectOptionalToken(t));return s}advanceLexer(){const{maxTokens:t}=this._options,n=this._lexer.advance();if(t!==void 0&&n.kind!==p.EOF&&(++this._tokenCounter,this._tokenCounter>t))throw C(this._lexer.source,n.start,`Document contains more that ${t} tokens. Parsing aborted.`)}}function Te(e){const t=e.value;return gn(e.kind)+(t!=null?` "${t}"`:"")}function gn(e){return mr(e)?`"${e}"`:e}function Ur(e){return`"${e.replace(Pr,Fr)}"`}const Pr=/[\x00-\x1f\x22\x5c\x7f-\x9f]/g;function Fr(e){return Br[e.charCodeAt(0)]}const Br=["\\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"],jr=Object.freeze({});function $r(e,t,n=dn){const s=new Map;for(const w of Object.values(v))s.set(w,Vr(t,w));let r,i=Array.isArray(e),o=[e],a=-1,c=[],u=e,f,l;const h=[],m=[];do{a++;const w=a===o.length,q=w&&c.length!==0;if(w){if(f=m.length===0?void 0:h[h.length-1],u=l,l=m.pop(),q)if(i){u=u.slice();let M=0;for(const[F,z]of c){const G=F-M;z===null?(u.splice(G,1),M++):u[G]=z}}else{u=Object.defineProperties({},Object.getOwnPropertyDescriptors(u));for(const[M,F]of c)u[M]=F}a=r.index,o=r.keys,c=r.edits,i=r.inArray,r=r.prev}else if(l){if(f=i?a:o[a],u=l[f],u==null)continue;h.push(f)}let D;if(!Array.isArray(u)){var y,T;Mt(u)||_e(!1,`Invalid AST Node: ${ft(u)}.`);const M=w?(y=s.get(u.kind))===null||y===void 0?void 0:y.leave:(T=s.get(u.kind))===null||T===void 0?void 0:T.enter;if(D=M==null?void 0:M.call(t,u,f,l,h,m),D===jr)break;if(D===!1){if(!w){h.pop();continue}}else if(D!==void 0&&(c.push([f,D]),!w))if(Mt(D))u=D;else{h.pop();continue}}if(D===void 0&&q&&c.push([f,u]),w)h.pop();else{var _;r={inArray:i,index:a,keys:o,edits:c,prev:r},i=Array.isArray(u),o=i?u:(_=n[u.kind])!==null&&_!==void 0?_:[],a=-1,c=[],l&&m.push(l),l=u}}while(r!==void 0);return c.length!==0?c[c.length-1][1]:e}function Vr(e,t){const n=e[t];return typeof n=="object"?n:typeof n=="function"?{enter:n,leave:void 0}:{enter:e.enter,leave:e.leave}}function En(e){return $r(e,zr)}const Hr=80,zr={Name:{leave:e=>e.value},Variable:{leave:e=>"$"+e.name},Document:{leave:e=>E(e.definitions,`
25
25
 
26
- `)},OperationDefinition:{leave(e){const t=I("(",E(e.variableDefinitions,", "),")"),n=E([e.operation,E([e.name,t]),E(e.directives," ")]," ");return(n==="query"?"":n+" ")+e.selectionSet}},VariableDefinition:{leave:({variable:e,type:t,defaultValue:n,directives:s})=>e+": "+t+I(" = ",n)+I(" ",E(s," "))},SelectionSet:{leave:({selections:e})=>L(e)},Field:{leave({alias:e,name:t,arguments:n,directives:s,selectionSet:r}){const i=I("",e,": ")+t;let o=i+I("(",E(n,", "),")");return o.length>Vr&&(o=i+I(`(
27
- `,_e(E(n,`
26
+ `)},OperationDefinition:{leave(e){const t=I("(",E(e.variableDefinitions,", "),")"),n=E([e.operation,E([e.name,t]),E(e.directives," ")]," ");return(n==="query"?"":n+" ")+e.selectionSet}},VariableDefinition:{leave:({variable:e,type:t,defaultValue:n,directives:s})=>e+": "+t+I(" = ",n)+I(" ",E(s," "))},SelectionSet:{leave:({selections:e})=>L(e)},Field:{leave({alias:e,name:t,arguments:n,directives:s,selectionSet:r}){const i=I("",e,": ")+t;let o=i+I("(",E(n,", "),")");return o.length>Hr&&(o=i+I(`(
27
+ `,Ie(E(n,`
28
28
  `)),`
29
- )`)),E([o,E(s," "),r]," ")}},Argument:{leave:({name:e,value:t})=>e+": "+t},FragmentSpread:{leave:({name:e,directives:t})=>"..."+e+I(" ",E(t," "))},InlineFragment:{leave:({typeCondition:e,directives:t,selectionSet:n})=>E(["...",I("on ",e),E(t," "),n]," ")},FragmentDefinition:{leave:({name:e,typeCondition:t,variableDefinitions:n,directives:s,selectionSet:r})=>`fragment ${e}${I("(",E(n,", "),")")} on ${t} ${I("",E(s," ")," ")}`+r},IntValue:{leave:({value:e})=>e},FloatValue:{leave:({value:e})=>e},StringValue:{leave:({value:e,block:t})=>t?fr(e):Lr(e)},BooleanValue:{leave:({value:e})=>e?"true":"false"},NullValue:{leave:()=>"null"},EnumValue:{leave:({value:e})=>e},ListValue:{leave:({values:e})=>"["+E(e,", ")+"]"},ObjectValue:{leave:({fields:e})=>"{"+E(e,", ")+"}"},ObjectField:{leave:({name:e,value:t})=>e+": "+t},Directive:{leave:({name:e,arguments:t})=>"@"+e+I("(",E(t,", "),")")},NamedType:{leave:({name:e})=>e},ListType:{leave:({type:e})=>"["+e+"]"},NonNullType:{leave:({type:e})=>e+"!"},SchemaDefinition:{leave:({description:e,directives:t,operationTypes:n})=>I("",e,`
29
+ )`)),E([o,E(s," "),r]," ")}},Argument:{leave:({name:e,value:t})=>e+": "+t},FragmentSpread:{leave:({name:e,directives:t})=>"..."+e+I(" ",E(t," "))},InlineFragment:{leave:({typeCondition:e,directives:t,selectionSet:n})=>E(["...",I("on ",e),E(t," "),n]," ")},FragmentDefinition:{leave:({name:e,typeCondition:t,variableDefinitions:n,directives:s,selectionSet:r})=>`fragment ${e}${I("(",E(n,", "),")")} on ${t} ${I("",E(s," ")," ")}`+r},IntValue:{leave:({value:e})=>e},FloatValue:{leave:({value:e})=>e},StringValue:{leave:({value:e,block:t})=>t?pr(e):Ur(e)},BooleanValue:{leave:({value:e})=>e?"true":"false"},NullValue:{leave:()=>"null"},EnumValue:{leave:({value:e})=>e},ListValue:{leave:({values:e})=>"["+E(e,", ")+"]"},ObjectValue:{leave:({fields:e})=>"{"+E(e,", ")+"}"},ObjectField:{leave:({name:e,value:t})=>e+": "+t},Directive:{leave:({name:e,arguments:t})=>"@"+e+I("(",E(t,", "),")")},NamedType:{leave:({name:e})=>e},ListType:{leave:({type:e})=>"["+e+"]"},NonNullType:{leave:({type:e})=>e+"!"},SchemaDefinition:{leave:({description:e,directives:t,operationTypes:n})=>I("",e,`
30
30
  `)+E(["schema",E(t," "),L(n)]," ")},OperationTypeDefinition:{leave:({operation:e,type:t})=>e+": "+t},ScalarTypeDefinition:{leave:({description:e,name:t,directives:n})=>I("",e,`
31
31
  `)+E(["scalar",t,E(n," ")]," ")},ObjectTypeDefinition:{leave:({description:e,name:t,interfaces:n,directives:s,fields:r})=>I("",e,`
32
32
  `)+E(["type",t,I("implements ",E(n," & ")),E(s," "),L(r)]," ")},FieldDefinition:{leave:({description:e,name:t,arguments:n,type:s,directives:r})=>I("",e,`
33
- `)+t+(Pt(n)?I(`(
34
- `,_e(E(n,`
33
+ `)+t+(Ut(n)?I(`(
34
+ `,Ie(E(n,`
35
35
  `)),`
36
36
  )`):I("(",E(n,", "),")"))+": "+s+I(" ",E(r," "))},InputValueDefinition:{leave:({description:e,name:t,type:n,defaultValue:s,directives:r})=>I("",e,`
37
37
  `)+E([t+": "+n,I("= ",s),E(r," ")]," ")},InterfaceTypeDefinition:{leave:({description:e,name:t,interfaces:n,directives:s,fields:r})=>I("",e,`
@@ -40,12 +40,12 @@ spurious results.`)}}return!1};class mn{constructor(t,n="GraphQL request",s={lin
40
40
  `)+E(["enum",t,E(n," "),L(s)]," ")},EnumValueDefinition:{leave:({description:e,name:t,directives:n})=>I("",e,`
41
41
  `)+E([t,E(n," ")]," ")},InputObjectTypeDefinition:{leave:({description:e,name:t,directives:n,fields:s})=>I("",e,`
42
42
  `)+E(["input",t,E(n," "),L(s)]," ")},DirectiveDefinition:{leave:({description:e,name:t,arguments:n,repeatable:s,locations:r})=>I("",e,`
43
- `)+"directive @"+t+(Pt(n)?I(`(
44
- `,_e(E(n,`
43
+ `)+"directive @"+t+(Ut(n)?I(`(
44
+ `,Ie(E(n,`
45
45
  `)),`
46
46
  )`):I("(",E(n,", "),")"))+(s?" repeatable":"")+" on "+E(r," | ")},SchemaExtension:{leave:({directives:e,operationTypes:t})=>E(["extend schema",E(e," "),L(t)]," ")},ScalarTypeExtension:{leave:({name:e,directives:t})=>E(["extend scalar",e,E(t," ")]," ")},ObjectTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:s})=>E(["extend type",e,I("implements ",E(t," & ")),E(n," "),L(s)]," ")},InterfaceTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:s})=>E(["extend interface",e,I("implements ",E(t," & ")),E(n," "),L(s)]," ")},UnionTypeExtension:{leave:({name:e,directives:t,types:n})=>E(["extend union",e,E(t," "),I("= ",E(n," | "))]," ")},EnumTypeExtension:{leave:({name:e,directives:t,values:n})=>E(["extend enum",e,E(t," "),L(n)]," ")},InputObjectTypeExtension:{leave:({name:e,directives:t,fields:n})=>E(["extend input",e,E(t," "),L(n)]," ")}};function E(e,t=""){var n;return(n=e==null?void 0:e.filter(s=>s).join(t))!==null&&n!==void 0?n:""}function L(e){return I(`{
47
- `,_e(E(e,`
47
+ `,Ie(E(e,`
48
48
  `)),`
49
- }`)}function I(e,t,n=""){return t!=null&&t!==""?e+t+n:""}function _e(e){return I(" ",e.replace(/\n/g,`
50
- `))}function Pt(e){var t;return(t=e==null?void 0:e.some(n=>n.includes(`
51
- `)))!==null&&t!==void 0?t:!1}const Ut=e=>{var s,r;let t;const n=e.definitions.filter(i=>i.kind==="OperationDefinition");return n.length===1&&(t=(r=(s=n[0])==null?void 0:s.name)==null?void 0:r.value),t},Ue=e=>{if(typeof e=="string"){let n;try{const s=qr(e);n=Ut(s)}catch{}return{query:e,operationName:n}}const t=Ut(e);return{query:En(e),operationName:t}};class ue extends Error{constructor(t,n){const s=`${ue.extractMessage(t)}: ${JSON.stringify({response:t,request:n})}`;super(s),Object.setPrototypeOf(this,ue.prototype),this.response=t,this.request=n,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,ue)}static extractMessage(t){var n,s;return((s=(n=t.errors)==null?void 0:n[0])==null?void 0:s.message)??`GraphQL Error (Code: ${t.status})`}}var zr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Gr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var We={exports:{}};(function(e,t){var n=typeof self<"u"?self:zr,s=function(){function i(){this.fetch=!1,this.DOMException=n.DOMException}return i.prototype=n,new i}();(function(i){(function(o){var a={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{return!1}}(),formData:"FormData"in i,arrayBuffer:"ArrayBuffer"in i};function c(l){return l&&DataView.prototype.isPrototypeOf(l)}if(a.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],h=ArrayBuffer.isView||function(l){return l&&u.indexOf(Object.prototype.toString.call(l))>-1};function d(l){if(typeof l!="string"&&(l=String(l)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(l))throw new TypeError("Invalid character in header field name");return l.toLowerCase()}function f(l){return typeof l!="string"&&(l=String(l)),l}function m(l){var g={next:function(){var S=l.shift();return{done:S===void 0,value:S}}};return a.iterable&&(g[Symbol.iterator]=function(){return g}),g}function y(l){this.map={},l instanceof y?l.forEach(function(g,S){this.append(S,g)},this):Array.isArray(l)?l.forEach(function(g){this.append(g[0],g[1])},this):l&&Object.getOwnPropertyNames(l).forEach(function(g){this.append(g,l[g])},this)}y.prototype.append=function(l,g){l=d(l),g=f(g);var S=this.map[l];this.map[l]=S?S+", "+g:g},y.prototype.delete=function(l){delete this.map[d(l)]},y.prototype.get=function(l){return l=d(l),this.has(l)?this.map[l]:null},y.prototype.has=function(l){return this.map.hasOwnProperty(d(l))},y.prototype.set=function(l,g){this.map[d(l)]=f(g)},y.prototype.forEach=function(l,g){for(var S in this.map)this.map.hasOwnProperty(S)&&l.call(g,this.map[S],S,this)},y.prototype.keys=function(){var l=[];return this.forEach(function(g,S){l.push(S)}),m(l)},y.prototype.values=function(){var l=[];return this.forEach(function(g){l.push(g)}),m(l)},y.prototype.entries=function(){var l=[];return this.forEach(function(g,S){l.push([S,g])}),m(l)},a.iterable&&(y.prototype[Symbol.iterator]=y.prototype.entries);function v(l){if(l.bodyUsed)return Promise.reject(new TypeError("Already read"));l.bodyUsed=!0}function _(l){return new Promise(function(g,S){l.onload=function(){g(l.result)},l.onerror=function(){S(l.error)}})}function w(l){var g=new FileReader,S=_(g);return g.readAsArrayBuffer(l),S}function q(l){var g=new FileReader,S=_(g);return g.readAsText(l),S}function D(l){for(var g=new Uint8Array(l),S=new Array(g.length),k=0;k<g.length;k++)S[k]=String.fromCharCode(g[k]);return S.join("")}function M(l){if(l.slice)return l.slice(0);var g=new Uint8Array(l.byteLength);return g.set(new Uint8Array(l)),g.buffer}function F(){return this.bodyUsed=!1,this._initBody=function(l){this._bodyInit=l,l?typeof l=="string"?this._bodyText=l:a.blob&&Blob.prototype.isPrototypeOf(l)?this._bodyBlob=l:a.formData&&FormData.prototype.isPrototypeOf(l)?this._bodyFormData=l:a.searchParams&&URLSearchParams.prototype.isPrototypeOf(l)?this._bodyText=l.toString():a.arrayBuffer&&a.blob&&c(l)?(this._bodyArrayBuffer=M(l.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(l)||h(l))?this._bodyArrayBuffer=M(l):this._bodyText=l=Object.prototype.toString.call(l):this._bodyText="",this.headers.get("content-type")||(typeof l=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):a.searchParams&&URLSearchParams.prototype.isPrototypeOf(l)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a.blob&&(this.blob=function(){var l=v(this);if(l)return l;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?v(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(w)}),this.text=function(){var l=v(this);if(l)return l;if(this._bodyBlob)return q(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(D(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},a.formData&&(this.formData=function(){return this.text().then(ye)}),this.json=function(){return this.text().then(JSON.parse)},this}var z=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function G(l){var g=l.toUpperCase();return z.indexOf(g)>-1?g:l}function P(l,g){g=g||{};var S=g.body;if(l instanceof P){if(l.bodyUsed)throw new TypeError("Already read");this.url=l.url,this.credentials=l.credentials,g.headers||(this.headers=new y(l.headers)),this.method=l.method,this.mode=l.mode,this.signal=l.signal,!S&&l._bodyInit!=null&&(S=l._bodyInit,l.bodyUsed=!0)}else this.url=String(l);if(this.credentials=g.credentials||this.credentials||"same-origin",(g.headers||!this.headers)&&(this.headers=new y(g.headers)),this.method=G(g.method||this.method||"GET"),this.mode=g.mode||this.mode||null,this.signal=g.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&S)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(S)}P.prototype.clone=function(){return new P(this,{body:this._bodyInit})};function ye(l){var g=new FormData;return l.trim().split("&").forEach(function(S){if(S){var k=S.split("="),O=k.shift().replace(/\+/g," "),A=k.join("=").replace(/\+/g," ");g.append(decodeURIComponent(O),decodeURIComponent(A))}}),g}function me(l){var g=new y,S=l.replace(/\r?\n[\t ]+/g," ");return S.split(/\r?\n/).forEach(function(k){var O=k.split(":"),A=O.shift().trim();if(A){var ge=O.join(":").trim();g.append(A,ge)}}),g}F.call(P.prototype);function U(l,g){g||(g={}),this.type="default",this.status=g.status===void 0?200:g.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in g?g.statusText:"OK",this.headers=new y(g.headers),this.url=g.url||"",this._initBody(l)}F.call(U.prototype),U.prototype.clone=function(){return new U(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},U.error=function(){var l=new U(null,{status:0,statusText:""});return l.type="error",l};var Sn=[301,302,303,307,308];U.redirect=function(l,g){if(Sn.indexOf(g)===-1)throw new RangeError("Invalid status code");return new U(null,{status:g,headers:{location:l}})},o.DOMException=i.DOMException;try{new o.DOMException}catch{o.DOMException=function(g,S){this.message=g,this.name=S;var k=Error(g);this.stack=k.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function De(l,g){return new Promise(function(S,k){var O=new P(l,g);if(O.signal&&O.signal.aborted)return k(new o.DOMException("Aborted","AbortError"));var A=new XMLHttpRequest;function ge(){A.abort()}A.onload=function(){var oe={status:A.status,statusText:A.statusText,headers:me(A.getAllResponseHeaders()||"")};oe.url="responseURL"in A?A.responseURL:oe.headers.get("X-Request-URL");var Re="response"in A?A.response:A.responseText;S(new U(Re,oe))},A.onerror=function(){k(new TypeError("Network request failed"))},A.ontimeout=function(){k(new TypeError("Network request failed"))},A.onabort=function(){k(new o.DOMException("Aborted","AbortError"))},A.open(O.method,O.url,!0),O.credentials==="include"?A.withCredentials=!0:O.credentials==="omit"&&(A.withCredentials=!1),"responseType"in A&&a.blob&&(A.responseType="blob"),O.headers.forEach(function(oe,Re){A.setRequestHeader(Re,oe)}),O.signal&&(O.signal.addEventListener("abort",ge),A.onreadystatechange=function(){A.readyState===4&&O.signal.removeEventListener("abort",ge)}),A.send(typeof O._bodyInit>"u"?null:O._bodyInit)})}return De.polyfill=!0,i.fetch||(i.fetch=De,i.Headers=y,i.Request=P,i.Response=U),o.Headers=y,o.Request=P,o.Response=U,o.fetch=De,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(s),s.fetch.ponyfill=!0,delete s.fetch.polyfill;var r=s;t=r.fetch,t.default=r.fetch,t.fetch=r.fetch,t.Headers=r.Headers,t.Request=r.Request,t.Response=r.Response,e.exports=t})(We,We.exports);var be=We.exports;const Ie=Gr(be),Jr=_n({__proto__:null,default:Ie},[be]),K=e=>{let t={};return e&&(typeof Headers<"u"&&e instanceof Headers||Jr&&be.Headers&&e instanceof be.Headers?t=Ks(e):Array.isArray(e)?e.forEach(([n,s])=>{n&&s!==void 0&&(t[n]=s)}):t=e),t},Ft=e=>e.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),Yr=e=>{if(!Array.isArray(e.query)){const s=e,r=[`query=${encodeURIComponent(Ft(s.query))}`];return e.variables&&r.push(`variables=${encodeURIComponent(s.jsonSerializer.stringify(s.variables))}`),s.operationName&&r.push(`operationName=${encodeURIComponent(s.operationName)}`),r.join("&")}if(typeof e.variables<"u"&&!Array.isArray(e.variables))throw new Error("Cannot create query with given variable type, array expected");const t=e,n=e.query.reduce((s,r,i)=>(s.push({query:Ft(r),variables:t.variables?t.jsonSerializer.stringify(t.variables[i]):void 0}),s),[]);return`query=${encodeURIComponent(t.jsonSerializer.stringify(n))}`},Qr=e=>async t=>{const{url:n,query:s,variables:r,operationName:i,fetch:o,fetchOptions:a,middleware:c}=t,u={...t.headers};let h="",d;e==="POST"?(d=Xr(s,r,i,a.jsonSerializer),typeof d=="string"&&(u["Content-Type"]="application/json")):h=Yr({query:s,variables:r,operationName:i,jsonSerializer:a.jsonSerializer??lt});const f={method:e,headers:u,body:d,...a};let m=n,y=f;if(c){const v=await Promise.resolve(c({...f,url:n,operationName:i,variables:r})),{url:_,...w}=v;m=_,y=w}return h&&(m=`${m}?${h}`),await o(m,y)};class vn{constructor(t,n={}){this.url=t,this.requestConfig=n,this.rawRequest=async(...s)=>{const[r,i,o]=s,a=er(r,i,o),{headers:c,fetch:u=Ie,method:h="POST",requestMiddleware:d,responseMiddleware:f,...m}=this.requestConfig,{url:y}=this;a.signal!==void 0&&(m.signal=a.signal);const{operationName:v}=Ue(a.query);return Fe({url:y,query:a.query,variables:a.variables,headers:{...K(Be(c)),...K(a.requestHeaders)},operationName:v,fetch:u,method:h,fetchOptions:m,middleware:d}).then(_=>(f&&f(_),_)).catch(_=>{throw f&&f(_),_})}}async request(t,...n){const[s,r]=n,i=Zs(t,s,r),{headers:o,fetch:a=Ie,method:c="POST",requestMiddleware:u,responseMiddleware:h,...d}=this.requestConfig,{url:f}=this;i.signal!==void 0&&(d.signal=i.signal);const{query:m,operationName:y}=Ue(i.document);return Fe({url:f,query:m,variables:i.variables,headers:{...K(Be(o)),...K(i.requestHeaders)},operationName:y,fetch:a,method:c,fetchOptions:d,middleware:u}).then(v=>(h&&h(v),v.data)).catch(v=>{throw h&&h(v),v})}batchRequests(t,n){const s=tr(t,n),{headers:r,...i}=this.requestConfig;s.signal!==void 0&&(i.signal=s.signal);const o=s.documents.map(({document:c})=>Ue(c).query),a=s.documents.map(({variables:c})=>c);return Fe({url:this.url,query:o,variables:a,headers:{...K(Be(r)),...K(s.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??Ie,method:this.requestConfig.method||"POST",fetchOptions:i,middleware:this.requestConfig.requestMiddleware}).then(c=>(this.requestConfig.responseMiddleware&&this.requestConfig.responseMiddleware(c),c.data)).catch(c=>{throw this.requestConfig.responseMiddleware&&this.requestConfig.responseMiddleware(c),c})}setHeaders(t){return this.requestConfig.headers=t,this}setHeader(t,n){const{headers:s}=this.requestConfig;return s?s[t]=n:this.requestConfig.headers={[t]:n},this}setEndpoint(t){return this.url=t,this}}const Fe=async e=>{const{query:t,variables:n,fetchOptions:s}=e,r=Qr(Ws(e.method??"post")),i=Array.isArray(e.query),o=await r(e),a=await Wr(o,s.jsonSerializer??lt),c=Array.isArray(a)?!a.some(({data:h})=>!h):!!a.data,u=Array.isArray(a)||!a.errors||Array.isArray(a.errors)&&!a.errors.length||s.errorPolicy==="all"||s.errorPolicy==="ignore";if(o.ok&&u&&c){const{errors:h,...d}=(Array.isArray(a),a),f=s.errorPolicy==="ignore"?d:a;return{...i?{data:f}:f,headers:o.headers,status:o.status}}else{const h=typeof a=="string"?{error:a}:a;throw new ue({...h,status:o.status,headers:o.headers},{query:t,variables:n})}};async function pe(e,t,...n){const s=nr(e,t,...n);return new vn(s.url).request({...s})}const Xr=(e,t,n,s)=>{const r=s??lt;if(!Array.isArray(e))return r.stringify({query:e,variables:t,operationName:n});if(typeof t<"u"&&!Array.isArray(t))throw new Error("Cannot create request body with given variable type, array expected");const i=e.reduce((o,a,c)=>(o.push({query:a,variables:t?t[c]:void 0}),o),[]);return r.stringify(i)},Wr=async(e,t)=>{let n;return e.headers.forEach((s,r)=>{r.toLowerCase()==="content-type"&&(n=s)}),n&&(n.toLowerCase().startsWith("application/json")||n.toLowerCase().startsWith("application/graphql+json")||n.toLowerCase().startsWith("application/graphql-response+json"))?t.parse(await e.text()):e.text()},Be=e=>typeof e=="function"?e():e,Kr=V(async({input:e})=>{var t,n;if(!e.endpoint||e.endpoint==="")throw new Error("No endpoint provided.");if(!e.document)throw new Error("No request document provided.");if(!e.requestHeaders)throw new Error("No request headers provided.");try{const s=await pe(e.endpoint,e.document,{},e.requestHeaders);if(!((n=(t=s.placeOrder)==null?void 0:t.checkoutSuccess)!=null&&n.id))throw console.log("Could not place order."),new Error("Could not place order.");return{type:"PLACE_ORDER_SUCCESS",successId:s.placeOrder.checkoutSuccess.id}}catch(s){throw console.log("Request to place order failed."),console.log(s),new Error("Request to place order failed.")}}),Zr=V(async({input:e})=>{var t;if(!e.endpoint||e.endpoint==="")throw new Error("No endpoint provided.");if(!e.data)throw new Error("No data provided.");if(!e.document)throw new Error("No request document provided.");if(!e.requestHeaders)throw new Error("No request headers provided.");try{const n=await pe(e.endpoint,e.document,{step:e.data.step,data:{[e.data.step]:e.data.data}},e.requestHeaders);if(!((t=n.checkoutStep)!=null&&t.quote))throw console.log("Could not add items to quote."),new Error("Could not add items to quote.");return{type:"SUBMIT_STEP_DATA_SUCCESS",quote:n.checkoutStep.quote}}catch{throw console.log("Request to add submit step data failed."),new Error("Request to add submit step data failed.")}}),ei=({context:e})=>Object.keys(e.quote).length>0,Ke=fe({types:{context:{},events:{},input:{}},actions:{changeStep:x(Gs),nextStep:x(Js),resetCheckout:x(Ys),updateQuote:x(Qs),updateSuccessId:x(Xs)},actors:{placeOrder:Kr,submitStepData:Zr},guards:{quoteExists:ei}}).createMachine({id:"checkout",initial:"uninitialized",context:({input:e})=>{var t,n,s,r,i,o,a,c,u,h,d,f,m,y,v,_,w;return{currentStep:((t=e==null?void 0:e.initialContext)==null?void 0:t.currentStep)??"",errors:[],isLoggedIn:((n=e==null?void 0:e.initialContext)==null?void 0:n.isLoggedIn)??!1,steps:((s=e==null?void 0:e.initialContext)==null?void 0:s.steps)??[],successId:"",quote:((r=e==null?void 0:e.initialContext)==null?void 0:r.quote)??{},endpoints:{client:"",server:"",...(i=e==null?void 0:e.initialContext)==null?void 0:i.endpoints},graphql:{placeOrder:{document:((c=(a=(o=e==null?void 0:e.initialContext)==null?void 0:o.graphql)==null?void 0:a.placeOrder)==null?void 0:c.document)??"",requestHeaders:((d=(h=(u=e==null?void 0:e.initialContext)==null?void 0:u.graphql)==null?void 0:h.placeOrder)==null?void 0:d.requestHeaders)??void 0},submitStepData:{document:((y=(m=(f=e==null?void 0:e.initialContext)==null?void 0:f.graphql)==null?void 0:m.submitStepData)==null?void 0:y.document)??"",requestHeaders:((w=(_=(v=e==null?void 0:e.initialContext)==null?void 0:v.graphql)==null?void 0:_.submitStepData)==null?void 0:w.requestHeaders)??void 0}}}},states:{uninitialized:{always:{guard:"quoteExists",target:"initializing"}},initializing:{always:[{target:"showStep"}]},showStep:{on:{SUBMIT_STEP_DATA:"submittingStepData",CHANGE_STEP:"changingStep",PLACE_ORDER:"placingOrder"}},submittingStepData:{invoke:{input:({context:e,event:t})=>(Ge(t,"SUBMIT_STEP_DATA"),{endpoint:e.endpoints.client,data:t.data,document:e.graphql.submitStepData.document,requestHeaders:e.graphql.submitStepData.requestHeaders}),src:"submitStepData",onDone:[{actions:["updateQuote","nextStep"],target:"showStep"}],onError:{target:"showStep"}}},changingStep:{always:{actions:["changeStep"],target:"showStep"}},placingOrder:{invoke:{input:({context:e,event:t})=>(Ge(t,"PLACE_ORDER"),{endpoint:e.endpoints.client,document:e.graphql.placeOrder.document,requestHeaders:e.graphql.placeOrder.requestHeaders}),src:"placeOrder",onDone:[{actions:["updateSuccessId"],target:"success"}],onError:{target:"showStep"}}},success:{type:"final"}}}),pt=N.createContext({}),ti=()=>{const e=N.useContext(pt);if(!e||!e.getSnapshot)throw new Error("checkoutActor is not properly initialized");const[t,n]=N.useState(e.getSnapshot());return N.useEffect(()=>{if(!e||!e.getSnapshot){console.error("checkoutActor is not properly initialized");return}const s=e.subscribe(r=>{n(r)});return()=>{s.unsubscribe()}},[e]),{checkoutActor:e,currentStep:t.context.currentStep}},ni=async(e={inspect:void 0,currentStep:"",steps:[],quote:{id:"",locale:""},endpoints:{client:"",server:""},graphql:{}})=>typeof window<"u"?(console.warn("App.getInitialProps::getAuth should not be run on the frontend. You are probably missing getServerSideProps in your page."),$(Ke,{inspect:e.inspect,input:{initialContext:{endpoints:e.endpoints}}}).start()):$(Ke,{input:{initialContext:{currentStep:e.currentStep,steps:e.steps,endpoints:e.endpoints,graphql:e.graphql,quote:{...e.quote}}},inspect:e.inspect}).start();function si({actor:e,children:t}){return Ce.jsx(pt.Provider,{value:e,children:t})}let ri=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");const Tn=fe({actors:{tick:Ss(({sendBack:e,input:t})=>{const n=setInterval(()=>{e({type:"TICK"})},t.interval);return()=>{clearInterval(n)}})},types:{context:{},events:{},input:{}}}).createMachine({id:"timer",initial:"running",context:({input:e})=>({elapsed:0,duration:e.initialContext.duration??3e3,interval:100,intervalId:null}),states:{paused:{on:{RESUME_TIMER:{target:"running",guard:({context:e})=>e.elapsed<e.duration}}},running:{invoke:{input:({context:e})=>({interval:e.interval}),src:"tick"},always:[{target:"completed",guard:({context:e})=>e.elapsed>=e.duration}],on:{TICK:{actions:x(({context:e,event:t})=>t.type!=="TICK"?e:{elapsed:e.elapsed+e.interval})},PAUSE_TIMER:{target:"paused"}}},completed:{type:"final"}}}),ii=fe({actors:{timer:Tn},types:{context:{},events:{},input:{}},actions:{addItem:x(({context:e,event:t})=>{if(t.type!=="ADD_ITEM")return e;const n=`notification-${ri()}`,s=t.duration??e.duration,r=N.cloneElement(t.item,{duration:s,id:n,key:t.item.key??n,...t.item.props}),i={duration:s,id:n,element:r},o=e.items;return e.order==="desc"?o.push(i):o.unshift(i),{items:o,activeItem:n}}),removeItem:x(({context:e,event:t})=>{if(t.type!=="REMOVE_ITEM"&&t.type!=="xstate.done.actor.timer")return e;const n=e.items;return e.order==="desc"?(n.pop(),{items:n,activeItem:n.length>0?n[n.length-1].id:null}):(n.shift(),{items:n,activeItem:n.length>0?n[0].id:null})})},delays:{ITEM_TIMEOUT:({context:e})=>e.items[e.items.length-1].duration??e.duration},guards:{itemHasTimeout:({context:e})=>e.items[e.items.length-1].duration>0||e.duration>0}}).createMachine({id:"toast",context:({input:e})=>{var t,n,s,r;return{items:((t=e==null?void 0:e.initialContext)==null?void 0:t.items)??[],order:((n=e==null?void 0:e.initialContext)==null?void 0:n.order)??"desc",duration:((s=e==null?void 0:e.initialContext)==null?void 0:s.duration)??0,activeItem:((r=e==null?void 0:e.initialContext)==null?void 0:r.activeItem)??null}},initial:"idle",states:{idle:{on:{ADD_ITEM:{target:"adding"}}},active:{invoke:{id:"timer",src:"timer",input:({context:e})=>({initialContext:{duration:e.items[e.items.length-1].duration??e.duration}}),onDone:{target:"removing",guard:"itemHasTimeout"}},on:{ADD_ITEM:{target:"adding"},REMOVE_ITEM:{target:"removing"},SET_IDLE:{target:"idle"},RESUME_TIMER:{actions:kt("timer",{type:"RESUME_TIMER"})},PAUSE_TIMER:{actions:kt("timer",{type:"PAUSE_TIMER"})}}},adding:{entry:["addItem"],on:{SET_IDLE:{target:"idle"},SET_ACTIVE:{target:"active"}}},removing:{entry:"removeItem",on:{SET_IDLE:{target:"idle"},SET_ACTIVE:{target:"active"}}}}}),yt=N.createContext({}),oi=()=>{const e=N.useContext(yt);if(!e||!e.getSnapshot)throw new Error("toastActor is not properly initialized");const[t,n]=N.useState(()=>e.getSnapshot());return N.useEffect(()=>{if(!e||!e.getSnapshot){console.error("toastActor is not properly initialized");return}(()=>{n(e.getSnapshot())})();const r=e.subscribe(i=>{n(i)});return()=>{r.unsubscribe()}},[e]),{toastActor:e}};function ai({children:e,actor:t}){return Ce.jsx(yt.Provider,{value:t,children:e})}function ci({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="ADD_ITEMS_SUCCESS"?e:{quote:{...e.quote,...n.output.quote},itemsAdded:n.output.itemsAdded}}function ui({event:e}){if(!e.type.includes("xstate.done.actor"))return{type:"EMIT_ADD_ITEMS",itemsAdded:[]};const t=e;return t.output.type!=="ADD_ITEMS_SUCCESS"?{type:"EMIT_ADD_ITEMS",itemsAdded:[]}:{type:"EMIT_ADD_ITEMS",itemsAdded:t.output.itemsAdded}}function di({event:e}){if(!e.type.includes("xstate.done.actor"))return{type:"EMIT_REMOVE_ITEMS",itemsRemoved:[]};const t=e;return t.output.type!=="REMOVE_ITEMS_SUCCESS"?{type:"EMIT_REMOVE_ITEMS",itemsRemoved:[]}:{type:"EMIT_REMOVE_ITEMS",itemsRemoved:t.output.itemsRemoved}}function li({event:e}){if(!e.type.includes("xstate.done.actor"))return{type:"EMIT_UPDATE_ITEMS",itemsUpdated:[]};const t=e;return t.output.type!=="UPDATE_ITEMS_SUCCESS"?{type:"EMIT_UPDATE_ITEMS",itemsUpdated:[]}:{type:"EMIT_UPDATE_ITEMS",itemsUpdated:t.output.itemsUpdated}}function hi({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="REMOVE_ITEMS_SUCCESS"?e:{quote:{...e.quote,...n.output.quote},itemsRemoved:n.output.itemsRemoved}}function fi({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="REFRESH_SUCCESS"?e:{quote:{...e.quote,...n.output.quote}}}function pi({context:e,event:t}){const n=t;if(n.type!=="RESET")return e;const{locale:s}=n.data;return{quote:{id:"",locale:s,baseCurrency:"USD",currencyConversionRate:1,dateCreated:null,dateLastUpdated:null,currency:"USD",items:[],promotions:[],shippingAddresses:{available:[],applied:[]},paymentMethods:{available:[],applied:[]},totals:{discount:0,taxAmount:0,shippingAmount:0,shippingTaxAmount:0,subtotal:0,grandTotal:0},appliedPriceRules:[],appliedPromotions:[],shippingMethods:[],storeCredit:[],rewards:[],giftCards:[]}}}function yi({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="UPDATE_ITEMS_SUCCESS"?e:{quote:{...e.quote,...n.output.quote},itemsUpdated:n.output.itemsUpdated}}const mi=V(async({input:e})=>{var t;if(!e.endpoint||e.endpoint==="")throw new Error("No endpoint provided.");if(e.items.length<1)throw new Error("No items provided.");if(!e.document)throw new Error("No request document provided.");if(!e.requestHeaders)throw new Error("No request headers provided.");try{const n=await pe(e.endpoint,e.document,{items:e.items},e.requestHeaders);if(!((t=n.quoteAddItem)!=null&&t.quote))throw new Error("Could not add items to quote.");return{type:"ADD_ITEMS_SUCCESS",quote:n.quoteAddItem.quote,itemsAdded:n.quoteAddItem.itemsAdded}}catch{throw new Error("Request to add item(s) failed.")}}),gi=V(async({input:e})=>{var t;if(!e.endpoint||e.endpoint==="")throw new Error("No endpoint provided.");if(e.items.length<1)throw new Error("No items provided.");try{const n=await pe(e.endpoint,"");if(!((t=n.quoteRemoveItem)!=null&&t.quote))throw new Error("Could not remove items from quote.");return{type:"REMOVE_ITEMS_SUCCESS",quote:n.quoteRemoveItem.quote,itemsRemoved:n.quoteRemoveItem.itemsRemoved}}catch{throw new Error("Request to remove item(s) failed.")}}),je=typeof window>"u",Ei=V(async({input:e})=>{var n,s,r,i;if(!e.endpoint)throw console.log("no endpoint"),new Error("No endpoint provided.");if(!e.endpointSsr)throw console.log("no endpoint ssr"),new Error("No SSR endpoint provided.");if(!e.locale)throw console.log("no locale"),new Error("No locale provided.");if(!e.document)throw console.log("no request document"),new Error("No request document provided.");if(!e.requestHeaders)throw console.log("no headers"),new Error("No request headers provided.");const t=new vn(je?e.endpointSsr:e.endpoint,je?{fetch,method:"POST"}:{credentials:"include",method:"POST",mode:"cors"});try{const{data:o,headers:a,status:c,errors:u,extensions:h}=await t.rawRequest(En(e.document),{},je?{...e.requestHeaders,Cookie:`quote_${e.locale}=${e.quoteId??""}`}:e.requestHeaders),d=o;if(!((n=d.refreshQuote)!=null&&n.quote))throw console.log("userError: ",(s=d.refreshQuote)==null?void 0:s.userErrors[0].code,(r=d.refreshQuote)==null?void 0:r.userErrors[0].field,(i=d.refreshQuote)==null?void 0:i.userErrors[0].message),new Error("Could not add items to quote.");return{type:"REFRESH_SUCCESS",quote:d.refreshQuote.quote}}catch(o){throw console.log("refresh error",o),new Error("Request to add item(s) failed.")}}),vi=V(async({input:e})=>{var t;if(!e.endpoint||e.endpoint==="")throw new Error("No endpoint provided.");if(e.items.length<1)throw new Error("No items provided.");if(!e.document)throw new Error("No request document provided.");if(!e.requestHeaders)throw new Error("No request headers provided.");try{const n=await pe(e.endpoint,e.document,{items:e.items},e.requestHeaders);if(!((t=n.quoteUpdateItem)!=null&&t.quote))throw new Error("Could not add items to quote.");return{type:"UPDATE_ITEMS_SUCCESS",quote:n.quoteUpdateItem.quote,itemsUpdated:n.quoteUpdateItem.itemsUpdated}}catch{throw new Error("Request to add item(s) failed.")}}),Ti=({context:e})=>typeof window>"u"&&e.quote.id!==""||typeof window<"u",Si=({context:e})=>!!e.quote.items&&e.quote.items.length>0,Ze=fe({types:{context:{},emitted:{},events:{},input:{}},actions:{addItems:x(ci),notifyAddItems:Le(ui),notifyRemoveItems:Le(di),notifyUpdateItems:Le(li),removeItems:x(hi),refresh:x(fi),reset:x(pi),updateItems:x(yi)},actors:{addItems:mi,removeItems:gi,refresh:Ei,updateItems:vi},guards:{canRefresh:Ti,hasItems:Si}}).createMachine({id:"quote",initial:"initializing",context:({input:e})=>{var t,n,s,r,i,o,a,c,u,h,d,f,m,y,v,_,w,q,D,M,F,z,G,P,ye,me;return{quote:{id:"",locale:"",baseCurrency:"USD",currencyConversionRate:1,dateCreated:null,dateLastUpdated:null,currency:"USD",items:[],promotions:[],shippingAddresses:{available:[],applied:[]},paymentMethods:{available:[],applied:[]},totals:{discount:0,taxAmount:0,shippingAmount:0,shippingTaxAmount:0,subtotal:0,grandTotal:0},appliedPriceRules:[],appliedPromotions:[],shippingMethods:[],storeCredit:[],rewards:[],giftCards:[],...(t=e==null?void 0:e.initialContext)==null?void 0:t.quote},errors:[],endpoints:{client:"",server:"",...(n=e==null?void 0:e.initialContext)==null?void 0:n.endpoints},graphql:{refresh:{document:((i=(r=(s=e==null?void 0:e.initialContext)==null?void 0:s.graphql)==null?void 0:r.refresh)==null?void 0:i.document)??"",requestHeaders:((c=(a=(o=e==null?void 0:e.initialContext)==null?void 0:o.graphql)==null?void 0:a.refresh)==null?void 0:c.requestHeaders)??void 0},addItems:{document:((d=(h=(u=e==null?void 0:e.initialContext)==null?void 0:u.graphql)==null?void 0:h.addItems)==null?void 0:d.document)??"",requestHeaders:((y=(m=(f=e==null?void 0:e.initialContext)==null?void 0:f.graphql)==null?void 0:m.addItems)==null?void 0:y.requestHeaders)??void 0},removeItems:{document:((w=(_=(v=e==null?void 0:e.initialContext)==null?void 0:v.graphql)==null?void 0:_.removeItems)==null?void 0:w.document)??"",requestHeaders:((M=(D=(q=e==null?void 0:e.initialContext)==null?void 0:q.graphql)==null?void 0:D.removeItems)==null?void 0:M.requestHeaders)??void 0},updateItems:{document:((G=(z=(F=e==null?void 0:e.initialContext)==null?void 0:F.graphql)==null?void 0:z.updateItems)==null?void 0:G.document)??"",requestHeaders:((me=(ye=(P=e==null?void 0:e.initialContext)==null?void 0:P.graphql)==null?void 0:ye.updateItems)==null?void 0:me.requestHeaders)??void 0}}}},states:{uninitialized:{on:{REFRESH:"refreshing"}},empty:{on:{ADD_ITEMS:"addingItems",UPDATE_ITEMS:"updatingItems"}},active:{on:{ADD_ITEMS:"addingItems",REMOVE_ITEMS:"removingItems",REFRESH:"refreshing",UPDATE_ITEMS:"updatingItems",RESET:"resetting"}},initializing:{always:[{target:"refreshing",guard:"canRefresh"},{target:"uninitialized"}]},refreshing:{invoke:{input:({context:e})=>({endpoint:e.endpoints.client,endpointSsr:e.endpoints.server,quoteId:e.quote.id,locale:e.quote.locale,document:e.graphql.refresh.document,requestHeaders:e.graphql.refresh.requestHeaders}),src:"refresh",onDone:[{actions:["refresh"],target:"checkingItems"}],onError:{target:"empty"}}},checkingItems:{always:[{guard:"hasItems",target:"active"},{target:"empty"}]},addingItems:{invoke:{input:({context:e,event:t})=>{var n,s;return{endpoint:e.endpoints.client,items:t.type==="ADD_ITEMS"?t.items:[],document:(n=e.graphql.addItems)==null?void 0:n.document,requestHeaders:(s=e.graphql.addItems)==null?void 0:s.requestHeaders}},src:"addItems",onDone:[{actions:["addItems","notifyAddItems"],target:"active"}],onError:[{guard:"hasItems",target:"active"},{target:"empty"}]}},removingItems:{invoke:{input:({context:e,event:t})=>{var n,s;return{endpoint:e.endpoints.client,items:t.type==="REMOVE_ITEMS"?t.items:[],document:(n=e.graphql.removeItems)==null?void 0:n.document,requestHeaders:(s=e.graphql.removeItems)==null?void 0:s.requestHeaders}},src:"removeItems",onDone:[{actions:["removeItems","notifyRemoveItems"],target:"checkingItems"}],onError:[{guard:"hasItems",target:"active"},{target:"empty"}]}},updatingItems:{invoke:{input:({context:e,event:t})=>{var n,s;return{endpoint:e.endpoints.client,items:t.type==="UPDATE_ITEMS"?t.items:[],document:(n=e.graphql.updateItems)==null?void 0:n.document,requestHeaders:(s=e.graphql.updateItems)==null?void 0:s.requestHeaders}},src:"updateItems",onDone:[{actions:["updateItems","notifyUpdateItems"],target:"checkingItems"}],onError:[{guard:"hasItems",target:"active"},{target:"empty"}]}},resetting:{always:[{actions:["reset"],target:"uninitialized"}]}}}),mt=N.createContext({}),_i=()=>{var c;const e=N.useContext(mt);if(!e||!e.getSnapshot)throw new Error("quoteActor is not properly initialized");const[t,n]=N.useState(()=>e.getSnapshot());N.useEffect(()=>{if(!e||!e.getSnapshot){console.error("quoteActor is not properly initialized");return}(()=>{n(e.getSnapshot())})();const h=e.subscribe(d=>{n(d)});return()=>{h.unsubscribe()}},[e]);const s=t.context.quote.items??[],r=((c=t.context.quote.items)==null?void 0:c.length)??0,i=t.matches("addingItems"),o=t.matches("removingItems"),a=t.matches("addingItems")||t.matches("removingItems");return{quoteActor:e,items:s,itemsCount:r,isAddingItems:i,isRemovingItems:o,isUpdatingItems:a}},Ii=async(e={inspect:void 0,quote:{id:"",locale:""},endpoints:{client:"",server:""},graphql:{}})=>typeof window<"u"?(console.warn("App.getInitialProps::getAuth should not be run on the frontend. You are probably missing getServerSideProps in your page."),$(Ze,{inspect:e.inspect,input:{initialContext:{endpoints:e.endpoints}}}).start()):$(Ze,{input:{initialContext:{endpoints:e.endpoints,graphql:e.graphql,quote:{id:e.quote.id??"",locale:e.quote.locale??""}}},inspect:e.inspect}).start();function Ai({actor:e,children:t}){return Ce.jsx(mt.Provider,{value:e,children:t})}exports.AuthContext=dt;exports.AuthProvider=zs;exports.CheckoutContext=pt;exports.CheckoutProvider=si;exports.QuoteContext=mt;exports.QuoteProvider=Ai;exports.ToastContext=yt;exports.ToastProvider=ai;exports.authMachine=an;exports.checkoutMachine=Ke;exports.getAuth=Hs;exports.getCheckout=ni;exports.getQuote=Ii;exports.quoteMachine=Ze;exports.timerMachine=Tn;exports.toastMachine=ii;exports.useAuth=Vs;exports.useCheckout=ti;exports.useQuote=_i;exports.useToast=oi;
49
+ }`)}function I(e,t,n=""){return t!=null&&t!==""?e+t+n:""}function Ie(e){return I(" ",e.replace(/\n/g,`
50
+ `))}function Ut(e){var t;return(t=e==null?void 0:e.some(n=>n.includes(`
51
+ `)))!==null&&t!==void 0?t:!1}const Pt=e=>{var s,r;let t;const n=e.definitions.filter(i=>i.kind==="OperationDefinition");return n.length===1&&(t=(r=(s=n[0])==null?void 0:s.name)==null?void 0:r.value),t},Pe=e=>{if(typeof e=="string"){let n;try{const s=Mr(e);n=Pt(s)}catch{}return{query:e,operationName:n}}const t=Pt(e);return{query:En(e),operationName:t}};class ue extends Error{constructor(t,n){const s=`${ue.extractMessage(t)}: ${JSON.stringify({response:t,request:n})}`;super(s),Object.setPrototypeOf(this,ue.prototype),this.response=t,this.request=n,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,ue)}static extractMessage(t){var n,s;return((s=(n=t.errors)==null?void 0:n[0])==null?void 0:s.message)??`GraphQL Error (Code: ${t.status})`}}var Gr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Jr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var We={exports:{}};(function(e,t){var n=typeof self<"u"?self:Gr,s=function(){function i(){this.fetch=!1,this.DOMException=n.DOMException}return i.prototype=n,new i}();(function(i){(function(o){var a={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{return!1}}(),formData:"FormData"in i,arrayBuffer:"ArrayBuffer"in i};function c(d){return d&&DataView.prototype.isPrototypeOf(d)}if(a.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],f=ArrayBuffer.isView||function(d){return d&&u.indexOf(Object.prototype.toString.call(d))>-1};function l(d){if(typeof d!="string"&&(d=String(d)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(d))throw new TypeError("Invalid character in header field name");return d.toLowerCase()}function h(d){return typeof d!="string"&&(d=String(d)),d}function m(d){var g={next:function(){var S=d.shift();return{done:S===void 0,value:S}}};return a.iterable&&(g[Symbol.iterator]=function(){return g}),g}function y(d){this.map={},d instanceof y?d.forEach(function(g,S){this.append(S,g)},this):Array.isArray(d)?d.forEach(function(g){this.append(g[0],g[1])},this):d&&Object.getOwnPropertyNames(d).forEach(function(g){this.append(g,d[g])},this)}y.prototype.append=function(d,g){d=l(d),g=h(g);var S=this.map[d];this.map[d]=S?S+", "+g:g},y.prototype.delete=function(d){delete this.map[l(d)]},y.prototype.get=function(d){return d=l(d),this.has(d)?this.map[d]:null},y.prototype.has=function(d){return this.map.hasOwnProperty(l(d))},y.prototype.set=function(d,g){this.map[l(d)]=h(g)},y.prototype.forEach=function(d,g){for(var S in this.map)this.map.hasOwnProperty(S)&&d.call(g,this.map[S],S,this)},y.prototype.keys=function(){var d=[];return this.forEach(function(g,S){d.push(S)}),m(d)},y.prototype.values=function(){var d=[];return this.forEach(function(g){d.push(g)}),m(d)},y.prototype.entries=function(){var d=[];return this.forEach(function(g,S){d.push([S,g])}),m(d)},a.iterable&&(y.prototype[Symbol.iterator]=y.prototype.entries);function T(d){if(d.bodyUsed)return Promise.reject(new TypeError("Already read"));d.bodyUsed=!0}function _(d){return new Promise(function(g,S){d.onload=function(){g(d.result)},d.onerror=function(){S(d.error)}})}function w(d){var g=new FileReader,S=_(g);return g.readAsArrayBuffer(d),S}function q(d){var g=new FileReader,S=_(g);return g.readAsText(d),S}function D(d){for(var g=new Uint8Array(d),S=new Array(g.length),O=0;O<g.length;O++)S[O]=String.fromCharCode(g[O]);return S.join("")}function M(d){if(d.slice)return d.slice(0);var g=new Uint8Array(d.byteLength);return g.set(new Uint8Array(d)),g.buffer}function F(){return this.bodyUsed=!1,this._initBody=function(d){this._bodyInit=d,d?typeof d=="string"?this._bodyText=d:a.blob&&Blob.prototype.isPrototypeOf(d)?this._bodyBlob=d:a.formData&&FormData.prototype.isPrototypeOf(d)?this._bodyFormData=d:a.searchParams&&URLSearchParams.prototype.isPrototypeOf(d)?this._bodyText=d.toString():a.arrayBuffer&&a.blob&&c(d)?(this._bodyArrayBuffer=M(d.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(d)||f(d))?this._bodyArrayBuffer=M(d):this._bodyText=d=Object.prototype.toString.call(d):this._bodyText="",this.headers.get("content-type")||(typeof d=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):a.searchParams&&URLSearchParams.prototype.isPrototypeOf(d)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a.blob&&(this.blob=function(){var d=T(this);if(d)return d;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?T(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(w)}),this.text=function(){var d=T(this);if(d)return d;if(this._bodyBlob)return q(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(D(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},a.formData&&(this.formData=function(){return this.text().then(ye)}),this.json=function(){return this.text().then(JSON.parse)},this}var z=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function G(d){var g=d.toUpperCase();return z.indexOf(g)>-1?g:d}function U(d,g){g=g||{};var S=g.body;if(d instanceof U){if(d.bodyUsed)throw new TypeError("Already read");this.url=d.url,this.credentials=d.credentials,g.headers||(this.headers=new y(d.headers)),this.method=d.method,this.mode=d.mode,this.signal=d.signal,!S&&d._bodyInit!=null&&(S=d._bodyInit,d.bodyUsed=!0)}else this.url=String(d);if(this.credentials=g.credentials||this.credentials||"same-origin",(g.headers||!this.headers)&&(this.headers=new y(g.headers)),this.method=G(g.method||this.method||"GET"),this.mode=g.mode||this.mode||null,this.signal=g.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&S)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(S)}U.prototype.clone=function(){return new U(this,{body:this._bodyInit})};function ye(d){var g=new FormData;return d.trim().split("&").forEach(function(S){if(S){var O=S.split("="),k=O.shift().replace(/\+/g," "),A=O.join("=").replace(/\+/g," ");g.append(decodeURIComponent(k),decodeURIComponent(A))}}),g}function me(d){var g=new y,S=d.replace(/\r?\n[\t ]+/g," ");return S.split(/\r?\n/).forEach(function(O){var k=O.split(":"),A=k.shift().trim();if(A){var ge=k.join(":").trim();g.append(A,ge)}}),g}F.call(U.prototype);function P(d,g){g||(g={}),this.type="default",this.status=g.status===void 0?200:g.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in g?g.statusText:"OK",this.headers=new y(g.headers),this.url=g.url||"",this._initBody(d)}F.call(P.prototype),P.prototype.clone=function(){return new P(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},P.error=function(){var d=new P(null,{status:0,statusText:""});return d.type="error",d};var Sn=[301,302,303,307,308];P.redirect=function(d,g){if(Sn.indexOf(g)===-1)throw new RangeError("Invalid status code");return new P(null,{status:g,headers:{location:d}})},o.DOMException=i.DOMException;try{new o.DOMException}catch{o.DOMException=function(g,S){this.message=g,this.name=S;var O=Error(g);this.stack=O.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function Re(d,g){return new Promise(function(S,O){var k=new U(d,g);if(k.signal&&k.signal.aborted)return O(new o.DOMException("Aborted","AbortError"));var A=new XMLHttpRequest;function ge(){A.abort()}A.onload=function(){var oe={status:A.status,statusText:A.statusText,headers:me(A.getAllResponseHeaders()||"")};oe.url="responseURL"in A?A.responseURL:oe.headers.get("X-Request-URL");var qe="response"in A?A.response:A.responseText;S(new P(qe,oe))},A.onerror=function(){O(new TypeError("Network request failed"))},A.ontimeout=function(){O(new TypeError("Network request failed"))},A.onabort=function(){O(new o.DOMException("Aborted","AbortError"))},A.open(k.method,k.url,!0),k.credentials==="include"?A.withCredentials=!0:k.credentials==="omit"&&(A.withCredentials=!1),"responseType"in A&&a.blob&&(A.responseType="blob"),k.headers.forEach(function(oe,qe){A.setRequestHeader(qe,oe)}),k.signal&&(k.signal.addEventListener("abort",ge),A.onreadystatechange=function(){A.readyState===4&&k.signal.removeEventListener("abort",ge)}),A.send(typeof k._bodyInit>"u"?null:k._bodyInit)})}return Re.polyfill=!0,i.fetch||(i.fetch=Re,i.Headers=y,i.Request=U,i.Response=P),o.Headers=y,o.Request=U,o.Response=P,o.fetch=Re,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(s),s.fetch.ponyfill=!0,delete s.fetch.polyfill;var r=s;t=r.fetch,t.default=r.fetch,t.fetch=r.fetch,t.Headers=r.Headers,t.Request=r.Request,t.Response=r.Response,e.exports=t})(We,We.exports);var Ce=We.exports;const Ae=Jr(Ce),Yr=_n({__proto__:null,default:Ae},[Ce]),K=e=>{let t={};return e&&(typeof Headers<"u"&&e instanceof Headers||Yr&&Ce.Headers&&e instanceof Ce.Headers?t=Zs(e):Array.isArray(e)?e.forEach(([n,s])=>{n&&s!==void 0&&(t[n]=s)}):t=e),t},Ft=e=>e.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),Qr=e=>{if(!Array.isArray(e.query)){const s=e,r=[`query=${encodeURIComponent(Ft(s.query))}`];return e.variables&&r.push(`variables=${encodeURIComponent(s.jsonSerializer.stringify(s.variables))}`),s.operationName&&r.push(`operationName=${encodeURIComponent(s.operationName)}`),r.join("&")}if(typeof e.variables<"u"&&!Array.isArray(e.variables))throw new Error("Cannot create query with given variable type, array expected");const t=e,n=e.query.reduce((s,r,i)=>(s.push({query:Ft(r),variables:t.variables?t.jsonSerializer.stringify(t.variables[i]):void 0}),s),[]);return`query=${encodeURIComponent(t.jsonSerializer.stringify(n))}`},Xr=e=>async t=>{const{url:n,query:s,variables:r,operationName:i,fetch:o,fetchOptions:a,middleware:c}=t,u={...t.headers};let f="",l;e==="POST"?(l=Wr(s,r,i,a.jsonSerializer),typeof l=="string"&&(u["Content-Type"]="application/json")):f=Qr({query:s,variables:r,operationName:i,jsonSerializer:a.jsonSerializer??lt});const h={method:e,headers:u,body:l,...a};let m=n,y=h;if(c){const T=await Promise.resolve(c({...h,url:n,operationName:i,variables:r})),{url:_,...w}=T;m=_,y=w}return f&&(m=`${m}?${f}`),await o(m,y)};class Tn{constructor(t,n={}){this.url=t,this.requestConfig=n,this.rawRequest=async(...s)=>{const[r,i,o]=s,a=tr(r,i,o),{headers:c,fetch:u=Ae,method:f="POST",requestMiddleware:l,responseMiddleware:h,...m}=this.requestConfig,{url:y}=this;a.signal!==void 0&&(m.signal=a.signal);const{operationName:T}=Pe(a.query);return Fe({url:y,query:a.query,variables:a.variables,headers:{...K(Be(c)),...K(a.requestHeaders)},operationName:T,fetch:u,method:f,fetchOptions:m,middleware:l}).then(_=>(h&&h(_),_)).catch(_=>{throw h&&h(_),_})}}async request(t,...n){const[s,r]=n,i=er(t,s,r),{headers:o,fetch:a=Ae,method:c="POST",requestMiddleware:u,responseMiddleware:f,...l}=this.requestConfig,{url:h}=this;i.signal!==void 0&&(l.signal=i.signal);const{query:m,operationName:y}=Pe(i.document);return Fe({url:h,query:m,variables:i.variables,headers:{...K(Be(o)),...K(i.requestHeaders)},operationName:y,fetch:a,method:c,fetchOptions:l,middleware:u}).then(T=>(f&&f(T),T.data)).catch(T=>{throw f&&f(T),T})}batchRequests(t,n){const s=nr(t,n),{headers:r,...i}=this.requestConfig;s.signal!==void 0&&(i.signal=s.signal);const o=s.documents.map(({document:c})=>Pe(c).query),a=s.documents.map(({variables:c})=>c);return Fe({url:this.url,query:o,variables:a,headers:{...K(Be(r)),...K(s.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??Ae,method:this.requestConfig.method||"POST",fetchOptions:i,middleware:this.requestConfig.requestMiddleware}).then(c=>(this.requestConfig.responseMiddleware&&this.requestConfig.responseMiddleware(c),c.data)).catch(c=>{throw this.requestConfig.responseMiddleware&&this.requestConfig.responseMiddleware(c),c})}setHeaders(t){return this.requestConfig.headers=t,this}setHeader(t,n){const{headers:s}=this.requestConfig;return s?s[t]=n:this.requestConfig.headers={[t]:n},this}setEndpoint(t){return this.url=t,this}}const Fe=async e=>{const{query:t,variables:n,fetchOptions:s}=e,r=Xr(Ks(e.method??"post")),i=Array.isArray(e.query),o=await r(e),a=await Kr(o,s.jsonSerializer??lt),c=Array.isArray(a)?!a.some(({data:f})=>!f):!!a.data,u=Array.isArray(a)||!a.errors||Array.isArray(a.errors)&&!a.errors.length||s.errorPolicy==="all"||s.errorPolicy==="ignore";if(o.ok&&u&&c){const{errors:f,...l}=(Array.isArray(a),a),h=s.errorPolicy==="ignore"?l:a;return{...i?{data:h}:h,headers:o.headers,status:o.status}}else{const f=typeof a=="string"?{error:a}:a;throw new ue({...f,status:o.status,headers:o.headers},{query:t,variables:n})}};async function pe(e,t,...n){const s=sr(e,t,...n);return new Tn(s.url).request({...s})}const Wr=(e,t,n,s)=>{const r=s??lt;if(!Array.isArray(e))return r.stringify({query:e,variables:t,operationName:n});if(typeof t<"u"&&!Array.isArray(t))throw new Error("Cannot create request body with given variable type, array expected");const i=e.reduce((o,a,c)=>(o.push({query:a,variables:t?t[c]:void 0}),o),[]);return r.stringify(i)},Kr=async(e,t)=>{let n;return e.headers.forEach((s,r)=>{r.toLowerCase()==="content-type"&&(n=s)}),n&&(n.toLowerCase().startsWith("application/json")||n.toLowerCase().startsWith("application/graphql+json")||n.toLowerCase().startsWith("application/graphql-response+json"))?t.parse(await e.text()):e.text()},Be=e=>typeof e=="function"?e():e,Zr=V(async({input:e})=>{var t,n;if(!e.endpoint||e.endpoint==="")throw new Error("No endpoint provided.");if(!e.document)throw new Error("No request document provided.");if(!e.requestHeaders)throw new Error("No request headers provided.");try{const s=await pe(e.endpoint,e.document,{},e.requestHeaders);if(!((n=(t=s.placeOrder)==null?void 0:t.checkoutSuccess)!=null&&n.id))throw console.log("Could not place order."),new Error("Could not place order.");return{type:"PLACE_ORDER_SUCCESS",successId:s.placeOrder.checkoutSuccess.id}}catch(s){throw console.log("Request to place order failed."),console.log(s),new Error("Request to place order failed.")}}),ei=V(async({input:e})=>{var t;if(!e.endpoint||e.endpoint==="")throw new Error("No endpoint provided.");if(!e.data)throw new Error("No data provided.");if(!e.document)throw new Error("No request document provided.");if(!e.requestHeaders)throw new Error("No request headers provided.");try{const n=await pe(e.endpoint,e.document,{step:e.data.step,data:{[e.data.step]:e.data.data}},e.requestHeaders);if(!((t=n.checkoutStep)!=null&&t.quote))throw console.log("Could not add items to quote."),new Error("Could not add items to quote.");return{type:"SUBMIT_STEP_DATA_SUCCESS",quote:n.checkoutStep.quote}}catch{throw console.log("Request to add submit step data failed."),new Error("Request to add submit step data failed.")}}),ti=({context:e})=>Object.keys(e.quote).length>0,Ke=fe({types:{context:{},events:{},input:{}},actions:{changeStep:x(Js),nextStep:x(Ys),resetCheckout:x(Qs),updateQuote:x(Xs),updateSuccessId:x(Ws)},actors:{placeOrder:Zr,submitStepData:ei},guards:{quoteExists:ti}}).createMachine({id:"checkout",initial:"uninitialized",context:({input:e})=>{var t,n,s,r,i,o,a,c,u,f,l,h,m,y,T,_,w;return{currentStep:((t=e==null?void 0:e.initialContext)==null?void 0:t.currentStep)??"",errors:[],isLoggedIn:((n=e==null?void 0:e.initialContext)==null?void 0:n.isLoggedIn)??!1,steps:((s=e==null?void 0:e.initialContext)==null?void 0:s.steps)??[],successId:"",quote:((r=e==null?void 0:e.initialContext)==null?void 0:r.quote)??{},endpoints:{client:"",server:"",...(i=e==null?void 0:e.initialContext)==null?void 0:i.endpoints},graphql:{placeOrder:{document:((c=(a=(o=e==null?void 0:e.initialContext)==null?void 0:o.graphql)==null?void 0:a.placeOrder)==null?void 0:c.document)??"",requestHeaders:((l=(f=(u=e==null?void 0:e.initialContext)==null?void 0:u.graphql)==null?void 0:f.placeOrder)==null?void 0:l.requestHeaders)??void 0},submitStepData:{document:((y=(m=(h=e==null?void 0:e.initialContext)==null?void 0:h.graphql)==null?void 0:m.submitStepData)==null?void 0:y.document)??"",requestHeaders:((w=(_=(T=e==null?void 0:e.initialContext)==null?void 0:T.graphql)==null?void 0:_.submitStepData)==null?void 0:w.requestHeaders)??void 0}}}},states:{uninitialized:{always:{guard:"quoteExists",target:"initializing"}},initializing:{always:[{target:"showStep"}]},showStep:{on:{SUBMIT_STEP_DATA:"submittingStepData",CHANGE_STEP:"changingStep",PLACE_ORDER:"placingOrder"}},submittingStepData:{invoke:{input:({context:e,event:t})=>(Ge(t,"SUBMIT_STEP_DATA"),{endpoint:e.endpoints.client,data:t.data,document:e.graphql.submitStepData.document,requestHeaders:e.graphql.submitStepData.requestHeaders}),src:"submitStepData",onDone:[{actions:["updateQuote","nextStep"],target:"showStep"}],onError:{target:"showStep"}}},changingStep:{always:{actions:["changeStep"],target:"showStep"}},placingOrder:{invoke:{input:({context:e,event:t})=>(Ge(t,"PLACE_ORDER"),{endpoint:e.endpoints.client,document:e.graphql.placeOrder.document,requestHeaders:e.graphql.placeOrder.requestHeaders}),src:"placeOrder",onDone:[{actions:["updateSuccessId"],target:"success"}],onError:{target:"showStep"}}},success:{type:"final"}}}),pt=N.createContext({}),ni=()=>{const e=N.useContext(pt);if(!e||!e.getSnapshot)throw new Error("checkoutActor is not properly initialized");const[t,n]=N.useState(e.getSnapshot());return N.useEffect(()=>{if(!e||!e.getSnapshot){console.error("checkoutActor is not properly initialized");return}const s=e.subscribe(r=>{n(r)});return()=>{s.unsubscribe()}},[e]),{checkoutActor:e,currentStep:t.context.currentStep}},si=async(e={inspect:void 0,currentStep:"",steps:[],quote:{id:"",locale:""},endpoints:{client:"",server:""},graphql:{}})=>typeof window<"u"?(console.warn("App.getInitialProps::getAuth should not be run on the frontend. You are probably missing getServerSideProps in your page."),$(Ke,{inspect:e.inspect,input:{initialContext:{endpoints:e.endpoints}}}).start()):$(Ke,{input:{initialContext:{currentStep:e.currentStep,steps:e.steps,endpoints:e.endpoints,graphql:e.graphql,quote:{...e.quote}}},inspect:e.inspect}).start();function ri({actor:e,children:t}){return ke.jsx(pt.Provider,{value:e,children:t})}let ii=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");const vn=fe({actors:{tick:Ss(({sendBack:e,input:t})=>{const n=setInterval(()=>{e({type:"TICK"})},t.interval);return()=>{clearInterval(n)}})},types:{context:{},events:{},input:{}}}).createMachine({id:"timer",initial:"running",context:({input:e})=>({elapsed:0,duration:e.initialContext.duration??3e3,interval:100,intervalId:null}),states:{paused:{on:{RESUME_TIMER:{target:"running",guard:({context:e})=>e.elapsed<e.duration}}},running:{invoke:{input:({context:e})=>({interval:e.interval}),src:"tick"},always:[{target:"completed",guard:({context:e})=>e.elapsed>=e.duration}],on:{TICK:{actions:x(({context:e,event:t})=>t.type!=="TICK"?e:{elapsed:e.elapsed+e.interval})},PAUSE_TIMER:{target:"paused"}}},completed:{type:"final"}}}),oi=fe({actors:{timer:vn},types:{context:{},events:{},input:{}},actions:{addItem:x(({context:e,event:t})=>{if(t.type!=="ADD_ITEM")return e;const n=`notification-${ii()}`,s=t.duration??e.duration,r=N.cloneElement(t.item,{duration:s,id:n,key:t.item.key??n,...t.item.props}),i={duration:s,id:n,element:r},o=e.items;return e.order==="desc"?o.push(i):o.unshift(i),{items:o,activeItem:n}}),removeItem:x(({context:e,event:t})=>{if(t.type!=="REMOVE_ITEM"&&t.type!=="xstate.done.actor.timer")return e;const n=e.items;return e.order==="desc"?(n.pop(),{items:n,activeItem:n.length>0?n[n.length-1].id:null}):(n.shift(),{items:n,activeItem:n.length>0?n[0].id:null})})},delays:{ITEM_TIMEOUT:({context:e})=>e.items[e.items.length-1].duration??e.duration},guards:{itemHasTimeout:({context:e})=>e.items[e.items.length-1].duration>0||e.duration>0}}).createMachine({id:"toast",context:({input:e})=>{var t,n,s,r;return{items:((t=e==null?void 0:e.initialContext)==null?void 0:t.items)??[],order:((n=e==null?void 0:e.initialContext)==null?void 0:n.order)??"desc",duration:((s=e==null?void 0:e.initialContext)==null?void 0:s.duration)??0,activeItem:((r=e==null?void 0:e.initialContext)==null?void 0:r.activeItem)??null}},initial:"idle",states:{idle:{on:{ADD_ITEM:{target:"adding"}}},active:{invoke:{id:"timer",src:"timer",input:({context:e})=>({initialContext:{duration:e.items[e.items.length-1].duration??e.duration}}),onDone:{target:"removing",guard:"itemHasTimeout"}},on:{ADD_ITEM:{target:"adding"},REMOVE_ITEM:{target:"removing"},SET_IDLE:{target:"idle"},RESUME_TIMER:{actions:Ot("timer",{type:"RESUME_TIMER"})},PAUSE_TIMER:{actions:Ot("timer",{type:"PAUSE_TIMER"})}}},adding:{entry:["addItem"],on:{SET_IDLE:{target:"idle"},SET_ACTIVE:{target:"active"}}},removing:{entry:"removeItem",on:{SET_IDLE:{target:"idle"},SET_ACTIVE:{target:"active"}}}}}),yt=N.createContext({}),ai=()=>{const e=N.useContext(yt);if(!e||!e.getSnapshot)throw new Error("toastActor is not properly initialized");const[t,n]=N.useState(()=>e.getSnapshot());return N.useEffect(()=>{if(!e||!e.getSnapshot){console.error("toastActor is not properly initialized");return}(()=>{n(e.getSnapshot())})();const r=e.subscribe(i=>{n(i)});return()=>{r.unsubscribe()}},[e]),{toastActor:e}};function ci({children:e,actor:t}){return ke.jsx(yt.Provider,{value:t,children:e})}function ui({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="ADD_ITEMS_SUCCESS"?e:{quote:{...e.quote,...n.output.quote},itemsAdded:n.output.itemsAdded}}function di({event:e}){if(!e.type.includes("xstate.done.actor"))return{type:"EMIT_ADD_ITEMS",itemsAdded:[]};const t=e;return t.output.type!=="ADD_ITEMS_SUCCESS"?{type:"EMIT_ADD_ITEMS",itemsAdded:[]}:{type:"EMIT_ADD_ITEMS",itemsAdded:t.output.itemsAdded}}function li({event:e}){if(!e.type.includes("xstate.done.actor"))return{type:"EMIT_REMOVE_ITEMS",itemsRemoved:[]};const t=e;return t.output.type!=="REMOVE_ITEMS_SUCCESS"?{type:"EMIT_REMOVE_ITEMS",itemsRemoved:[]}:{type:"EMIT_REMOVE_ITEMS",itemsRemoved:t.output.itemsRemoved}}function hi({event:e}){if(!e.type.includes("xstate.done.actor"))return{type:"EMIT_UPDATE_ITEMS",itemsUpdated:[]};const t=e;return t.output.type!=="UPDATE_ITEMS_SUCCESS"?{type:"EMIT_UPDATE_ITEMS",itemsUpdated:[]}:{type:"EMIT_UPDATE_ITEMS",itemsUpdated:t.output.itemsUpdated}}function fi({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="REMOVE_ITEMS_SUCCESS"?e:{quote:{...e.quote,...n.output.quote},itemsRemoved:n.output.itemsRemoved}}function pi({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="REFRESH_SUCCESS"?e:{quote:{...e.quote,...n.output.quote}}}function yi({context:e,event:t}){const n=t;if(n.type!=="RESET")return e;const{locale:s}=n.data;return{quote:{id:"",locale:s,baseCurrency:"USD",currencyConversionRate:1,dateCreated:null,dateLastUpdated:null,currency:"USD",items:[],promotions:[],shippingAddresses:{available:[],applied:[]},paymentMethods:{available:[],applied:[]},totals:{discount:0,taxAmount:0,shippingAmount:0,shippingTaxAmount:0,subtotal:0,grandTotal:0},appliedPriceRules:[],appliedPromotions:[],shippingMethods:[],storeCredit:[],rewards:[],giftCards:[]}}}function mi({context:e,event:t}){const n=t;return n.type!=="SYNC_ACCESS_TOKEN"?e:{quote:{...e.quote,accessToken:n.accessToken}}}function gi({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="UPDATE_ITEMS_SUCCESS"?e:{quote:{...e.quote,...n.output.quote},itemsUpdated:n.output.itemsUpdated}}const Ei=V(async({input:e})=>{var n;if(!e.endpoint||e.endpoint==="")throw new Error("No endpoint provided.");if(e.items.length<1)throw new Error("No items provided.");if(!e.document)throw new Error("No request document provided.");if(!e.requestHeaders)throw new Error("No request headers provided.");let{requestHeaders:t}=e;e.accessToken&&(t={...t,Authorization:`Bearer ${e.accessToken}`});try{const s=await pe(e.endpoint,e.document,{items:e.items},t);if(!((n=s.quoteAddItem)!=null&&n.quote))throw new Error("Could not add items to quote.");return{type:"ADD_ITEMS_SUCCESS",quote:s.quoteAddItem.quote,itemsAdded:s.quoteAddItem.itemsAdded}}catch{throw new Error("Request to add item(s) failed.")}}),Ti=V(async({input:e})=>{var n;if(!e.endpoint||e.endpoint==="")throw new Error("No endpoint provided.");if(e.items.length<1)throw new Error("No items provided.");let{requestHeaders:t}=e;e.accessToken&&(t={...t,Authorization:`Bearer ${e.accessToken}`});try{const s=await pe(e.endpoint,e.document,{items:e.items},t);if(!((n=s.quoteRemoveItem)!=null&&n.quote))throw new Error("Could not remove items from quote.");return{type:"REMOVE_ITEMS_SUCCESS",quote:s.quoteRemoveItem.quote,itemsRemoved:s.quoteRemoveItem.itemsRemoved}}catch{throw new Error("Request to remove item(s) failed.")}}),je=typeof window>"u",vi=V(async({input:e})=>{var s,r,i,o;if(!e.endpoint)throw console.log("no endpoint"),new Error("No endpoint provided.");if(!e.endpointSsr)throw console.log("no endpoint ssr"),new Error("No SSR endpoint provided.");if(!e.locale)throw console.log("no locale"),new Error("No locale provided.");if(!e.document)throw console.log("no request document"),new Error("No request document provided.");if(!e.requestHeaders)throw console.log("no headers"),new Error("No request headers provided.");const t=new Tn(je?e.endpointSsr:e.endpoint,je?{fetch,method:"POST"}:{credentials:"include",method:"POST",mode:"cors"});let n=je?{...e.requestHeaders,Cookie:`quote_${e.locale}=${e.quoteId??""}`}:e.requestHeaders;e.accessToken&&(n={...n,Authorization:`Bearer ${e.accessToken}`});try{const{data:a,headers:c,status:u,errors:f,extensions:l}=await t.rawRequest(En(e.document),{},n),h=a;if(!((s=h.refreshQuote)!=null&&s.quote))throw console.log("userError: ",(r=h.refreshQuote)==null?void 0:r.userErrors[0].code,(i=h.refreshQuote)==null?void 0:i.userErrors[0].field,(o=h.refreshQuote)==null?void 0:o.userErrors[0].message),new Error("Could not add items to quote.");return{type:"REFRESH_SUCCESS",quote:h.refreshQuote.quote}}catch(a){throw console.log("refresh error",a),new Error("Request to add item(s) failed.")}}),Si=V(async({input:e})=>{var n;if(!e.endpoint||e.endpoint==="")throw new Error("No endpoint provided.");if(e.items.length<1)throw new Error("No items provided.");if(!e.document)throw new Error("No request document provided.");if(!e.requestHeaders)throw new Error("No request headers provided.");let{requestHeaders:t}=e;e.accessToken&&(t={...t,Authorization:`Bearer ${e.accessToken}`});try{const s=await pe(e.endpoint,e.document,{items:e.items},t);if(!((n=s.quoteUpdateItem)!=null&&n.quote))throw new Error("Could not add items to quote.");return{type:"UPDATE_ITEMS_SUCCESS",quote:s.quoteUpdateItem.quote,itemsUpdated:s.quoteUpdateItem.itemsUpdated}}catch{throw new Error("Request to add item(s) failed.")}}),_i=({context:e})=>typeof window>"u"&&e.quote.id!==""||typeof window<"u",Ii=({context:e})=>!!e.quote.items&&e.quote.items.length>0,Ze=fe({types:{context:{},emitted:{},events:{},input:{}},actions:{addItems:x(ui),notifyAddItems:Se(di),notifyRemoveItems:Se(li),notifyUpdateItems:Se(hi),removeItems:x(fi),refresh:x(pi),reset:x(yi),syncAccessToken:x(mi),updateItems:x(gi)},actors:{addItems:Ei,removeItems:Ti,refresh:vi,updateItems:Si},guards:{canRefresh:_i,hasItems:Ii}}).createMachine({id:"quote",initial:"initializing",context:({input:e})=>{var t,n,s,r,i,o,a,c,u,f,l,h,m,y,T,_,w,q,D,M,F,z,G,U,ye,me;return{quote:{id:"",accessToken:"",locale:"",baseCurrency:"USD",currencyConversionRate:1,dateCreated:null,dateLastUpdated:null,currency:"USD",items:[],promotions:[],shippingAddresses:{available:[],applied:[]},paymentMethods:{available:[],applied:[]},totals:{discount:0,taxAmount:0,shippingAmount:0,shippingTaxAmount:0,subtotal:0,grandTotal:0},appliedPriceRules:[],appliedPromotions:[],shippingMethods:[],storeCredit:[],rewards:[],giftCards:[],...(t=e==null?void 0:e.initialContext)==null?void 0:t.quote},errors:[],endpoints:{client:"",server:"",...(n=e==null?void 0:e.initialContext)==null?void 0:n.endpoints},graphql:{refresh:{document:((i=(r=(s=e==null?void 0:e.initialContext)==null?void 0:s.graphql)==null?void 0:r.refresh)==null?void 0:i.document)??"",requestHeaders:((c=(a=(o=e==null?void 0:e.initialContext)==null?void 0:o.graphql)==null?void 0:a.refresh)==null?void 0:c.requestHeaders)??void 0},addItems:{document:((l=(f=(u=e==null?void 0:e.initialContext)==null?void 0:u.graphql)==null?void 0:f.addItems)==null?void 0:l.document)??"",requestHeaders:((y=(m=(h=e==null?void 0:e.initialContext)==null?void 0:h.graphql)==null?void 0:m.addItems)==null?void 0:y.requestHeaders)??void 0},removeItems:{document:((w=(_=(T=e==null?void 0:e.initialContext)==null?void 0:T.graphql)==null?void 0:_.removeItems)==null?void 0:w.document)??"",requestHeaders:((M=(D=(q=e==null?void 0:e.initialContext)==null?void 0:q.graphql)==null?void 0:D.removeItems)==null?void 0:M.requestHeaders)??void 0},updateItems:{document:((G=(z=(F=e==null?void 0:e.initialContext)==null?void 0:F.graphql)==null?void 0:z.updateItems)==null?void 0:G.document)??"",requestHeaders:((me=(ye=(U=e==null?void 0:e.initialContext)==null?void 0:U.graphql)==null?void 0:ye.updateItems)==null?void 0:me.requestHeaders)??void 0}}}},states:{uninitialized:{on:{REFRESH:"refreshing"}},empty:{on:{ADD_ITEMS:"addingItems",UPDATE_ITEMS:"updatingItems"}},active:{on:{ADD_ITEMS:"addingItems",REMOVE_ITEMS:"removingItems",REFRESH:"refreshing",UPDATE_ITEMS:"updatingItems",RESET:"resetting"}},initializing:{always:[{target:"refreshing",guard:"canRefresh"},{target:"uninitialized"}]},refreshing:{invoke:{input:({context:e})=>({accessToken:e.quote.accessToken,endpoint:e.endpoints.client,endpointSsr:e.endpoints.server,quoteId:e.quote.id,locale:e.quote.locale,document:e.graphql.refresh.document,requestHeaders:e.graphql.refresh.requestHeaders}),src:"refresh",onDone:[{actions:["refresh"],target:"checkingItems"}],onError:{target:"empty"}}},checkingItems:{always:[{guard:"hasItems",target:"active"},{target:"empty"}]},addingItems:{invoke:{input:({context:e,event:t})=>{var n,s;return{accessToken:e.quote.accessToken,endpoint:e.endpoints.client,items:t.type==="ADD_ITEMS"?t.items:[],document:(n=e.graphql.addItems)==null?void 0:n.document,requestHeaders:(s=e.graphql.addItems)==null?void 0:s.requestHeaders}},src:"addItems",onDone:[{actions:["addItems","notifyAddItems"],target:"active"}],onError:[{guard:"hasItems",target:"active"},{target:"empty"}]}},removingItems:{invoke:{input:({context:e,event:t})=>{var n,s;return{accessToken:e.quote.accessToken,endpoint:e.endpoints.client,items:t.type==="REMOVE_ITEMS"?t.items:[],document:(n=e.graphql.removeItems)==null?void 0:n.document,requestHeaders:(s=e.graphql.removeItems)==null?void 0:s.requestHeaders}},src:"removeItems",onDone:[{actions:["removeItems","notifyRemoveItems"],target:"checkingItems"}],onError:[{guard:"hasItems",target:"active"},{target:"empty"}]}},updatingItems:{invoke:{input:({context:e,event:t})=>{var n,s;return{accessToken:e.quote.accessToken,endpoint:e.endpoints.client,items:t.type==="UPDATE_ITEMS"?t.items:[],document:(n=e.graphql.updateItems)==null?void 0:n.document,requestHeaders:(s=e.graphql.updateItems)==null?void 0:s.requestHeaders}},src:"updateItems",onDone:[{actions:["updateItems","notifyUpdateItems"],target:"checkingItems"}],onError:[{guard:"hasItems",target:"active"},{target:"empty"}]}},resetting:{always:[{actions:["reset"],target:"uninitialized"}]}},on:{SYNC_ACCESS_TOKEN:{actions:["syncAccessToken"]}}}),mt=N.createContext({}),Ai=()=>{var c;const e=N.useContext(mt);if(!e||!e.getSnapshot)throw new Error("quoteActor is not properly initialized");const[t,n]=N.useState(()=>e.getSnapshot());N.useEffect(()=>{if(!e||!e.getSnapshot){console.error("quoteActor is not properly initialized");return}(()=>{n(e.getSnapshot())})();const f=e.subscribe(l=>{n(l)});return()=>{f.unsubscribe()}},[e]);const s=t.context.quote.items??[],r=((c=t.context.quote.items)==null?void 0:c.length)??0,i=t.matches("addingItems"),o=t.matches("removingItems"),a=t.matches("addingItems")||t.matches("removingItems");return{quoteActor:e,items:s,itemsCount:r,isAddingItems:i,isRemovingItems:o,isUpdatingItems:a}},wi=async(e={inspect:void 0,quote:{id:"",locale:""},endpoints:{client:"",server:""},graphql:{}})=>typeof window<"u"?(console.warn("App.getInitialProps::getAuth should not be run on the frontend. You are probably missing getServerSideProps in your page."),$(Ze,{inspect:e.inspect,input:{initialContext:{endpoints:e.endpoints}}}).start()):$(Ze,{input:{initialContext:{endpoints:e.endpoints,graphql:e.graphql,quote:{...e.quote}}},inspect:e.inspect}).start();function xi({actor:e,children:t}){return ke.jsx(mt.Provider,{value:e,children:t})}exports.AuthContext=dt;exports.AuthProvider=Gs;exports.CheckoutContext=pt;exports.CheckoutProvider=ri;exports.QuoteContext=mt;exports.QuoteProvider=xi;exports.ToastContext=yt;exports.ToastProvider=ci;exports.authMachine=an;exports.checkoutMachine=Ke;exports.getAuth=zs;exports.getCheckout=si;exports.getQuote=wi;exports.quoteMachine=Ze;exports.timerMachine=vn;exports.toastMachine=oi;exports.useAuth=Hs;exports.useCheckout=ni;exports.useQuote=Ai;exports.useToast=ai;