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