@clicktap/state 0.13.8 → 0.13.9

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.
Files changed (3) hide show
  1. package/index.js +8 -8
  2. package/index.mjs +48 -42
  3. package/package.json +1 -1
package/index.js CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ye=require("react/jsx-runtime"),P=require("react");function En(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 vn(){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 Tn(){const e=vn();if(e.__xstate__)return e.__xstate__}const _n=e=>{if(typeof window>"u")return;const t=Tn();t&&t.register(e)};class lt{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 Lt=".",In="",Mt="",Sn="#",xn="*",Pt="xstate.init",An="xstate.error",ce="xstate.stop";function wn(e,t){return{type:`xstate.after.${e}.${t}`}}function Fe(e,t){return{type:`xstate.done.state.${e}`,output:t}}function bn(e,t){return{type:`xstate.done.actor.${e}`,output:t}}function qt(e,t){return{type:`xstate.error.actor.${e}`,error:t}}function Ft(e){return{type:Pt,input:e}}function F(e){setTimeout(()=>{throw e})}const On=(()=>typeof Symbol=="function"&&Symbol.observable||"@@observable")();function ht(e,t){return`${e.sessionId}.${t}`}let Nn=0;function kn(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,v,S=Math.random().toString(36).slice(2))=>{const A={source:h,target:m,event:y,delay:v,id:S,startedAt:Date.now()},R=ht(h,S);l._snapshot._scheduledEvents[R]=A;const D=a.setTimeout(()=>{delete o[R],delete l._snapshot._scheduledEvents[R],l._relay(h,m,y)},v);o[R]=D},cancel:(h,m)=>{const y=ht(h,m),v=o[y];delete o[y],delete l._snapshot._scheduledEvents[y],a.clearTimeout(v)},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 v;return(v=y.next)==null?void 0:v.call(y,m)})},l={_snapshot:{_scheduledEvents:((t==null?void 0:t.snapshot)&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${Nn++}`,_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:v,event:S,delay:A,id:R}=h[m];u.schedule(y,v,S,A,R)}},_clock:a,_logger:c};return l}function Ut(e,t){const n=ft(e),s=ft(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?Ut(n[r],s[r]):!1)}function Qe(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 ft(e){if(as(e))return e.value;if(typeof e!="string")return e;const t=Qe(e);return Cn(t)}function Cn(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 pt(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 Bt(e){return jt(e)?e:[e]}function U(e){return e===void 0?[]:Bt(e)}function Ue(e,t,n,s){return typeof e=="function"?e({context:t,event:n,self:s}):e}function jt(e){return Array.isArray(e)}function Dn(e){return e.type.startsWith("xstate.error.actor")}function X(e){return Bt(e).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function $t(e){if(!(e===void 0||e===In))return U(e)}function yt(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 mt(e,t){return`${t}.${e}`}function Xe(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 We=1;let k=function(e){return e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped",e}({});const Rn={clock:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},logger:console.log.bind(console),devTools:!1};class Ln{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 lt(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=k.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={...Rn,...n},{clock:r,logger:i,parent:o,syncSnapshot:a,id:c,systemId:u,inspect:f}=s;this.system=o?o.system:kn(this,{clock:r,logger:i}),f&&!o&&this.system.inspect(yt(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){F(a)}break;case"done":for(const o of this.observers)try{(i=o.next)==null||i.call(o,t)}catch(a){F(a)}this._stopProcedure(),this._complete(),this._doneEvent=bn(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=yt(t,n,s);if(this._processingStatus!==k.Stopped)this.observers.add(r);else switch(this._snapshot.status){case"done":try{(i=r.complete)==null||i.call(r)}catch(o){F(o)}break;case"error":{const o=this._snapshot.error;if(!r.error)F(o);else try{r.error(o)}catch(a){F(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===k.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=k.Running;const t=Ft(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===ce&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===k.Stopped?this:(this.mailbox.clear(),this._processingStatus===k.NotStarted?(this._processingStatus=k.Stopped,this):(this.mailbox.enqueue({type:ce}),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){F(s)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||F(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){F(i)}}this.observers.clear(),n&&F(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,qt(this.id,t))}_stopProcedure(){return this._processingStatus!==k.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new lt(this._process.bind(this)),this._processingStatus=k.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==k.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:_n)(this)}toJSON(){return{xstate$$type:We,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[On](){return this}getSnapshot(){return this._snapshot}}function B(e,...[t]){return new Ln(e,t)}function Mn(e,t,n,s,{sendId:r}){const i=typeof r=="function"?r(n,s):r;return[t,i]}function Pn(e,t){e.defer(()=>{e.system.scheduler.cancel(e.self,t)})}function qn(e){function t(n,s){}return t.type="xstate.cancel",t.sendId=e,t.resolve=Mn,t.execute=Pn,t}function Fn(e,t,n,s,{id:r,systemId:i,src:o,input:a,syncSnapshot:c}){const u=typeof o=="string"?Xe(t.machine,o):o,f=typeof r=="function"?r(n):r;let l;return u&&(l=B(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})),[G(t,{children:{...t.children,[f]:l}}),{id:r,actorRef:l}]}function Un(e,{id:t,actorRef:n}){n&&e.defer(()=>{n._processingStatus!==k.Stopped&&n.start()})}function Bn(...[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=Fn,i.execute=Un,i}function jn(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]),[G(t,{children:a}),o]}function $n(e,t){if(t){if(e.system._unregister(t),t._processingStatus!==k.Running){e.stopChild(t);return}e.defer(()=>{e.stopChild(t)})}}function Vt(e){function t(n,s){}return t.type="xstate.stopChild",t.actorRef=e,t.resolve=jn,t.execute=$n,t}function Ke(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 Ke(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 Ze=e=>e.type==="atomic"||e.type==="final";function ee(e){return Object.values(e.states).filter(t=>t.type!=="history")}function de(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 Te(e){const t=new Set(e),n=Gt(t);for(const s of t)if(s.type==="compound"&&(!n.get(s)||!n.get(s).length))gt(s).forEach(r=>t.add(r));else if(s.type==="parallel"){for(const r of ee(s))if(r.type!=="history"&&!t.has(r)){const i=gt(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 Ht(e,t){const n=t.get(e);if(!n)return{};if(e.type==="compound"){const r=n[0];if(r){if(Ze(r))return r.key}else return{}}const s={};for(const r of n)s[r.key]=Ht(r,t);return s}function Gt(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 zt(e,t){const n=Te(t);return Ht(e,Gt(n))}function et(e,t){return t.type==="compound"?ee(t).some(n=>n.type==="final"&&e.has(n)):t.type==="parallel"?ee(t).every(n=>et(e,n)):t.type==="final"}const xe=e=>e[0]===Sn;function Vn(e,t){return e.transitions.get(t)||[...e.transitions.keys()].filter(s=>{if(s===xn)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 Hn(e){const t=e.config.after;if(!t)return[];const n=(r,i)=>{const o=wn(r,e.id),a=o.type;return e.entry.push(ms(o,{id:a,delay:r})),e.exit.push(qn(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 U(a).map(f=>({...f,event:u,delay:c}))}).map(r=>{const{delay:i}=r;return{...V(e,r.event,r),delay:i}})}function V(e,t,n){const s=$t(n.target),r=n.reenter??!1,i=Jn(e,s),o={...n,actions:U(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 Gn(e){const t=new Map;if(e.config.on)for(const n of Object.keys(e.config.on)){if(n===Mt)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const s=e.config.on[n];t.set(n,X(s).map(r=>V(e,n,r)))}if(e.config.onDone){const n=`xstate.done.state.${e.id}`;t.set(n,X(e.config.onDone).map(s=>V(e,n,s)))}for(const n of e.invoke){if(n.onDone){const s=`xstate.done.actor.${n.id}`;t.set(s,X(n.onDone).map(r=>V(e,s,r)))}if(n.onError){const s=`xstate.error.actor.${n.id}`;t.set(s,X(n.onError).map(r=>V(e,s,r)))}if(n.onSnapshot){const s=`xstate.snapshot.${n.id}`;t.set(s,X(n.onSnapshot).map(r=>V(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 zn(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"?[]:U(t.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...s,source:`#${e.id}`,target:n?[`#${n.id}`]:[]})};return s}function Jn(e,t){if(t!==void 0)return t.map(n=>{if(typeof n!="string")return n;if(xe(n))return e.machine.getStateNodeById(n);const s=n[0]===Lt;if(s&&!e.parent)return _e(e,n.slice(1));const r=s?e.key+n:n;if(e.parent)try{return _e(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 Jt(e){const t=$t(e.config.target);return t?{target:t.map(n=>typeof n=="string"?_e(e.parent,n):n)}:e.parent.initial}function H(e){return e.type==="history"}function gt(e){const t=Yt(e);for(const n of t)for(const s of de(n,e))t.add(s);return t}function Yt(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 ee(s))n(r)}}return n(e),t}function te(e,t){if(xe(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 _e(e,t){if(typeof t=="string"&&xe(t))try{return e.machine.getStateNodeById(t)}catch{}const n=Qe(t).slice();let s=e;for(;n.length;){const r=n.shift();if(!r.length)break;s=te(s,r)}return s}function Ie(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=>te(e,r)).filter(Boolean);return[e.machine.root,e].concat(s,n.reduce((r,i)=>{const o=te(e,i);if(!o)return r;const a=Ie(o,t[i]);return r.concat(a)},[]))}function Yn(e,t,n,s){const i=te(e,t).next(n,s);return!i||!i.length?e.next(n,s):i}function Qn(e,t,n,s){const r=Object.keys(t),i=te(e,r[0]),o=tt(i,t[r[0]],n,s);return!o||!o.length?e.next(n,s):o}function Xn(e,t,n,s){const r=[];for(const i of Object.keys(t)){const o=t[i];if(!o)continue;const a=te(e,i),c=tt(a,o,n,s);c&&r.push(...c)}return r.length?r:e.next(n,s)}function tt(e,t,n,s){return typeof t=="string"?Yn(e,t,n,s):Object.keys(t).length===1?Qn(e,t,n,s):Xn(e,t,n,s)}function Wn(e){return Object.keys(e.states).map(t=>e.states[t]).filter(t=>t.type==="history")}function j(e,t){let n=e;for(;n.parent&&n.parent!==t;)n=n.parent;return n.parent===t}function Kn(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 Qt(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(Kn(Be([r],t,n),Be([a],t,n)))if(j(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 Zn(e){const[t,...n]=e;for(const s of de(t,void 0))if(n.every(r=>j(r,s)))return s}function nt(e,t){if(!e.target)return[];const n=new Set;for(const s of e.target)if(H(s))if(t[s.id])for(const r of t[s.id])n.add(r);else for(const r of nt(Jt(s),t))n.add(r);else n.add(s);return[...n]}function Xt(e,t){const n=nt(e,t);if(!n)return;if(!e.reenter&&n.every(r=>r===e.source||j(r,e.source)))return e.source;const s=Zn(n.concat(e.source));if(s)return s;if(!e.reenter)return e.source.machine.root}function Be(e,t,n){var r;const s=new Set;for(const i of e)if((r=i.target)!=null&&r.length){const o=Xt(i,n);i.reenter&&i.source===o&&s.add(o);for(const a of t)j(a,o)&&s.add(a)}return[...s]}function es(e,t){if(e.length!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function je(e,t,n,s,r,i){if(!e.length)return t;const o=new Set(t._nodes);let a=t.historyValue;const c=Qt(e,o,a);let u=t;r||([u,a]=rs(u,s,n,c,o,a,i)),u=ne(u,s,n,c.flatMap(l=>l.actions),i),u=ns(u,s,n,c,o,i,a,r);const f=[...o];u.status==="done"&&(u=ne(u,s,n,f.sort((l,h)=>h.order-l.order).flatMap(l=>l.exit),i));try{return a===t.historyValue&&es(t._nodes,o)?u:G(u,{_nodes:f,historyValue:a})}catch(l){throw l}}function ts(e,t,n,s,r){if(s.output===void 0)return;const i=Fe(r.id,r.output!==void 0&&r.parent?Ue(r.output,e.context,t,n.self):void 0);return Ue(s.output,e.context,i,n.self)}function ns(e,t,n,s,r,i,o,a){let c=e;const u=new Set,f=new Set;ss(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(Bn(y.src,{...y,syncSnapshot:!!y.onSnapshot}));if(f.has(h)){const y=h.initial.actions;m.push(...y)}if(c=ne(c,t,n,m,i,h.invoke.map(y=>y.id)),h.type==="final"){const y=h.parent;let v=(y==null?void 0:y.type)==="parallel"?y:y==null?void 0:y.parent,S=v||h;for((y==null?void 0:y.type)==="compound"&&i.push(Fe(y.id,h.output!==void 0?Ue(h.output,c.context,t,n.self):void 0));(v==null?void 0:v.type)==="parallel"&&!l.has(v)&&et(r,v);)l.add(v),i.push(Fe(v.id)),S=v,v=v.parent;if(v)continue;c=G(c,{status:"done",output:ts(c,t,n,c.machine.root,S)})}}return c}function ss(e,t,n,s){for(const r of e){const i=Xt(r,t);for(const a of r.target||[])!H(a)&&(r.source!==a||r.source!==i||r.reenter)&&(s.add(a),n.add(a)),W(a,t,n,s);const o=nt(r,t);for(const a of o){const c=de(a,i);(i==null?void 0:i.type)==="parallel"&&c.push(i),Wt(s,t,n,c,!r.source.parent&&r.reenter?void 0:i)}}}function W(e,t,n,s){var r;if(H(e))if(t[e.id]){const i=t[e.id];for(const o of i)s.add(o),W(o,t,n,s);for(const o of i)ke(o,e.parent,s,t,n)}else{const i=Jt(e);for(const o of i.target)s.add(o),i===((r=e.parent)==null?void 0:r.initial)&&n.add(e.parent),W(o,t,n,s);for(const o of i.target)ke(o,e.parent,s,t,n)}else if(e.type==="compound"){const[i]=e.initial.target;H(i)||(s.add(i),n.add(i)),W(i,t,n,s),ke(i,e,s,t,n)}else if(e.type==="parallel")for(const i of ee(e).filter(o=>!H(o)))[...s].some(o=>j(o,i))||(H(i)||(s.add(i),n.add(i)),W(i,t,n,s))}function Wt(e,t,n,s,r){for(const i of s)if((!r||j(i,r))&&e.add(i),i.type==="parallel")for(const o of ee(i).filter(a=>!H(a)))[...e].some(a=>j(a,o))||(e.add(o),W(o,t,n,e))}function ke(e,t,n,s,r){Wt(n,s,r,de(e,t))}function rs(e,t,n,s,r,i,o){let a=e;const c=Be(s,r,i);c.sort((f,l)=>l.order-f.order);let u;for(const f of c)for(const l of Wn(f)){let h;l.history==="deep"?h=m=>Ze(m)&&j(m,f):h=m=>m.parent===f,u??(u={...i}),u[l.id]=Array.from(r).filter(h)}for(const f of c)a=ne(a,t,n,[...f.exit,...f.invoke.map(l=>Vt(l.id))],o),r.delete(f);return[a,u||i]}let Et=!1;function Kt(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{Et=f,f(l,h)}finally{Et=!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===k.Running?m():n.defer(()=>{m()});continue}const y=f,[v,S,A]=y.resolve(n,a,l,h,f,r);a=v,"retryResolve"in y&&(i==null||i.push([y,S])),"execute"in y&&(n.self._processingStatus===k.Running?y.execute(n,S):n.defer(y.execute.bind(null,n,S))),A&&(a=Kt(a,t,n,A,r,i))}return a}function ne(e,t,n,s,r,i){const o=i?[]:void 0,a=Kt(e,t,n,s,{internalQueue:r,deferredActorIds:i},o);return o==null||o.forEach(([c,u])=>{c.retryResolve(n,a,u)}),a}function Ce(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===ce)return r=G(vt(r,t,n),{status:"stopped"}),o(r,t,[]),{snapshot:r,microstates:i};let a=t;if(a.type!==Pt){const u=a,f=Dn(u),l=Tt(u,r);if(f&&!l.length)return r=G(e,{status:"error",error:u.error}),o(r,u,[]),{snapshot:r,microstates:i};r=je(l,e,n,a,!1,s),o(r,u,l)}let c=!0;for(;r.status==="active";){let u=c?is(r,a):[];const f=u.length?r:void 0;if(!u.length){if(!s.length)break;a=s.shift(),u=Tt(a,r)}r=je(u,r,n,a,!1,s),c=r!==f,o(r,a,u)}return r.status!=="active"&&vt(r,a,n),{snapshot:r,microstates:i}}function vt(e,t,n){return ne(e,t,n,Object.values(e.children).map(s=>Vt(s)),[])}function Tt(e,t){return t.machine.getTransitionData(t,e)}function is(e,t){const n=new Set,s=e._nodes.filter(Ze);for(const r of s)e:for(const i of[r].concat(de(r,void 0)))if(i.always){for(const o of i.always)if(o.guard===void 0||Ke(o.guard,e.context,t,e)){n.add(o);break e}}return Qt(Array.from(n),new Set(e._nodes),e.historyValue)}function os(e,t){const n=Te(Ie(e,t));return zt(e,[...n])}function as(e){return!!e&&typeof e=="object"&&"machine"in e&&"value"in e}const cs=function(t){return Ut(t,this.value)},us=function(t){return this.tags.has(t)},ds=function(t){const n=this.machine.getTransitionData(this,t);return!!(n!=null&&n.length)&&n.some(s=>s.target!==void 0||s.actions.length)},ls=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)}},hs=function(){return this._nodes.reduce((t,n)=>(n.meta!==void 0&&(t[n.id]=n.meta),t),{})};function me(e,t){return{status:e.status,output:e.output,error:e.error,machine:t,context:e.context,_nodes:e._nodes,value:zt(t.root,e._nodes),tags:new Set(e._nodes.flatMap(n=>n.tags)),children:e.children,historyValue:e.historyValue||{},matches:cs,hasTag:us,can:ds,getMeta:hs,toJSON:ls}}function G(e,t={}){return me({...e,...t},e.machine)}function fs(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 v in i){const S=i[v];m[v]={snapshot:S.getPersistedSnapshot(t),src:S.src,systemId:S._systemId,syncSnapshot:S._syncSnapshot}}return{...h,context:Zt(o),children:m}}function Zt(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:We,id:s.id};else{const r=Zt(s);r!==s&&(t??(t=Array.isArray(e)?e.slice():{...e}),t[n]=r)}}return t??e}function ps(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 ys(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 ms(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=ps,n.execute=ys,n}const _t=new WeakMap;function gs(e){return{config:e,start:(n,s)=>{const{self:r,system:i}=s,o={receivers:void 0,dispose:void 0};_t.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=_t.get(r.self);return s.type===ce?(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 It="xstate.promise.resolve",St="xstate.promise.reject",pe=new WeakMap;function Z(e){return{config:e,transition:(n,s,r)=>{var i;if(n.status!=="active")return n;switch(s.type){case It:{const o=s.data;return{...n,status:"done",output:o,input:void 0}}case St:return{...n,status:"error",error:s.data,input:void 0};case ce:return(i=pe.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;pe.set(s,i),Promise.resolve(e({input:n.input,system:r,self:s,signal:i.signal})).then(a=>{s.getSnapshot().status==="active"&&(pe.delete(s),r._relay(s,s,{type:It,data:a}))},a=>{s.getSnapshot().status==="active"&&(pe.delete(s),r._relay(s,s,{type:St,data:a}))})},getInitialSnapshot:(n,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedSnapshot:n=>n,restoreSnapshot:n=>n}}function Es(e,{machine:t,context:n},s,r){const i=(o,a={})=>{const{systemId:c,input:u}=a;if(typeof o=="string"){const f=Xe(t,o);if(!f)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const l=B(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 B(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!==k.Stopped&&c.start()}),c}}function vs(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:Es(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[G(t,{context:c,children:Object.keys(i).length?{...t.children,...i}:t.children})]}function C(e){function t(n,s){}return t.type="xstate.assign",t.assignment=e,t.resolve=vs,t}let xt=function(e){return e.Parent="#_parent",e.Internal="#_internal",e}({});function Ts(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 v=u&&u[a];l=typeof v=="function"?v(n,s):v}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===xt.Parent?m=e.self._parent:h===xt.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 _s(e,t,n){typeof n.to=="string"&&(n.to=t.children[n.to])}function Is(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===An?qt(e.self.id,s.data):s)})}function At(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=Ts,s.retryResolve=_s,s.execute=Is,s}const wt=new WeakMap;function Y(e,t,n){let s=wt.get(e);return s?t in s||(s[t]=n()):(s={[t]:n()},wt.set(e,s)),s[t]}const Ss={},ie=e=>typeof e=="string"?{type:e}:typeof e=="function"?"resolve"in e?{type:e.type}:{type:e.name}:e;class st{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(Lt),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?pt(this.config.states,(s,r)=>new st(s,{_parent:this,_key:r,_machine:this.machine})):Ss,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=U(this.config.entry).slice(),this.exit=U(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=U(t.tags).slice()}_initialize(){this.transitions=Gn(this),this.config.always&&(this.always=X(this.config.always).map(t=>V(this,Mt,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(ie),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(ie),eventType:null})}:void 0,history:this.history,states:pt(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(ie)})),entry:this.entry.map(ie),exit:this.exit.map(ie),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 Y(this,"invoke",()=>U(this.config.invoke).map((t,n)=>{const{src:s,systemId:r}=t,i=t.id??mt(this.id,n),o=typeof s=="string"?s:`xstate.invoke.${mt(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 Y(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 Y(this,"delayedTransitions",()=>Hn(this))}get initial(){return Y(this,"initial",()=>zn(this,this.config.initial))}next(t,n){const s=n.type,r=[];let i;const o=Y(this,`candidates-${s}`,()=>Vn(this,s));for(const a of o){const{guard:c}=a,u=t.context;let f=!1;try{f=!c||Ke(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 Y(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 xs="#";class rt{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 st(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 rt(this.config,{actions:{...n,...t.actions},guards:{...s,...t.guards},actors:{...r,...t.actors},delays:{...i,...t.delays}})}resolveState(t){const n=os(this.root,t.value),s=Te(Ie(this.root,n));return me({_nodes:[...s],context:t.context||{},children:{},status:et(s,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,n,s){return Ce(t,n,s).snapshot}microstep(t,n,s){return Ce(t,n,s).microstates}getTransitionData(t,n){return tt(this.root,t.value,t,n)||[]}getPreInitialState(t,n,s){const{context:r}=this.config,i=me({context:typeof r!="function"&&r?r:{},_nodes:[this.root],children:{},status:"active"},this);return typeof r=="function"?ne(i,n,t,[C(({spawn:a,event:c,self:u})=>r({spawn:a,input:c.input,self:u}))],s):i}getInitialSnapshot(t,n){const s=Ft(n),r=[],i=this.getPreInitialState(t,s,r),o=je([{target:[...Yt(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],i,t,s,!0,r),{snapshot:a}=Ce(o,s,t,r);return a}start(t){Object.values(t.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(t){const n=Qe(t),s=n.slice(1),r=xe(n[0])?n[0].slice(xs.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 _e(i,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,n){return fs(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"?Xe(this,l):l;if(!h)return;const m=B(h,{id:c,parent:n.self,syncSnapshot:u.syncSnapshot,snapshot:f,src:l,systemId:u.systemId});s[c]=m});const i=me({...t,children:s,_nodes:Array.from(Te(Ie(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===We){c[f]=u[l.id];continue}a(l,u)}}}}return a(i.context,s),i}}function As(e,t){return new rt(e,t)}function Ae({schemas:e,actors:t,actions:n,guards:s,delays:r}){return{createMachine:i=>As({...i,schemas:e},{actors:t,actions:n,guards:s,delays:r})}}async function De(e,t){const n=await fetch(e,t);return n.status===200?n.json():Promise.resolve({message:n.statusText,success:!1})}const $e=Ae({types:{context:{},events:{},input:{}},actions:{setUserContext:C(({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}}),unsetUserContext:C(()=>({user:null,accessToken:"",refreshToken:"",ignoreRefreshToken:!1})),setAccessToken:C(({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}}),unsetRefreshToken:C(()=>({refreshToken:""})),setIgnoreRefreshToken:C(()=>({ignoreRefreshToken:!0})),addError:C(({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: ","")]}}),clearErrors:C(()=>({errors:[]}))},actors:{refreshAccessToken:Z(async({input:e})=>{let t;if(typeof window>"u"){if(e.context.refreshToken==="")throw new Error("Unauthorized.");try{const s=await De(e.context.endpoints.ssrRefresh,{method:"POST",mode:"cors",credentials:"include",headers:{Cookie:`refresh_token=${e.context.refreshToken}`,"Content-Type":"application/json","clicktap-scope":"view","clicktap-scope-id":"default"}});if(typeof s.accessToken>"u")throw new Error("Unauthorized.");return{type:"REFRESH_TOKEN_SUCCESS",accessToken:s.accessToken}}catch(n){throw console.log(n),new Error("Could not complete refresh request (server)")}}else{t=await De(e.context.endpoints.refresh,{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()});const n=t;if(typeof n.accessToken>"u")throw new Error("Unauthorized.");return{type:"REFRESH_TOKEN_SUCCESS",accessToken:n.accessToken}}}),authenticate:Z(async({input:e})=>{var s;const n=await De(e.context.endpoints.login,{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(((s=n.message)==null?void 0:s.toString())??"Sign in failed. Please try again.");return{type:"AUTHENTICATE_SUCCESS",accessToken:n.accessToken}}),unauthenticate:Z(async({input:e})=>(await fetch(e.context.endpoints.logout,{method:"POST",mode:"cors",credentials:"include",headers:{"clicktap-scope":"view","clicktap-scope-id":"default"}}),{type:"UNAUTHENTICATE"}))}}).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})=>t.type!=="LOGIN"?{context:e,username:"",password:""}:{context:e,username:t.username,password:t.password},onDone:[{actions:"setUserContext",target:"loggedIn"}],onError:[{actions:"addError",target:"loggedOut"}]}},unauthenticating:{invoke:{src:"unauthenticate",input:({context:e})=>({context:e}),onDone:[{actions:"unsetUserContext",target:"loggedOut"}],onError:[{actions:["unsetUserContext","setIgnoreRefreshToken"],target:"loggedOut"}]}},refreshing:{invoke:{src:"refreshAccessToken",input:({context:e})=>({context:e}),onDone:[{actions:["unsetRefreshToken","setAccessToken"],target:"loggedIn"}],onError:[{actions:"unsetRefreshToken",target:"unauthenticating"}]}},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"}}}}}),it=P.createContext({}),ws=()=>{const e=P.useContext(it),[t,n]=P.useState(typeof window<"u"&&e.getSnapshot().value==="loggedIn");return P.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}},bs=async(e="",t={inspect:void 0,endpoints:{login:"",logout:"",refresh:"",ssrRefresh:""}})=>typeof window<"u"?(console.warn("App.getInitialProps::getAuth should not be run on the frontend. You are probably missing getServerSideProps in your page."),B($e,{inspect:t.inspect,input:{initialContext:{endpoints:t.endpoints}}}).start()):B($e,{input:{initialContext:{endpoints:t.endpoints,refreshToken:e}},inspect:t.inspect}).start();function Os({actor:e,children:t}){return Ye.jsx(it.Provider,{value:e,children:t})}let Ns=(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 en=Ae({actors:{tick:gs(({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:C(({context:e,event:t})=>t.type!=="TICK"?e:{elapsed:e.elapsed+e.interval})},PAUSE_TIMER:{target:"paused"}}},completed:{type:"final"}}}),ks=Ae({actors:{timer:en},types:{context:{},events:{},input:{}},actions:{addItem:C(({context:e,event:t})=>{if(t.type!=="ADD_ITEM")return e;const n=`notification-${Ns()}`,s=t.duration??e.duration,r=P.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:C(({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:{items:[],order:"desc",duration:0,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:At("timer",{type:"RESUME_TIMER"})},PAUSE_TIMER:{actions:At("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"}}}}}),ot=P.createContext({}),Cs=()=>P.useContext(ot);function Ds({children:e,actor:t}){return Ye.jsx(ot.Provider,{value:t,children:e})}function Rs({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="ADD_ITEMS_SUCCESS"?e:{...e.quote,...n.output.quote}}function Ls({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="REMOVE_ITEMS_SUCCESS"?e:{...e.quote,...n.output.quote}}function Ms({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}}}const at=JSON,Ps=e=>e.toUpperCase(),qs=e=>{const t={};return e.forEach((n,s)=>{t[s]=n}),t},Fs=(e,t,n)=>e.document?e:{document:e,variables:t,requestHeaders:n,signal:void 0},Us=(e,t,n)=>e.query?e:{query:e,variables:t,requestHeaders:n,signal:void 0},Bs=(e,t)=>e.documents?e:{documents:e,requestHeaders:t,signal:void 0},js=(e,t,...n)=>{const[s,r]=n;return e.document?e:{url:e,document:t,variables:s,requestHeaders:r,signal:void 0}};function ge(e,t){if(!!!e)throw new Error(t)}function $s(e){return typeof e=="object"&&e!==null}function Vs(e,t){if(!!!e)throw new Error(t??"Unexpected invariant triggered.")}const Hs=/\r\n|[\n\r]/g;function Ve(e,t){let n=0,s=1;for(const r of e.body.matchAll(Hs)){if(typeof r.index=="number"||Vs(!1),r.index>=t)break;n=r.index+r[0].length,s+=1}return{line:s,column:t+1-n}}function Gs(e){return tn(e.source,Ve(e.source,e.start))}function tn(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}
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ye=require("react/jsx-runtime"),P=require("react");function En(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 vn(){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 Tn(){const e=vn();if(e.__xstate__)return e.__xstate__}const _n=e=>{if(typeof window>"u")return;const t=Tn();t&&t.register(e)};class lt{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 Lt=".",In="",Mt="",Sn="#",xn="*",Pt="xstate.init",An="xstate.error",ce="xstate.stop";function wn(e,t){return{type:`xstate.after.${e}.${t}`}}function Ue(e,t){return{type:`xstate.done.state.${e}`,output:t}}function bn(e,t){return{type:`xstate.done.actor.${e}`,output:t}}function qt(e,t){return{type:`xstate.error.actor.${e}`,error:t}}function Ut(e){return{type:Pt,input:e}}function U(e){setTimeout(()=>{throw e})}const On=(()=>typeof Symbol=="function"&&Symbol.observable||"@@observable")();function ht(e,t){return`${e.sessionId}.${t}`}let Nn=0;function Cn(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,v,S=Math.random().toString(36).slice(2))=>{const A={source:h,target:m,event:y,delay:v,id:S,startedAt:Date.now()},R=ht(h,S);l._snapshot._scheduledEvents[R]=A;const D=a.setTimeout(()=>{delete o[R],delete l._snapshot._scheduledEvents[R],l._relay(h,m,y)},v);o[R]=D},cancel:(h,m)=>{const y=ht(h,m),v=o[y];delete o[y],delete l._snapshot._scheduledEvents[y],a.clearTimeout(v)},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 v;return(v=y.next)==null?void 0:v.call(y,m)})},l={_snapshot:{_scheduledEvents:((t==null?void 0:t.snapshot)&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${Nn++}`,_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:v,event:S,delay:A,id:R}=h[m];u.schedule(y,v,S,A,R)}},_clock:a,_logger:c};return l}function Ft(e,t){const n=ft(e),s=ft(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?Ft(n[r],s[r]):!1)}function Qe(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 ft(e){if(as(e))return e.value;if(typeof e!="string")return e;const t=Qe(e);return kn(t)}function kn(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 pt(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 Bt(e){return jt(e)?e:[e]}function F(e){return e===void 0?[]:Bt(e)}function Fe(e,t,n,s){return typeof e=="function"?e({context:t,event:n,self:s}):e}function jt(e){return Array.isArray(e)}function Dn(e){return e.type.startsWith("xstate.error.actor")}function X(e){return Bt(e).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function $t(e){if(!(e===void 0||e===In))return F(e)}function yt(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 mt(e,t){return`${t}.${e}`}function Xe(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 We=1;let C=function(e){return e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped",e}({});const Rn={clock:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},logger:console.log.bind(console),devTools:!1};class Ln{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 lt(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=C.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={...Rn,...n},{clock:r,logger:i,parent:o,syncSnapshot:a,id:c,systemId:u,inspect:f}=s;this.system=o?o.system:Cn(this,{clock:r,logger:i}),f&&!o&&this.system.inspect(yt(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){U(a)}break;case"done":for(const o of this.observers)try{(i=o.next)==null||i.call(o,t)}catch(a){U(a)}this._stopProcedure(),this._complete(),this._doneEvent=bn(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=yt(t,n,s);if(this._processingStatus!==C.Stopped)this.observers.add(r);else switch(this._snapshot.status){case"done":try{(i=r.complete)==null||i.call(r)}catch(o){U(o)}break;case"error":{const o=this._snapshot.error;if(!r.error)U(o);else try{r.error(o)}catch(a){U(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===C.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=C.Running;const t=Ut(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===ce&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===C.Stopped?this:(this.mailbox.clear(),this._processingStatus===C.NotStarted?(this._processingStatus=C.Stopped,this):(this.mailbox.enqueue({type:ce}),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){U(s)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||U(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){U(i)}}this.observers.clear(),n&&U(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,qt(this.id,t))}_stopProcedure(){return this._processingStatus!==C.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new lt(this._process.bind(this)),this._processingStatus=C.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==C.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:_n)(this)}toJSON(){return{xstate$$type:We,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[On](){return this}getSnapshot(){return this._snapshot}}function B(e,...[t]){return new Ln(e,t)}function Mn(e,t,n,s,{sendId:r}){const i=typeof r=="function"?r(n,s):r;return[t,i]}function Pn(e,t){e.defer(()=>{e.system.scheduler.cancel(e.self,t)})}function qn(e){function t(n,s){}return t.type="xstate.cancel",t.sendId=e,t.resolve=Mn,t.execute=Pn,t}function Un(e,t,n,s,{id:r,systemId:i,src:o,input:a,syncSnapshot:c}){const u=typeof o=="string"?Xe(t.machine,o):o,f=typeof r=="function"?r(n):r;let l;return u&&(l=B(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})),[G(t,{children:{...t.children,[f]:l}}),{id:r,actorRef:l}]}function Fn(e,{id:t,actorRef:n}){n&&e.defer(()=>{n._processingStatus!==C.Stopped&&n.start()})}function Bn(...[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=Un,i.execute=Fn,i}function jn(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]),[G(t,{children:a}),o]}function $n(e,t){if(t){if(e.system._unregister(t),t._processingStatus!==C.Running){e.stopChild(t);return}e.defer(()=>{e.stopChild(t)})}}function Vt(e){function t(n,s){}return t.type="xstate.stopChild",t.actorRef=e,t.resolve=jn,t.execute=$n,t}function Ke(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 Ke(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 Ze=e=>e.type==="atomic"||e.type==="final";function ee(e){return Object.values(e.states).filter(t=>t.type!=="history")}function de(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 Te(e){const t=new Set(e),n=Gt(t);for(const s of t)if(s.type==="compound"&&(!n.get(s)||!n.get(s).length))gt(s).forEach(r=>t.add(r));else if(s.type==="parallel"){for(const r of ee(s))if(r.type!=="history"&&!t.has(r)){const i=gt(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 Ht(e,t){const n=t.get(e);if(!n)return{};if(e.type==="compound"){const r=n[0];if(r){if(Ze(r))return r.key}else return{}}const s={};for(const r of n)s[r.key]=Ht(r,t);return s}function Gt(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 zt(e,t){const n=Te(t);return Ht(e,Gt(n))}function et(e,t){return t.type==="compound"?ee(t).some(n=>n.type==="final"&&e.has(n)):t.type==="parallel"?ee(t).every(n=>et(e,n)):t.type==="final"}const xe=e=>e[0]===Sn;function Vn(e,t){return e.transitions.get(t)||[...e.transitions.keys()].filter(s=>{if(s===xn)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 Hn(e){const t=e.config.after;if(!t)return[];const n=(r,i)=>{const o=wn(r,e.id),a=o.type;return e.entry.push(ms(o,{id:a,delay:r})),e.exit.push(qn(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 F(a).map(f=>({...f,event:u,delay:c}))}).map(r=>{const{delay:i}=r;return{...V(e,r.event,r),delay:i}})}function V(e,t,n){const s=$t(n.target),r=n.reenter??!1,i=Jn(e,s),o={...n,actions:F(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 Gn(e){const t=new Map;if(e.config.on)for(const n of Object.keys(e.config.on)){if(n===Mt)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const s=e.config.on[n];t.set(n,X(s).map(r=>V(e,n,r)))}if(e.config.onDone){const n=`xstate.done.state.${e.id}`;t.set(n,X(e.config.onDone).map(s=>V(e,n,s)))}for(const n of e.invoke){if(n.onDone){const s=`xstate.done.actor.${n.id}`;t.set(s,X(n.onDone).map(r=>V(e,s,r)))}if(n.onError){const s=`xstate.error.actor.${n.id}`;t.set(s,X(n.onError).map(r=>V(e,s,r)))}if(n.onSnapshot){const s=`xstate.snapshot.${n.id}`;t.set(s,X(n.onSnapshot).map(r=>V(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 zn(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"?[]:F(t.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...s,source:`#${e.id}`,target:n?[`#${n.id}`]:[]})};return s}function Jn(e,t){if(t!==void 0)return t.map(n=>{if(typeof n!="string")return n;if(xe(n))return e.machine.getStateNodeById(n);const s=n[0]===Lt;if(s&&!e.parent)return _e(e,n.slice(1));const r=s?e.key+n:n;if(e.parent)try{return _e(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 Jt(e){const t=$t(e.config.target);return t?{target:t.map(n=>typeof n=="string"?_e(e.parent,n):n)}:e.parent.initial}function H(e){return e.type==="history"}function gt(e){const t=Yt(e);for(const n of t)for(const s of de(n,e))t.add(s);return t}function Yt(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 ee(s))n(r)}}return n(e),t}function te(e,t){if(xe(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 _e(e,t){if(typeof t=="string"&&xe(t))try{return e.machine.getStateNodeById(t)}catch{}const n=Qe(t).slice();let s=e;for(;n.length;){const r=n.shift();if(!r.length)break;s=te(s,r)}return s}function Ie(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=>te(e,r)).filter(Boolean);return[e.machine.root,e].concat(s,n.reduce((r,i)=>{const o=te(e,i);if(!o)return r;const a=Ie(o,t[i]);return r.concat(a)},[]))}function Yn(e,t,n,s){const i=te(e,t).next(n,s);return!i||!i.length?e.next(n,s):i}function Qn(e,t,n,s){const r=Object.keys(t),i=te(e,r[0]),o=tt(i,t[r[0]],n,s);return!o||!o.length?e.next(n,s):o}function Xn(e,t,n,s){const r=[];for(const i of Object.keys(t)){const o=t[i];if(!o)continue;const a=te(e,i),c=tt(a,o,n,s);c&&r.push(...c)}return r.length?r:e.next(n,s)}function tt(e,t,n,s){return typeof t=="string"?Yn(e,t,n,s):Object.keys(t).length===1?Qn(e,t,n,s):Xn(e,t,n,s)}function Wn(e){return Object.keys(e.states).map(t=>e.states[t]).filter(t=>t.type==="history")}function j(e,t){let n=e;for(;n.parent&&n.parent!==t;)n=n.parent;return n.parent===t}function Kn(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 Qt(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(Kn(Be([r],t,n),Be([a],t,n)))if(j(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 Zn(e){const[t,...n]=e;for(const s of de(t,void 0))if(n.every(r=>j(r,s)))return s}function nt(e,t){if(!e.target)return[];const n=new Set;for(const s of e.target)if(H(s))if(t[s.id])for(const r of t[s.id])n.add(r);else for(const r of nt(Jt(s),t))n.add(r);else n.add(s);return[...n]}function Xt(e,t){const n=nt(e,t);if(!n)return;if(!e.reenter&&n.every(r=>r===e.source||j(r,e.source)))return e.source;const s=Zn(n.concat(e.source));if(s)return s;if(!e.reenter)return e.source.machine.root}function Be(e,t,n){var r;const s=new Set;for(const i of e)if((r=i.target)!=null&&r.length){const o=Xt(i,n);i.reenter&&i.source===o&&s.add(o);for(const a of t)j(a,o)&&s.add(a)}return[...s]}function es(e,t){if(e.length!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function je(e,t,n,s,r,i){if(!e.length)return t;const o=new Set(t._nodes);let a=t.historyValue;const c=Qt(e,o,a);let u=t;r||([u,a]=rs(u,s,n,c,o,a,i)),u=ne(u,s,n,c.flatMap(l=>l.actions),i),u=ns(u,s,n,c,o,i,a,r);const f=[...o];u.status==="done"&&(u=ne(u,s,n,f.sort((l,h)=>h.order-l.order).flatMap(l=>l.exit),i));try{return a===t.historyValue&&es(t._nodes,o)?u:G(u,{_nodes:f,historyValue:a})}catch(l){throw l}}function ts(e,t,n,s,r){if(s.output===void 0)return;const i=Ue(r.id,r.output!==void 0&&r.parent?Fe(r.output,e.context,t,n.self):void 0);return Fe(s.output,e.context,i,n.self)}function ns(e,t,n,s,r,i,o,a){let c=e;const u=new Set,f=new Set;ss(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(Bn(y.src,{...y,syncSnapshot:!!y.onSnapshot}));if(f.has(h)){const y=h.initial.actions;m.push(...y)}if(c=ne(c,t,n,m,i,h.invoke.map(y=>y.id)),h.type==="final"){const y=h.parent;let v=(y==null?void 0:y.type)==="parallel"?y:y==null?void 0:y.parent,S=v||h;for((y==null?void 0:y.type)==="compound"&&i.push(Ue(y.id,h.output!==void 0?Fe(h.output,c.context,t,n.self):void 0));(v==null?void 0:v.type)==="parallel"&&!l.has(v)&&et(r,v);)l.add(v),i.push(Ue(v.id)),S=v,v=v.parent;if(v)continue;c=G(c,{status:"done",output:ts(c,t,n,c.machine.root,S)})}}return c}function ss(e,t,n,s){for(const r of e){const i=Xt(r,t);for(const a of r.target||[])!H(a)&&(r.source!==a||r.source!==i||r.reenter)&&(s.add(a),n.add(a)),W(a,t,n,s);const o=nt(r,t);for(const a of o){const c=de(a,i);(i==null?void 0:i.type)==="parallel"&&c.push(i),Wt(s,t,n,c,!r.source.parent&&r.reenter?void 0:i)}}}function W(e,t,n,s){var r;if(H(e))if(t[e.id]){const i=t[e.id];for(const o of i)s.add(o),W(o,t,n,s);for(const o of i)Ce(o,e.parent,s,t,n)}else{const i=Jt(e);for(const o of i.target)s.add(o),i===((r=e.parent)==null?void 0:r.initial)&&n.add(e.parent),W(o,t,n,s);for(const o of i.target)Ce(o,e.parent,s,t,n)}else if(e.type==="compound"){const[i]=e.initial.target;H(i)||(s.add(i),n.add(i)),W(i,t,n,s),Ce(i,e,s,t,n)}else if(e.type==="parallel")for(const i of ee(e).filter(o=>!H(o)))[...s].some(o=>j(o,i))||(H(i)||(s.add(i),n.add(i)),W(i,t,n,s))}function Wt(e,t,n,s,r){for(const i of s)if((!r||j(i,r))&&e.add(i),i.type==="parallel")for(const o of ee(i).filter(a=>!H(a)))[...e].some(a=>j(a,o))||(e.add(o),W(o,t,n,e))}function Ce(e,t,n,s,r){Wt(n,s,r,de(e,t))}function rs(e,t,n,s,r,i,o){let a=e;const c=Be(s,r,i);c.sort((f,l)=>l.order-f.order);let u;for(const f of c)for(const l of Wn(f)){let h;l.history==="deep"?h=m=>Ze(m)&&j(m,f):h=m=>m.parent===f,u??(u={...i}),u[l.id]=Array.from(r).filter(h)}for(const f of c)a=ne(a,t,n,[...f.exit,...f.invoke.map(l=>Vt(l.id))],o),r.delete(f);return[a,u||i]}let Et=!1;function Kt(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{Et=f,f(l,h)}finally{Et=!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===C.Running?m():n.defer(()=>{m()});continue}const y=f,[v,S,A]=y.resolve(n,a,l,h,f,r);a=v,"retryResolve"in y&&(i==null||i.push([y,S])),"execute"in y&&(n.self._processingStatus===C.Running?y.execute(n,S):n.defer(y.execute.bind(null,n,S))),A&&(a=Kt(a,t,n,A,r,i))}return a}function ne(e,t,n,s,r,i){const o=i?[]:void 0,a=Kt(e,t,n,s,{internalQueue:r,deferredActorIds:i},o);return o==null||o.forEach(([c,u])=>{c.retryResolve(n,a,u)}),a}function ke(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===ce)return r=G(vt(r,t,n),{status:"stopped"}),o(r,t,[]),{snapshot:r,microstates:i};let a=t;if(a.type!==Pt){const u=a,f=Dn(u),l=Tt(u,r);if(f&&!l.length)return r=G(e,{status:"error",error:u.error}),o(r,u,[]),{snapshot:r,microstates:i};r=je(l,e,n,a,!1,s),o(r,u,l)}let c=!0;for(;r.status==="active";){let u=c?is(r,a):[];const f=u.length?r:void 0;if(!u.length){if(!s.length)break;a=s.shift(),u=Tt(a,r)}r=je(u,r,n,a,!1,s),c=r!==f,o(r,a,u)}return r.status!=="active"&&vt(r,a,n),{snapshot:r,microstates:i}}function vt(e,t,n){return ne(e,t,n,Object.values(e.children).map(s=>Vt(s)),[])}function Tt(e,t){return t.machine.getTransitionData(t,e)}function is(e,t){const n=new Set,s=e._nodes.filter(Ze);for(const r of s)e:for(const i of[r].concat(de(r,void 0)))if(i.always){for(const o of i.always)if(o.guard===void 0||Ke(o.guard,e.context,t,e)){n.add(o);break e}}return Qt(Array.from(n),new Set(e._nodes),e.historyValue)}function os(e,t){const n=Te(Ie(e,t));return zt(e,[...n])}function as(e){return!!e&&typeof e=="object"&&"machine"in e&&"value"in e}const cs=function(t){return Ft(t,this.value)},us=function(t){return this.tags.has(t)},ds=function(t){const n=this.machine.getTransitionData(this,t);return!!(n!=null&&n.length)&&n.some(s=>s.target!==void 0||s.actions.length)},ls=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)}},hs=function(){return this._nodes.reduce((t,n)=>(n.meta!==void 0&&(t[n.id]=n.meta),t),{})};function me(e,t){return{status:e.status,output:e.output,error:e.error,machine:t,context:e.context,_nodes:e._nodes,value:zt(t.root,e._nodes),tags:new Set(e._nodes.flatMap(n=>n.tags)),children:e.children,historyValue:e.historyValue||{},matches:cs,hasTag:us,can:ds,getMeta:hs,toJSON:ls}}function G(e,t={}){return me({...e,...t},e.machine)}function fs(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 v in i){const S=i[v];m[v]={snapshot:S.getPersistedSnapshot(t),src:S.src,systemId:S._systemId,syncSnapshot:S._syncSnapshot}}return{...h,context:Zt(o),children:m}}function Zt(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:We,id:s.id};else{const r=Zt(s);r!==s&&(t??(t=Array.isArray(e)?e.slice():{...e}),t[n]=r)}}return t??e}function ps(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 ys(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 ms(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=ps,n.execute=ys,n}const _t=new WeakMap;function gs(e){return{config:e,start:(n,s)=>{const{self:r,system:i}=s,o={receivers:void 0,dispose:void 0};_t.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=_t.get(r.self);return s.type===ce?(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 It="xstate.promise.resolve",St="xstate.promise.reject",pe=new WeakMap;function Z(e){return{config:e,transition:(n,s,r)=>{var i;if(n.status!=="active")return n;switch(s.type){case It:{const o=s.data;return{...n,status:"done",output:o,input:void 0}}case St:return{...n,status:"error",error:s.data,input:void 0};case ce:return(i=pe.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;pe.set(s,i),Promise.resolve(e({input:n.input,system:r,self:s,signal:i.signal})).then(a=>{s.getSnapshot().status==="active"&&(pe.delete(s),r._relay(s,s,{type:It,data:a}))},a=>{s.getSnapshot().status==="active"&&(pe.delete(s),r._relay(s,s,{type:St,data:a}))})},getInitialSnapshot:(n,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedSnapshot:n=>n,restoreSnapshot:n=>n}}function Es(e,{machine:t,context:n},s,r){const i=(o,a={})=>{const{systemId:c,input:u}=a;if(typeof o=="string"){const f=Xe(t,o);if(!f)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const l=B(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 B(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!==C.Stopped&&c.start()}),c}}function vs(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:Es(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[G(t,{context:c,children:Object.keys(i).length?{...t.children,...i}:t.children})]}function k(e){function t(n,s){}return t.type="xstate.assign",t.assignment=e,t.resolve=vs,t}let xt=function(e){return e.Parent="#_parent",e.Internal="#_internal",e}({});function Ts(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 v=u&&u[a];l=typeof v=="function"?v(n,s):v}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===xt.Parent?m=e.self._parent:h===xt.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 _s(e,t,n){typeof n.to=="string"&&(n.to=t.children[n.to])}function Is(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===An?qt(e.self.id,s.data):s)})}function At(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=Ts,s.retryResolve=_s,s.execute=Is,s}const wt=new WeakMap;function Y(e,t,n){let s=wt.get(e);return s?t in s||(s[t]=n()):(s={[t]:n()},wt.set(e,s)),s[t]}const Ss={},ie=e=>typeof e=="string"?{type:e}:typeof e=="function"?"resolve"in e?{type:e.type}:{type:e.name}:e;class st{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(Lt),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?pt(this.config.states,(s,r)=>new st(s,{_parent:this,_key:r,_machine:this.machine})):Ss,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=F(this.config.entry).slice(),this.exit=F(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=F(t.tags).slice()}_initialize(){this.transitions=Gn(this),this.config.always&&(this.always=X(this.config.always).map(t=>V(this,Mt,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(ie),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(ie),eventType:null})}:void 0,history:this.history,states:pt(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(ie)})),entry:this.entry.map(ie),exit:this.exit.map(ie),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 Y(this,"invoke",()=>F(this.config.invoke).map((t,n)=>{const{src:s,systemId:r}=t,i=t.id??mt(this.id,n),o=typeof s=="string"?s:`xstate.invoke.${mt(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 Y(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 Y(this,"delayedTransitions",()=>Hn(this))}get initial(){return Y(this,"initial",()=>zn(this,this.config.initial))}next(t,n){const s=n.type,r=[];let i;const o=Y(this,`candidates-${s}`,()=>Vn(this,s));for(const a of o){const{guard:c}=a,u=t.context;let f=!1;try{f=!c||Ke(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 Y(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 xs="#";class rt{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 st(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 rt(this.config,{actions:{...n,...t.actions},guards:{...s,...t.guards},actors:{...r,...t.actors},delays:{...i,...t.delays}})}resolveState(t){const n=os(this.root,t.value),s=Te(Ie(this.root,n));return me({_nodes:[...s],context:t.context||{},children:{},status:et(s,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,n,s){return ke(t,n,s).snapshot}microstep(t,n,s){return ke(t,n,s).microstates}getTransitionData(t,n){return tt(this.root,t.value,t,n)||[]}getPreInitialState(t,n,s){const{context:r}=this.config,i=me({context:typeof r!="function"&&r?r:{},_nodes:[this.root],children:{},status:"active"},this);return typeof r=="function"?ne(i,n,t,[k(({spawn:a,event:c,self:u})=>r({spawn:a,input:c.input,self:u}))],s):i}getInitialSnapshot(t,n){const s=Ut(n),r=[],i=this.getPreInitialState(t,s,r),o=je([{target:[...Yt(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],i,t,s,!0,r),{snapshot:a}=ke(o,s,t,r);return a}start(t){Object.values(t.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(t){const n=Qe(t),s=n.slice(1),r=xe(n[0])?n[0].slice(xs.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 _e(i,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,n){return fs(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"?Xe(this,l):l;if(!h)return;const m=B(h,{id:c,parent:n.self,syncSnapshot:u.syncSnapshot,snapshot:f,src:l,systemId:u.systemId});s[c]=m});const i=me({...t,children:s,_nodes:Array.from(Te(Ie(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===We){c[f]=u[l.id];continue}a(l,u)}}}}return a(i.context,s),i}}function As(e,t){return new rt(e,t)}function Ae({schemas:e,actors:t,actions:n,guards:s,delays:r}){return{createMachine:i=>As({...i,schemas:e},{actors:t,actions:n,guards:s,delays:r})}}async function De(e,t){const n=await fetch(e,t);return n.status===200?n.json():Promise.resolve({message:n.statusText,success:!1})}const $e=Ae({types:{context:{},events:{},input:{}},actions:{setUserContext:k(({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}}),unsetUserContext:k(()=>({user:null,accessToken:"",refreshToken:"",ignoreRefreshToken:!1})),setAccessToken:k(({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}}),unsetRefreshToken:k(()=>({refreshToken:""})),setIgnoreRefreshToken:k(()=>({ignoreRefreshToken:!0})),addError:k(({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: ","")]}}),clearErrors:k(()=>({errors:[]}))},actors:{refreshAccessToken:Z(async({input:e})=>{let t;if(typeof window>"u"){if(e.context.refreshToken==="")throw new Error("Unauthorized.");try{const s=await De(e.context.endpoints.ssrRefresh,{method:"POST",mode:"cors",credentials:"include",headers:{Cookie:`refresh_token=${e.context.refreshToken}`,"Content-Type":"application/json","clicktap-scope":"view","clicktap-scope-id":"default"}});if(typeof s.accessToken>"u")throw new Error("Unauthorized.");return{type:"REFRESH_TOKEN_SUCCESS",accessToken:s.accessToken}}catch(n){throw console.log(n),new Error("Could not complete refresh request (server)")}}else{t=await De(e.context.endpoints.refresh,{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()});const n=t;if(typeof n.accessToken>"u")throw new Error("Unauthorized.");return{type:"REFRESH_TOKEN_SUCCESS",accessToken:n.accessToken}}}),authenticate:Z(async({input:e})=>{var s;const n=await De(e.context.endpoints.login,{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(((s=n.message)==null?void 0:s.toString())??"Sign in failed. Please try again.");return{type:"AUTHENTICATE_SUCCESS",accessToken:n.accessToken}}),unauthenticate:Z(async({input:e})=>(await fetch(e.context.endpoints.logout,{method:"POST",mode:"cors",credentials:"include",headers:{"clicktap-scope":"view","clicktap-scope-id":"default"}}),{type:"UNAUTHENTICATE"}))}}).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})=>t.type!=="LOGIN"?{context:e,username:"",password:""}:{context:e,username:t.username,password:t.password},onDone:[{actions:"setUserContext",target:"loggedIn"}],onError:[{actions:"addError",target:"loggedOut"}]}},unauthenticating:{invoke:{src:"unauthenticate",input:({context:e})=>({context:e}),onDone:[{actions:"unsetUserContext",target:"loggedOut"}],onError:[{actions:["unsetUserContext","setIgnoreRefreshToken"],target:"loggedOut"}]}},refreshing:{invoke:{src:"refreshAccessToken",input:({context:e})=>({context:e}),onDone:[{actions:["unsetRefreshToken","setAccessToken"],target:"loggedIn"}],onError:[{actions:"unsetRefreshToken",target:"unauthenticating"}]}},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"}}}}}),it=P.createContext({}),ws=()=>{const e=P.useContext(it),[t,n]=P.useState(typeof window<"u"&&e.getSnapshot().value==="loggedIn");return P.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}},bs=async(e="",t={inspect:void 0,endpoints:{login:"",logout:"",refresh:"",ssrRefresh:""}})=>typeof window<"u"?(console.warn("App.getInitialProps::getAuth should not be run on the frontend. You are probably missing getServerSideProps in your page."),B($e,{inspect:t.inspect,input:{initialContext:{endpoints:t.endpoints}}}).start()):B($e,{input:{initialContext:{endpoints:t.endpoints,refreshToken:e}},inspect:t.inspect}).start();function Os({actor:e,children:t}){return Ye.jsx(it.Provider,{value:e,children:t})}let Ns=(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 en=Ae({actors:{tick:gs(({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:k(({context:e,event:t})=>t.type!=="TICK"?e:{elapsed:e.elapsed+e.interval})},PAUSE_TIMER:{target:"paused"}}},completed:{type:"final"}}}),Cs=Ae({actors:{timer:en},types:{context:{},events:{},input:{}},actions:{addItem:k(({context:e,event:t})=>{if(t.type!=="ADD_ITEM")return e;const n=`notification-${Ns()}`,s=t.duration??e.duration,r=P.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:k(({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:{items:[],order:"desc",duration:0,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:At("timer",{type:"RESUME_TIMER"})},PAUSE_TIMER:{actions:At("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"}}}}}),ot=P.createContext({}),ks=()=>P.useContext(ot);function Ds({children:e,actor:t}){return Ye.jsx(ot.Provider,{value:t,children:e})}function Rs({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="ADD_ITEMS_SUCCESS"?e:{...e.quote,...n.output.quote}}function Ls({context:e,event:t}){if(!t.type.includes("xstate.done.actor"))return e;const n=t;return n.output.type!=="REMOVE_ITEMS_SUCCESS"?e:{...e.quote,...n.output.quote}}function Ms({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}}}const at=JSON,Ps=e=>e.toUpperCase(),qs=e=>{const t={};return e.forEach((n,s)=>{t[s]=n}),t},Us=(e,t,n)=>e.document?e:{document:e,variables:t,requestHeaders:n,signal:void 0},Fs=(e,t,n)=>e.query?e:{query:e,variables:t,requestHeaders:n,signal:void 0},Bs=(e,t)=>e.documents?e:{documents:e,requestHeaders:t,signal:void 0},js=(e,t,...n)=>{const[s,r]=n;return e.document?e:{url:e,document:t,variables:s,requestHeaders:r,signal:void 0}};function ge(e,t){if(!!!e)throw new Error(t)}function $s(e){return typeof e=="object"&&e!==null}function Vs(e,t){if(!!!e)throw new Error(t??"Unexpected invariant triggered.")}const Hs=/\r\n|[\n\r]/g;function Ve(e,t){let n=0,s=1;for(const r of e.body.matchAll(Hs)){if(typeof r.index=="number"||Vs(!1),r.index>=t)break;n=r.index+r[0].length,s+=1}return{line:s,column:t+1-n}}function Gs(e){return tn(e.source,Ve(e.source,e.start))}function tn(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
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 v=0;v<l.length;v+=80)y.push(l.slice(v,v+80));return u+bt([[`${o} |`,y[0]],...y.slice(1,h+1).map(v=>["|",v]),["|","^".padStart(m)],["|",y[h+1]]])}return u+bt([[`${o-1} |`,f[r-1]],[`${o} |`,l],["|","^".padStart(c)],[`${o+1} |`,f[r+1]]])}function bt(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
5
  `)}function zs(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 ct extends Error{constructor(t,...n){var s,r,i;const{nodes:o,source:a,positions:c,path:u,originalError:f,extensions:l}=zs(n);super(t),this.name="GraphQLError",this.path=u??void 0,this.originalError=f??void 0,this.nodes=Ot(Array.isArray(o)?o:o?[o]:void 0);const h=Ot((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=>Ve(a,y)):h==null?void 0:h.map(y=>Ve(y.source,y.start));const m=$s(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,ct):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
 
@@ -8,7 +8,7 @@ ${l.message}`)}if(f){r.push(...a.actions),i=a;break}}return i?[i]:void 0}get eve
8
8
 
9
9
  `+tn(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 Ot(e){return e===void 0||e.length===0?void 0:e}function b(e,t,n){return new ct(`Syntax Error: ${n}`,{source:e,positions:[t]})}class Js{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 nn{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 sn={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"]},Ys=new Set(Object.keys(sn));function Nt(e){const t=e==null?void 0:e.kind;return typeof t=="string"&&Ys.has(t)}var K;(function(e){e.QUERY="query",e.MUTATION="mutation",e.SUBSCRIPTION="subscription"})(K||(K={}));var He;(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"})(He||(He={}));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 Ge(e){return e===9||e===32}function ue(e){return e>=48&&e<=57}function rn(e){return e>=97&&e<=122||e>=65&&e<=90}function on(e){return rn(e)||e===95}function Qs(e){return rn(e)||ue(e)||e===95}function Xs(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=Ws(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 Ws(e){let t=0;for(;t<e.length&&Ge(e.charCodeAt(t));)++t;return t}function Ks(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||Ge(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&&Ge(e.charCodeAt(0));return(f&&!h||i)&&(l+=`
10
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 Zs{constructor(t){const n=new nn(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=tr(this,t.end);t.next=n,n.prev=t,t=n}while(t.kind===p.COMMENT);return t}}function er(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 se(e){return e>=0&&e<=55295||e>=57344&&e<=1114111}function we(e,t){return an(e.charCodeAt(t))&&cn(e.charCodeAt(t+1))}function an(e){return e>=55296&&e<=56319}function cn(e){return e>=56320&&e<=57343}function z(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 w(e,t,n,s,r){const i=e.line,o=1+n-e.lineStart;return new nn(t,n,s,i,o,r)}function tr(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 nr(e,r);case 33:return w(e,p.BANG,r,r+1);case 36:return w(e,p.DOLLAR,r,r+1);case 38:return w(e,p.AMP,r,r+1);case 40:return w(e,p.PAREN_L,r,r+1);case 41:return w(e,p.PAREN_R,r,r+1);case 46:if(n.charCodeAt(r+1)===46&&n.charCodeAt(r+2)===46)return w(e,p.SPREAD,r,r+3);break;case 58:return w(e,p.COLON,r,r+1);case 61:return w(e,p.EQUALS,r,r+1);case 64:return w(e,p.AT,r,r+1);case 91:return w(e,p.BRACKET_L,r,r+1);case 93:return w(e,p.BRACKET_R,r,r+1);case 123:return w(e,p.BRACE_L,r,r+1);case 124:return w(e,p.PIPE,r,r+1);case 125:return w(e,p.BRACE_R,r,r+1);case 34:return n.charCodeAt(r+1)===34&&n.charCodeAt(r+2)===34?cr(e,r):rr(e,r)}if(ue(i)||i===45)return sr(e,r,i);if(on(i))return ur(e,r);throw b(e.source,r,i===39?`Unexpected single quote character ('), did you mean to use a double quote (")?`:se(i)||we(n,r)?`Unexpected character: ${z(e,r)}.`:`Invalid character: ${z(e,r)}.`)}return w(e,p.EOF,s,s)}function nr(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(se(i))++r;else if(we(n,r))r+=2;else break}return w(e,p.COMMENT,t,r,n.slice(t+1,r))}function sr(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),ue(i))throw b(e.source,r,`Invalid number, unexpected digit after 0: ${z(e,r)}.`)}else r=Re(e,r,i),i=s.charCodeAt(r);if(i===46&&(o=!0,i=s.charCodeAt(++r),r=Re(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=Re(e,r,i),i=s.charCodeAt(r)),i===46||on(i))throw b(e.source,r,`Invalid number, expected digit but got: ${z(e,r)}.`);return w(e,o?p.FLOAT:p.INT,t,r,s.slice(t,r))}function Re(e,t,n){if(!ue(n))throw b(e.source,t,`Invalid number, expected digit but got: ${z(e,t)}.`);const s=e.source.body;let r=t+1;for(;ue(s.charCodeAt(r));)++r;return r}function rr(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),w(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?ir(e,r):or(e,r):ar(e,r);o+=c.value,r+=c.size,i=r;continue}if(a===10||a===13)break;if(se(a))++r;else if(we(n,r))r+=2;else throw b(e.source,r,`Invalid character within String: ${z(e,r)}.`)}throw b(e.source,r,"Unterminated string.")}function ir(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||!se(s))break;return{value:String.fromCodePoint(s),size:r}}if(s=s<<4|oe(i),s<0)break}throw b(e.source,t,`Invalid Unicode escape sequence: "${n.slice(t,t+r)}".`)}function or(e,t){const n=e.source.body,s=kt(n,t+2);if(se(s))return{value:String.fromCodePoint(s),size:6};if(an(s)&&n.charCodeAt(t+6)===92&&n.charCodeAt(t+7)===117){const r=kt(n,t+8);if(cn(r))return{value:String.fromCodePoint(s,r),size:12}}throw b(e.source,t,`Invalid Unicode escape sequence: "${n.slice(t,t+6)}".`)}function kt(e,t){return oe(e.charCodeAt(t))<<12|oe(e.charCodeAt(t+1))<<8|oe(e.charCodeAt(t+2))<<4|oe(e.charCodeAt(t+3))}function oe(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:-1}function ar(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:`
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 Zs{constructor(t){const n=new nn(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=tr(this,t.end);t.next=n,n.prev=t,t=n}while(t.kind===p.COMMENT);return t}}function er(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 se(e){return e>=0&&e<=55295||e>=57344&&e<=1114111}function we(e,t){return an(e.charCodeAt(t))&&cn(e.charCodeAt(t+1))}function an(e){return e>=55296&&e<=56319}function cn(e){return e>=56320&&e<=57343}function z(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 w(e,t,n,s,r){const i=e.line,o=1+n-e.lineStart;return new nn(t,n,s,i,o,r)}function tr(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 nr(e,r);case 33:return w(e,p.BANG,r,r+1);case 36:return w(e,p.DOLLAR,r,r+1);case 38:return w(e,p.AMP,r,r+1);case 40:return w(e,p.PAREN_L,r,r+1);case 41:return w(e,p.PAREN_R,r,r+1);case 46:if(n.charCodeAt(r+1)===46&&n.charCodeAt(r+2)===46)return w(e,p.SPREAD,r,r+3);break;case 58:return w(e,p.COLON,r,r+1);case 61:return w(e,p.EQUALS,r,r+1);case 64:return w(e,p.AT,r,r+1);case 91:return w(e,p.BRACKET_L,r,r+1);case 93:return w(e,p.BRACKET_R,r,r+1);case 123:return w(e,p.BRACE_L,r,r+1);case 124:return w(e,p.PIPE,r,r+1);case 125:return w(e,p.BRACE_R,r,r+1);case 34:return n.charCodeAt(r+1)===34&&n.charCodeAt(r+2)===34?cr(e,r):rr(e,r)}if(ue(i)||i===45)return sr(e,r,i);if(on(i))return ur(e,r);throw b(e.source,r,i===39?`Unexpected single quote character ('), did you mean to use a double quote (")?`:se(i)||we(n,r)?`Unexpected character: ${z(e,r)}.`:`Invalid character: ${z(e,r)}.`)}return w(e,p.EOF,s,s)}function nr(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(se(i))++r;else if(we(n,r))r+=2;else break}return w(e,p.COMMENT,t,r,n.slice(t+1,r))}function sr(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),ue(i))throw b(e.source,r,`Invalid number, unexpected digit after 0: ${z(e,r)}.`)}else r=Re(e,r,i),i=s.charCodeAt(r);if(i===46&&(o=!0,i=s.charCodeAt(++r),r=Re(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=Re(e,r,i),i=s.charCodeAt(r)),i===46||on(i))throw b(e.source,r,`Invalid number, expected digit but got: ${z(e,r)}.`);return w(e,o?p.FLOAT:p.INT,t,r,s.slice(t,r))}function Re(e,t,n){if(!ue(n))throw b(e.source,t,`Invalid number, expected digit but got: ${z(e,t)}.`);const s=e.source.body;let r=t+1;for(;ue(s.charCodeAt(r));)++r;return r}function rr(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),w(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?ir(e,r):or(e,r):ar(e,r);o+=c.value,r+=c.size,i=r;continue}if(a===10||a===13)break;if(se(a))++r;else if(we(n,r))r+=2;else throw b(e.source,r,`Invalid character within String: ${z(e,r)}.`)}throw b(e.source,r,"Unterminated string.")}function ir(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||!se(s))break;return{value:String.fromCodePoint(s),size:r}}if(s=s<<4|oe(i),s<0)break}throw b(e.source,t,`Invalid Unicode escape sequence: "${n.slice(t,t+r)}".`)}function or(e,t){const n=e.source.body,s=Ct(n,t+2);if(se(s))return{value:String.fromCodePoint(s),size:6};if(an(s)&&n.charCodeAt(t+6)===92&&n.charCodeAt(t+7)===117){const r=Ct(n,t+8);if(cn(r))return{value:String.fromCodePoint(s,r),size:12}}throw b(e.source,t,`Invalid Unicode escape sequence: "${n.slice(t,t+6)}".`)}function Ct(e,t){return oe(e.charCodeAt(t))<<12|oe(e.charCodeAt(t+1))<<8|oe(e.charCodeAt(t+2))<<4|oe(e.charCodeAt(t+3))}function oe(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:-1}function ar(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
12
  `,size:2};case 114:return{value:"\r",size:2};case 116:return{value:" ",size:2}}throw b(e.source,t,`Invalid character escape sequence: "${n.slice(t,t+2)}".`)}function cr(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=w(e,p.BLOCK_STRING,t,i+3,Xs(c).join(`
13
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(se(u))++i;else if(we(n,i))i+=2;else throw b(e.source,i,`Invalid character within String: ${z(e,i)}.`)}throw b(e.source,i,"Unterminated string.")}function ur(e,t){const n=e.source.body,s=n.length;let r=t+1;for(;r<s;){const i=n.charCodeAt(r);if(Qs(i))++r;else break}return w(e,p.NAME,t,r,n.slice(t,r))}const dr=10,un=2;function ut(e){return be(e,[])}function be(e,t){switch(typeof e){case"string":return JSON.stringify(e);case"function":return e.name?`[function ${e.name}]`:"[function]";case"object":return lr(e,t);default:return String(e)}}function lr(e,t){if(e===null)return"null";if(t.includes(e))return"[Circular]";const n=[...t,e];if(hr(e)){const s=e.toJSON();if(s!==e)return typeof s=="string"?s:be(s,n)}else if(Array.isArray(e))return pr(e,n);return fr(e,n)}function hr(e){return typeof e.toJSON=="function"}function fr(e,t){const n=Object.entries(e);return n.length===0?"{}":t.length>un?"["+yr(e)+"]":"{ "+n.map(([r,i])=>r+": "+be(i,t)).join(", ")+" }"}function pr(e,t){if(e.length===0)return"[]";if(t.length>un)return"[Array]";const n=Math.min(dr,e.length),s=e.length-n,r=[];for(let i=0;i<n;++i)r.push(be(e[i],t));return s===1?r.push("... 1 more item"):s>1&&r.push(`... ${s} more items`),"["+r.join(", ")+"]"}function yr(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 mr=globalThis.process&&globalThis.process.env.NODE_ENV==="production"?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=ut(t);throw new Error(`Cannot use ${r} "${o}" from another module or realm.
14
14
 
@@ -30,7 +30,7 @@ spurious results.`)}}return!1};class dn{constructor(t,n="GraphQL request",s={lin
30
30
  `)+E(["schema",E(t," "),M(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," "),M(r)]," ")},FieldDefinition:{leave:({description:e,name:t,arguments:n,type:s,directives:r})=>I("",e,`
33
- `)+t+(Ct(n)?I(`(
33
+ `)+t+(kt(n)?I(`(
34
34
  `,Ee(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,`
@@ -40,12 +40,12 @@ spurious results.`)}}return!1};class dn{constructor(t,n="GraphQL request",s={lin
40
40
  `)+E(["enum",t,E(n," "),M(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," "),M(s)]," ")},DirectiveDefinition:{leave:({description:e,name:t,arguments:n,repeatable:s,locations:r})=>I("",e,`
43
- `)+"directive @"+t+(Ct(n)?I(`(
43
+ `)+"directive @"+t+(kt(n)?I(`(
44
44
  `,Ee(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," "),M(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," "),M(s)]," ")},InterfaceTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:s})=>E(["extend interface",e,I("implements ",E(t," & ")),E(n," "),M(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," "),M(n)]," ")},InputObjectTypeExtension:{leave:({name:e,directives:t,fields:n})=>E(["extend input",e,E(t," "),M(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 M(e){return I(`{
47
47
  `,Ee(E(e,`
48
48
  `)),`
49
49
  }`)}function I(e,t,n=""){return t!=null&&t!==""?e+t+n:""}function Ee(e){return I(" ",e.replace(/\n/g,`
50
- `))}function Ct(e){var t;return(t=e==null?void 0:e.some(n=>n.includes(`
51
- `)))!==null&&t!==void 0?t:!1}const Dt=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},Le=e=>{if(typeof e=="string"){let n;try{const s=Er(e);n=Dt(s)}catch{}return{query:e,operationName:n}}const t=Dt(e);return{query:hn(e),operationName:t}};class ae extends Error{constructor(t,n){const s=`${ae.extractMessage(t)}: ${JSON.stringify({response:t,request:n})}`;super(s),Object.setPrototypeOf(this,ae.prototype),this.response=t,this.request=n,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,ae)}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 Nr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function kr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ze={exports:{}};(function(e,t){var n=typeof self<"u"?self:Nr,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 _=d.shift();return{done:_===void 0,value:_}}};return a.iterable&&(g[Symbol.iterator]=function(){return g}),g}function y(d){this.map={},d instanceof y?d.forEach(function(g,_){this.append(_,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 _=this.map[d];this.map[d]=_?_+", "+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 _ in this.map)this.map.hasOwnProperty(_)&&d.call(g,this.map[_],_,this)},y.prototype.keys=function(){var d=[];return this.forEach(function(g,_){d.push(_)}),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,_){d.push([_,g])}),m(d)},a.iterable&&(y.prototype[Symbol.iterator]=y.prototype.entries);function v(d){if(d.bodyUsed)return Promise.reject(new TypeError("Already read"));d.bodyUsed=!0}function S(d){return new Promise(function(g,_){d.onload=function(){g(d.result)},d.onerror=function(){_(d.error)}})}function A(d){var g=new FileReader,_=S(g);return g.readAsArrayBuffer(d),_}function R(d){var g=new FileReader,_=S(g);return g.readAsText(d),_}function D(d){for(var g=new Uint8Array(d),_=new Array(g.length),N=0;N<g.length;N++)_[N]=String.fromCharCode(g[N]);return _.join("")}function L(d){if(d.slice)return d.slice(0);var g=new Uint8Array(d.byteLength);return g.set(new Uint8Array(d)),g.buffer}function J(){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=L(d.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(d)||f(d))?this._bodyArrayBuffer=L(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=v(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?v(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(A)}),this.text=function(){var d=v(this);if(d)return d;if(this._bodyBlob)return R(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(yn)}),this.json=function(){return this.text().then(JSON.parse)},this}var le=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function he(d){var g=d.toUpperCase();return le.indexOf(g)>-1?g:d}function $(d,g){g=g||{};var _=g.body;if(d instanceof $){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,!_&&d._bodyInit!=null&&(_=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=he(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")&&_)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(_)}$.prototype.clone=function(){return new $(this,{body:this._bodyInit})};function yn(d){var g=new FormData;return d.trim().split("&").forEach(function(_){if(_){var N=_.split("="),O=N.shift().replace(/\+/g," "),x=N.join("=").replace(/\+/g," ");g.append(decodeURIComponent(O),decodeURIComponent(x))}}),g}function mn(d){var g=new y,_=d.replace(/\r?\n[\t ]+/g," ");return _.split(/\r?\n/).forEach(function(N){var O=N.split(":"),x=O.shift().trim();if(x){var fe=O.join(":").trim();g.append(x,fe)}}),g}J.call($.prototype);function q(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)}J.call(q.prototype),q.prototype.clone=function(){return new q(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},q.error=function(){var d=new q(null,{status:0,statusText:""});return d.type="error",d};var gn=[301,302,303,307,308];q.redirect=function(d,g){if(gn.indexOf(g)===-1)throw new RangeError("Invalid status code");return new q(null,{status:g,headers:{location:d}})},o.DOMException=i.DOMException;try{new o.DOMException}catch{o.DOMException=function(g,_){this.message=g,this.name=_;var N=Error(g);this.stack=N.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function Oe(d,g){return new Promise(function(_,N){var O=new $(d,g);if(O.signal&&O.signal.aborted)return N(new o.DOMException("Aborted","AbortError"));var x=new XMLHttpRequest;function fe(){x.abort()}x.onload=function(){var re={status:x.status,statusText:x.statusText,headers:mn(x.getAllResponseHeaders()||"")};re.url="responseURL"in x?x.responseURL:re.headers.get("X-Request-URL");var Ne="response"in x?x.response:x.responseText;_(new q(Ne,re))},x.onerror=function(){N(new TypeError("Network request failed"))},x.ontimeout=function(){N(new TypeError("Network request failed"))},x.onabort=function(){N(new o.DOMException("Aborted","AbortError"))},x.open(O.method,O.url,!0),O.credentials==="include"?x.withCredentials=!0:O.credentials==="omit"&&(x.withCredentials=!1),"responseType"in x&&a.blob&&(x.responseType="blob"),O.headers.forEach(function(re,Ne){x.setRequestHeader(Ne,re)}),O.signal&&(O.signal.addEventListener("abort",fe),x.onreadystatechange=function(){x.readyState===4&&O.signal.removeEventListener("abort",fe)}),x.send(typeof O._bodyInit>"u"?null:O._bodyInit)})}return Oe.polyfill=!0,i.fetch||(i.fetch=Oe,i.Headers=y,i.Request=$,i.Response=q),o.Headers=y,o.Request=$,o.Response=q,o.fetch=Oe,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})(ze,ze.exports);var Se=ze.exports;const ve=kr(Se),Cr=En({__proto__:null,default:ve},[Se]),Q=e=>{let t={};return e&&(typeof Headers<"u"&&e instanceof Headers||Cr&&Se.Headers&&e instanceof Se.Headers?t=qs(e):Array.isArray(e)?e.forEach(([n,s])=>{n&&s!==void 0&&(t[n]=s)}):t=e),t},Rt=e=>e.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),Dr=e=>{if(!Array.isArray(e.query)){const s=e,r=[`query=${encodeURIComponent(Rt(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:Rt(r),variables:t.variables?t.jsonSerializer.stringify(t.variables[i]):void 0}),s),[]);return`query=${encodeURIComponent(t.jsonSerializer.stringify(n))}`},Rr=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=Lr(s,r,i,a.jsonSerializer),typeof l=="string"&&(u["Content-Type"]="application/json")):f=Dr({query:s,variables:r,operationName:i,jsonSerializer:a.jsonSerializer??at});const h={method:e,headers:u,body:l,...a};let m=n,y=h;if(c){const v=await Promise.resolve(c({...h,url:n,operationName:i,variables:r})),{url:S,...A}=v;m=S,y=A}return f&&(m=`${m}?${f}`),await o(m,y)};class fn{constructor(t,n={}){this.url=t,this.requestConfig=n,this.rawRequest=async(...s)=>{const[r,i,o]=s,a=Us(r,i,o),{headers:c,fetch:u=ve,method:f="POST",requestMiddleware:l,responseMiddleware:h,...m}=this.requestConfig,{url:y}=this;a.signal!==void 0&&(m.signal=a.signal);const{operationName:v}=Le(a.query);return Me({url:y,query:a.query,variables:a.variables,headers:{...Q(Pe(c)),...Q(a.requestHeaders)},operationName:v,fetch:u,method:f,fetchOptions:m,middleware:l}).then(S=>(h&&h(S),S)).catch(S=>{throw h&&h(S),S})}}async request(t,...n){const[s,r]=n,i=Fs(t,s,r),{headers:o,fetch:a=ve,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}=Le(i.document);return Me({url:h,query:m,variables:i.variables,headers:{...Q(Pe(o)),...Q(i.requestHeaders)},operationName:y,fetch:a,method:c,fetchOptions:l,middleware:u}).then(v=>(f&&f(v),v.data)).catch(v=>{throw f&&f(v),v})}batchRequests(t,n){const s=Bs(t,n),{headers:r,...i}=this.requestConfig;s.signal!==void 0&&(i.signal=s.signal);const o=s.documents.map(({document:c})=>Le(c).query),a=s.documents.map(({variables:c})=>c);return Me({url:this.url,query:o,variables:a,headers:{...Q(Pe(r)),...Q(s.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??ve,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 Me=async e=>{const{query:t,variables:n,fetchOptions:s}=e,r=Rr(Ps(e.method??"post")),i=Array.isArray(e.query),o=await r(e),a=await Mr(o,s.jsonSerializer??at),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 ae({...f,status:o.status,headers:o.headers},{query:t,variables:n})}};async function pn(e,t,...n){const s=js(e,t,...n);return new fn(s.url).request({...s})}const Lr=(e,t,n,s)=>{const r=s??at;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)},Mr=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()},Pe=e=>typeof e=="function"?e():e,Pr=Z(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 pn(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}}catch{throw new Error("Request to add item(s) failed.")}}),qr=Z(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 pn(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}}catch{throw new Error("Request to remove item(s) failed.")}}),qe=typeof window>"u",Fr=Z(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 fn(qe?e.endpointSsr:e.endpoint,qe?{fetch,method:"POST"}:{credentials:"include",method:"POST",mode:"cors"});try{const{data:o,headers:a,status:c,errors:u,extensions:f}=await t.rawRequest(hn(e.document),{},qe?{...e.requestHeaders,Cookie:`quote_${e.locale}=${e.quoteId??""}`}:e.requestHeaders),l=o;if(!((n=l.refreshQuote)!=null&&n.quote))throw console.log("userError: ",(s=l.refreshQuote)==null?void 0:s.userErrors[0].code,(r=l.refreshQuote)==null?void 0:r.userErrors[0].field,(i=l.refreshQuote)==null?void 0:i.userErrors[0].message),new Error("Could not add items to quote.");return{type:"REFRESH_SUCCESS",quote:l.refreshQuote.quote}}catch(o){throw console.log("refresh error",o),new Error("Request to add item(s) failed.")}}),Ur=({context:e})=>typeof window>"u"&&e.quote.id!==""||typeof window<"u",Br=({context:e})=>!!e.quote.items&&e.quote.items.length>0,Je=Ae({types:{context:{},events:{},input:{}},actions:{addItems:C(Rs),removeItems:C(Ls),refresh:C(Ms)},actors:{addItems:Pr,removeItems:qr,refresh:Fr},guards:{canRefresh:Ur,hasItems:Br}}).createMachine({id:"quote",initial:"initializing",context:({input:e})=>{var t,n,s,r,i,o,a,c,u,f,l,h,m,y;return{quote:{id:"",locale:"",baseCurrency:"USD",currencyConversionRate:1,dateCreated:null,dateLastUpdated:null,currency:"USD",items:[],promotions:[],shippingAddresses:{available:[],selected:null},totals:{discount:0,tax:0,shipping:0,shippingTax:0,subtotal:0,grandTotal:0},appliedPriceRules:[],appliedPromotions:[],shippingMethods:[],paymentMethods:[],storeCredit:[],rewards:[],giftCards:[],...(t=e==null?void 0:e.initialContext)==null?void 0:t.quote},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}},errors:[]}},states:{uninitialized:{on:{REFRESH:"refreshing"}},empty:{on:{ADD_ITEMS:"addingItems"}},active:{on:{ADD_ITEMS:"addingItems",REMOVE_ITEMS:"removingItems",REFRESH:"refreshing"}},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"],guard:"hasItems",target:"active"},{actions:["refresh"],target:"empty"}],onError:{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"],target:"active"}],onError:[{guard:"hasItems",target:"active"},{target:"empty"}]}},removingItems:{}}}),dt=P.createContext({}),jr=()=>{const e=P.useContext(dt),[t,n]=P.useState(()=>{var r;const s=e.getSnapshot();return{items:s.context.quote.items??[],itemsCount:((r=s.context.quote.items)==null?void 0:r.length)??0,isAddingItems:s.value==="addingItems",isRemovingItems:s.value==="removingItems",isUpdatingItems:s.value==="addingItems"||s.value==="removingItems"}});return P.useEffect(()=>{const s=e.subscribe(r=>{const i=r.context.quote.items??[];n(o=>({...o,items:i,itemsCount:i.length,isAddingItems:r.matches("addingItems"),isRemovingItems:r.matches("removingItems"),isUpdatingItems:r.matches("addingItems")||r.matches("removingItems")}))});return()=>{s.unsubscribe()}},[e]),{quoteActor:e,isAddingItems:t.isAddingItems,isRemovingItems:t.isRemovingItems,isUpdatingItems:t.isUpdatingItems,items:t.items,itemsCount:t.itemsCount}},$r=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."),B(Je,{inspect:e.inspect,input:{initialContext:{endpoints:e.endpoints}}}).start()):B(Je,{input:{initialContext:{endpoints:e.endpoints,graphql:e.graphql,quote:{id:e.quote.id??"",locale:e.quote.locale??""}}},inspect:e.inspect}).start();function Vr({actor:e,children:t}){return Ye.jsx(dt.Provider,{value:e,children:t})}exports.AuthContext=it;exports.AuthProvider=Os;exports.QuoteContext=dt;exports.QuoteProvider=Vr;exports.ToastContext=ot;exports.ToastProvider=Ds;exports.authMachine=$e;exports.getAuth=bs;exports.getQuote=$r;exports.quoteMachine=Je;exports.timerMachine=en;exports.toastMachine=ks;exports.useAuth=ws;exports.useQuote=jr;exports.useToast=Cs;
50
+ `))}function kt(e){var t;return(t=e==null?void 0:e.some(n=>n.includes(`
51
+ `)))!==null&&t!==void 0?t:!1}const Dt=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},Le=e=>{if(typeof e=="string"){let n;try{const s=Er(e);n=Dt(s)}catch{}return{query:e,operationName:n}}const t=Dt(e);return{query:hn(e),operationName:t}};class ae extends Error{constructor(t,n){const s=`${ae.extractMessage(t)}: ${JSON.stringify({response:t,request:n})}`;super(s),Object.setPrototypeOf(this,ae.prototype),this.response=t,this.request=n,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,ae)}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 Nr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Cr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ze={exports:{}};(function(e,t){var n=typeof self<"u"?self:Nr,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 _=d.shift();return{done:_===void 0,value:_}}};return a.iterable&&(g[Symbol.iterator]=function(){return g}),g}function y(d){this.map={},d instanceof y?d.forEach(function(g,_){this.append(_,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 _=this.map[d];this.map[d]=_?_+", "+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 _ in this.map)this.map.hasOwnProperty(_)&&d.call(g,this.map[_],_,this)},y.prototype.keys=function(){var d=[];return this.forEach(function(g,_){d.push(_)}),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,_){d.push([_,g])}),m(d)},a.iterable&&(y.prototype[Symbol.iterator]=y.prototype.entries);function v(d){if(d.bodyUsed)return Promise.reject(new TypeError("Already read"));d.bodyUsed=!0}function S(d){return new Promise(function(g,_){d.onload=function(){g(d.result)},d.onerror=function(){_(d.error)}})}function A(d){var g=new FileReader,_=S(g);return g.readAsArrayBuffer(d),_}function R(d){var g=new FileReader,_=S(g);return g.readAsText(d),_}function D(d){for(var g=new Uint8Array(d),_=new Array(g.length),N=0;N<g.length;N++)_[N]=String.fromCharCode(g[N]);return _.join("")}function L(d){if(d.slice)return d.slice(0);var g=new Uint8Array(d.byteLength);return g.set(new Uint8Array(d)),g.buffer}function J(){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=L(d.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(d)||f(d))?this._bodyArrayBuffer=L(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=v(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?v(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(A)}),this.text=function(){var d=v(this);if(d)return d;if(this._bodyBlob)return R(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(yn)}),this.json=function(){return this.text().then(JSON.parse)},this}var le=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function he(d){var g=d.toUpperCase();return le.indexOf(g)>-1?g:d}function $(d,g){g=g||{};var _=g.body;if(d instanceof $){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,!_&&d._bodyInit!=null&&(_=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=he(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")&&_)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(_)}$.prototype.clone=function(){return new $(this,{body:this._bodyInit})};function yn(d){var g=new FormData;return d.trim().split("&").forEach(function(_){if(_){var N=_.split("="),O=N.shift().replace(/\+/g," "),x=N.join("=").replace(/\+/g," ");g.append(decodeURIComponent(O),decodeURIComponent(x))}}),g}function mn(d){var g=new y,_=d.replace(/\r?\n[\t ]+/g," ");return _.split(/\r?\n/).forEach(function(N){var O=N.split(":"),x=O.shift().trim();if(x){var fe=O.join(":").trim();g.append(x,fe)}}),g}J.call($.prototype);function q(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)}J.call(q.prototype),q.prototype.clone=function(){return new q(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},q.error=function(){var d=new q(null,{status:0,statusText:""});return d.type="error",d};var gn=[301,302,303,307,308];q.redirect=function(d,g){if(gn.indexOf(g)===-1)throw new RangeError("Invalid status code");return new q(null,{status:g,headers:{location:d}})},o.DOMException=i.DOMException;try{new o.DOMException}catch{o.DOMException=function(g,_){this.message=g,this.name=_;var N=Error(g);this.stack=N.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function Oe(d,g){return new Promise(function(_,N){var O=new $(d,g);if(O.signal&&O.signal.aborted)return N(new o.DOMException("Aborted","AbortError"));var x=new XMLHttpRequest;function fe(){x.abort()}x.onload=function(){var re={status:x.status,statusText:x.statusText,headers:mn(x.getAllResponseHeaders()||"")};re.url="responseURL"in x?x.responseURL:re.headers.get("X-Request-URL");var Ne="response"in x?x.response:x.responseText;_(new q(Ne,re))},x.onerror=function(){N(new TypeError("Network request failed"))},x.ontimeout=function(){N(new TypeError("Network request failed"))},x.onabort=function(){N(new o.DOMException("Aborted","AbortError"))},x.open(O.method,O.url,!0),O.credentials==="include"?x.withCredentials=!0:O.credentials==="omit"&&(x.withCredentials=!1),"responseType"in x&&a.blob&&(x.responseType="blob"),O.headers.forEach(function(re,Ne){x.setRequestHeader(Ne,re)}),O.signal&&(O.signal.addEventListener("abort",fe),x.onreadystatechange=function(){x.readyState===4&&O.signal.removeEventListener("abort",fe)}),x.send(typeof O._bodyInit>"u"?null:O._bodyInit)})}return Oe.polyfill=!0,i.fetch||(i.fetch=Oe,i.Headers=y,i.Request=$,i.Response=q),o.Headers=y,o.Request=$,o.Response=q,o.fetch=Oe,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})(ze,ze.exports);var Se=ze.exports;const ve=Cr(Se),kr=En({__proto__:null,default:ve},[Se]),Q=e=>{let t={};return e&&(typeof Headers<"u"&&e instanceof Headers||kr&&Se.Headers&&e instanceof Se.Headers?t=qs(e):Array.isArray(e)?e.forEach(([n,s])=>{n&&s!==void 0&&(t[n]=s)}):t=e),t},Rt=e=>e.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),Dr=e=>{if(!Array.isArray(e.query)){const s=e,r=[`query=${encodeURIComponent(Rt(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:Rt(r),variables:t.variables?t.jsonSerializer.stringify(t.variables[i]):void 0}),s),[]);return`query=${encodeURIComponent(t.jsonSerializer.stringify(n))}`},Rr=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=Lr(s,r,i,a.jsonSerializer),typeof l=="string"&&(u["Content-Type"]="application/json")):f=Dr({query:s,variables:r,operationName:i,jsonSerializer:a.jsonSerializer??at});const h={method:e,headers:u,body:l,...a};let m=n,y=h;if(c){const v=await Promise.resolve(c({...h,url:n,operationName:i,variables:r})),{url:S,...A}=v;m=S,y=A}return f&&(m=`${m}?${f}`),await o(m,y)};class fn{constructor(t,n={}){this.url=t,this.requestConfig=n,this.rawRequest=async(...s)=>{const[r,i,o]=s,a=Fs(r,i,o),{headers:c,fetch:u=ve,method:f="POST",requestMiddleware:l,responseMiddleware:h,...m}=this.requestConfig,{url:y}=this;a.signal!==void 0&&(m.signal=a.signal);const{operationName:v}=Le(a.query);return Me({url:y,query:a.query,variables:a.variables,headers:{...Q(Pe(c)),...Q(a.requestHeaders)},operationName:v,fetch:u,method:f,fetchOptions:m,middleware:l}).then(S=>(h&&h(S),S)).catch(S=>{throw h&&h(S),S})}}async request(t,...n){const[s,r]=n,i=Us(t,s,r),{headers:o,fetch:a=ve,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}=Le(i.document);return Me({url:h,query:m,variables:i.variables,headers:{...Q(Pe(o)),...Q(i.requestHeaders)},operationName:y,fetch:a,method:c,fetchOptions:l,middleware:u}).then(v=>(f&&f(v),v.data)).catch(v=>{throw f&&f(v),v})}batchRequests(t,n){const s=Bs(t,n),{headers:r,...i}=this.requestConfig;s.signal!==void 0&&(i.signal=s.signal);const o=s.documents.map(({document:c})=>Le(c).query),a=s.documents.map(({variables:c})=>c);return Me({url:this.url,query:o,variables:a,headers:{...Q(Pe(r)),...Q(s.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??ve,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 Me=async e=>{const{query:t,variables:n,fetchOptions:s}=e,r=Rr(Ps(e.method??"post")),i=Array.isArray(e.query),o=await r(e),a=await Mr(o,s.jsonSerializer??at),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 ae({...f,status:o.status,headers:o.headers},{query:t,variables:n})}};async function pn(e,t,...n){const s=js(e,t,...n);return new fn(s.url).request({...s})}const Lr=(e,t,n,s)=>{const r=s??at;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)},Mr=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()},Pe=e=>typeof e=="function"?e():e,Pr=Z(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 pn(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}}catch{throw new Error("Request to add item(s) failed.")}}),qr=Z(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 pn(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}}catch{throw new Error("Request to remove item(s) failed.")}}),qe=typeof window>"u",Ur=Z(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 fn(qe?e.endpointSsr:e.endpoint,qe?{fetch,method:"POST"}:{credentials:"include",method:"POST",mode:"cors"});try{const{data:o,headers:a,status:c,errors:u,extensions:f}=await t.rawRequest(hn(e.document),{},qe?{...e.requestHeaders,Cookie:`quote_${e.locale}=${e.quoteId??""}`}:e.requestHeaders),l=o;if(!((n=l.refreshQuote)!=null&&n.quote))throw console.log("userError: ",(s=l.refreshQuote)==null?void 0:s.userErrors[0].code,(r=l.refreshQuote)==null?void 0:r.userErrors[0].field,(i=l.refreshQuote)==null?void 0:i.userErrors[0].message),new Error("Could not add items to quote.");return{type:"REFRESH_SUCCESS",quote:l.refreshQuote.quote}}catch(o){throw console.log("refresh error",o),new Error("Request to add item(s) failed.")}}),Fr=({context:e})=>typeof window>"u"&&e.quote.id!==""||typeof window<"u",Br=({context:e})=>!!e.quote.items&&e.quote.items.length>0,Je=Ae({types:{context:{},events:{},input:{}},actions:{addItems:k(Rs),removeItems:k(Ls),refresh:k(Ms)},actors:{addItems:Pr,removeItems:qr,refresh:Ur},guards:{canRefresh:Fr,hasItems:Br}}).createMachine({id:"quote",initial:"initializing",context:({input:e})=>{var t,n,s,r,i,o,a,c,u,f,l,h,m,y;return{quote:{id:"",locale:"",baseCurrency:"USD",currencyConversionRate:1,dateCreated:null,dateLastUpdated:null,currency:"USD",items:[],promotions:[],shippingAddresses:{available:[],selected:null},totals:{discount:0,tax:0,shipping:0,shippingTax:0,subtotal:0,grandTotal:0},appliedPriceRules:[],appliedPromotions:[],shippingMethods:[],paymentMethods:[],storeCredit:[],rewards:[],giftCards:[],...(t=e==null?void 0:e.initialContext)==null?void 0:t.quote},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}},errors:[]}},states:{uninitialized:{on:{REFRESH:"refreshing"}},empty:{on:{ADD_ITEMS:"addingItems"}},active:{on:{ADD_ITEMS:"addingItems",REMOVE_ITEMS:"removingItems",REFRESH:"refreshing"}},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"],guard:"hasItems",target:"active"},{actions:["refresh"],target:"empty"}],onError:{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"],target:"active"}],onError:[{guard:"hasItems",target:"active"},{target:"empty"}]}},removingItems:{}}}),dt=P.createContext({}),jr=()=>{const e=P.useContext(dt),[t,n]=P.useState(()=>{var r;const s=e==null?void 0:e.getSnapshot();return s?{items:s.context.quote.items??[],itemsCount:((r=s.context.quote.items)==null?void 0:r.length)??0,isAddingItems:s.value==="addingItems",isRemovingItems:s.value==="removingItems",isUpdatingItems:s.value==="addingItems"||s.value==="removingItems"}:(console.log("no snpashot, quoteActor",e),{items:[],itemsCount:0,isAddingItems:!1,isRemovingItems:!1,isUpdatingItems:!1})});return P.useEffect(()=>{const s=e.subscribe(r=>{const i=r.context.quote.items??[];console.log("fsm items",i),console.log("fsm items count",i.length),n(o=>({...o,items:i,itemsCount:i.length,isAddingItems:r.matches("addingItems"),isRemovingItems:r.matches("removingItems"),isUpdatingItems:r.matches("addingItems")||r.matches("removingItems")}))});return()=>{s.unsubscribe()}},[e]),{quoteActor:e,isAddingItems:t.isAddingItems,isRemovingItems:t.isRemovingItems,isUpdatingItems:t.isUpdatingItems,items:t.items,itemsCount:t.itemsCount}},$r=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."),B(Je,{inspect:e.inspect,input:{initialContext:{endpoints:e.endpoints}}}).start()):B(Je,{input:{initialContext:{endpoints:e.endpoints,graphql:e.graphql,quote:{id:e.quote.id??"",locale:e.quote.locale??""}}},inspect:e.inspect}).start();function Vr({actor:e,children:t}){return Ye.jsx(dt.Provider,{value:e,children:t})}exports.AuthContext=it;exports.AuthProvider=Os;exports.QuoteContext=dt;exports.QuoteProvider=Vr;exports.ToastContext=ot;exports.ToastProvider=Ds;exports.authMachine=$e;exports.getAuth=bs;exports.getQuote=$r;exports.quoteMachine=Je;exports.timerMachine=en;exports.toastMachine=Cs;exports.useAuth=ws;exports.useQuote=jr;exports.useToast=ks;
package/index.mjs CHANGED
@@ -90,7 +90,7 @@ function qt(e, t) {
90
90
  error: t
91
91
  };
92
92
  }
93
- function Ft(e) {
93
+ function Ut(e) {
94
94
  return {
95
95
  type: Pt,
96
96
  input: e
@@ -202,9 +202,9 @@ function Rn(e, t) {
202
202
  };
203
203
  return l;
204
204
  }
205
- function Ut(e, t) {
205
+ function Ft(e, t) {
206
206
  const n = ut(e), s = ut(t);
207
- return typeof s == "string" ? typeof n == "string" ? s === n : !1 : typeof n == "string" ? n in s : Object.keys(n).every((r) => r in s ? Ut(n[r], s[r]) : !1);
207
+ return typeof s == "string" ? typeof n == "string" ? s === n : !1 : typeof n == "string" ? n in s : Object.keys(n).every((r) => r in s ? Ft(n[r], s[r]) : !1);
208
208
  }
209
209
  function Ye(e) {
210
210
  if (jt(e))
@@ -256,10 +256,10 @@ function dt(e, t) {
256
256
  function Bt(e) {
257
257
  return jt(e) ? e : [e];
258
258
  }
259
- function F(e) {
259
+ function U(e) {
260
260
  return e === void 0 ? [] : Bt(e);
261
261
  }
262
- function Fe(e, t, n, s) {
262
+ function Ue(e, t, n, s) {
263
263
  return typeof e == "function" ? e({
264
264
  context: t,
265
265
  event: n,
@@ -279,7 +279,7 @@ function X(e) {
279
279
  }
280
280
  function $t(e) {
281
281
  if (!(e === void 0 || e === An))
282
- return F(e);
282
+ return U(e);
283
283
  }
284
284
  function lt(e, t, n) {
285
285
  var i, o, a;
@@ -523,7 +523,7 @@ class qn {
523
523
  error: () => {
524
524
  }
525
525
  }), this.system._register(this.sessionId, this), this._systemId && this.system._set(this._systemId, this), this._processingStatus = k.Running;
526
- const t = Ft(this.options.input);
526
+ const t = Ut(this.options.input);
527
527
  switch (this.system._sendInspectionEvent({
528
528
  type: "@xstate.event",
529
529
  sourceRef: this._parent,
@@ -682,16 +682,16 @@ class qn {
682
682
  return this._snapshot;
683
683
  }
684
684
  }
685
- function U(e, ...[t]) {
685
+ function F(e, ...[t]) {
686
686
  return new qn(e, t);
687
687
  }
688
- function Fn(e, t, n, s, {
688
+ function Un(e, t, n, s, {
689
689
  sendId: r
690
690
  }) {
691
691
  const i = typeof r == "function" ? r(n, s) : r;
692
692
  return [t, i];
693
693
  }
694
- function Un(e, t) {
694
+ function Fn(e, t) {
695
695
  e.defer(() => {
696
696
  e.system.scheduler.cancel(e.self, t);
697
697
  });
@@ -699,7 +699,7 @@ function Un(e, t) {
699
699
  function Bn(e) {
700
700
  function t(n, s) {
701
701
  }
702
- return t.type = "xstate.cancel", t.sendId = e, t.resolve = Fn, t.execute = Un, t;
702
+ return t.type = "xstate.cancel", t.sendId = e, t.resolve = Un, t.execute = Fn, t;
703
703
  }
704
704
  function jn(e, t, n, s, {
705
705
  id: r,
@@ -710,7 +710,7 @@ function jn(e, t, n, s, {
710
710
  }) {
711
711
  const u = typeof o == "string" ? Xe(t.machine, o) : o, f = typeof r == "function" ? r(n) : r;
712
712
  let l;
713
- return u && (l = U(u, {
713
+ return u && (l = F(u, {
714
714
  id: f,
715
715
  src: o,
716
716
  parent: e.self,
@@ -894,7 +894,7 @@ function Jn(e) {
894
894
  const o = t[r], a = typeof o == "string" ? {
895
895
  target: o
896
896
  } : o, c = Number.isNaN(+r) ? r : +r, u = n(c);
897
- return F(a).map((f) => ({
897
+ return U(a).map((f) => ({
898
898
  ...f,
899
899
  event: u,
900
900
  delay: c
@@ -912,7 +912,7 @@ function Jn(e) {
912
912
  function $(e, t, n) {
913
913
  const s = $t(n.target), r = n.reenter ?? !1, i = Qn(e, s), o = {
914
914
  ...n,
915
- actions: F(n.actions),
915
+ actions: U(n.actions),
916
916
  guard: n.guard,
917
917
  target: i,
918
918
  source: e,
@@ -965,7 +965,7 @@ function Xn(e, t) {
965
965
  throw new Error(`Initial state node "${t}" not found on parent state node #${e.id}`);
966
966
  const s = {
967
967
  source: e,
968
- actions: !t || typeof t == "string" ? [] : F(t.actions),
968
+ actions: !t || typeof t == "string" ? [] : U(t.actions),
969
969
  eventType: null,
970
970
  reenter: !1,
971
971
  target: n ? [n] : [],
@@ -1117,7 +1117,7 @@ function Xt(e, t, n) {
1117
1117
  let i = !1;
1118
1118
  const o = /* @__PURE__ */ new Set();
1119
1119
  for (const a of s)
1120
- if (ts(Ue([r], t, n), Ue([a], t, n)))
1120
+ if (ts(Fe([r], t, n), Fe([a], t, n)))
1121
1121
  if (B(r.source, a.source))
1122
1122
  o.add(a);
1123
1123
  else {
@@ -1166,7 +1166,7 @@ function Qt(e, t) {
1166
1166
  if (!e.reenter)
1167
1167
  return e.source.machine.root;
1168
1168
  }
1169
- function Ue(e, t, n) {
1169
+ function Fe(e, t, n) {
1170
1170
  var r;
1171
1171
  const s = /* @__PURE__ */ new Set();
1172
1172
  for (const i of e)
@@ -1208,8 +1208,8 @@ function Be(e, t, n, s, r, i) {
1208
1208
  function rs(e, t, n, s, r) {
1209
1209
  if (s.output === void 0)
1210
1210
  return;
1211
- const i = qe(r.id, r.output !== void 0 && r.parent ? Fe(r.output, e.context, t, n.self) : void 0);
1212
- return Fe(s.output, e.context, i, n.self);
1211
+ const i = qe(r.id, r.output !== void 0 && r.parent ? Ue(r.output, e.context, t, n.self) : void 0);
1212
+ return Ue(s.output, e.context, i, n.self);
1213
1213
  }
1214
1214
  function is(e, t, n, s, r, i, o, a) {
1215
1215
  let c = e;
@@ -1232,7 +1232,7 @@ function is(e, t, n, s, r, i, o, a) {
1232
1232
  if (c = te(c, t, n, m, i, h.invoke.map((y) => y.id)), h.type === "final") {
1233
1233
  const y = h.parent;
1234
1234
  let v = (y == null ? void 0 : y.type) === "parallel" ? y : y == null ? void 0 : y.parent, S = v || h;
1235
- for ((y == null ? void 0 : y.type) === "compound" && i.push(qe(y.id, h.output !== void 0 ? Fe(h.output, c.context, t, n.self) : void 0)); (v == null ? void 0 : v.type) === "parallel" && !l.has(v) && Ze(r, v); )
1235
+ for ((y == null ? void 0 : y.type) === "compound" && i.push(qe(y.id, h.output !== void 0 ? Ue(h.output, c.context, t, n.self) : void 0)); (v == null ? void 0 : v.type) === "parallel" && !l.has(v) && Ze(r, v); )
1236
1236
  l.add(v), i.push(qe(v.id)), S = v, v = v.parent;
1237
1237
  if (v)
1238
1238
  continue;
@@ -1294,7 +1294,7 @@ function Ne(e, t, n, s, r) {
1294
1294
  }
1295
1295
  function as(e, t, n, s, r, i, o) {
1296
1296
  let a = e;
1297
- const c = Ue(s, r, i);
1297
+ const c = Fe(s, r, i);
1298
1298
  c.sort((f, l) => l.order - f.order);
1299
1299
  let u;
1300
1300
  for (const f of c)
@@ -1459,7 +1459,7 @@ function ds(e) {
1459
1459
  return !!e && typeof e == "object" && "machine" in e && "value" in e;
1460
1460
  }
1461
1461
  const ls = function(t) {
1462
- return Ut(t, this.value);
1462
+ return Ft(t, this.value);
1463
1463
  }, hs = function(t) {
1464
1464
  return this.tags.has(t);
1465
1465
  }, fs = function(t) {
@@ -1727,7 +1727,7 @@ function _s(e, {
1727
1727
  const f = Xe(t, o);
1728
1728
  if (!f)
1729
1729
  throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);
1730
- const l = U(f, {
1730
+ const l = F(f, {
1731
1731
  id: a.id,
1732
1732
  parent: e.self,
1733
1733
  syncSnapshot: a.syncSnapshot,
@@ -1741,7 +1741,7 @@ function _s(e, {
1741
1741
  });
1742
1742
  return r[l.id] = l, l;
1743
1743
  } else
1744
- return U(o, {
1744
+ return F(o, {
1745
1745
  id: a.id,
1746
1746
  parent: e.self,
1747
1747
  syncSnapshot: a.syncSnapshot,
@@ -1876,7 +1876,7 @@ class nt {
1876
1876
  _machine: this.machine
1877
1877
  })) : ws, this.type === "compound" && !this.config.initial)
1878
1878
  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.`);
1879
- this.history = this.config.history === !0 ? "shallow" : this.config.history || !1, this.entry = F(this.config.entry).slice(), this.exit = F(this.config.exit).slice(), this.meta = this.config.meta, this.output = this.type === "final" || !this.parent ? this.config.output : void 0, this.tags = F(t.tags).slice();
1879
+ this.history = this.config.history === !0 ? "shallow" : this.config.history || !1, this.entry = U(this.config.entry).slice(), this.exit = U(this.config.exit).slice(), this.meta = this.config.meta, this.output = this.type === "final" || !this.parent ? this.config.output : void 0, this.tags = U(t.tags).slice();
1880
1880
  }
1881
1881
  /** @internal */
1882
1882
  _initialize() {
@@ -1931,7 +1931,7 @@ class nt {
1931
1931
  * The logic invoked as actors by this state node.
1932
1932
  */
1933
1933
  get invoke() {
1934
- return J(this, "invoke", () => F(this.config.invoke).map((t, n) => {
1934
+ return J(this, "invoke", () => U(this.config.invoke).map((t, n) => {
1935
1935
  const {
1936
1936
  src: s,
1937
1937
  systemId: r
@@ -2131,7 +2131,7 @@ class st {
2131
2131
  * Returns the initial `State` instance, with reference to `self` as an `ActorRef`.
2132
2132
  */
2133
2133
  getInitialSnapshot(t, n) {
2134
- const s = Ft(n), r = [], i = this.getPreInitialState(t, s, r), o = Be([{
2134
+ const s = Ut(n), r = [], i = this.getPreInitialState(t, s, r), o = Be([{
2135
2135
  target: [...Yt(this.root)],
2136
2136
  source: this.root,
2137
2137
  reenter: !0,
@@ -2170,7 +2170,7 @@ class st {
2170
2170
  const u = r[c], f = u.snapshot, l = u.src, h = typeof l == "string" ? Xe(this, l) : l;
2171
2171
  if (!h)
2172
2172
  return;
2173
- const m = U(h, {
2173
+ const m = F(h, {
2174
2174
  id: c,
2175
2175
  parent: n.self,
2176
2176
  syncSnapshot: u.syncSnapshot,
@@ -2551,14 +2551,14 @@ const St = xe({
2551
2551
  endpoints: { login: "", logout: "", refresh: "", ssrRefresh: "" }
2552
2552
  }) => typeof window < "u" ? (console.warn(
2553
2553
  "App.getInitialProps::getAuth should not be run on the frontend. You are probably missing getServerSideProps in your page."
2554
- ), U(St, {
2554
+ ), F(St, {
2555
2555
  inspect: t.inspect,
2556
2556
  input: {
2557
2557
  initialContext: {
2558
2558
  endpoints: t.endpoints
2559
2559
  }
2560
2560
  }
2561
- }).start()) : U(St, {
2561
+ }).start()) : F(St, {
2562
2562
  input: {
2563
2563
  initialContext: {
2564
2564
  endpoints: t.endpoints,
@@ -2836,11 +2836,11 @@ const rt = JSON, Ls = (e) => e.toUpperCase(), Ms = (e) => {
2836
2836
  variables: t,
2837
2837
  requestHeaders: n,
2838
2838
  signal: void 0
2839
- }, Fs = (e, t) => e.documents ? e : {
2839
+ }, Us = (e, t) => e.documents ? e : {
2840
2840
  documents: e,
2841
2841
  requestHeaders: t,
2842
2842
  signal: void 0
2843
- }, Us = (e, t, ...n) => {
2843
+ }, Fs = (e, t, ...n) => {
2844
2844
  const [s, r] = n;
2845
2845
  return e.document ? e : {
2846
2846
  url: e,
@@ -5783,7 +5783,7 @@ class pn {
5783
5783
  }
5784
5784
  // prettier-ignore
5785
5785
  batchRequests(t, n) {
5786
- const s = Fs(t, n), { headers: r, ...i } = this.requestConfig;
5786
+ const s = Us(t, n), { headers: r, ...i } = this.requestConfig;
5787
5787
  s.signal !== void 0 && (i.signal = s.signal);
5788
5788
  const o = s.documents.map(({ document: c }) => Re(c).query), a = s.documents.map(({ variables: c }) => c);
5789
5789
  return Le({
@@ -5842,7 +5842,7 @@ const Le = async (e) => {
5842
5842
  }
5843
5843
  };
5844
5844
  async function yn(e, t, ...n) {
5845
- const s = Us(e, t, ...n);
5845
+ const s = Fs(e, t, ...n);
5846
5846
  return new pn(s.url).request({
5847
5847
  ...s
5848
5848
  });
@@ -5950,7 +5950,7 @@ const Dr = (e, t, n, s) => {
5950
5950
  throw console.log("refresh error", o), new Error("Request to add item(s) failed.");
5951
5951
  }
5952
5952
  }
5953
- ), qr = ({ context: e }) => typeof window > "u" && e.quote.id !== "" || typeof window < "u", Fr = ({ context: e }) => !!e.quote.items && e.quote.items.length > 0, Ct = xe({
5953
+ ), qr = ({ context: e }) => typeof window > "u" && e.quote.id !== "" || typeof window < "u", Ur = ({ context: e }) => !!e.quote.items && e.quote.items.length > 0, Ct = xe({
5954
5954
  types: {
5955
5955
  context: {},
5956
5956
  events: {},
@@ -5968,7 +5968,7 @@ const Dr = (e, t, n, s) => {
5968
5968
  },
5969
5969
  guards: {
5970
5970
  canRefresh: qr,
5971
- hasItems: Fr
5971
+ hasItems: Ur
5972
5972
  }
5973
5973
  }).createMachine({
5974
5974
  /** @todo do we need to add the view to the id? (e.g. quote_en-us) */
@@ -6236,19 +6236,25 @@ const Dr = (e, t, n, s) => {
6236
6236
  ), Jr = () => {
6237
6237
  const e = Je(mn), [t, n] = Dt(() => {
6238
6238
  var r;
6239
- const s = e.getSnapshot();
6240
- return {
6239
+ const s = e == null ? void 0 : e.getSnapshot();
6240
+ return s ? {
6241
6241
  items: s.context.quote.items ?? [],
6242
6242
  itemsCount: ((r = s.context.quote.items) == null ? void 0 : r.length) ?? 0,
6243
6243
  isAddingItems: s.value === "addingItems",
6244
6244
  isRemovingItems: s.value === "removingItems",
6245
6245
  isUpdatingItems: s.value === "addingItems" || s.value === "removingItems"
6246
- };
6246
+ } : (console.log("no snpashot, quoteActor", e), {
6247
+ items: [],
6248
+ itemsCount: 0,
6249
+ isAddingItems: !1,
6250
+ isRemovingItems: !1,
6251
+ isUpdatingItems: !1
6252
+ });
6247
6253
  });
6248
6254
  return Rt(() => {
6249
6255
  const s = e.subscribe((r) => {
6250
6256
  const i = r.context.quote.items ?? [];
6251
- n((o) => ({
6257
+ console.log("fsm items", i), console.log("fsm items count", i.length), n((o) => ({
6252
6258
  ...o,
6253
6259
  items: i,
6254
6260
  itemsCount: i.length,
@@ -6275,14 +6281,14 @@ const Dr = (e, t, n, s) => {
6275
6281
  graphql: {}
6276
6282
  }) => typeof window < "u" ? (console.warn(
6277
6283
  "App.getInitialProps::getAuth should not be run on the frontend. You are probably missing getServerSideProps in your page."
6278
- ), U(Ct, {
6284
+ ), F(Ct, {
6279
6285
  inspect: e.inspect,
6280
6286
  input: {
6281
6287
  initialContext: {
6282
6288
  endpoints: e.endpoints
6283
6289
  }
6284
6290
  }
6285
- }).start()) : U(Ct, {
6291
+ }).start()) : F(Ct, {
6286
6292
  input: {
6287
6293
  initialContext: {
6288
6294
  endpoints: e.endpoints,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clicktap/state",
3
- "version": "0.13.8",
3
+ "version": "0.13.9",
4
4
  "private": false,
5
5
  "author": "Clicktap",
6
6
  "description": "A state management library for Clicktap reference frontend.",