gapless.js 4.0.2 → 4.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +9 -13
- package/dist/index.mjs +3 -3
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/Queue.ts +110 -138
- package/src/Track.ts +134 -218
- package/src/machines/fetchDecode.machine.ts +130 -0
- package/src/machines/queue.machine.ts +237 -68
- package/src/machines/track.machine.ts +254 -74
package/dist/index.d.ts
CHANGED
|
@@ -94,8 +94,8 @@ declare class Track {
|
|
|
94
94
|
private _trackUrl;
|
|
95
95
|
private _resolvedUrl;
|
|
96
96
|
private readonly skipHEAD;
|
|
97
|
-
|
|
98
|
-
private
|
|
97
|
+
/** Temporary holder between fetch and decode steps (unserializable — stays on Track class). */
|
|
98
|
+
private _pendingArrayBuffer;
|
|
99
99
|
readonly audio: HTMLAudioElement;
|
|
100
100
|
private readonly _webAudioDisabled;
|
|
101
101
|
private get ctx();
|
|
@@ -106,11 +106,9 @@ declare class Track {
|
|
|
106
106
|
private webAudioStartedAt;
|
|
107
107
|
/** Track-time (seconds) frozen at the moment of the most recent pause. */
|
|
108
108
|
private pausedAtTrackTime;
|
|
109
|
-
scheduledStartContextTime: number | null;
|
|
110
109
|
private readonly _actor;
|
|
111
110
|
private readonly queueRef;
|
|
112
111
|
private rafId;
|
|
113
|
-
private _notifiedLookahead;
|
|
114
112
|
constructor(opts: {
|
|
115
113
|
trackUrl: string;
|
|
116
114
|
index: number;
|
|
@@ -138,16 +136,16 @@ declare class Track {
|
|
|
138
136
|
get webAudioLoadingState(): WebAudioLoadingState;
|
|
139
137
|
get hasSourceNode(): boolean;
|
|
140
138
|
get machineState(): string;
|
|
139
|
+
get scheduledStartContextTime(): number | null;
|
|
141
140
|
get isBufferLoaded(): boolean;
|
|
142
141
|
toInfo(): TrackInfo;
|
|
143
142
|
private _playHtml5;
|
|
144
|
-
private
|
|
145
|
-
private _playWebAudio;
|
|
143
|
+
private _seekHtml5;
|
|
146
144
|
private _startSourceNode;
|
|
147
145
|
private _stopSourceNode;
|
|
148
146
|
private _disconnectGain;
|
|
147
|
+
private _seekWebAudio;
|
|
149
148
|
private _handleWebAudioEnded;
|
|
150
|
-
private _startLoad;
|
|
151
149
|
startProgressLoop(): void;
|
|
152
150
|
private _stopProgressLoop;
|
|
153
151
|
}
|
|
@@ -165,8 +163,8 @@ declare class Queue implements TrackQueueRef {
|
|
|
165
163
|
private readonly _onDebug?;
|
|
166
164
|
readonly webAudioIsDisabled: boolean;
|
|
167
165
|
private _volume;
|
|
168
|
-
/**
|
|
169
|
-
private
|
|
166
|
+
/** Index of the next track with a pre-scheduled gapless start, or null. */
|
|
167
|
+
private _scheduledNextIndex;
|
|
170
168
|
private _throttledUpdatePositionState;
|
|
171
169
|
constructor(options?: GaplessOptions);
|
|
172
170
|
play(): void;
|
|
@@ -201,13 +199,11 @@ declare class Queue implements TrackQueueRef {
|
|
|
201
199
|
onError(error: Error): void;
|
|
202
200
|
onPlayBlocked(): void;
|
|
203
201
|
onDebug(msg: string): void;
|
|
202
|
+
/** Look up a track by index — safe for use inside machine actions. */
|
|
203
|
+
private _trackAt;
|
|
204
204
|
private get _currentTrack();
|
|
205
|
-
private _deactivateCurrent;
|
|
206
|
-
private _activateCurrent;
|
|
207
205
|
private _preloadAhead;
|
|
208
206
|
private _cancelScheduledGapless;
|
|
209
|
-
private _cancelAllScheduledGapless;
|
|
210
|
-
private _cancelAndRescheduleGapless;
|
|
211
207
|
private _tryScheduleGapless;
|
|
212
208
|
private _computeTrackEndTime;
|
|
213
209
|
}
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function Te(){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 Se(){let n=Te();if(n.__xstate__)return n.__xstate__}var Pt=n=>{if(typeof window>"u")return;let t=Se();t&&t.register(n)};var Z=class{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){let e={value:t,next:null};if(this._current){this._last.next=e,this._last=e;return}this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){let t=this._current;this._process(t.value),this._current=t.next}this._last=null}},Tt=".",xe="",St="",ke="#",be="*",Mt="xstate.init",Nt="xstate.error",gt="xstate.stop";function Ae(n,t){return{type:`xstate.after.${n}.${t}`}}function yt(n,t){return{type:`xstate.done.state.${n}`,output:t}}function Ee(n,t){return{type:`xstate.done.actor.${n}`,output:t,actorId:n}}function xt(n,t){return{type:`xstate.error.actor.${n}`,error:t,actorId:n}}function nt(n){return{type:Mt,input:n}}function T(n){setTimeout(()=>{throw n})}var Ie=typeof Symbol=="function"&&Symbol.observable||"@@observable";function kt(n,t){let e=Ot(n),s=Ot(t);return typeof s=="string"?typeof e=="string"?s===e:!1:typeof e=="string"?e in s:Object.keys(e).every(i=>i in s?kt(e[i],s[i]):!1)}function st(n){if(Gt(n))return n;let t=[],e="";for(let s=0;s<n.length;s++){switch(n.charCodeAt(s)){case 92:e+=n[s+1],s++;continue;case 46:t.push(e),e="";continue}e+=n[s]}return t.push(e),t}function Ot(n){if(re(n))return n.value;if(typeof n!="string")return n;let t=st(n);return Ut(t)}function Ut(n){if(n.length===1)return n[0];let t={},e=t;for(let s=0;s<n.length-1;s++)if(s===n.length-2)e[n[s]]=n[s+1];else{let i=e;e={},i[n[s]]=e}return t}function bt(n,t){let e={},s=Object.keys(n);for(let i=0;i<s.length;i++){let r=s[i];e[r]=t(n[r],r,n,i)}return e}function Bt(n){return Gt(n)?n:[n]}function S(n){return n===void 0?[]:Bt(n)}function _t(n,t,e,s){return typeof n=="function"?n({context:t,event:e,self:s}):n}function Gt(n){return Array.isArray(n)}function we(n){return n.type.startsWith("xstate.error.actor")}function A(n){return Bt(n).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function qt(n){if(!(n===void 0||n===xe))return S(n)}function tt(n,t,e){var r,o,a;let s=typeof n=="object",i=s?n:void 0;return{next:(r=s?n.next:n)==null?void 0:r.bind(i),error:(o=s?n.error:t)==null?void 0:o.bind(i),complete:(a=s?n.complete:e)==null?void 0:a.bind(i)}}function At(n,t){return`${t}.${n}`}function H(n,t){let e=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!e)return n.implementations.actors[t];let[,s,i]=e,o=n.getStateNodeById(i).config.invoke;return(Array.isArray(o)?o[s]:o).src}function Wt(n,t){if(t===n||t===be)return!0;if(!t.endsWith(".*"))return!1;let e=t.split("."),s=n.split(".");for(let i=0;i<e.length;i++){let r=e[i],o=s[i];if(r==="*")return i===e.length-1;if(r!==o)return!1}return!0}function Rt(n,t){return`${n.sessionId}.${t}`}var De=0;function Pe(n,t){let e=new Map,s=new Map,i=new WeakMap,r=new Set,o={},{clock:a,logger:c}=t,f={schedule:(u,l,h,y,_=Math.random().toString(36).slice(2))=>{let P={source:u,target:l,event:h,delay:y,id:_,startedAt:Date.now()},O=Rt(u,_);d._snapshot._scheduledEvents[O]=P;let ve=a.setTimeout(()=>{delete o[O],delete d._snapshot._scheduledEvents[O],d._relay(u,l,h)},y);o[O]=ve},cancel:(u,l)=>{let h=Rt(u,l),y=o[h];delete o[h],delete d._snapshot._scheduledEvents[h],y!==void 0&&a.clearTimeout(y)},cancelAll:u=>{for(let l in d._snapshot._scheduledEvents){let h=d._snapshot._scheduledEvents[l];h.source===u&&f.cancel(u,h.id)}}},p=u=>{if(!r.size)return;let l={...u,rootId:n.sessionId};r.forEach(h=>{var y;return(y=h.next)==null?void 0:y.call(h,l)})},d={_snapshot:{_scheduledEvents:((t==null?void 0:t.snapshot)&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${De++}`,_register:(u,l)=>(e.set(u,l),u),_unregister:u=>{e.delete(u.sessionId);let l=i.get(u);l!==void 0&&(s.delete(l),i.delete(u))},get:u=>s.get(u),getAll:()=>Object.fromEntries(s.entries()),_set:(u,l)=>{let h=s.get(u);if(h&&h!==l)throw new Error(`Actor with system ID '${u}' already exists.`);s.set(u,l),i.set(l,u)},inspect:u=>{let l=tt(u);return r.add(l),{unsubscribe(){r.delete(l)}}},_sendInspectionEvent:p,_relay:(u,l,h)=>{d._sendInspectionEvent({type:"@xstate.event",sourceRef:u,actorRef:l,event:h}),l._send(h)},scheduler:f,getSnapshot:()=>({_scheduledEvents:{...d._snapshot._scheduledEvents}}),start:()=>{let u=d._snapshot._scheduledEvents;d._snapshot._scheduledEvents={};for(let l in u){let{source:h,target:y,event:_,delay:P,id:O}=u[l];f.schedule(h,y,_,P,O)}},_clock:a,_logger:c};return d}var ft=!1,it=1,m=(function(n){return n[n.NotStarted=0]="NotStarted",n[n.Running=1]="Running",n[n.Stopped=2]="Stopped",n})({}),Oe={clock:{setTimeout:(n,t)=>setTimeout(n,t),clearTimeout:n=>clearTimeout(n)},logger:console.log.bind(console),devTools:!1},et=class{constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new Z(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=m.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=[];let s={...Oe,...e},{clock:i,logger:r,parent:o,syncSnapshot:a,id:c,systemId:f,inspect:p}=s;this.system=o?o.system:Pe(this,{clock:i,logger:r}),p&&!o&&this.system.inspect(tt(p)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=(e==null?void 0:e.logger)??this.system._logger,this.clock=(e==null?void 0:e.clock)??this.system._clock,this._parent=o,this._syncSnapshot=a,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:d=>{this._deferred.push(d)},system:this.system,stopChild:d=>{if(d._parent!==this)throw new Error(`Cannot stop child actor ${d.id} of ${this.id} because it is not a child`);d._stop()},emit:d=>{let u=this.eventListeners.get(d.type),l=this.eventListeners.get("*");if(!u&&!l)return;let h=[...u?u.values():[],...l?l.values():[]];for(let y of h)try{y(d)}catch(_){T(_)}},actionExecutor:d=>{let u=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:d.type,params:d.params}}),!d.exec)return;let l=ft;try{ft=!0,d.exec(d.info,d.params)}finally{ft=l}};this._processingStatus===m.Running?u():this._deferred.push(u)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),f&&(this.systemId=f,this.system._set(f,this)),this._initState((e==null?void 0:e.snapshot)??(e==null?void 0:e.state)),f&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(t){var e;try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,(e=this.options)==null?void 0:e.input)}catch(s){this._snapshot={status:"error",output:void 0,error:s}}}update(t,e){var i,r;this._snapshot=t;let s;for(;s=this._deferred.shift();)try{s()}catch(o){this._deferred.length=0,this._snapshot={...t,status:"error",error:o}}switch(this._snapshot.status){case"active":for(let o of this.observers)try{(i=o.next)==null||i.call(o,t)}catch(a){T(a)}break;case"done":for(let o of this.observers)try{(r=o.next)==null||r.call(o,t)}catch(a){T(a)}this._stopProcedure(),this._complete(),this._doneEvent=Ee(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:e,snapshot:t})}subscribe(t,e,s){var r;let i=tt(t,e,s);if(this._processingStatus!==m.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{(r=i.complete)==null||r.call(i)}catch(o){T(o)}break;case"error":{let o=this._snapshot.error;if(!i.error)T(o);else try{i.error(o)}catch(a){T(a)}break}}return{unsubscribe:()=>{this.observers.delete(i)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));let i=e.bind(void 0);return s.add(i),{unsubscribe:()=>{s.delete(i)}}}start(){if(this._processingStatus===m.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=m.Running;let t=nt(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 e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(i){s={err:i}}if(s){let{err:i}=s;this._snapshot={...this._snapshot,status:"error",error:i},this._error(i);return}this.update(e,t),t.type===gt&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===m.Stopped?this:(this.mailbox.clear(),this._processingStatus===m.NotStarted?(this._processingStatus=m.Stopped,this):(this.mailbox.enqueue({type:gt}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){var t;for(let e of this.observers)try{(t=e.complete)==null||t.call(e)}catch(s){T(s)}this.observers.clear(),this.eventListeners.clear()}_reportError(t){if(!this.observers.size){this._parent||T(t),this.eventListeners.clear();return}let e=!1;for(let s of this.observers){let i=s.error;e||=!i;try{i==null||i(t)}catch(r){T(r)}}this.observers.clear(),this.eventListeners.clear(),e&&T(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,xt(this.id,t))}_stopProcedure(){return this._processingStatus!==m.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Z(this._process.bind(this)),this._processingStatus=m.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==m.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){let{devTools:t}=this.options;t&&(typeof t=="function"?t:Pt)(this)}toJSON(){return{xstate$$type:it,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[Ie](){return this}getSnapshot(){return this._snapshot}};function v(n,...[t]){return new et(n,t)}function Re(n,t,e,s,{sendId:i}){let r=typeof i=="function"?i(e,s):i;return[t,{sendId:r},void 0]}function Le(n,t){n.defer(()=>{n.system.scheduler.cancel(n.self,t.sendId)})}function $(n){function t(e,s){}return t.type="xstate.cancel",t.sendId=n,t.resolve=Re,t.execute=Le,t}function Ce(n,t,e,s,{id:i,systemId:r,src:o,input:a,syncSnapshot:c}){let f=typeof o=="string"?H(t.machine,o):o,p=typeof i=="function"?i(e):i,d,u;return f&&(u=typeof a=="function"?a({context:t.context,event:e.event,self:n.self}):a,d=v(f,{id:p,src:o,parent:n.self,syncSnapshot:c,systemId:r,input:u})),[b(t,{children:{...t.children,[p]:d}}),{id:i,systemId:r,actorRef:d,src:o,input:u},void 0]}function $e(n,{actorRef:t}){t&&n.defer(()=>{t._processingStatus!==m.Stopped&&t.start()})}function M(...[n,{id:t,systemId:e,input:s,syncSnapshot:i=!1}={}]){function r(o,a){}return r.type="xstate.spawnChild",r.id=t,r.systemId=e,r.src=n,r.input=s,r.syncSnapshot=i,r.resolve=Ce,r.execute=$e,r}function Me(n,t,e,s,{actorRef:i}){let r=typeof i=="function"?i(e,s):i,o=typeof r=="string"?t.children[r]:r,a=t.children;return o&&(a={...a},delete a[o.id]),[b(t,{children:a}),o,void 0]}function Ht(n,t){let e=t.getSnapshot();if(e&&"children"in e)for(let s of Object.values(e.children))Ht(n,s);n.system._unregister(t)}function Ne(n,t){if(t){if(Ht(n,t),t._processingStatus!==m.Running){n.stopChild(t);return}n.defer(()=>{n.stopChild(t)})}}function w(n){function t(e,s){}return t.type="xstate.stopChild",t.actorRef=n,t.resolve=Me,t.execute=Ne,t}function N(n,t,e,s){let{machine:i}=s,r=typeof n=="function",o=r?n:i.implementations.guards[typeof n=="string"?n:n.type];if(!r&&!o)throw new Error(`Guard '${typeof n=="string"?n:n.type}' is not implemented.'.`);if(typeof o!="function")return N(o,t,e,s);let a={context:t,event:e},c=r||typeof n=="string"?void 0:"params"in n?typeof n.params=="function"?n.params({context:t,event:e}):n.params:void 0;return"check"in o?o.check(s,a,o):o(a,c)}function rt(n){return n.type==="atomic"||n.type==="final"}function L(n){return Object.values(n.states).filter(t=>t.type!=="history")}function U(n,t){let e=[];if(t===n)return e;let s=n.parent;for(;s&&s!==t;)e.push(s),s=s.parent;return e}function j(n){let t=new Set(n),e=Vt(t);for(let s of t)if(s.type==="compound"&&(!e.get(s)||!e.get(s).length))Lt(s).forEach(i=>t.add(i));else if(s.type==="parallel"){for(let i of L(s))if(i.type!=="history"&&!t.has(i)){let r=Lt(i);for(let o of r)t.add(o)}}for(let s of t){let i=s.parent;for(;i;)t.add(i),i=i.parent}return t}function jt(n,t){let e=t.get(n);if(!e)return{};if(n.type==="compound"){let i=e[0];if(i){if(rt(i))return i.key}else return{}}let s={};for(let i of e)s[i.key]=jt(i,t);return s}function Vt(n){let t=new Map;for(let e of n)t.has(e)||t.set(e,[]),e.parent&&(t.has(e.parent)||t.set(e.parent,[]),t.get(e.parent).push(e));return t}function Ft(n,t){let e=j(t);return jt(n,Vt(e))}function ot(n,t){return t.type==="compound"?L(t).some(e=>e.type==="final"&&n.has(e)):t.type==="parallel"?L(t).every(e=>ot(n,e)):t.type==="final"}var V=n=>n[0]===ke;function Kt(n,t){return n.transitions.get(t)||[...n.transitions.keys()].filter(s=>Wt(t,s)).sort((s,i)=>i.length-s.length).flatMap(s=>n.transitions.get(s))}function Yt(n){let t=n.config.after;if(!t)return[];let e=i=>{let r=Ae(i,n.id),o=r.type;return n.entry.push(G(r,{id:o,delay:i})),n.exit.push($(o)),o};return Object.keys(t).flatMap(i=>{let r=t[i],o=typeof r=="string"?{target:r}:r,a=Number.isNaN(+i)?i:+i,c=e(a);return S(o).map(f=>({...f,event:c,delay:a}))}).map(i=>{let{delay:r}=i;return{...x(n,i.event,i),delay:r}})}function x(n,t,e){let s=qt(e.target),i=e.reenter??!1,r=Ue(n,s),o={...e,actions:S(e.actions),guard:e.guard,target:r,source:n,reenter:i,eventType:t,toJSON:()=>({...o,source:`#${n.id}`,target:r?r.map(a=>`#${a.id}`):void 0})};return o}function Jt(n){let t=new Map;if(n.config.on)for(let e of Object.keys(n.config.on)){if(e===St)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');let s=n.config.on[e];t.set(e,A(s).map(i=>x(n,e,i)))}if(n.config.onDone){let e=`xstate.done.state.${n.id}`;t.set(e,A(n.config.onDone).map(s=>x(n,e,s)))}for(let e of n.invoke){if(e.onDone){let s=`xstate.done.actor.${e.id}`;t.set(s,A(e.onDone).map(i=>x(n,s,i)))}if(e.onError){let s=`xstate.error.actor.${e.id}`;t.set(s,A(e.onError).map(i=>x(n,s,i)))}if(e.onSnapshot){let s=`xstate.snapshot.${e.id}`;t.set(s,A(e.onSnapshot).map(i=>x(n,s,i)))}}for(let e of n.after){let s=t.get(e.eventType);s||(s=[],t.set(e.eventType,s)),s.push(e)}return t}function Xt(n){let t=[],e=s=>{Object.values(s).forEach(i=>{if(i.config.route&&i.config.id){let r=i.config.id,o=i.config.route.guard,a=(f,p)=>f.event.to!==`#${r}`?!1:o&&typeof o=="function"?o(f,p):!0,c={...i.config.route,guard:a,target:`#${r}`};t.push(x(n,"xstate.route",c))}i.states&&e(i.states)})};e(n.states),t.length>0&&n.transitions.set("xstate.route",t)}function zt(n,t){let e=typeof t=="string"?n.states[t]:t?n.states[t.target]:void 0;if(!e&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${n.id}`);let s={source:n,actions:!t||typeof t=="string"?[]:S(t.actions),eventType:null,reenter:!1,target:e?[e]:[],toJSON:()=>({...s,source:`#${n.id}`,target:e?[`#${e.id}`]:[]})};return s}function Ue(n,t){if(t!==void 0)return t.map(e=>{if(typeof e!="string")return e;if(V(e))return n.machine.getStateNodeById(e);let s=e[0]===Tt;if(s&&!n.parent)return W(n,e.slice(1));let i=s?n.key+e:e;if(n.parent)try{return W(n.parent,i)}catch(r){throw new Error(`Invalid transition definition for state node '${n.id}':
|
|
2
|
-
${r.message}`)}else throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`)})}function Qt(n){let t=qt(n.config.target);return t?{target:t.map(e=>typeof e=="string"?W(n.parent,e):e)}:n.parent.initial}function E(n){return n.type==="history"}function Lt(n){let t=Zt(n);for(let e of t)for(let s of U(e,n))t.add(s);return t}function Zt(n){let t=new Set;function e(s){if(!t.has(s)){if(t.add(s),s.type==="compound")e(s.initial.target[0]);else if(s.type==="parallel")for(let i of L(s))e(i)}}return e(n),t}function C(n,t){if(V(t))return n.machine.getStateNodeById(t);if(!n.states)throw new Error(`Unable to retrieve child state '${t}' from '${n.id}'; no child states exist.`);let e=n.states[t];if(!e)throw new Error(`Child state '${t}' does not exist on '${n.id}'`);return e}function W(n,t){if(typeof t=="string"&&V(t))try{return n.machine.getStateNodeById(t)}catch{}let e=st(t).slice(),s=n;for(;e.length;){let i=e.shift();if(!i.length)break;s=C(s,i)}return s}function B(n,t){if(typeof t=="string"){let i=n.states[t];if(!i)throw new Error(`State '${t}' does not exist on '${n.id}'`);return[n,i]}let e=Object.keys(t),s=e.map(i=>C(n,i)).filter(Boolean);return[n.machine.root,n].concat(s,e.reduce((i,r)=>{let o=C(n,r);if(!o)return i;let a=B(o,t[r]);return i.concat(a)},[]))}function Be(n,t,e,s){let r=C(n,t).next(e,s);return!r||!r.length?n.next(e,s):r}function Ge(n,t,e,s){let i=Object.keys(t),r=C(n,i[0]),o=at(r,t[i[0]],e,s);return!o||!o.length?n.next(e,s):o}function qe(n,t,e,s){let i=[];for(let r of Object.keys(t)){let o=t[r];if(!o)continue;let a=C(n,r),c=at(a,o,e,s);c&&i.push(...c)}return i.length?i:n.next(e,s)}function at(n,t,e,s){return typeof t=="string"?Be(n,t,e,s):Object.keys(t).length===1?Ge(n,t,e,s):qe(n,t,e,s)}function We(n){return Object.keys(n.states).map(t=>n.states[t]).filter(t=>t.type==="history")}function k(n,t){let e=n;for(;e.parent&&e.parent!==t;)e=e.parent;return e.parent===t}function He(n,t){let e=new Set(n),s=new Set(t);for(let i of e)if(s.has(i))return!0;for(let i of s)if(e.has(i))return!0;return!1}function te(n,t,e){let s=new Set;for(let i of n){let r=!1,o=new Set;for(let a of s)if(He(mt([i],t,e),mt([a],t,e)))if(k(i.source,a.source))o.add(a);else{r=!0;break}if(!r){for(let a of o)s.delete(a);s.add(i)}}return Array.from(s)}function je(n){let[t,...e]=n;for(let s of U(t,void 0))if(e.every(i=>k(i,s)))return s}function Et(n,t){if(!n.target)return[];let e=new Set;for(let s of n.target)if(E(s))if(t[s.id])for(let i of t[s.id])e.add(i);else for(let i of Et(Qt(s),t))e.add(i);else e.add(s);return[...e]}function ee(n,t){let e=Et(n,t);if(!e)return;if(!n.reenter&&e.every(i=>i===n.source||k(i,n.source)))return n.source;let s=je(e.concat(n.source));if(s)return s;if(!n.reenter)return n.source.machine.root}function mt(n,t,e){var i;let s=new Set;for(let r of n)if((i=r.target)!=null&&i.length){let o=ee(r,e);r.reenter&&r.source===o&&s.add(o);for(let a of t)k(a,o)&&s.add(a)}return[...s]}function Ve(n,t){if(n.length!==t.size)return!1;for(let e of n)if(!t.has(e))return!1;return!0}function It(n,t,e,s,i){return vt([{target:[...Zt(n)],source:n,reenter:!0,actions:[],eventType:null,toJSON:null}],t,e,s,!0,i)}function vt(n,t,e,s,i,r){let o=[];if(!n.length)return[t,o];let a=e.actionExecutor;e.actionExecutor=c=>{o.push(c),a(c)};try{let c=new Set(t._nodes),f=t.historyValue,p=te(n,c,f),d=t;i||([d,f]=Je(d,s,e,p,c,f,r,e.actionExecutor)),d=I(d,s,e,p.flatMap(l=>l.actions),r,void 0),d=Ke(d,s,e,p,c,r,f,i);let u=[...c];d.status==="done"&&(d=I(d,s,e,u.sort((l,h)=>h.order-l.order).flatMap(l=>l.exit),r,void 0));try{return f===t.historyValue&&Ve(t._nodes,c)?[d,o]:[b(d,{_nodes:u,historyValue:f}),o]}catch(l){throw l}}finally{e.actionExecutor=a}}function Fe(n,t,e,s,i){if(s.output===void 0)return;let r=yt(i.id,i.output!==void 0&&i.parent?_t(i.output,n.context,t,e.self):void 0);return _t(s.output,n.context,r,e.self)}function Ke(n,t,e,s,i,r,o,a){let c=n,f=new Set,p=new Set;Ye(s,o,p,f),a&&p.add(n.machine.root);let d=new Set;for(let u of[...f].sort((l,h)=>l.order-h.order)){i.add(u);let l=[];l.push(...u.entry);for(let h of u.invoke)l.push(M(h.src,{...h,syncSnapshot:!!h.onSnapshot}));if(p.has(u)){let h=u.initial.actions;l.push(...h)}if(c=I(c,t,e,l,r,u.invoke.map(h=>h.id)),u.type==="final"){let h=u.parent,y=(h==null?void 0:h.type)==="parallel"?h:h==null?void 0:h.parent,_=y||u;for((h==null?void 0:h.type)==="compound"&&r.push(yt(h.id,u.output!==void 0?_t(u.output,c.context,t,e.self):void 0));(y==null?void 0:y.type)==="parallel"&&!d.has(y)&&ot(i,y);)d.add(y),r.push(yt(y.id)),_=y,y=y.parent;if(y)continue;c=b(c,{status:"done",output:Fe(c,t,e,c.machine.root,_)})}}return c}function Ye(n,t,e,s){for(let i of n){let r=ee(i,t);for(let a of i.target||[])!E(a)&&(i.source!==a||i.source!==r||i.reenter)&&(s.add(a),e.add(a)),R(a,t,e,s);let o=Et(i,t);for(let a of o){let c=U(a,r);(r==null?void 0:r.type)==="parallel"&&c.push(r),ne(s,t,e,c,!i.source.parent&&i.reenter?void 0:r)}}}function R(n,t,e,s){var i;if(E(n))if(t[n.id]){let r=t[n.id];for(let o of r)s.add(o),R(o,t,e,s);for(let o of r)pt(o,n.parent,s,t,e)}else{let r=Qt(n);for(let o of r.target)s.add(o),r===((i=n.parent)==null?void 0:i.initial)&&e.add(n.parent),R(o,t,e,s);for(let o of r.target)pt(o,n.parent,s,t,e)}else if(n.type==="compound"){let[r]=n.initial.target;E(r)||(s.add(r),e.add(r)),R(r,t,e,s),pt(r,n,s,t,e)}else if(n.type==="parallel")for(let r of L(n).filter(o=>!E(o)))[...s].some(o=>k(o,r))||(E(r)||(s.add(r),e.add(r)),R(r,t,e,s))}function ne(n,t,e,s,i){for(let r of s)if((!i||k(r,i))&&n.add(r),r.type==="parallel")for(let o of L(r).filter(a=>!E(a)))[...n].some(a=>k(a,o))||(n.add(o),R(o,t,e,n))}function pt(n,t,e,s,i){ne(e,s,i,U(n,t))}function Je(n,t,e,s,i,r,o,a){let c=n,f=mt(s,i,r);f.sort((d,u)=>u.order-d.order);let p;for(let d of f)for(let u of We(d)){let l;u.history==="deep"?l=h=>rt(h)&&k(h,d):l=h=>h.parent===d,p??={...r},p[u.id]=Array.from(i).filter(l)}for(let d of f)c=I(c,t,e,[...d.exit,...d.invoke.map(u=>w(u.id))],o,void 0),i.delete(d);return[c,p||r]}function Xe(n,t){return n.implementations.actions[t]}function se(n,t,e,s,i,r){let{machine:o}=n,a=n;for(let c of s){let f=typeof c=="function",p=f?c:Xe(o,typeof c=="string"?c:c.type),d={context:a.context,event:t,self:e.self,system:e.system},u=f||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)){e.actionExecutor({type:typeof c=="string"?c:typeof c=="object"?c.type:c.name||"(anonymous)",info:d,params:u,exec:p});continue}let l=p,[h,y,_]=l.resolve(e,a,d,u,p,i);a=h,"retryResolve"in l&&(r==null||r.push([l,y])),"execute"in l&&e.actionExecutor({type:l.type,info:d,params:y,exec:l.execute.bind(null,e,y)}),_&&(a=se(a,t,e,_,i,r))}return a}function I(n,t,e,s,i,r){let o=r?[]:void 0,a=se(n,t,e,s,{internalQueue:i,deferredActorIds:r},o);return o==null||o.forEach(([c,f])=>{c.retryResolve(e,a,f)}),a}function F(n,t,e,s){let i=n,r=[];function o(f,p,d){e.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:e.self,event:p,snapshot:f[0],_transitions:d}),r.push(f)}if(t.type===gt)return i=b(Ct(i,t,e),{status:"stopped"}),o([i,[]],t,[]),{snapshot:i,microsteps:r};let a=t;if(a.type!==Mt){let f=a,p=we(f),d=$t(f,i);if(p&&!d.length)return i=b(n,{status:"error",error:f.error}),o([i,[]],f,[]),{snapshot:i,microsteps:r};let u=vt(d,n,e,a,!1,s);i=u[0],o(u,f,d)}let c=!0;for(;i.status==="active";){let f=c?ze(i,a):[],p=f.length?i:void 0;if(!f.length){if(!s.length)break;a=s.shift(),f=$t(a,i)}let d=vt(f,i,e,a,!1,s);i=d[0],c=i!==p,o(d,a,f)}return i.status!=="active"&&Ct(i,a,e),{snapshot:i,microsteps:r}}function Ct(n,t,e){return I(n,t,e,Object.values(n.children).map(s=>w(s)),[],void 0)}function $t(n,t){return t.machine.getTransitionData(t,n)}function ze(n,t){let e=new Set,s=n._nodes.filter(rt);for(let i of s)t:for(let r of[i].concat(U(i,void 0)))if(r.always){for(let o of r.always)if(o.guard===void 0||N(o.guard,n.context,t,n)){e.add(o);break t}}return te(Array.from(e),new Set(n._nodes),n.historyValue)}function ie(n,t){let e=j(B(n,t));return Ft(n,[...e])}function re(n){return!!n&&typeof n=="object"&&"machine"in n&&"value"in n}var Qe=function(t){return kt(t,this.value)},Ze=function(t){return this.tags.has(t)},tn=function(t){let e=this.machine.getTransitionData(this,t);return!!(e!=null&&e.length)&&e.some(s=>s.target!==void 0||s.actions.length)},en=function(){let{_nodes:t,tags:e,machine:s,getMeta:i,toJSON:r,can:o,hasTag:a,matches:c,...f}=this;return{...f,tags:Array.from(e)}},nn=function(){return this._nodes.reduce((t,e)=>(e.meta!==void 0&&(t[e.id]=e.meta),t),{})};function K(n,t){return{status:n.status,output:n.output,error:n.error,machine:t,context:n.context,_nodes:n._nodes,value:Ft(t.root,n._nodes),tags:new Set(n._nodes.flatMap(e=>e.tags)),children:n.children,historyValue:n.historyValue||{},matches:Qe,hasTag:Ze,can:tn,getMeta:nn,toJSON:en}}function b(n,t={}){return K({...n,...t},n.machine)}function sn(n){if(typeof n!="object"||n===null)return{};let t={};for(let e in n){let s=n[e];Array.isArray(s)&&(t[e]=s.map(i=>({id:i.id})))}return t}function oe(n,t){let{_nodes:e,tags:s,machine:i,children:r,context:o,can:a,hasTag:c,matches:f,getMeta:p,toJSON:d,...u}=n,l={};for(let y in r){let _=r[y];l[y]={snapshot:_.getPersistedSnapshot(t),src:_.src,systemId:_.systemId,syncSnapshot:_._syncSnapshot}}return{...u,context:ae(o),children:l,historyValue:sn(u.historyValue)}}function ae(n){let t;for(let e in n){let s=n[e];if(s&&typeof s=="object")if("sessionId"in s&&"send"in s&&"ref"in s)t??=Array.isArray(n)?n.slice():{...n},t[e]={xstate$$type:it,id:s.id};else{let i=ae(s);i!==s&&(t??=Array.isArray(n)?n.slice():{...n},t[e]=i)}}return t??n}function rn(n,t,e,s,{event:i,id:r,delay:o},{internalQueue:a}){let c=t.machine.implementations.delays;if(typeof i=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${i}" }) instead`);let f=typeof i=="function"?i(e,s):i,p;if(typeof o=="string"){let d=c&&c[o];p=typeof d=="function"?d(e,s):d}else p=typeof o=="function"?o(e,s):o;return typeof p!="number"&&a.push(f),[t,{event:f,id:r,delay:p},void 0]}function on(n,t){let{event:e,delay:s,id:i}=t;if(typeof s=="number"){n.defer(()=>{let r=n.self;n.system.scheduler.schedule(r,r,e,s,i)});return}}function G(n,t){function e(s,i){}return e.type="xstate.raise",e.event=n,e.id=t==null?void 0:t.id,e.delay=t==null?void 0:t.delay,e.resolve=rn,e.execute=on,e}function ce(n,t){return{config:n,transition:(e,s,i)=>({...e,context:n(e.context,s,i)}),getInitialSnapshot:(e,s)=>({status:"active",output:void 0,error:void 0,context:typeof t=="function"?t({input:s}):t}),getPersistedSnapshot:e=>e,restoreSnapshot:e=>e}}var Dn=ce(n=>{},void 0);function an(n,{machine:t,context:e},s,i){let r=(o,a)=>{if(typeof o=="string"){let c=H(t,o);if(!c)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);let f=v(c,{id:a==null?void 0:a.id,parent:n.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:typeof(a==null?void 0:a.input)=="function"?a.input({context:e,event:s,self:n.self}):a==null?void 0:a.input,src:o,systemId:a==null?void 0:a.systemId});return i[f.id]=f,f}else return v(o,{id:a==null?void 0:a.id,parent:n.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:a==null?void 0:a.input,src:o,systemId:a==null?void 0:a.systemId})};return(o,a)=>{let c=r(o,a);return i[c.id]=c,n.defer(()=>{c._processingStatus!==m.Stopped&&c.start()}),c}}function cn(n,t,e,s,{assignment:i}){if(!t.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");let r={},o={context:t.context,event:e.event,spawn:an(n,t,e.event,r),self:n.self,system:n.system},a={};if(typeof i=="function")a=i(o,s);else for(let f of Object.keys(i)){let p=i[f];a[f]=typeof p=="function"?p(o,s):p}let c=Object.assign({},t.context,a);return[b(t,{context:c,children:Object.keys(r).length?{...t.children,...r}:t.children}),void 0,void 0]}function g(n){function t(e,s){}return t.type="xstate.assign",t.assignment=n,t.resolve=cn,t}var ue=new WeakMap;function q(n,t,e){let s=ue.get(n);return s?t in s||(s[t]=e()):(s={[t]:e()},ue.set(n,s)),s[t]}var un={},Y=n=>typeof n=="string"?{type:n}:typeof n=="function"?"resolve"in n?{type:n.type}:{type:n.name}:n,ct=class n{constructor(t,e){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=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(Tt),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?bt(this.config.states,(s,i)=>new n(s,{_parent:this,_key:i,_machine:this.machine})):un,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=S(this.config.entry).slice(),this.exit=S(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=S(t.tags).slice()}_initialize(){this.transitions=Jt(this),this.config.always&&(this.always=A(this.config.always).map(t=>x(this,St,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(Y),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Y),eventType:null})}:void 0,history:this.history,states:bt(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(Y)})),entry:this.entry.map(Y),exit:this.exit.map(Y),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",()=>S(this.config.invoke).map((t,e)=>{let{src:s,systemId:i}=t,r=t.id??At(this.id,e),o=typeof s=="string"?s:`xstate.invoke.${At(this.id,e)}`;return{...t,src:o,id:r,systemId:i,toJSON(){let{onDone:a,onError:c,...f}=t;return{...f,type:"xstate.invoke",src:o,id:r}}}}))}get on(){return q(this,"on",()=>[...this.transitions].flatMap(([e,s])=>s.map(i=>[e,i])).reduce((e,[s,i])=>(e[s]=e[s]||[],e[s].push(i),e),{}))}get after(){return q(this,"delayedTransitions",()=>Yt(this))}get initial(){return q(this,"initial",()=>zt(this,this.config.initial))}next(t,e){let s=e.type,i=[],r,o=q(this,`candidates-${s}`,()=>Kt(this,s));for(let a of o){let{guard:c}=a,f=t.context,p=!1;try{p=!c||N(c,f,e,t)}catch(d){let 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
|
-
${d.message}`)}if(p){i.push(...a.actions),r=a;break}}return r?[r]:void 0}get events(){return q(this,"events",()=>{let{states:t}=this,e=new Set(this.ownEvents);if(t)for(let s of Object.keys(t)){let i=t[s];if(i.states)for(let r of i.events)e.add(`${r}`)}return Array.from(e)})}get ownEvents(){let t=Object.keys(Object.fromEntries(this.transitions)),e=new Set(t.filter(s=>this.transitions.get(s).some(i=>!(!i.target&&!i.actions.length&&!i.reenter))));return Array.from(e)}},dn="#",ut=class n{constructor(t,e){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:(e==null?void 0:e.actors)??{},actions:(e==null?void 0:e.actions)??{},delays:(e==null?void 0:e.delays)??{},guards:(e==null?void 0:e.guards)??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new ct(t,{_key:this.id,_machine:this}),this.root._initialize(),Xt(this.root),this.states=this.root.states,this.events=this.root.events}provide(t){let{actions:e,guards:s,actors:i,delays:r}=this.implementations;return new n(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...i,...t.actors},delays:{...r,...t.delays}})}resolveState(t){let e=ie(this.root,t.value),s=j(B(this.root,e));return K({_nodes:[...s],context:t.context||{},children:{},status:ot(s,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return F(t,e,s,[]).snapshot}microstep(t,e,s){return F(t,e,s,[]).microsteps.map(([i])=>i)}getTransitionData(t,e){return at(this.root,t.value,t,e)||[]}_getPreInitialState(t,e,s){let{context:i}=this.config,r=K({context:typeof i!="function"&&i?i:{},_nodes:[this.root],children:{},status:"active"},this);return typeof i=="function"?I(r,e,t,[g(({spawn:a,event:c,self:f})=>i({spawn:a,input:c.input,self:f}))],s,void 0):r}getInitialSnapshot(t,e){let s=nt(e),i=[],r=this._getPreInitialState(t,s,i),[o]=It(this.root,r,t,s,i),{snapshot:a}=F(o,s,t,i);return a}start(t){Object.values(t.children).forEach(e=>{e.getSnapshot().status==="active"&&e.start()})}getStateNodeById(t){let e=st(t),s=e.slice(1),i=V(e[0])?e[0].slice(dn.length):e[0],r=this.idMap.get(i);if(!r)throw new Error(`Child state node '#${i}' does not exist on machine '${this.id}'`);return W(r,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return oe(t,e)}restoreSnapshot(t,e){let s={},i=t.children;Object.keys(i).forEach(d=>{let u=i[d],l=u.snapshot,h=u.src,y=typeof h=="string"?H(this,h):h;if(!y)return;let _=v(y,{id:d,parent:e.self,syncSnapshot:u.syncSnapshot,snapshot:l,src:h,systemId:u.systemId});s[d]=_});function r(d,u){if(u instanceof ct)return u;try{return d.machine.getStateNodeById(u.id)}catch{}}function o(d,u){if(!u||typeof u!="object")return{};let l={};for(let h in u){let y=u[h];for(let _ of y){let P=r(d,_);P&&(l[h]??=[],l[h].push(P))}}return l}let a=o(this.root,t.historyValue),c=K({...t,children:s,_nodes:Array.from(j(B(this.root,t.value))),historyValue:a},this),f=new Set;function p(d,u){if(!f.has(d)){f.add(d);for(let l in d){let h=d[l];if(h&&typeof h=="object"){if("xstate$$type"in h&&h.xstate$$type===it){d[l]=u[h.id];continue}p(h,u)}}}}return p(c.context,s),c}};function hn(n,t,e,s,{event:i}){let r=typeof i=="function"?i(e,s):i;return[t,{event:r},void 0]}function ln(n,{event:t}){n.defer(()=>n.emit(t))}function Dt(n){function t(e,s){}return t.type="xstate.emit",t.event=n,t.resolve=hn,t.execute=ln,t}var wt=(function(n){return n.Parent="#_parent",n.Internal="#_internal",n})({});function fn(n,t,e,s,{to:i,event:r,id:o,delay:a},c){var h;let f=t.machine.implementations.delays;if(typeof r=="string")throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${r}" }) instead`);let p=typeof r=="function"?r(e,s):r,d;if(typeof a=="string"){let y=f&&f[a];d=typeof y=="function"?y(e,s):y}else d=typeof a=="function"?a(e,s):a;let u=typeof i=="function"?i(e,s):i,l;if(typeof u=="string"){if(u===wt.Parent?l=n.self._parent:u===wt.Internal?l=n.self:u.startsWith("#_")?l=t.children[u.slice(2)]:l=(h=c.deferredActorIds)!=null&&h.includes(u)?u:t.children[u],!l)throw new Error(`Unable to send event to actor '${u}' from machine '${t.machine.id}'.`)}else l=u||n.self;return[t,{to:l,targetId:typeof u=="string"?u:void 0,event:p,id:o,delay:d},void 0]}function pn(n,t,e){typeof e.to=="string"&&(e.to=t.children[e.to])}function gn(n,t){n.defer(()=>{let{to:e,event:s,delay:i,id:r}=t;if(typeof i=="number"){n.system.scheduler.schedule(n.self,e,s,i,r);return}n.system._relay(n.self,e,s.type===Nt?xt(n.self.id,s.data):s)})}function dt(n,t,e){function s(i,r){}return s.type="xstate.sendTo",s.to=n,s.event=t,s.id=e==null?void 0:e.id,s.delay=e==null?void 0:e.delay,s.resolve=fn,s.retryResolve=pn,s.execute=gn,s}function yn(n,t){return dt(wt.Parent,n,t)}function _n(n,t,e,s,{collect:i}){let r=[],o=function(c){r.push(c)};return o.assign=(...a)=>{r.push(g(...a))},o.cancel=(...a)=>{r.push($(...a))},o.raise=(...a)=>{r.push(G(...a))},o.sendTo=(...a)=>{r.push(dt(...a))},o.sendParent=(...a)=>{r.push(yn(...a))},o.spawnChild=(...a)=>{r.push(M(...a))},o.stopChild=(...a)=>{r.push(w(...a))},o.emit=(...a)=>{r.push(Dt(...a))},i({context:e.context,event:e.event,enqueue:o,check:a=>N(a,t.context,e.event,t),self:n.self,system:n.system},s),[t,void 0,r]}function de(n){function t(e,s){}return t.type="xstate.enqueueActions",t.collect=n,t.resolve=_n,t}function mn(n,t,e,s,{value:i,label:r}){return[t,{value:typeof i=="function"?i(e,s):i,label:r},void 0]}function vn({logger:n},{value:t,label:e}){e?n(e,t):n(t)}function he(n=({context:e,event:s})=>({context:e,event:s}),t){function e(s,i){}return e.type="xstate.log",e.value=n,e.label=t,e.resolve=mn,e.execute=vn,e}function Tn(n,t){return new ut(n,t)}function J({schemas:n,actors:t,actions:e,guards:s,delays:i}){return{assign:g,sendTo:dt,raise:G,log:he,cancel:$,stopChild:w,enqueueActions:de,emit:Dt,spawnChild:M,createStateConfig:r=>r,createAction:r=>r,createMachine:r=>Tn({...r,schemas:n},{actors:t,actions:e,guards:s,delays:i}),extend:r=>J({schemas:n,actors:t,actions:{...e,...r.actions},guards:{...s,...r.guards},delays:{...i,...r.delays}})}}var Sn=typeof window<"u",X;function xn(){if(!Sn)return null;let n=window.AudioContext??window.webkitAudioContext;return n?new n:null}function z(){return X===void 0?null:X}function le(){X===void 0&&(X=xn());let n=X;return n&&n.state==="suspended"?n.resume():Promise.resolve()}var ht=typeof navigator<"u"&&"mediaSession"in navigator;function fe(n){if(!ht)return;let{mediaSession:t}=navigator;t.setActionHandler("play",n.onPlay),t.setActionHandler("pause",n.onPause),t.setActionHandler("nexttrack",n.onNext),t.setActionHandler("previoustrack",n.onPrevious),t.setActionHandler("seekto",e=>{e.seekTime!=null&&n.onSeek(e.seekTime)})}function D(n){if(ht){if(!n){navigator.mediaSession.metadata=null;return}navigator.mediaSession.metadata=new MediaMetadata({title:n.title??"",artist:n.artist??"",album:n.album??"",artwork:n.artwork??[]})}}function pe(n){ht&&(navigator.mediaSession.playbackState=n?"playing":"paused")}function ge(n,t,e=1){if(ht)try{navigator.mediaSession.setPositionState({duration:n,position:t,playbackRate:e})}catch{}}function ye(n){return J({types:{context:{},events:{}},guards:{hasNextTrack:({context:t})=>t.currentTrackIndex+1<t.trackCount,playImmediately:({event:t})=>!!t.playImmediately}}).createMachine({id:"queue",initial:"idle",context:n,on:{ADD_TRACK:{actions:g({trackCount:({context:t})=>t.trackCount+1})},REMOVE_TRACK:{actions:g({trackCount:({context:t})=>Math.max(0,t.trackCount-1),currentTrackIndex:({context:t,event:e})=>e.index<t.currentTrackIndex?Math.max(0,t.currentTrackIndex-1):t.currentTrackIndex})}},states:{idle:{on:{PLAY:{target:"playing"},GOTO:[{guard:"playImmediately",target:"playing",actions:g({currentTrackIndex:({event:t})=>t.index})},{target:"paused",actions:g({currentTrackIndex:({event:t})=>t.index})}]}},playing:{on:{PAUSE:{target:"paused"},TOGGLE:{target:"paused"},NEXT:{actions:g({currentTrackIndex:({context:t})=>{let e=t.currentTrackIndex+1;return e<t.trackCount?e:t.currentTrackIndex}})},PREVIOUS:{actions:g({currentTrackIndex:({context:t})=>Math.max(0,t.currentTrackIndex-1)})},GOTO:{actions:g({currentTrackIndex:({event:t})=>t.index})},SEEK:{},TRACK_ENDED:[{guard:"hasNextTrack",target:"playing",actions:g({currentTrackIndex:({context:t})=>t.currentTrackIndex+1})},{target:"ended"}],TRACK_LOADED:{}}},paused:{on:{PLAY:{target:"playing"},TOGGLE:{target:"playing"},NEXT:{actions:g({currentTrackIndex:({context:t})=>{let e=t.currentTrackIndex+1;return e<t.trackCount?e:t.currentTrackIndex}})},PREVIOUS:{actions:g({currentTrackIndex:({context:t})=>Math.max(0,t.currentTrackIndex-1)})},GOTO:[{guard:"playImmediately",target:"playing",actions:g({currentTrackIndex:({event:t})=>t.index})},{actions:g({currentTrackIndex:({event:t})=>t.index})}],SEEK:{},TRACK_ENDED:[{guard:"hasNextTrack",target:"paused",actions:g({currentTrackIndex:({context:t})=>t.currentTrackIndex+1})},{target:"ended"}]}},ended:{on:{PLAY:{target:"playing",actions:g({currentTrackIndex:()=>0})},GOTO:[{guard:"playImmediately",target:"playing",actions:g({currentTrackIndex:({event:t})=>t.index})},{target:"paused",actions:g({currentTrackIndex:({event:t})=>t.index})}]}}}})}function _e(n){return J({types:{context:{},events:{}}}).createMachine({id:"track",initial:"idle",context:n,states:{idle:{on:{HTML5_ENDED:{},PLAY:{target:"html5",actions:g({isPlaying:()=>!0})},PLAY_WEBAUDIO:{target:"webaudio",actions:g({isPlaying:()=>!0,webAudioLoadingState:()=>"LOADED",playbackType:()=>"WEBAUDIO"})},PRELOAD:{target:"loading"},BUFFER_LOADING:{actions:g({webAudioLoadingState:()=>"LOADING"})},URL_RESOLVED:{actions:g({resolvedUrl:({event:t})=>t.url})}}},html5:{on:{PAUSE:{actions:g({isPlaying:()=>!1})},PLAY:{actions:g({isPlaying:()=>!0})},BUFFER_LOADING:{actions:g({webAudioLoadingState:()=>"LOADING"})},PLAY_WEBAUDIO:{target:"webaudio",actions:g({isPlaying:()=>!0,webAudioLoadingState:()=>"LOADED",playbackType:()=>"WEBAUDIO"})},BUFFER_READY:{actions:g({webAudioLoadingState:()=>"LOADED"})},BUFFER_ERROR:{actions:g({webAudioLoadingState:()=>"ERROR"})},SEEK:{actions:g({pausedAtTrackTime:({event:t})=>t.time})},HTML5_ENDED:{target:"idle",actions:g({isPlaying:()=>!1})},URL_RESOLVED:{actions:g({resolvedUrl:({event:t})=>t.url})},DEACTIVATE:{target:"loading",actions:g({isPlaying:()=>!1})}}},loading:{on:{BUFFER_LOADING:{actions:g({webAudioLoadingState:()=>"LOADING"})},BUFFER_READY:{target:"idle",actions:g({webAudioLoadingState:()=>"LOADED"})},BUFFER_ERROR:{target:"idle",actions:g({webAudioLoadingState:()=>"ERROR"})},PLAY:{target:"html5",actions:g({isPlaying:()=>!0})},PLAY_WEBAUDIO:{target:"webaudio",actions:g({isPlaying:()=>!0,webAudioLoadingState:()=>"LOADED",playbackType:()=>"WEBAUDIO"})},URL_RESOLVED:{actions:g({resolvedUrl:({event:t})=>t.url})}}},webaudio:{on:{PAUSE:{actions:g({isPlaying:()=>!1})},PLAY:{actions:g({isPlaying:()=>!0})},PLAY_WEBAUDIO:{actions:g({isPlaying:()=>!0,playbackType:()=>"WEBAUDIO"})},SEEK:{actions:g({pausedAtTrackTime:({event:t})=>t.time})},SET_VOLUME:{},WEBAUDIO_ENDED:{target:"idle",actions:g({isPlaying:()=>!1})},DEACTIVATE:{target:"idle",actions:g({isPlaying:()=>!1})}}}}})}var kn=5,Q=class{index;metadata;_trackUrl;_resolvedUrl;skipHEAD;loadedHEAD=!1;abortController=null;audio;_webAudioDisabled;get ctx(){if(this._webAudioDisabled)return null;let t=z();return t&&!this.gainNode&&(this.gainNode=t.createGain(),this.gainNode.gain.value=this.audio.volume),t}gainNode=null;sourceNode=null;audioBuffer=null;webAudioStartedAt=0;pausedAtTrackTime=0;scheduledStartContextTime=null;_actor;queueRef;rafId=null;_notifiedLookahead=!1;constructor(t){this.index=t.index,this._trackUrl=t.trackUrl,this._resolvedUrl=t.trackUrl,this.skipHEAD=t.skipHEAD??!1,this.metadata=t.metadata??{},this.queueRef=t.queue,this.audio=new Audio,this.audio.preload="none",this.audio.src=this._trackUrl,this.audio.volume=t.queue.volume,this.audio.controls=!1,this.audio.onerror=()=>{var r,o;let s=(r=this.audio.error)==null?void 0:r.code;if(s===1)return;let i=((o=this.audio.error)==null?void 0:o.message)??"unknown";this.queueRef.onError(new Error(`HTML5 audio error on track ${this.index} (code ${s}): ${i}`))},this.audio.onended=()=>{let s=this._actor.getSnapshot().value;this.queueRef.onDebug(`audio.onended track=${this.index} machineState=${s} queueIdx=${this.queueRef.currentTrackIndex}`),(s==="html5"||s==="idle")&&(this._actor.send({type:"HTML5_ENDED"}),this.queueRef.onTrackEnded(this))},this._webAudioDisabled=t.queue.webAudioIsDisabled;let e={trackUrl:this._trackUrl,resolvedUrl:this._trackUrl,skipHEAD:this.skipHEAD,playbackType:"HTML5",webAudioLoadingState:"NONE",webAudioStartedAt:0,pausedAtTrackTime:0,isPlaying:!1};this._actor=v(_e(e)),this._actor.start()}play(){let t=this._actor.getSnapshot().value,e=!1;this.queueRef.onDebug(`Track.play() track=${this.index} machineState=${t} hasBuffer=${!!this.audioBuffer} hasCtx=${!!this.ctx} audioPaused=${this.audio.paused}`),t==="webaudio"?e=this._playWebAudio():this.audioBuffer&&this.ctx&&(t==="loading"||t==="idle")&&(e=this._playWebAudio()),e||t==="html5"&&!this.audio.paused||this._playHtml5(),this._actor.send({type:e?"PLAY_WEBAUDIO":"PLAY"}),this.startProgressLoop()}pause(){this._actor.getSnapshot().value==="webaudio"?(this.pausedAtTrackTime=this.currentTime,this._stopSourceNode(),this._disconnectGain()):this.audio.pause(),this._actor.send({type:"PAUSE"}),this._stopProgressLoop(),this.queueRef.onProgress(this.toInfo())}seek(t){let e=Math.max(0,isNaN(this.duration)?t:Math.min(t,this.duration));if(this.pausedAtTrackTime=e,this._actor.getSnapshot().value==="webaudio"){let i=this._actor.getSnapshot().context.isPlaying;this._stopSourceNode(),this.scheduledStartContextTime=null,i&&this._startSourceNode(e)}else this.audio.preload!=="auto"&&(this.audio.preload="auto"),this.audio.readyState>=HTMLMediaElement.HAVE_METADATA?this.audio.currentTime=e:(this.audio.addEventListener("loadedmetadata",()=>{this.audio.currentTime=e},{once:!0}),this.audio.load());this._actor.send({type:"SEEK",time:e}),this.queueRef.onProgress(this.toInfo())}setVolume(t){let e=Math.min(1,Math.max(0,t));this.audio.volume=e,this.gainNode&&(this.gainNode.gain.value=e),this._actor.send({type:"SET_VOLUME",volume:e})}preload(){this.queueRef.onDebug(`preload() track=${this.index} state=${this._actor.getSnapshot().value} hasBuffer=${!!this.audioBuffer} hasCtx=${!!this.ctx}`),this._actor.getSnapshot().value==="idle"&&this._actor.send({type:"PRELOAD"}),!(this.audioBuffer||!this.ctx)&&this._startLoad()}seekToEnd(t=6){let e=this.duration;!isNaN(e)&&e>t&&this.seek(e-t)}activate(){this._actor.getSnapshot().value==="webaudio"&&(this._stopSourceNode(),this._disconnectGain(),this.scheduledStartContextTime=null,this._stopProgressLoop(),this._actor.send({type:"DEACTIVATE"})),this.webAudioStartedAt=0,this.pausedAtTrackTime=0,this._notifiedLookahead=!1,(this.audio.ended||this.audio.currentTime>0)&&(this.audio.currentTime=0)}deactivate(){this.queueRef.onDebug(`Track.deactivate() track=${this.index} machineState=${this._actor.getSnapshot().value} isPlaying=${this.isPlaying}`),this._stopSourceNode(),this._disconnectGain(),this.webAudioStartedAt=0,this.pausedAtTrackTime=0,this.scheduledStartContextTime=null,this.audio.pause(),this.audio.currentTime=0,this._stopProgressLoop(),this._actor.send({type:"DEACTIVATE"}),this.queueRef.onDebug(`Track.deactivate() done track=${this.index} machineState=${this._actor.getSnapshot().value}`)}destroy(){var t,e;this.deactivate(),(t=this.abortController)==null||t.abort(),this.audioBuffer=null,(e=this.gainNode)==null||e.disconnect(),this.gainNode=null,this._actor.stop()}cancelGaplessStart(){this.scheduledStartContextTime!==null&&(this._stopSourceNode(),this._disconnectGain(),this.scheduledStartContextTime=null,this.webAudioStartedAt=0,this.pausedAtTrackTime=0,this._stopProgressLoop(),this._actor.send({type:"DEACTIVATE"}))}scheduleGaplessStart(t){!this.ctx||!this.audioBuffer||!this.gainNode||(this.scheduledStartContextTime=t,this._stopSourceNode(),this.sourceNode=this.ctx.createBufferSource(),this.sourceNode.buffer=this.audioBuffer,this.sourceNode.connect(this.gainNode),this.gainNode.connect(this.ctx.destination),this.sourceNode.onended=this._handleWebAudioEnded,this.sourceNode.start(t,0),this.webAudioStartedAt=t,this._actor.send({type:"PLAY_WEBAUDIO"}),this.queueRef.onDebug(`scheduleGaplessStart track=${this.index} when=${t.toFixed(3)} ctxNow=${this.ctx.currentTime.toFixed(3)} delta=${(t-this.ctx.currentTime).toFixed(3)}s ctxState=${this.ctx.state}`))}get currentTime(){return this._isUsingWebAudio?this._actor.getSnapshot().context.isPlaying?this.ctx?Math.max(0,this.ctx.currentTime-this.webAudioStartedAt):0:this.pausedAtTrackTime:this.audio.currentTime}get duration(){return this.audioBuffer?this.audioBuffer.duration:this.audio.duration}get isPaused(){return this._isUsingWebAudio?!this._actor.getSnapshot().context.isPlaying:this.audio.paused}get isPlaying(){return this._actor.getSnapshot().context.isPlaying}get trackUrl(){return this._resolvedUrl}get playbackType(){return this._actor.getSnapshot().context.playbackType}get webAudioLoadingState(){return this._actor.getSnapshot().context.webAudioLoadingState}get hasSourceNode(){return this.sourceNode!==null}get machineState(){return this._actor.getSnapshot().value}get isBufferLoaded(){return this.audioBuffer!==null}toInfo(){var t;return{index:this.index,currentTime:this.currentTime,duration:this.duration,isPlaying:this.isPlaying,isPaused:this.isPaused,volume:((t=this.gainNode)==null?void 0:t.gain.value)??this.audio.volume,trackUrl:this.trackUrl,playbackType:this.playbackType,webAudioLoadingState:this.webAudioLoadingState,metadata:this.metadata,machineState:this.machineState}}_playHtml5(){this.audio.preload!=="auto"&&(this.audio.preload="auto");let t=this.audio.play();t&&t.catch(e=>{e instanceof Error&&e.name==="NotAllowedError"?this.queueRef.onPlayBlocked():e instanceof Error&&e.name==="AbortError"||this.queueRef.onError(e instanceof Error?e:new Error(String(e)))})}get _isUsingWebAudio(){return this._actor.getSnapshot().value==="webaudio"}_playWebAudio(){if(!this.ctx||!this.audioBuffer||!this.gainNode)return this.queueRef.onDebug(`_playWebAudio BAIL track=${this.index} ctx=${!!this.ctx} buf=${!!this.audioBuffer} gain=${!!this.gainNode}`),!1;let e=this._actor.getSnapshot().context.isPlaying?0:this.pausedAtTrackTime;return this._startSourceNode(e),!0}_startSourceNode(t){!this.ctx||!this.audioBuffer||!this.gainNode||(this._stopSourceNode(),this.ctx.state==="suspended"&&this.ctx.resume(),this.sourceNode=this.ctx.createBufferSource(),this.sourceNode.buffer=this.audioBuffer,this.sourceNode.connect(this.gainNode),this.gainNode.connect(this.ctx.destination),this.sourceNode.onended=this._handleWebAudioEnded,this.webAudioStartedAt=this.ctx.currentTime-t,this.sourceNode.start(0,t))}_stopSourceNode(){if(this.sourceNode){this.sourceNode.onended=null;try{this.sourceNode.stop()}catch{}try{this.sourceNode.disconnect()}catch{}this.sourceNode=null}}_disconnectGain(){if(!(!this.gainNode||!this.ctx))try{this.gainNode.disconnect(this.ctx.destination)}catch{}}_handleWebAudioEnded=()=>{this.queueRef.onDebug(`_handleWebAudioEnded track=${this.index} sourceNode=${!!this.sourceNode} queueIdx=${this.queueRef.currentTrackIndex}`),this.sourceNode&&(this._actor.send({type:"WEBAUDIO_ENDED"}),this._stopProgressLoop(),this.queueRef.onTrackEnded(this))};_startLoad(){let t=this._actor.getSnapshot();if(!this.ctx||this.audioBuffer||t.context.webAudioLoadingState!=="NONE"){this.queueRef.onDebug(`_startLoad() SKIPPED track=${this.index} hasCtx=${!!this.ctx} hasBuffer=${!!this.audioBuffer} loadingState=${t.context.webAudioLoadingState}`);return}this.queueRef.onDebug(`_startLoad() STARTING track=${this.index} url=${this._resolvedUrl.slice(0,60)}`),this._actor.send({type:"BUFFER_LOADING"}),this.abortController=new AbortController;let e=s=>{fetch(s,{signal:this.abortController.signal}).then(i=>{if(!i.ok)throw new Error(`HTTP ${i.status} for ${s}`);return i.arrayBuffer()}).then(i=>this.ctx.decodeAudioData(i)).then(i=>{this.audioBuffer=i,this._actor.send({type:"BUFFER_READY"}),this.queueRef.onTrackBufferReady(this)}).catch(i=>{i instanceof Error&&i.name==="AbortError"||(console.error(`gapless.js: decode failed for track ${this.index}`,i),this._actor.send({type:"BUFFER_ERROR"}))})};this.skipHEAD||this.loadedHEAD?e(this._resolvedUrl):fetch(this._trackUrl,{method:"HEAD",signal:this.abortController.signal}).then(s=>{s.redirected&&s.url&&(this._resolvedUrl=s.url,this.audio.src=s.url,this._actor.send({type:"URL_RESOLVED",url:s.url})),this.loadedHEAD=!0,e(this._resolvedUrl)}).catch(s=>{s instanceof Error&&s.name==="AbortError"||(this.loadedHEAD=!0,e(this._trackUrl))})}startProgressLoop(){if(this.rafId!==null)return;let t=()=>{if(this.isPaused||!this.isPlaying){this.rafId=null;return}this.queueRef.onProgress(this.toInfo());let e=this.duration-this.currentTime;!this._notifiedLookahead&&!isNaN(e)&&e<=kn&&(this._notifiedLookahead=!0,this.queueRef.onTrackBufferReady(this)),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}_stopProgressLoop(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}};function me(n,t){let e=0;return(...s)=>{let i=performance.now();i-e<t||(e=i,n(...s))}}var bn=2,lt=class{_tracks=[];_actor;_onProgress;_onEnded;_onPlayNextTrack;_onPlayPreviousTrack;_onStartNewTrack;_onError;_onPlayBlocked;_onDebug;webAudioIsDisabled;_volume;_scheduledIndices=new Set;_throttledUpdatePositionState=me((t,e)=>ge(t,e),1e3);constructor(t={}){let{tracks:e=[],onProgress:s,onEnded:i,onPlayNextTrack:r,onPlayPreviousTrack:o,onStartNewTrack:a,onError:c,onPlayBlocked:f,onDebug:p,webAudioIsDisabled:d=!1,trackMetadata:u=[],volume:l=1}=t;this._volume=Math.min(1,Math.max(0,l)),this.webAudioIsDisabled=d,this._onProgress=s,this._onEnded=i,this._onPlayNextTrack=r,this._onPlayPreviousTrack=o,this._onStartNewTrack=a,this._onError=c,this._onPlayBlocked=f,this._onDebug=p,this._tracks=e.map((h,y)=>new Q({trackUrl:h,index:y,queue:this,metadata:u[y]})),this._actor=v(ye({currentTrackIndex:0,trackCount:this._tracks.length})),this._actor.subscribe(h=>{pe(h.value==="playing")}),this._actor.start(),fe({onPlay:()=>this.play(),onPause:()=>{this._actor.getSnapshot().value==="playing"&&this.pause()},onNext:()=>this.next(),onPrevious:()=>this.previous(),onSeek:h=>this.seek(h)})}play(){let t=this._currentTrack;t&&(t.play(),this._actor.send({type:"PLAY"}),D(t.metadata),this._preloadAhead(t.index),this._tryScheduleGapless(t))}pause(){var t;this._actor.send({type:"PAUSE"}),this._cancelScheduledGapless(),(t=this._currentTrack)==null||t.pause()}togglePlayPause(){this._actor.getSnapshot().value==="playing"?this.pause():this.play()}next(){var i,r;if(this._actor.getSnapshot().context.currentTrackIndex+1>=this._tracks.length)return;this._deactivateCurrent(),this._cancelAllScheduledGapless(),this._actor.send({type:"NEXT"}),this._activateCurrent(!0);let s=this._currentTrack;s&&((i=this._onStartNewTrack)==null||i.call(this,s.toInfo()),(r=this._onPlayNextTrack)==null||r.call(this,s.toInfo()),D(s.metadata)),this._preloadAhead(this._actor.getSnapshot().context.currentTrackIndex)}previous(){var s,i;let t=this._currentTrack;if(t&&t.currentTime>8){t.seek(0),t.play();return}this._deactivateCurrent(),this._cancelAllScheduledGapless(),this._actor.send({type:"PREVIOUS"}),this._activateCurrent(!0);let e=this._currentTrack;e&&((s=this._onStartNewTrack)==null||s.call(this,e.toInfo()),(i=this._onPlayPreviousTrack)==null||i.call(this,e.toInfo()),D(e.metadata))}gotoTrack(t,e=!1){var r,o;if(t<0||t>=this._tracks.length)return;let s=this._actor.getSnapshot();this.onDebug(`gotoTrack(${t}, playImmediately=${e}) queueState=${s.value} curIdx=${s.context.currentTrackIndex}`),this._deactivateCurrent(),this._cancelAllScheduledGapless(),this._actor.send({type:"GOTO",index:t,playImmediately:e});let i=this._actor.getSnapshot();if(this.onDebug(`gotoTrack after GOTO \u2192 queueState=${i.value} curIdx=${i.context.currentTrackIndex}`),e){this._activateCurrent(!0);let a=this._currentTrack;a&&(this.onDebug(`gotoTrack activateCurrent done, track=${a.index} trackState=${a.playbackType} isPlaying=${a.isPlaying}`),(r=this._onStartNewTrack)==null||r.call(this,a.toInfo()),D(a.metadata)),this._preloadAhead(t)}else(o=this._currentTrack)==null||o.seek(0)}seek(t){var e;(e=this._currentTrack)==null||e.seek(t),this._cancelAndRescheduleGapless()}setVolume(t){let e=Math.min(1,Math.max(0,t));this._volume=e;for(let s of this._tracks)s.setVolume(e)}addTrack(t,e={}){let s=this._tracks.length,i=e.metadata??{};this._tracks.push(new Q({trackUrl:t,index:s,queue:this,skipHEAD:e.skipHEAD,metadata:i})),this._actor.send({type:"ADD_TRACK"})}removeTrack(t){if(!(t<0||t>=this._tracks.length)){this._tracks[t].destroy(),this._tracks.splice(t,1);for(let e=t;e<this._tracks.length;e++)this._tracks[e].index=e;this._scheduledIndices.delete(t),this._actor.send({type:"REMOVE_TRACK",index:t})}}resumeAudioContext(){return le()}destroy(){for(let t of this._tracks)t.destroy();this._tracks=[],this._actor.stop()}get currentTrack(){var t;return(t=this._currentTrack)==null?void 0:t.toInfo()}get currentTrackIndex(){return this._actor.getSnapshot().context.currentTrackIndex}get tracks(){return this._tracks.map(t=>t.toInfo())}get isPlaying(){return this._actor.getSnapshot().value==="playing"}get isPaused(){return this._actor.getSnapshot().value==="paused"}get volume(){return this._volume}get queueSnapshot(){let t=this._actor.getSnapshot();return{state:t.value,context:t.context}}onTrackEnded(t){var i,r,o,a;let e=this._actor.getSnapshot();if(this.onDebug(`onTrackEnded track=${t.index} queueState=${e.value} curIdx=${e.context.currentTrackIndex}`),t.index!==e.context.currentTrackIndex)return;t.deactivate(),this._actor.send({type:"TRACK_ENDED"});let s=this._actor.getSnapshot();if(this.onDebug(`onTrackEnded after TRACK_ENDED \u2192 queueState=${s.value} curIdx=${s.context.currentTrackIndex}`),s.value==="ended"){(i=this._onEnded)==null||i.call(this);return}if(s.value==="playing"){let c=this._currentTrack;c&&(this._scheduledIndices.has(c.index)?(this.onDebug(`onTrackEnded: gapless track ${c.index} \u2014 sourceNode=${c.hasSourceNode} isPlaying=${c.isPlaying} machineState=${c.machineState}`),c.startProgressLoop()):c.play(),(r=this._onStartNewTrack)==null||r.call(this,c.toInfo()),(o=this._onPlayNextTrack)==null||o.call(this,c.toInfo()),D(c.metadata),this._preloadAhead(c.index))}if(s.value==="paused"){let c=this._currentTrack;c&&((a=this._onStartNewTrack)==null||a.call(this,c.toInfo()),D(c.metadata))}}onTrackBufferReady(t){this._actor.send({type:"TRACK_LOADED",index:t.index}),this._tryScheduleGapless(t),this._preloadAhead(this._actor.getSnapshot().context.currentTrackIndex)}onProgress(t){var e;t.index===this._actor.getSnapshot().context.currentTrackIndex&&(isNaN(t.duration)||this._throttledUpdatePositionState(t.duration,t.currentTime),(e=this._onProgress)==null||e.call(this,t))}onError(t){var e;(e=this._onError)==null||e.call(this,t)}onPlayBlocked(){var t;(t=this._onPlayBlocked)==null||t.call(this)}onDebug(t){var e;(e=this._onDebug)==null||e.call(this,t)}get _currentTrack(){return this._tracks[this._actor.getSnapshot().context.currentTrackIndex]}_deactivateCurrent(){var t;(t=this._currentTrack)==null||t.deactivate()}_activateCurrent(t){let e=this._currentTrack;e&&(e.activate(),t&&!this._scheduledIndices.has(e.index)&&e.play())}_preloadAhead(t){let e=t+bn+1;this.onDebug(`_preloadAhead(${t}) limit=${e} trackCount=${this._tracks.length}`);for(let s=t+1;s<this._tracks.length&&s<e;s++){let i=this._tracks[s];if(i.isBufferLoaded)this.onDebug(`_preloadAhead: track ${s} already loaded`);else{this.onDebug(`_preloadAhead: starting preload for track ${s}`),i.preload();break}}}_cancelScheduledGapless(){let e=this._actor.getSnapshot().context.currentTrackIndex+1;e<this._tracks.length&&this._scheduledIndices.has(e)&&(this._tracks[e].cancelGaplessStart(),this._scheduledIndices.delete(e),this.onDebug(`_cancelScheduledGapless: cancelled track ${e}`))}_cancelAllScheduledGapless(){var t;for(let e of this._scheduledIndices)(t=this._tracks[e])==null||t.cancelGaplessStart();this._scheduledIndices.clear()}_cancelAndRescheduleGapless(){this._cancelScheduledGapless();let t=this._currentTrack;t&&this._tryScheduleGapless(t)}_tryScheduleGapless(t){let e=z();if(!e||this.webAudioIsDisabled)return;let i=this._actor.getSnapshot().context.currentTrackIndex,r=i+1;if(r>=this._tracks.length)return;let o=this._tracks[i],a=this._tracks[r];if(!o.isBufferLoaded||!a.isBufferLoaded||this._scheduledIndices.has(r)||!o.isPlaying)return;let c=this._computeTrackEndTime(o);c!==null&&(c<e.currentTime+.01||(a.scheduleGaplessStart(c),this._scheduledIndices.add(r)))}_computeTrackEndTime(t){let e=z();if(!e||!t.isBufferLoaded)return null;let s=t.duration;if(isNaN(s))return null;if(t.scheduledStartContextTime!==null)return t.scheduledStartContextTime+s;let i=s-t.currentTime;return i<=0?null:e.currentTime+i}};export{lt as Queue,lt as default};
|
|
1
|
+
function be(){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 Ie(){let n=be();if(n.__xstate__)return n.__xstate__}var Ot=n=>{if(typeof window>"u")return;let t=Ie();t&&t.register(n)};var st=class{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){let e={value:t,next:null};if(this._current){this._last.next=e,this._last=e;return}this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){let t=this._current;this._process(t.value),this._current=t.next}this._last=null}},xt=".",we="",bt="",Pe="#",Ce="*",Ht="xstate.init",Wt="xstate.error",F="xstate.stop";function De(n,t){return{type:`xstate.after.${n}.${t}`}}function St(n,t){return{type:`xstate.done.state.${n}`,output:t}}function Le(n,t){return{type:`xstate.done.actor.${n}`,output:t,actorId:n}}function It(n,t){return{type:`xstate.error.actor.${n}`,error:t,actorId:n}}function ot(n){return{type:Ht,input:n}}function S(n){setTimeout(()=>{throw n})}var Re=typeof Symbol=="function"&&Symbol.observable||"@@observable";function wt(n,t){let e=Mt(n),s=Mt(t);return typeof s=="string"?typeof e=="string"?s===e:!1:typeof e=="string"?e in s:Object.keys(e).every(r=>r in s?wt(e[r],s[r]):!1)}function at(n){if(jt(n))return n;let t=[],e="";for(let s=0;s<n.length;s++){switch(n.charCodeAt(s)){case 92:e+=n[s+1],s++;continue;case 46:t.push(e),e="";continue}e+=n[s]}return t.push(e),t}function Mt(n){if(de(n))return n.value;if(typeof n!="string")return n;let t=at(n);return qt(t)}function qt(n){if(n.length===1)return n[0];let t={},e=t;for(let s=0;s<n.length-1;s++)if(s===n.length-2)e[n[s]]=n[s+1];else{let r=e;e={},r[n[s]]=e}return t}function Pt(n,t){let e={},s=Object.keys(n);for(let r=0;r<s.length;r++){let i=s[r];e[i]=t(n[i],i,n,r)}return e}function Ft(n){return jt(n)?n:[n]}function A(n){return n===void 0?[]:Ft(n)}function At(n,t,e,s){return typeof n=="function"?n({context:t,event:e,self:s}):n}function jt(n){return Array.isArray(n)}function Ne(n){return n.type.startsWith("xstate.error.actor")}function w(n){return Ft(n).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function Vt(n){if(!(n===void 0||n===we))return A(n)}function rt(n,t,e){var i,o,a;let s=typeof n=="object",r=s?n:void 0;return{next:(i=s?n.next:n)==null?void 0:i.bind(r),error:(o=s?n.error:t)==null?void 0:o.bind(r),complete:(a=s?n.complete:e)==null?void 0:a.bind(r)}}function Ct(n,t){return`${t}.${n}`}function V(n,t){let e=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!e)return n.implementations.actors[t];let[,s,r]=e,o=n.getStateNodeById(r).config.invoke;return(Array.isArray(o)?o[s]:o).src}function Kt(n,t){if(t===n||t===Ce)return!0;if(!t.endsWith(".*"))return!1;let e=t.split("."),s=n.split(".");for(let r=0;r<e.length;r++){let i=e[r],o=s[r];if(i==="*")return r===e.length-1;if(i!==o)return!1}return!0}function $t(n,t){return`${n.sessionId}.${t}`}var Oe=0;function Me(n,t){let e=new Map,s=new Map,r=new WeakMap,i=new Set,o={},{clock:a,logger:u}=t,f={schedule:(c,h,p,l,y=Math.random().toString(36).slice(2))=>{let _={source:c,target:h,event:p,delay:l,id:y,startedAt:Date.now()},k=$t(c,y);d._snapshot._scheduledEvents[k]=_;let xe=a.setTimeout(()=>{delete o[k],delete d._snapshot._scheduledEvents[k],d._relay(c,h,p)},l);o[k]=xe},cancel:(c,h)=>{let p=$t(c,h),l=o[p];delete o[p],delete d._snapshot._scheduledEvents[p],l!==void 0&&a.clearTimeout(l)},cancelAll:c=>{for(let h in d._snapshot._scheduledEvents){let p=d._snapshot._scheduledEvents[h];p.source===c&&f.cancel(c,p.id)}}},g=c=>{if(!i.size)return;let h={...c,rootId:n.sessionId};i.forEach(p=>{var l;return(l=p.next)==null?void 0:l.call(p,h)})},d={_snapshot:{_scheduledEvents:((t==null?void 0:t.snapshot)&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${Oe++}`,_register:(c,h)=>(e.set(c,h),c),_unregister:c=>{e.delete(c.sessionId);let h=r.get(c);h!==void 0&&(s.delete(h),r.delete(c))},get:c=>s.get(c),getAll:()=>Object.fromEntries(s.entries()),_set:(c,h)=>{let p=s.get(c);if(p&&p!==h)throw new Error(`Actor with system ID '${c}' already exists.`);s.set(c,h),r.set(h,c)},inspect:c=>{let h=rt(c);return i.add(h),{unsubscribe(){i.delete(h)}}},_sendInspectionEvent:g,_relay:(c,h,p)=>{d._sendInspectionEvent({type:"@xstate.event",sourceRef:c,actorRef:h,event:p}),h._send(p)},scheduler:f,getSnapshot:()=>({_scheduledEvents:{...d._snapshot._scheduledEvents}}),start:()=>{let c=d._snapshot._scheduledEvents;d._snapshot._scheduledEvents={};for(let h in c){let{source:p,target:l,event:y,delay:_,id:k}=c[h];f.schedule(p,l,y,_,k)}},_clock:a,_logger:u};return d}var vt=!1,ct=1,v=(function(n){return n[n.NotStarted=0]="NotStarted",n[n.Running=1]="Running",n[n.Stopped=2]="Stopped",n})({}),$e={clock:{setTimeout:(n,t)=>setTimeout(n,t),clearTimeout:n=>clearTimeout(n)},logger:console.log.bind(console),devTools:!1},it=class{constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new st(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=v.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=[];let s={...$e,...e},{clock:r,logger:i,parent:o,syncSnapshot:a,id:u,systemId:f,inspect:g}=s;this.system=o?o.system:Me(this,{clock:r,logger:i}),g&&!o&&this.system.inspect(rt(g)),this.sessionId=this.system._bookId(),this.id=u??this.sessionId,this.logger=(e==null?void 0:e.logger)??this.system._logger,this.clock=(e==null?void 0:e.clock)??this.system._clock,this._parent=o,this._syncSnapshot=a,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:d=>{this._deferred.push(d)},system:this.system,stopChild:d=>{if(d._parent!==this)throw new Error(`Cannot stop child actor ${d.id} of ${this.id} because it is not a child`);d._stop()},emit:d=>{let c=this.eventListeners.get(d.type),h=this.eventListeners.get("*");if(!c&&!h)return;let p=[...c?c.values():[],...h?h.values():[]];for(let l of p)try{l(d)}catch(y){S(y)}},actionExecutor:d=>{let c=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:d.type,params:d.params}}),!d.exec)return;let h=vt;try{vt=!0,d.exec(d.info,d.params)}finally{vt=h}};this._processingStatus===v.Running?c():this._deferred.push(c)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),f&&(this.systemId=f,this.system._set(f,this)),this._initState((e==null?void 0:e.snapshot)??(e==null?void 0:e.state)),f&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(t){var e;try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,(e=this.options)==null?void 0:e.input)}catch(s){this._snapshot={status:"error",output:void 0,error:s}}}update(t,e){var r,i;this._snapshot=t;let s;for(;s=this._deferred.shift();)try{s()}catch(o){this._deferred.length=0,this._snapshot={...t,status:"error",error:o}}switch(this._snapshot.status){case"active":for(let o of this.observers)try{(r=o.next)==null||r.call(o,t)}catch(a){S(a)}break;case"done":for(let o of this.observers)try{(i=o.next)==null||i.call(o,t)}catch(a){S(a)}this._stopProcedure(),this._complete(),this._doneEvent=Le(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:e,snapshot:t})}subscribe(t,e,s){var i;let r=rt(t,e,s);if(this._processingStatus!==v.Stopped)this.observers.add(r);else switch(this._snapshot.status){case"done":try{(i=r.complete)==null||i.call(r)}catch(o){S(o)}break;case"error":{let o=this._snapshot.error;if(!r.error)S(o);else try{r.error(o)}catch(a){S(a)}break}}return{unsubscribe:()=>{this.observers.delete(r)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));let r=e.bind(void 0);return s.add(r),{unsubscribe:()=>{s.delete(r)}}}start(){if(this._processingStatus===v.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=v.Running;let t=ot(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 e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(r){s={err:r}}if(s){let{err:r}=s;this._snapshot={...this._snapshot,status:"error",error:r},this._error(r);return}this.update(e,t),t.type===F&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===v.Stopped?this:(this.mailbox.clear(),this._processingStatus===v.NotStarted?(this._processingStatus=v.Stopped,this):(this.mailbox.enqueue({type:F}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){var t;for(let e of this.observers)try{(t=e.complete)==null||t.call(e)}catch(s){S(s)}this.observers.clear(),this.eventListeners.clear()}_reportError(t){if(!this.observers.size){this._parent||S(t),this.eventListeners.clear();return}let e=!1;for(let s of this.observers){let r=s.error;e||=!r;try{r==null||r(t)}catch(i){S(i)}}this.observers.clear(),this.eventListeners.clear(),e&&S(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,It(this.id,t))}_stopProcedure(){return this._processingStatus!==v.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new st(this._process.bind(this)),this._processingStatus=v.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==v.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){let{devTools:t}=this.options;t&&(typeof t=="function"?t:Ot)(this)}toJSON(){return{xstate$$type:ct,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[Re](){return this}getSnapshot(){return this._snapshot}};function T(n,...[t]){return new it(n,t)}function Ue(n,t,e,s,{sendId:r}){let i=typeof r=="function"?r(e,s):r;return[t,{sendId:i},void 0]}function Ge(n,t){n.defer(()=>{n.system.scheduler.cancel(n.self,t.sendId)})}function $(n){function t(e,s){}return t.type="xstate.cancel",t.sendId=n,t.resolve=Ue,t.execute=Ge,t}function Be(n,t,e,s,{id:r,systemId:i,src:o,input:a,syncSnapshot:u}){let f=typeof o=="string"?V(t.machine,o):o,g=typeof r=="function"?r(e):r,d,c;return f&&(c=typeof a=="function"?a({context:t.context,event:e.event,self:n.self}):a,d=T(f,{id:g,src:o,parent:n.self,syncSnapshot:u,systemId:i,input:c})),[I(t,{children:{...t.children,[g]:d}}),{id:r,systemId:i,actorRef:d,src:o,input:c},void 0]}function He(n,{actorRef:t}){t&&n.defer(()=>{t._processingStatus!==v.Stopped&&t.start()})}function U(...[n,{id:t,systemId:e,input:s,syncSnapshot:r=!1}={}]){function i(o,a){}return i.type="xstate.spawnChild",i.id=t,i.systemId=e,i.src=n,i.input=s,i.syncSnapshot=r,i.resolve=Be,i.execute=He,i}function We(n,t,e,s,{actorRef:r}){let i=typeof r=="function"?r(e,s):r,o=typeof i=="string"?t.children[i]:i,a=t.children;return o&&(a={...a},delete a[o.id]),[I(t,{children:a}),o,void 0]}function Yt(n,t){let e=t.getSnapshot();if(e&&"children"in e)for(let s of Object.values(e.children))Yt(n,s);n.system._unregister(t)}function qe(n,t){if(t){if(Yt(n,t),t._processingStatus!==v.Running){n.stopChild(t);return}n.defer(()=>{n.stopChild(t)})}}function D(n){function t(e,s){}return t.type="xstate.stopChild",t.actorRef=n,t.resolve=We,t.execute=qe,t}function G(n,t,e,s){let{machine:r}=s,i=typeof n=="function",o=i?n:r.implementations.guards[typeof n=="string"?n:n.type];if(!i&&!o)throw new Error(`Guard '${typeof n=="string"?n:n.type}' is not implemented.'.`);if(typeof o!="function")return G(o,t,e,s);let a={context:t,event:e},u=i||typeof n=="string"?void 0:"params"in n?typeof n.params=="function"?n.params({context:t,event:e}):n.params:void 0;return"check"in o?o.check(s,a,o):o(a,u)}function ut(n){return n.type==="atomic"||n.type==="final"}function O(n){return Object.values(n.states).filter(t=>t.type!=="history")}function B(n,t){let e=[];if(t===n)return e;let s=n.parent;for(;s&&s!==t;)e.push(s),s=s.parent;return e}function K(n){let t=new Set(n),e=zt(t);for(let s of t)if(s.type==="compound"&&(!e.get(s)||!e.get(s).length))Ut(s).forEach(r=>t.add(r));else if(s.type==="parallel"){for(let r of O(s))if(r.type!=="history"&&!t.has(r)){let i=Ut(r);for(let o of i)t.add(o)}}for(let s of t){let r=s.parent;for(;r;)t.add(r),r=r.parent}return t}function Jt(n,t){let e=t.get(n);if(!e)return{};if(n.type==="compound"){let r=e[0];if(r){if(ut(r))return r.key}else return{}}let s={};for(let r of e)s[r.key]=Jt(r,t);return s}function zt(n){let t=new Map;for(let e of n)t.has(e)||t.set(e,[]),e.parent&&(t.has(e.parent)||t.set(e.parent,[]),t.get(e.parent).push(e));return t}function Xt(n,t){let e=K(t);return Jt(n,zt(e))}function dt(n,t){return t.type==="compound"?O(t).some(e=>e.type==="final"&&n.has(e)):t.type==="parallel"?O(t).every(e=>dt(n,e)):t.type==="final"}var Y=n=>n[0]===Pe;function Qt(n,t){return n.transitions.get(t)||[...n.transitions.keys()].filter(s=>Kt(t,s)).sort((s,r)=>r.length-s.length).flatMap(s=>n.transitions.get(s))}function Zt(n){let t=n.config.after;if(!t)return[];let e=r=>{let i=De(r,n.id),o=i.type;return n.entry.push(W(i,{id:o,delay:r})),n.exit.push($(o)),o};return Object.keys(t).flatMap(r=>{let i=t[r],o=typeof i=="string"?{target:i}:i,a=Number.isNaN(+r)?r:+r,u=e(a);return A(o).map(f=>({...f,event:u,delay:a}))}).map(r=>{let{delay:i}=r;return{...E(n,r.event,r),delay:i}})}function E(n,t,e){let s=Vt(e.target),r=e.reenter??!1,i=Fe(n,s),o={...e,actions:A(e.actions),guard:e.guard,target:i,source:n,reenter:r,eventType:t,toJSON:()=>({...o,source:`#${n.id}`,target:i?i.map(a=>`#${a.id}`):void 0})};return o}function te(n){let t=new Map;if(n.config.on)for(let e of Object.keys(n.config.on)){if(e===bt)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');let s=n.config.on[e];t.set(e,w(s).map(r=>E(n,e,r)))}if(n.config.onDone){let e=`xstate.done.state.${n.id}`;t.set(e,w(n.config.onDone).map(s=>E(n,e,s)))}for(let e of n.invoke){if(e.onDone){let s=`xstate.done.actor.${e.id}`;t.set(s,w(e.onDone).map(r=>E(n,s,r)))}if(e.onError){let s=`xstate.error.actor.${e.id}`;t.set(s,w(e.onError).map(r=>E(n,s,r)))}if(e.onSnapshot){let s=`xstate.snapshot.${e.id}`;t.set(s,w(e.onSnapshot).map(r=>E(n,s,r)))}}for(let e of n.after){let s=t.get(e.eventType);s||(s=[],t.set(e.eventType,s)),s.push(e)}return t}function ee(n){let t=[],e=s=>{Object.values(s).forEach(r=>{if(r.config.route&&r.config.id){let i=r.config.id,o=r.config.route.guard,a=(f,g)=>f.event.to!==`#${i}`?!1:o&&typeof o=="function"?o(f,g):!0,u={...r.config.route,guard:a,target:`#${i}`};t.push(E(n,"xstate.route",u))}r.states&&e(r.states)})};e(n.states),t.length>0&&n.transitions.set("xstate.route",t)}function ne(n,t){let e=typeof t=="string"?n.states[t]:t?n.states[t.target]:void 0;if(!e&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${n.id}`);let s={source:n,actions:!t||typeof t=="string"?[]:A(t.actions),eventType:null,reenter:!1,target:e?[e]:[],toJSON:()=>({...s,source:`#${n.id}`,target:e?[`#${e.id}`]:[]})};return s}function Fe(n,t){if(t!==void 0)return t.map(e=>{if(typeof e!="string")return e;if(Y(e))return n.machine.getStateNodeById(e);let s=e[0]===xt;if(s&&!n.parent)return j(n,e.slice(1));let r=s?n.key+e:e;if(n.parent)try{return j(n.parent,r)}catch(i){throw new Error(`Invalid transition definition for state node '${n.id}':
|
|
2
|
+
${i.message}`)}else throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`)})}function se(n){let t=Vt(n.config.target);return t?{target:t.map(e=>typeof e=="string"?j(n.parent,e):e)}:n.parent.initial}function P(n){return n.type==="history"}function Ut(n){let t=re(n);for(let e of t)for(let s of B(e,n))t.add(s);return t}function re(n){let t=new Set;function e(s){if(!t.has(s)){if(t.add(s),s.type==="compound")e(s.initial.target[0]);else if(s.type==="parallel")for(let r of O(s))e(r)}}return e(n),t}function M(n,t){if(Y(t))return n.machine.getStateNodeById(t);if(!n.states)throw new Error(`Unable to retrieve child state '${t}' from '${n.id}'; no child states exist.`);let e=n.states[t];if(!e)throw new Error(`Child state '${t}' does not exist on '${n.id}'`);return e}function j(n,t){if(typeof t=="string"&&Y(t))try{return n.machine.getStateNodeById(t)}catch{}let e=at(t).slice(),s=n;for(;e.length;){let r=e.shift();if(!r.length)break;s=M(s,r)}return s}function H(n,t){if(typeof t=="string"){let r=n.states[t];if(!r)throw new Error(`State '${t}' does not exist on '${n.id}'`);return[n,r]}let e=Object.keys(t),s=e.map(r=>M(n,r)).filter(Boolean);return[n.machine.root,n].concat(s,e.reduce((r,i)=>{let o=M(n,i);if(!o)return r;let a=H(o,t[i]);return r.concat(a)},[]))}function je(n,t,e,s){let i=M(n,t).next(e,s);return!i||!i.length?n.next(e,s):i}function Ve(n,t,e,s){let r=Object.keys(t),i=M(n,r[0]),o=lt(i,t[r[0]],e,s);return!o||!o.length?n.next(e,s):o}function Ke(n,t,e,s){let r=[];for(let i of Object.keys(t)){let o=t[i];if(!o)continue;let a=M(n,i),u=lt(a,o,e,s);u&&r.push(...u)}return r.length?r:n.next(e,s)}function lt(n,t,e,s){return typeof t=="string"?je(n,t,e,s):Object.keys(t).length===1?Ve(n,t,e,s):Ke(n,t,e,s)}function Ye(n){return Object.keys(n.states).map(t=>n.states[t]).filter(t=>t.type==="history")}function b(n,t){let e=n;for(;e.parent&&e.parent!==t;)e=e.parent;return e.parent===t}function Je(n,t){let e=new Set(n),s=new Set(t);for(let r of e)if(s.has(r))return!0;for(let r of s)if(e.has(r))return!0;return!1}function ie(n,t,e){let s=new Set;for(let r of n){let i=!1,o=new Set;for(let a of s)if(Je(kt([r],t,e),kt([a],t,e)))if(b(r.source,a.source))o.add(a);else{i=!0;break}if(!i){for(let a of o)s.delete(a);s.add(r)}}return Array.from(s)}function ze(n){let[t,...e]=n;for(let s of B(t,void 0))if(e.every(r=>b(r,s)))return s}function Dt(n,t){if(!n.target)return[];let e=new Set;for(let s of n.target)if(P(s))if(t[s.id])for(let r of t[s.id])e.add(r);else for(let r of Dt(se(s),t))e.add(r);else e.add(s);return[...e]}function oe(n,t){let e=Dt(n,t);if(!e)return;if(!n.reenter&&e.every(r=>r===n.source||b(r,n.source)))return n.source;let s=ze(e.concat(n.source));if(s)return s;if(!n.reenter)return n.source.machine.root}function kt(n,t,e){var r;let s=new Set;for(let i of n)if((r=i.target)!=null&&r.length){let o=oe(i,e);i.reenter&&i.source===o&&s.add(o);for(let a of t)b(a,o)&&s.add(a)}return[...s]}function Xe(n,t){if(n.length!==t.size)return!1;for(let e of n)if(!t.has(e))return!1;return!0}function Lt(n,t,e,s,r){return Et([{target:[...re(n)],source:n,reenter:!0,actions:[],eventType:null,toJSON:null}],t,e,s,!0,r)}function Et(n,t,e,s,r,i){let o=[];if(!n.length)return[t,o];let a=e.actionExecutor;e.actionExecutor=u=>{o.push(u),a(u)};try{let u=new Set(t._nodes),f=t.historyValue,g=ie(n,u,f),d=t;r||([d,f]=en(d,s,e,g,u,f,i,e.actionExecutor)),d=C(d,s,e,g.flatMap(h=>h.actions),i,void 0),d=Ze(d,s,e,g,u,i,f,r);let c=[...u];d.status==="done"&&(d=C(d,s,e,c.sort((h,p)=>p.order-h.order).flatMap(h=>h.exit),i,void 0));try{return f===t.historyValue&&Xe(t._nodes,u)?[d,o]:[I(d,{_nodes:c,historyValue:f}),o]}catch(h){throw h}}finally{e.actionExecutor=a}}function Qe(n,t,e,s,r){if(s.output===void 0)return;let i=St(r.id,r.output!==void 0&&r.parent?At(r.output,n.context,t,e.self):void 0);return At(s.output,n.context,i,e.self)}function Ze(n,t,e,s,r,i,o,a){let u=n,f=new Set,g=new Set;tn(s,o,g,f),a&&g.add(n.machine.root);let d=new Set;for(let c of[...f].sort((h,p)=>h.order-p.order)){r.add(c);let h=[];h.push(...c.entry);for(let p of c.invoke)h.push(U(p.src,{...p,syncSnapshot:!!p.onSnapshot}));if(g.has(c)){let p=c.initial.actions;h.push(...p)}if(u=C(u,t,e,h,i,c.invoke.map(p=>p.id)),c.type==="final"){let p=c.parent,l=(p==null?void 0:p.type)==="parallel"?p:p==null?void 0:p.parent,y=l||c;for((p==null?void 0:p.type)==="compound"&&i.push(St(p.id,c.output!==void 0?At(c.output,u.context,t,e.self):void 0));(l==null?void 0:l.type)==="parallel"&&!d.has(l)&&dt(r,l);)d.add(l),i.push(St(l.id)),y=l,l=l.parent;if(l)continue;u=I(u,{status:"done",output:Qe(u,t,e,u.machine.root,y)})}}return u}function tn(n,t,e,s){for(let r of n){let i=oe(r,t);for(let a of r.target||[])!P(a)&&(r.source!==a||r.source!==i||r.reenter)&&(s.add(a),e.add(a)),N(a,t,e,s);let o=Dt(r,t);for(let a of o){let u=B(a,i);(i==null?void 0:i.type)==="parallel"&&u.push(i),ae(s,t,e,u,!r.source.parent&&r.reenter?void 0:i)}}}function N(n,t,e,s){var r;if(P(n))if(t[n.id]){let i=t[n.id];for(let o of i)s.add(o),N(o,t,e,s);for(let o of i)Tt(o,n.parent,s,t,e)}else{let i=se(n);for(let o of i.target)s.add(o),i===((r=n.parent)==null?void 0:r.initial)&&e.add(n.parent),N(o,t,e,s);for(let o of i.target)Tt(o,n.parent,s,t,e)}else if(n.type==="compound"){let[i]=n.initial.target;P(i)||(s.add(i),e.add(i)),N(i,t,e,s),Tt(i,n,s,t,e)}else if(n.type==="parallel")for(let i of O(n).filter(o=>!P(o)))[...s].some(o=>b(o,i))||(P(i)||(s.add(i),e.add(i)),N(i,t,e,s))}function ae(n,t,e,s,r){for(let i of s)if((!r||b(i,r))&&n.add(i),i.type==="parallel")for(let o of O(i).filter(a=>!P(a)))[...n].some(a=>b(a,o))||(n.add(o),N(o,t,e,n))}function Tt(n,t,e,s,r){ae(e,s,r,B(n,t))}function en(n,t,e,s,r,i,o,a){let u=n,f=kt(s,r,i);f.sort((d,c)=>c.order-d.order);let g;for(let d of f)for(let c of Ye(d)){let h;c.history==="deep"?h=p=>ut(p)&&b(p,d):h=p=>p.parent===d,g??={...i},g[c.id]=Array.from(r).filter(h)}for(let d of f)u=C(u,t,e,[...d.exit,...d.invoke.map(c=>D(c.id))],o,void 0),r.delete(d);return[u,g||i]}function nn(n,t){return n.implementations.actions[t]}function ce(n,t,e,s,r,i){let{machine:o}=n,a=n;for(let u of s){let f=typeof u=="function",g=f?u:nn(o,typeof u=="string"?u:u.type),d={context:a.context,event:t,self:e.self,system:e.system},c=f||typeof u=="string"?void 0:"params"in u?typeof u.params=="function"?u.params({context:a.context,event:t}):u.params:void 0;if(!g||!("resolve"in g)){e.actionExecutor({type:typeof u=="string"?u:typeof u=="object"?u.type:u.name||"(anonymous)",info:d,params:c,exec:g});continue}let h=g,[p,l,y]=h.resolve(e,a,d,c,g,r);a=p,"retryResolve"in h&&(i==null||i.push([h,l])),"execute"in h&&e.actionExecutor({type:h.type,info:d,params:l,exec:h.execute.bind(null,e,l)}),y&&(a=ce(a,t,e,y,r,i))}return a}function C(n,t,e,s,r,i){let o=i?[]:void 0,a=ce(n,t,e,s,{internalQueue:r,deferredActorIds:i},o);return o==null||o.forEach(([u,f])=>{u.retryResolve(e,a,f)}),a}function J(n,t,e,s){let r=n,i=[];function o(f,g,d){e.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:e.self,event:g,snapshot:f[0],_transitions:d}),i.push(f)}if(t.type===F)return r=I(Gt(r,t,e),{status:"stopped"}),o([r,[]],t,[]),{snapshot:r,microsteps:i};let a=t;if(a.type!==Ht){let f=a,g=Ne(f),d=Bt(f,r);if(g&&!d.length)return r=I(n,{status:"error",error:f.error}),o([r,[]],f,[]),{snapshot:r,microsteps:i};let c=Et(d,n,e,a,!1,s);r=c[0],o(c,f,d)}let u=!0;for(;r.status==="active";){let f=u?sn(r,a):[],g=f.length?r:void 0;if(!f.length){if(!s.length)break;a=s.shift(),f=Bt(a,r)}let d=Et(f,r,e,a,!1,s);r=d[0],u=r!==g,o(d,a,f)}return r.status!=="active"&&Gt(r,a,e),{snapshot:r,microsteps:i}}function Gt(n,t,e){return C(n,t,e,Object.values(n.children).map(s=>D(s)),[],void 0)}function Bt(n,t){return t.machine.getTransitionData(t,n)}function sn(n,t){let e=new Set,s=n._nodes.filter(ut);for(let r of s)t:for(let i of[r].concat(B(r,void 0)))if(i.always){for(let o of i.always)if(o.guard===void 0||G(o.guard,n.context,t,n)){e.add(o);break t}}return ie(Array.from(e),new Set(n._nodes),n.historyValue)}function ue(n,t){let e=K(H(n,t));return Xt(n,[...e])}function de(n){return!!n&&typeof n=="object"&&"machine"in n&&"value"in n}var rn=function(t){return wt(t,this.value)},on=function(t){return this.tags.has(t)},an=function(t){let e=this.machine.getTransitionData(this,t);return!!(e!=null&&e.length)&&e.some(s=>s.target!==void 0||s.actions.length)},cn=function(){let{_nodes:t,tags:e,machine:s,getMeta:r,toJSON:i,can:o,hasTag:a,matches:u,...f}=this;return{...f,tags:Array.from(e)}},un=function(){return this._nodes.reduce((t,e)=>(e.meta!==void 0&&(t[e.id]=e.meta),t),{})};function z(n,t){return{status:n.status,output:n.output,error:n.error,machine:t,context:n.context,_nodes:n._nodes,value:Xt(t.root,n._nodes),tags:new Set(n._nodes.flatMap(e=>e.tags)),children:n.children,historyValue:n.historyValue||{},matches:rn,hasTag:on,can:an,getMeta:un,toJSON:cn}}function I(n,t={}){return z({...n,...t},n.machine)}function dn(n){if(typeof n!="object"||n===null)return{};let t={};for(let e in n){let s=n[e];Array.isArray(s)&&(t[e]=s.map(r=>({id:r.id})))}return t}function le(n,t){let{_nodes:e,tags:s,machine:r,children:i,context:o,can:a,hasTag:u,matches:f,getMeta:g,toJSON:d,...c}=n,h={};for(let l in i){let y=i[l];h[l]={snapshot:y.getPersistedSnapshot(t),src:y.src,systemId:y.systemId,syncSnapshot:y._syncSnapshot}}return{...c,context:he(o),children:h,historyValue:dn(c.historyValue)}}function he(n){let t;for(let e in n){let s=n[e];if(s&&typeof s=="object")if("sessionId"in s&&"send"in s&&"ref"in s)t??=Array.isArray(n)?n.slice():{...n},t[e]={xstate$$type:ct,id:s.id};else{let r=he(s);r!==s&&(t??=Array.isArray(n)?n.slice():{...n},t[e]=r)}}return t??n}function ln(n,t,e,s,{event:r,id:i,delay:o},{internalQueue:a}){let u=t.machine.implementations.delays;if(typeof r=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${r}" }) instead`);let f=typeof r=="function"?r(e,s):r,g;if(typeof o=="string"){let d=u&&u[o];g=typeof d=="function"?d(e,s):d}else g=typeof o=="function"?o(e,s):o;return typeof g!="number"&&a.push(f),[t,{event:f,id:i,delay:g},void 0]}function hn(n,t){let{event:e,delay:s,id:r}=t;if(typeof s=="number"){n.defer(()=>{let i=n.self;n.system.scheduler.schedule(i,i,e,s,r)});return}}function W(n,t){function e(s,r){}return e.type="xstate.raise",e.event=n,e.id=t==null?void 0:t.id,e.delay=t==null?void 0:t.delay,e.resolve=ln,e.execute=hn,e}function ye(n,t){return{config:n,transition:(e,s,r)=>({...e,context:n(e.context,s,r)}),getInitialSnapshot:(e,s)=>({status:"active",output:void 0,error:void 0,context:typeof t=="function"?t({input:s}):t}),getPersistedSnapshot:e=>e,restoreSnapshot:e=>e}}var fe="xstate.promise.resolve",pe="xstate.promise.reject",X=new WeakMap;function x(n){return{config:n,transition:(e,s,r)=>{var i;if(e.status!=="active")return e;switch(s.type){case fe:{let o=s.data;return{...e,status:"done",output:o,input:void 0}}case pe:return{...e,status:"error",error:s.data,input:void 0};case F:return(i=X.get(r.self))==null||i.abort(),X.delete(r.self),{...e,status:"stopped",input:void 0};default:return e}},start:(e,{self:s,system:r,emit:i})=>{if(e.status!=="active")return;let o=new AbortController;X.set(s,o),Promise.resolve(n({input:e.input,system:r,self:s,signal:o.signal,emit:i})).then(u=>{s.getSnapshot().status==="active"&&(X.delete(s),r._relay(s,s,{type:fe,data:u}))},u=>{s.getSnapshot().status==="active"&&(X.delete(s),r._relay(s,s,{type:pe,data:u}))})},getInitialSnapshot:(e,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedSnapshot:e=>e,restoreSnapshot:e=>e}}var On=ye(n=>{},void 0);function fn(n,{machine:t,context:e},s,r){let i=(o,a)=>{if(typeof o=="string"){let u=V(t,o);if(!u)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);let f=T(u,{id:a==null?void 0:a.id,parent:n.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:typeof(a==null?void 0:a.input)=="function"?a.input({context:e,event:s,self:n.self}):a==null?void 0:a.input,src:o,systemId:a==null?void 0:a.systemId});return r[f.id]=f,f}else return T(o,{id:a==null?void 0:a.id,parent:n.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:a==null?void 0:a.input,src:o,systemId:a==null?void 0:a.systemId})};return(o,a)=>{let u=i(o,a);return r[u.id]=u,n.defer(()=>{u._processingStatus!==v.Stopped&&u.start()}),u}}function pn(n,t,e,s,{assignment:r}){if(!t.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");let i={},o={context:t.context,event:e.event,spawn:fn(n,t,e.event,i),self:n.self,system:n.system},a={};if(typeof r=="function")a=r(o,s);else for(let f of Object.keys(r)){let g=r[f];a[f]=typeof g=="function"?g(o,s):g}let u=Object.assign({},t.context,a);return[I(t,{context:u,children:Object.keys(i).length?{...t.children,...i}:t.children}),void 0,void 0]}function m(n){function t(e,s){}return t.type="xstate.assign",t.assignment=n,t.resolve=pn,t}var ge=new WeakMap;function q(n,t,e){let s=ge.get(n);return s?t in s||(s[t]=e()):(s={[t]:e()},ge.set(n,s)),s[t]}var yn={},Q=n=>typeof n=="string"?{type:n}:typeof n=="function"?"resolve"in n?{type:n.type}:{type:n.name}:n,ht=class n{constructor(t,e){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=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(xt),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?Pt(this.config.states,(s,r)=>new n(s,{_parent:this,_key:r,_machine:this.machine})):yn,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=A(this.config.entry).slice(),this.exit=A(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=A(t.tags).slice()}_initialize(){this.transitions=te(this),this.config.always&&(this.always=w(this.config.always).map(t=>E(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(Q),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Q),eventType:null})}:void 0,history:this.history,states:Pt(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(Q)})),entry:this.entry.map(Q),exit:this.exit.map(Q),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",()=>A(this.config.invoke).map((t,e)=>{let{src:s,systemId:r}=t,i=t.id??Ct(this.id,e),o=typeof s=="string"?s:`xstate.invoke.${Ct(this.id,e)}`;return{...t,src:o,id:i,systemId:r,toJSON(){let{onDone:a,onError:u,...f}=t;return{...f,type:"xstate.invoke",src:o,id:i}}}}))}get on(){return q(this,"on",()=>[...this.transitions].flatMap(([e,s])=>s.map(r=>[e,r])).reduce((e,[s,r])=>(e[s]=e[s]||[],e[s].push(r),e),{}))}get after(){return q(this,"delayedTransitions",()=>Zt(this))}get initial(){return q(this,"initial",()=>ne(this,this.config.initial))}next(t,e){let s=e.type,r=[],i,o=q(this,`candidates-${s}`,()=>Qt(this,s));for(let a of o){let{guard:u}=a,f=t.context,g=!1;try{g=!u||G(u,f,e,t)}catch(d){let c=typeof u=="string"?u:typeof u=="object"?u.type:void 0;throw new Error(`Unable to evaluate guard ${c?`'${c}' `:""}in transition for event '${s}' in state node '${this.id}':
|
|
3
|
+
${d.message}`)}if(g){r.push(...a.actions),i=a;break}}return i?[i]:void 0}get events(){return q(this,"events",()=>{let{states:t}=this,e=new Set(this.ownEvents);if(t)for(let s of Object.keys(t)){let r=t[s];if(r.states)for(let i of r.events)e.add(`${i}`)}return Array.from(e)})}get ownEvents(){let t=Object.keys(Object.fromEntries(this.transitions)),e=new Set(t.filter(s=>this.transitions.get(s).some(r=>!(!r.target&&!r.actions.length&&!r.reenter))));return Array.from(e)}},gn="#",ft=class n{constructor(t,e){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:(e==null?void 0:e.actors)??{},actions:(e==null?void 0:e.actions)??{},delays:(e==null?void 0:e.delays)??{},guards:(e==null?void 0:e.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 ht(t,{_key:this.id,_machine:this}),this.root._initialize(),ee(this.root),this.states=this.root.states,this.events=this.root.events}provide(t){let{actions:e,guards:s,actors:r,delays:i}=this.implementations;return new n(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...r,...t.actors},delays:{...i,...t.delays}})}resolveState(t){let e=ue(this.root,t.value),s=K(H(this.root,e));return z({_nodes:[...s],context:t.context||{},children:{},status:dt(s,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return J(t,e,s,[]).snapshot}microstep(t,e,s){return J(t,e,s,[]).microsteps.map(([r])=>r)}getTransitionData(t,e){return lt(this.root,t.value,t,e)||[]}_getPreInitialState(t,e,s){let{context:r}=this.config,i=z({context:typeof r!="function"&&r?r:{},_nodes:[this.root],children:{},status:"active"},this);return typeof r=="function"?C(i,e,t,[m(({spawn:a,event:u,self:f})=>r({spawn:a,input:u.input,self:f}))],s,void 0):i}getInitialSnapshot(t,e){let s=ot(e),r=[],i=this._getPreInitialState(t,s,r),[o]=Lt(this.root,i,t,s,r),{snapshot:a}=J(o,s,t,r);return a}start(t){Object.values(t.children).forEach(e=>{e.getSnapshot().status==="active"&&e.start()})}getStateNodeById(t){let e=at(t),s=e.slice(1),r=Y(e[0])?e[0].slice(gn.length):e[0],i=this.idMap.get(r);if(!i)throw new Error(`Child state node '#${r}' does not exist on machine '${this.id}'`);return j(i,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return le(t,e)}restoreSnapshot(t,e){let s={},r=t.children;Object.keys(r).forEach(d=>{let c=r[d],h=c.snapshot,p=c.src,l=typeof p=="string"?V(this,p):p;if(!l)return;let y=T(l,{id:d,parent:e.self,syncSnapshot:c.syncSnapshot,snapshot:h,src:p,systemId:c.systemId});s[d]=y});function i(d,c){if(c instanceof ht)return c;try{return d.machine.getStateNodeById(c.id)}catch{}}function o(d,c){if(!c||typeof c!="object")return{};let h={};for(let p in c){let l=c[p];for(let y of l){let _=i(d,y);_&&(h[p]??=[],h[p].push(_))}}return h}let a=o(this.root,t.historyValue),u=z({...t,children:s,_nodes:Array.from(K(H(this.root,t.value))),historyValue:a},this),f=new Set;function g(d,c){if(!f.has(d)){f.add(d);for(let h in d){let p=d[h];if(p&&typeof p=="object"){if("xstate$$type"in p&&p.xstate$$type===ct){d[h]=c[p.id];continue}g(p,c)}}}}return g(u.context,s),u}};function mn(n,t,e,s,{event:r}){let i=typeof r=="function"?r(e,s):r;return[t,{event:i},void 0]}function _n(n,{event:t}){n.defer(()=>n.emit(t))}function yt(n){function t(e,s){}return t.type="xstate.emit",t.event=n,t.resolve=mn,t.execute=_n,t}var pt=(function(n){return n.Parent="#_parent",n.Internal="#_internal",n})({});function vn(n,t,e,s,{to:r,event:i,id:o,delay:a},u){var p;let f=t.machine.implementations.delays;if(typeof i=="string")throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${i}" }) instead`);let g=typeof i=="function"?i(e,s):i,d;if(typeof a=="string"){let l=f&&f[a];d=typeof l=="function"?l(e,s):l}else d=typeof a=="function"?a(e,s):a;let c=typeof r=="function"?r(e,s):r,h;if(typeof c=="string"){if(c===pt.Parent?h=n.self._parent:c===pt.Internal?h=n.self:c.startsWith("#_")?h=t.children[c.slice(2)]:h=(p=u.deferredActorIds)!=null&&p.includes(c)?c:t.children[c],!h)throw new Error(`Unable to send event to actor '${c}' from machine '${t.machine.id}'.`)}else h=c||n.self;return[t,{to:h,targetId:typeof c=="string"?c:void 0,event:g,id:o,delay:d},void 0]}function Tn(n,t,e){typeof e.to=="string"&&(e.to=t.children[e.to])}function Sn(n,t){n.defer(()=>{let{to:e,event:s,delay:r,id:i}=t;if(typeof r=="number"){n.system.scheduler.schedule(n.self,e,s,r,i);return}n.system._relay(n.self,e,s.type===Wt?It(n.self.id,s.data):s)})}function Z(n,t,e){function s(r,i){}return s.type="xstate.sendTo",s.to=n,s.event=t,s.id=e==null?void 0:e.id,s.delay=e==null?void 0:e.delay,s.resolve=vn,s.retryResolve=Tn,s.execute=Sn,s}function L(n,t){return Z(pt.Parent,n,t)}function An(n,t,e,s,{collect:r}){let i=[],o=function(u){i.push(u)};return o.assign=(...a)=>{i.push(m(...a))},o.cancel=(...a)=>{i.push($(...a))},o.raise=(...a)=>{i.push(W(...a))},o.sendTo=(...a)=>{i.push(Z(...a))},o.sendParent=(...a)=>{i.push(L(...a))},o.spawnChild=(...a)=>{i.push(U(...a))},o.stopChild=(...a)=>{i.push(D(...a))},o.emit=(...a)=>{i.push(yt(...a))},r({context:e.context,event:e.event,enqueue:o,check:a=>G(a,t.context,e.event,t),self:n.self,system:n.system},s),[t,void 0,i]}function Rt(n){function t(e,s){}return t.type="xstate.enqueueActions",t.collect=n,t.resolve=An,t}function kn(n,t,e,s,{value:r,label:i}){return[t,{value:typeof r=="function"?r(e,s):r,label:i},void 0]}function En({logger:n},{value:t,label:e}){e?n(e,t):n(t)}function Nt(n=({context:e,event:s})=>({context:e,event:s}),t){function e(s,r){}return e.type="xstate.log",e.value=n,e.label=t,e.resolve=kn,e.execute=En,e}function xn(n,t){return new ft(n,t)}function R({schemas:n,actors:t,actions:e,guards:s,delays:r}){return{assign:m,sendTo:Z,raise:W,log:Nt,cancel:$,stopChild:D,enqueueActions:Rt,emit:yt,spawnChild:U,createStateConfig:i=>i,createAction:i=>i,createMachine:i=>xn({...i,schemas:n},{actors:t,actions:e,guards:s,delays:r}),extend:i=>R({schemas:n,actors:t,actions:{...e,...i.actions},guards:{...s,...i.guards},delays:{...r,...i.delays}})}}var bn=typeof window<"u",tt;function In(){if(!bn)return null;let n=window.AudioContext??window.webkitAudioContext;return n?new n:null}function et(){return tt===void 0?null:tt}function me(){tt===void 0&&(tt=In());let n=tt;return n&&n.state==="suspended"?n.resume():Promise.resolve()}var gt=typeof navigator<"u"&&"mediaSession"in navigator;function _e(n){if(!gt)return;let{mediaSession:t}=navigator;t.setActionHandler("play",n.onPlay),t.setActionHandler("pause",n.onPause),t.setActionHandler("nexttrack",n.onNext),t.setActionHandler("previoustrack",n.onPrevious),t.setActionHandler("seekto",e=>{e.seekTime!=null&&n.onSeek(e.seekTime)})}function ve(n){if(gt){if(!n){navigator.mediaSession.metadata=null;return}navigator.mediaSession.metadata=new MediaMetadata({title:n.title??"",artist:n.artist??"",album:n.album??"",artwork:n.artwork??[]})}}function Te(n){gt&&(navigator.mediaSession.playbackState=n?"playing":"paused")}function Se(n,t,e=1){if(gt)try{navigator.mediaSession.setPositionState({duration:n,position:t,playbackRate:e})}catch{}}function Ae(n){return R({types:{context:{},events:{}},guards:{hasNextTrack:({context:t})=>t.currentTrackIndex+1<t.trackCount,playImmediately:({event:t})=>!!t.playImmediately},actions:{incrementTrackCount:m({trackCount:({context:t})=>t.trackCount+1}),decrementTrackCount:m({trackCount:({context:t})=>Math.max(0,t.trackCount-1),currentTrackIndex:({context:t,event:e})=>e.index<t.currentTrackIndex?Math.max(0,t.currentTrackIndex-1):t.currentTrackIndex}),gotoTrackIndex:m({currentTrackIndex:({event:t})=>t.index}),advanceToNextTrack:m({currentTrackIndex:({context:t})=>{let e=t.currentTrackIndex+1;return e<t.trackCount?e:t.currentTrackIndex}}),goToPreviousTrack:m({currentTrackIndex:({context:t})=>Math.max(0,t.currentTrackIndex-1)}),advanceOnTrackEnd:m({currentTrackIndex:({context:t})=>t.currentTrackIndex+1}),resetToFirstTrack:m({currentTrackIndex:()=>0}),deactivateCurrent:()=>{},deactivateEndedTrack:()=>{},activateAndPlayCurrent:()=>{},playOrContinueGapless:()=>{},cancelAllGapless:()=>{},notifyStartNewTrack:()=>{},notifyPlayNextTrack:()=>{},notifyPlayPreviousTrack:()=>{},notifyEnded:()=>{},updateMediaSessionMetadata:()=>{},preloadAhead:()=>{},playCurrent:()=>{},pauseCurrent:()=>{},seekCurrent:()=>{},seekCurrentToZero:()=>{},scheduleGapless:()=>{},cancelScheduledGapless:()=>{},cancelAndRescheduleGapless:()=>{}}}).createMachine({id:"queue",initial:"idle",context:n,on:{ADD_TRACK:{actions:"incrementTrackCount"},REMOVE_TRACK:{actions:"decrementTrackCount"}},states:{idle:{on:{PLAY:{target:"playing",actions:["playCurrent","updateMediaSessionMetadata","preloadAhead","scheduleGapless"]},GOTO:[{guard:"playImmediately",target:"playing",actions:["deactivateCurrent","cancelAllGapless","gotoTrackIndex","activateAndPlayCurrent","notifyStartNewTrack","updateMediaSessionMetadata","preloadAhead"]},{target:"paused",actions:["deactivateCurrent","cancelAllGapless","gotoTrackIndex","seekCurrentToZero","preloadAhead"]}],TRACK_LOADED:{actions:["preloadAhead"]}}},playing:{on:{PAUSE:{target:"paused",actions:["cancelScheduledGapless","pauseCurrent"]},TOGGLE:{target:"paused",actions:["cancelScheduledGapless","pauseCurrent"]},NEXT:{actions:["deactivateCurrent","cancelAllGapless","advanceToNextTrack","activateAndPlayCurrent","notifyStartNewTrack","notifyPlayNextTrack","updateMediaSessionMetadata","preloadAhead"]},PREVIOUS:{actions:["deactivateCurrent","cancelAllGapless","goToPreviousTrack","activateAndPlayCurrent","notifyStartNewTrack","notifyPlayPreviousTrack","updateMediaSessionMetadata","preloadAhead"]},GOTO:[{guard:"playImmediately",actions:["deactivateCurrent","cancelAllGapless","gotoTrackIndex","activateAndPlayCurrent","notifyStartNewTrack","updateMediaSessionMetadata","preloadAhead"]},{actions:["deactivateCurrent","cancelAllGapless","gotoTrackIndex","seekCurrentToZero","preloadAhead"]}],SEEK:{actions:["seekCurrent","cancelAndRescheduleGapless"]},TRACK_ENDED:[{guard:"hasNextTrack",target:"playing",actions:["deactivateEndedTrack","advanceOnTrackEnd","playOrContinueGapless","notifyStartNewTrack","notifyPlayNextTrack","updateMediaSessionMetadata","preloadAhead"]},{target:"ended",actions:["deactivateEndedTrack","notifyEnded"]}],TRACK_LOADED:{actions:["scheduleGapless","preloadAhead"]}}},paused:{on:{PLAY:{target:"playing",actions:["playCurrent","updateMediaSessionMetadata","preloadAhead","scheduleGapless"]},TOGGLE:{target:"playing",actions:["playCurrent","updateMediaSessionMetadata","preloadAhead","scheduleGapless"]},NEXT:{actions:["deactivateCurrent","cancelAllGapless","advanceToNextTrack","activateAndPlayCurrent","notifyStartNewTrack","notifyPlayNextTrack","updateMediaSessionMetadata","preloadAhead"]},PREVIOUS:{actions:["deactivateCurrent","cancelAllGapless","goToPreviousTrack","activateAndPlayCurrent","notifyStartNewTrack","notifyPlayPreviousTrack","updateMediaSessionMetadata","preloadAhead"]},GOTO:[{guard:"playImmediately",target:"playing",actions:["deactivateCurrent","cancelAllGapless","gotoTrackIndex","activateAndPlayCurrent","notifyStartNewTrack","updateMediaSessionMetadata","preloadAhead"]},{actions:["deactivateCurrent","cancelAllGapless","gotoTrackIndex","seekCurrentToZero","preloadAhead"]}],SEEK:{actions:["seekCurrent"]},TRACK_ENDED:[{guard:"hasNextTrack",target:"paused",actions:["deactivateEndedTrack","advanceOnTrackEnd","notifyStartNewTrack","updateMediaSessionMetadata"]},{target:"ended",actions:["deactivateEndedTrack","notifyEnded"]}],TRACK_LOADED:{actions:["preloadAhead"]}}},ended:{on:{PLAY:{target:"playing",actions:["resetToFirstTrack","playCurrent","updateMediaSessionMetadata","preloadAhead","scheduleGapless"]},GOTO:[{guard:"playImmediately",target:"playing",actions:["deactivateCurrent","cancelAllGapless","gotoTrackIndex","activateAndPlayCurrent","notifyStartNewTrack","updateMediaSessionMetadata","preloadAhead"]},{target:"paused",actions:["deactivateCurrent","cancelAllGapless","gotoTrackIndex","seekCurrentToZero","preloadAhead"]}]}}}})}var mt=R({types:{context:{},input:{}},actors:{resolveUrl:x(async()=>null),fetchAudio:x(async()=>{}),decodeAudio:x(async()=>{})},guards:{shouldSkipHEAD:({context:n})=>n.skipHEAD}}).createMachine({id:"fetchDecode",initial:"resolvingUrl",context:({input:n})=>({trackUrl:n.trackUrl,resolvedUrl:n.resolvedUrl,skipHEAD:n.skipHEAD}),states:{resolvingUrl:{always:{guard:"shouldSkipHEAD",target:"fetching"},invoke:{id:"resolveUrl",src:"resolveUrl",input:({context:n})=>({trackUrl:n.trackUrl}),onDone:{target:"fetching",actions:[m({resolvedUrl:({event:n,context:t})=>n.output??t.resolvedUrl,skipHEAD:()=>!0}),L(({event:n,context:t})=>({type:"URL_RESOLVED",url:n.output??t.resolvedUrl}))]},onError:{target:"fetching",actions:m({skipHEAD:()=>!0})}}},fetching:{invoke:{id:"fetchAudio",src:"fetchAudio",input:({context:n})=>({resolvedUrl:n.resolvedUrl}),onDone:"decoding",onError:{target:"error",actions:L({type:"BUFFER_ERROR"})}}},decoding:{invoke:{id:"decodeAudio",src:"decodeAudio",input:()=>{},onDone:{target:"done",actions:L({type:"BUFFER_READY"})},onError:{target:"error",actions:L({type:"BUFFER_ERROR"})}}},done:{type:"final"},error:{type:"final"}}});function ke(n){return R({types:{context:{},events:{}},actors:{fetchDecode:mt},guards:{canPlayWebAudio:()=>!1,canStartFetch:({context:t})=>t.webAudioLoadingState==="NONE"&&t.fetchDecodeRef===null},actions:{playHtml5:()=>{},startSourceNode:()=>{},startScheduledSourceNode:()=>{},startProgressLoop:()=>{},pauseHtml5:()=>{},freezePausedTime:()=>{},stopSourceNode:()=>{},disconnectGain:()=>{},stopProgressLoop:()=>{},reportProgress:()=>{},seekHtml5:()=>{},seekWebAudio:()=>{},resetHtml5Element:()=>{},resetTiming:()=>{},notifyTrackEnded:()=>{},setIsPlaying:m({isPlaying:()=>!0}),clearIsPlaying:m({isPlaying:()=>!1}),setLoadingState:m({webAudioLoadingState:()=>"LOADING"}),setLoadedState:m({webAudioLoadingState:()=>"LOADED"}),setErrorState:m({webAudioLoadingState:()=>"ERROR"}),clearScheduleAndLookahead:m({scheduledStartContextTime:()=>null,notifiedLookahead:()=>!1}),setPlayingWebAudio:m({isPlaying:()=>!0,webAudioLoadingState:()=>"LOADED",playbackType:()=>"WEBAUDIO"}),setScheduledGapless:m({isPlaying:()=>!0,webAudioLoadingState:()=>"LOADED",playbackType:()=>"WEBAUDIO",scheduledStartContextTime:({event:t})=>t.when}),clearPlayingAndSchedule:m({isPlaying:()=>!1,scheduledStartContextTime:()=>null,notifiedLookahead:()=>!1}),setNotifiedLookahead:m({notifiedLookahead:()=>!0}),setResolvedUrl:m({resolvedUrl:({event:t})=>t.url}),clearScheduledStart:m({scheduledStartContextTime:()=>null}),setPlayingWebAudioType:m({isPlaying:()=>!0,playbackType:()=>"WEBAUDIO"})}}).createMachine({id:"track",initial:"idle",context:n,on:{START_FETCH:{guard:"canStartFetch",actions:m({webAudioLoadingState:()=>"LOADING",fetchDecodeRef:({context:t,spawn:e})=>e("fetchDecode",{id:"fetchDecode",input:{trackUrl:t.trackUrl,resolvedUrl:t.resolvedUrl,skipHEAD:t.skipHEAD}})})}},states:{idle:{on:{HTML5_ENDED:{actions:["notifyTrackEnded"]},DEACTIVATE:{actions:["resetHtml5Element","resetTiming","stopProgressLoop","clearScheduleAndLookahead"]},ACTIVATE:{actions:["resetTiming","resetHtml5Element","clearScheduleAndLookahead"]},PLAY:[{guard:"canPlayWebAudio",target:"webaudio",actions:["setPlayingWebAudio","startSourceNode","startProgressLoop"]},{target:"html5",actions:["setIsPlaying","playHtml5","startProgressLoop"]}],PLAY_WEBAUDIO:{target:"webaudio",actions:["setPlayingWebAudio","startSourceNode","startProgressLoop"]},SCHEDULE_GAPLESS:{target:"webaudio",actions:["setScheduledGapless","startScheduledSourceNode"]},PRELOAD:{target:"loading"},BUFFER_LOADING:{actions:"setLoadingState"},BUFFER_READY:{actions:"setLoadedState"},BUFFER_ERROR:{actions:"setErrorState"},URL_RESOLVED:{actions:"setResolvedUrl"}}},html5:{on:{PAUSE:{actions:["clearIsPlaying","pauseHtml5","stopProgressLoop","reportProgress"]},PLAY:{actions:["setIsPlaying","playHtml5","startProgressLoop"]},BUFFER_LOADING:{actions:"setLoadingState"},PLAY_WEBAUDIO:{target:"webaudio",actions:"setPlayingWebAudio"},BUFFER_READY:{actions:"setLoadedState"},BUFFER_ERROR:{actions:"setErrorState"},SEEK:{actions:["seekHtml5","reportProgress"]},LOOKAHEAD_REACHED:{actions:"setNotifiedLookahead"},HTML5_ENDED:{target:"idle",actions:["clearIsPlaying","stopProgressLoop","notifyTrackEnded"]},ACTIVATE:{target:"idle",actions:["clearPlayingAndSchedule","pauseHtml5","stopProgressLoop","resetTiming","resetHtml5Element"]},URL_RESOLVED:{actions:"setResolvedUrl"},DEACTIVATE:{target:"idle",actions:["clearIsPlaying","pauseHtml5","resetHtml5Element","resetTiming","stopProgressLoop"]}}},loading:{on:{BUFFER_LOADING:{actions:"setLoadingState"},BUFFER_READY:{target:"idle",actions:"setLoadedState"},BUFFER_ERROR:{target:"idle",actions:"setErrorState"},PLAY:[{guard:"canPlayWebAudio",target:"webaudio",actions:["setPlayingWebAudio","startSourceNode","startProgressLoop"]},{target:"html5",actions:["setIsPlaying","playHtml5","startProgressLoop"]}],PLAY_WEBAUDIO:{target:"webaudio",actions:["setPlayingWebAudio","startSourceNode","startProgressLoop"]},SCHEDULE_GAPLESS:{target:"webaudio",actions:["setScheduledGapless","startScheduledSourceNode"]},ACTIVATE:{target:"idle",actions:["clearPlayingAndSchedule","resetTiming","resetHtml5Element"]},DEACTIVATE:{target:"idle",actions:["clearIsPlaying","resetTiming"]},URL_RESOLVED:{actions:"setResolvedUrl"}}},webaudio:{on:{PAUSE:{actions:["clearIsPlaying","freezePausedTime","stopSourceNode","disconnectGain","stopProgressLoop","reportProgress"]},PLAY:[{guard:"canPlayWebAudio",actions:["setIsPlaying","startSourceNode","startProgressLoop"]},{actions:"setIsPlaying"}],PLAY_WEBAUDIO:{actions:"setPlayingWebAudioType"},SEEK:{actions:["clearScheduledStart","seekWebAudio","reportProgress"]},SET_VOLUME:{},CANCEL_GAPLESS:{target:"idle",actions:["clearPlayingAndSchedule","stopSourceNode","disconnectGain","stopProgressLoop","resetTiming"]},LOOKAHEAD_REACHED:{actions:"setNotifiedLookahead"},WEBAUDIO_ENDED:{target:"idle",actions:["clearIsPlaying","stopProgressLoop","notifyTrackEnded"]},ACTIVATE:{target:"idle",actions:["clearPlayingAndSchedule","stopSourceNode","disconnectGain","stopProgressLoop","resetTiming","resetHtml5Element"]},DEACTIVATE:{target:"idle",actions:["clearPlayingAndSchedule","stopSourceNode","disconnectGain","resetTiming","resetHtml5Element","stopProgressLoop"]}}}}})}var wn=5,nt=class{index;metadata;_trackUrl;_resolvedUrl;skipHEAD;_pendingArrayBuffer=null;audio;_webAudioDisabled;get ctx(){if(this._webAudioDisabled)return null;let t=et();return t&&!this.gainNode&&(this.gainNode=t.createGain(),this.gainNode.gain.value=this.audio.volume),t}gainNode=null;sourceNode=null;audioBuffer=null;webAudioStartedAt=0;pausedAtTrackTime=0;_actor;queueRef;rafId=null;constructor(t){this.index=t.index,this._trackUrl=t.trackUrl,this._resolvedUrl=t.trackUrl,this.skipHEAD=t.skipHEAD??!1,this.metadata=t.metadata??{},this.queueRef=t.queue,this.audio=new Audio,this.audio.preload="none",this.audio.src=this._trackUrl,this.audio.volume=t.queue.volume,this.audio.controls=!1,this.audio.onerror=()=>{var o,a;let r=(o=this.audio.error)==null?void 0:o.code;if(r===1)return;let i=((a=this.audio.error)==null?void 0:a.message)??"unknown";this.queueRef.onError(new Error(`HTML5 audio error on track ${this.index} (code ${r}): ${i}`))},this.audio.onended=()=>{this.queueRef.onDebug(`audio.onended track=${this.index} machineState=${this._actor.getSnapshot().value} queueIdx=${this.queueRef.currentTrackIndex}`),this._actor.send({type:"HTML5_ENDED"})},this._webAudioDisabled=t.queue.webAudioIsDisabled;let e={trackUrl:this._trackUrl,resolvedUrl:this._trackUrl,skipHEAD:this.skipHEAD,playbackType:"HTML5",webAudioLoadingState:"NONE",isPlaying:!1,scheduledStartContextTime:null,notifiedLookahead:!1,fetchDecodeRef:null},s=ke(e).provide({guards:{canPlayWebAudio:()=>!!(this.ctx&&this.audioBuffer&&this.gainNode)},actors:{fetchDecode:mt.provide({actors:{resolveUrl:x(async({signal:r})=>{let i=await fetch(this._trackUrl,{method:"HEAD",signal:r});return i.redirected&&i.url?(this._resolvedUrl=i.url,this.audio.src=i.url,i.url):null}),fetchAudio:x(async({input:r,signal:i})=>{let{resolvedUrl:o}=r,a=await fetch(o,{signal:i});if(!a.ok)throw new Error(`HTTP ${a.status} for ${o}`);this._pendingArrayBuffer=await a.arrayBuffer()}),decodeAudio:x(async()=>{let r=this._pendingArrayBuffer;if(this._pendingArrayBuffer=null,!r||!this.ctx)throw new Error("No ArrayBuffer or AudioContext");this.audioBuffer=await this.ctx.decodeAudioData(r),queueMicrotask(()=>this.queueRef.onTrackBufferReady(this))})}})},actions:{playHtml5:()=>this._playHtml5(),startSourceNode:()=>{this._startSourceNode(this.pausedAtTrackTime)},startScheduledSourceNode:({context:r})=>{let i=r.scheduledStartContextTime;i===null||!this.ctx||!this.audioBuffer||!this.gainNode||(this._stopSourceNode(),this.sourceNode=this.ctx.createBufferSource(),this.sourceNode.buffer=this.audioBuffer,this.sourceNode.connect(this.gainNode),this.gainNode.connect(this.ctx.destination),this.sourceNode.onended=this._handleWebAudioEnded,this.sourceNode.start(i,0),this.webAudioStartedAt=i,this.queueRef.onDebug(`startScheduledSourceNode track=${this.index} when=${i.toFixed(3)} ctxNow=${this.ctx.currentTime.toFixed(3)} delta=${(i-this.ctx.currentTime).toFixed(3)}s`))},startProgressLoop:()=>this.startProgressLoop(),pauseHtml5:()=>this.audio.pause(),freezePausedTime:()=>{this.pausedAtTrackTime=this.currentTime},stopSourceNode:()=>this._stopSourceNode(),disconnectGain:()=>this._disconnectGain(),stopProgressLoop:()=>this._stopProgressLoop(),reportProgress:()=>this.queueRef.onProgress(this.toInfo()),seekHtml5:()=>this._seekHtml5(),seekWebAudio:()=>this._seekWebAudio(),resetHtml5Element:()=>{this.audio.currentTime=0},resetTiming:()=>{this.webAudioStartedAt=0,this.pausedAtTrackTime=0},notifyTrackEnded:()=>{queueMicrotask(()=>this.queueRef.onTrackEnded(this))}}});this._actor=T(s),this._actor.start()}play(){this.queueRef.onDebug(`Track.play() track=${this.index} machineState=${this._actor.getSnapshot().value} hasBuffer=${!!this.audioBuffer} hasCtx=${!!this.ctx} audioPaused=${this.audio.paused}`),this._actor.send({type:"PLAY"})}pause(){this._actor.send({type:"PAUSE"})}seek(t){let e=Math.max(0,isNaN(this.duration)?t:Math.min(t,this.duration));this.pausedAtTrackTime=e,this._actor.send({type:"SEEK",time:e})}setVolume(t){let e=Math.min(1,Math.max(0,t));this.audio.volume=e,this.gainNode&&(this.gainNode.gain.value=e),this._actor.send({type:"SET_VOLUME",volume:e})}preload(){this.queueRef.onDebug(`preload() track=${this.index} state=${this._actor.getSnapshot().value} hasBuffer=${!!this.audioBuffer} hasCtx=${!!this.ctx}`),this._actor.getSnapshot().value==="idle"&&this._actor.send({type:"PRELOAD"}),!(this.audioBuffer||!this.ctx)&&this._actor.send({type:"START_FETCH"})}seekToEnd(t=6){let e=this.duration;!isNaN(e)&&e>t&&this.seek(e-t)}activate(){this._actor.send({type:"ACTIVATE"})}deactivate(){this.queueRef.onDebug(`Track.deactivate() track=${this.index} machineState=${this._actor.getSnapshot().value} isPlaying=${this.isPlaying}`),this._actor.send({type:"DEACTIVATE"}),this.queueRef.onDebug(`Track.deactivate() done track=${this.index} machineState=${this._actor.getSnapshot().value}`)}destroy(){var t;this.deactivate(),this._pendingArrayBuffer=null,this.audioBuffer=null,(t=this.gainNode)==null||t.disconnect(),this.gainNode=null,this._actor.stop()}cancelGaplessStart(){this._actor.getSnapshot().context.scheduledStartContextTime!==null&&this._actor.send({type:"CANCEL_GAPLESS"})}scheduleGaplessStart(t){!this.ctx||!this.audioBuffer||!this.gainNode||this._actor.send({type:"SCHEDULE_GAPLESS",when:t})}get currentTime(){let t=this._actor.getSnapshot();return t.value==="webaudio"?t.context.isPlaying?this.ctx?Math.max(0,this.ctx.currentTime-this.webAudioStartedAt):0:this.pausedAtTrackTime:this.audio.currentTime}get duration(){return this.audioBuffer?this.audioBuffer.duration:this.audio.duration}get isPaused(){let t=this._actor.getSnapshot();return t.value==="webaudio"?!t.context.isPlaying:this.audio.paused}get isPlaying(){return this._actor.getSnapshot().context.isPlaying}get trackUrl(){return this._resolvedUrl}get playbackType(){return this._actor.getSnapshot().context.playbackType}get webAudioLoadingState(){return this._actor.getSnapshot().context.webAudioLoadingState}get hasSourceNode(){return this.sourceNode!==null}get machineState(){return this._actor.getSnapshot().value}get scheduledStartContextTime(){return this._actor.getSnapshot().context.scheduledStartContextTime}get isBufferLoaded(){return this.audioBuffer!==null}toInfo(){var t;return{index:this.index,currentTime:this.currentTime,duration:this.duration,isPlaying:this.isPlaying,isPaused:this.isPaused,volume:((t=this.gainNode)==null?void 0:t.gain.value)??this.audio.volume,trackUrl:this.trackUrl,playbackType:this.playbackType,webAudioLoadingState:this.webAudioLoadingState,metadata:this.metadata,machineState:this.machineState}}_playHtml5(){this.audio.preload!=="auto"&&(this.audio.preload="auto");let t=this.audio.play();t&&t.catch(e=>{e instanceof Error&&e.name==="NotAllowedError"?this.queueRef.onPlayBlocked():e instanceof Error&&e.name==="AbortError"||this.queueRef.onError(e instanceof Error?e:new Error(String(e)))})}_seekHtml5(){let t=this.pausedAtTrackTime;this.audio.preload!=="auto"&&(this.audio.preload="auto"),this.audio.readyState>=HTMLMediaElement.HAVE_METADATA?this.audio.currentTime=t:(this.audio.addEventListener("loadedmetadata",()=>{this.audio.currentTime=t},{once:!0}),this.audio.load())}_startSourceNode(t){!this.ctx||!this.audioBuffer||!this.gainNode||(this._stopSourceNode(),this.ctx.state==="suspended"&&this.ctx.resume(),this.sourceNode=this.ctx.createBufferSource(),this.sourceNode.buffer=this.audioBuffer,this.sourceNode.connect(this.gainNode),this.gainNode.connect(this.ctx.destination),this.sourceNode.onended=this._handleWebAudioEnded,this.webAudioStartedAt=this.ctx.currentTime-t,this.sourceNode.start(0,t))}_stopSourceNode(){if(this.sourceNode){this.sourceNode.onended=null;try{this.sourceNode.stop()}catch{}try{this.sourceNode.disconnect()}catch{}this.sourceNode=null}}_disconnectGain(){if(!(!this.gainNode||!this.ctx))try{this.gainNode.disconnect(this.ctx.destination)}catch{}}_seekWebAudio(){let e=this._actor.getSnapshot().context.isPlaying,s=this.pausedAtTrackTime;this._stopSourceNode(),e&&this._startSourceNode(s)}_handleWebAudioEnded=()=>{this.queueRef.onDebug(`_handleWebAudioEnded track=${this.index} sourceNode=${!!this.sourceNode} queueIdx=${this.queueRef.currentTrackIndex}`),this.sourceNode&&this._actor.send({type:"WEBAUDIO_ENDED"})};startProgressLoop(){if(this.rafId!==null)return;let t=()=>{if(this.isPaused||!this.isPlaying){this.rafId=null;return}this.queueRef.onProgress(this.toInfo());let e=this.duration-this.currentTime;!this._actor.getSnapshot().context.notifiedLookahead&&!isNaN(e)&&e<=wn&&(this._actor.send({type:"LOOKAHEAD_REACHED"}),queueMicrotask(()=>this.queueRef.onTrackBufferReady(this))),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}_stopProgressLoop(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}};function Ee(n,t){let e=0;return(...s)=>{let r=performance.now();r-e<t||(e=r,n(...s))}}var Pn=2,_t=class{_tracks=[];_actor;_onProgress;_onEnded;_onPlayNextTrack;_onPlayPreviousTrack;_onStartNewTrack;_onError;_onPlayBlocked;_onDebug;webAudioIsDisabled;_volume;_scheduledNextIndex=null;_throttledUpdatePositionState=Ee((t,e)=>Se(t,e),1e3);constructor(t={}){let{tracks:e=[],onProgress:s,onEnded:r,onPlayNextTrack:i,onPlayPreviousTrack:o,onStartNewTrack:a,onError:u,onPlayBlocked:f,onDebug:g,webAudioIsDisabled:d=!1,trackMetadata:c=[],volume:h=1}=t;this._volume=Math.min(1,Math.max(0,h)),this.webAudioIsDisabled=d,this._onProgress=s,this._onEnded=r,this._onPlayNextTrack=i,this._onPlayPreviousTrack=o,this._onStartNewTrack=a,this._onError=u,this._onPlayBlocked=f,this._onDebug=g,this._tracks=e.map((l,y)=>new nt({trackUrl:l,index:y,queue:this,metadata:c[y]}));let p=Ae({currentTrackIndex:0,trackCount:this._tracks.length}).provide({actions:{deactivateCurrent:({context:l})=>{var y;(y=this._trackAt(l.currentTrackIndex))==null||y.deactivate()},deactivateEndedTrack:({context:l})=>{var y;(y=this._trackAt(l.currentTrackIndex))==null||y.deactivate()},activateAndPlayCurrent:({context:l})=>{let y=this._trackAt(l.currentTrackIndex);y&&(y.activate(),this._scheduledNextIndex!==y.index&&y.play())},playOrContinueGapless:({context:l})=>{let y=this._trackAt(l.currentTrackIndex);y&&(this._scheduledNextIndex!==y.index?y.play():(this._scheduledNextIndex=null,this.onDebug(`onTrackEnded: gapless track ${y.index} \u2014 sourceNode=${y.hasSourceNode} isPlaying=${y.isPlaying} machineState=${y.machineState}`),y.startProgressLoop()))},cancelAllGapless:()=>this._cancelScheduledGapless(),notifyStartNewTrack:({context:l})=>{var _;let y=this._trackAt(l.currentTrackIndex);y&&((_=this._onStartNewTrack)==null||_.call(this,y.toInfo()))},notifyPlayNextTrack:({context:l})=>{var _;let y=this._trackAt(l.currentTrackIndex);y&&((_=this._onPlayNextTrack)==null||_.call(this,y.toInfo()))},notifyPlayPreviousTrack:({context:l})=>{var _;let y=this._trackAt(l.currentTrackIndex);y&&((_=this._onPlayPreviousTrack)==null||_.call(this,y.toInfo()))},notifyEnded:()=>{var l;return(l=this._onEnded)==null?void 0:l.call(this)},updateMediaSessionMetadata:({context:l})=>{let y=this._trackAt(l.currentTrackIndex);y&&ve(y.metadata)},preloadAhead:({context:l})=>{this._preloadAhead(l.currentTrackIndex)},playCurrent:({context:l})=>{var y;(y=this._trackAt(l.currentTrackIndex))==null||y.play()},pauseCurrent:({context:l})=>{var y;(y=this._trackAt(l.currentTrackIndex))==null||y.pause()},seekCurrent:({context:l,event:y})=>{var k;let _=y;(k=this._trackAt(l.currentTrackIndex))==null||k.seek(_.time)},seekCurrentToZero:({context:l})=>{var y;(y=this._trackAt(l.currentTrackIndex))==null||y.seek(0)},scheduleGapless:({context:l})=>{this._tryScheduleGapless(l.currentTrackIndex)},cancelScheduledGapless:()=>{this._cancelScheduledGapless()},cancelAndRescheduleGapless:({context:l})=>{this._cancelScheduledGapless(),this._tryScheduleGapless(l.currentTrackIndex)}}});this._actor=T(p),this._actor.subscribe(l=>{Te(l.value==="playing")}),this._actor.start(),_e({onPlay:()=>this.play(),onPause:()=>{this._actor.getSnapshot().value==="playing"&&this.pause()},onNext:()=>this.next(),onPrevious:()=>this.previous(),onSeek:l=>this.seek(l)})}play(){this._currentTrack&&this._actor.send({type:"PLAY"})}pause(){this._actor.send({type:"PAUSE"})}togglePlayPause(){this._actor.getSnapshot().value==="playing"?this.pause():this.play()}next(){this._actor.getSnapshot().context.currentTrackIndex+1>=this._tracks.length||this._actor.send({type:"NEXT"})}previous(){let t=this._currentTrack;if(t&&t.currentTime>8){t.seek(0),t.play();return}this._actor.send({type:"PREVIOUS"})}gotoTrack(t,e=!1){t<0||t>=this._tracks.length||(this.onDebug(`gotoTrack(${t}, playImmediately=${e}) queueState=${this._actor.getSnapshot().value} curIdx=${this._actor.getSnapshot().context.currentTrackIndex}`),this._actor.send({type:"GOTO",index:t,playImmediately:e}))}seek(t){this._actor.send({type:"SEEK",time:t})}setVolume(t){let e=Math.min(1,Math.max(0,t));this._volume=e;for(let s of this._tracks)s.setVolume(e)}addTrack(t,e={}){let s=this._tracks.length,r=e.metadata??{};this._tracks.push(new nt({trackUrl:t,index:s,queue:this,skipHEAD:e.skipHEAD,metadata:r})),this._actor.send({type:"ADD_TRACK"})}removeTrack(t){if(!(t<0||t>=this._tracks.length)){this._tracks[t].destroy(),this._tracks.splice(t,1);for(let e=t;e<this._tracks.length;e++)this._tracks[e].index=e;this._scheduledNextIndex===t&&(this._scheduledNextIndex=null),this._actor.send({type:"REMOVE_TRACK",index:t})}}resumeAudioContext(){return me()}destroy(){for(let t of this._tracks)t.destroy();this._tracks=[],this._actor.stop()}get currentTrack(){var t;return(t=this._currentTrack)==null?void 0:t.toInfo()}get currentTrackIndex(){return this._actor.getSnapshot().context.currentTrackIndex}get tracks(){return this._tracks.map(t=>t.toInfo())}get isPlaying(){return this._actor.getSnapshot().value==="playing"}get isPaused(){return this._actor.getSnapshot().value==="paused"}get volume(){return this._volume}get queueSnapshot(){let t=this._actor.getSnapshot();return{state:t.value,context:t.context}}onTrackEnded(t){let e=this._actor.getSnapshot();if(this.onDebug(`onTrackEnded track=${t.index} queueState=${e.value} curIdx=${e.context.currentTrackIndex}`),t.index!==e.context.currentTrackIndex)return;this._actor.send({type:"TRACK_ENDED"});let s=this._actor.getSnapshot();this.onDebug(`onTrackEnded after TRACK_ENDED \u2192 queueState=${s.value} curIdx=${s.context.currentTrackIndex}`)}onTrackBufferReady(t){this._actor.send({type:"TRACK_LOADED",index:t.index})}onProgress(t){var e;t.index===this._actor.getSnapshot().context.currentTrackIndex&&(isNaN(t.duration)||this._throttledUpdatePositionState(t.duration,t.currentTime),(e=this._onProgress)==null||e.call(this,t))}onError(t){var e;(e=this._onError)==null||e.call(this,t)}onPlayBlocked(){var t;(t=this._onPlayBlocked)==null||t.call(this)}onDebug(t){var e;(e=this._onDebug)==null||e.call(this,t)}_trackAt(t){return this._tracks[t]}get _currentTrack(){return this._tracks[this._actor.getSnapshot().context.currentTrackIndex]}_preloadAhead(t){let e=t+Pn+1;this.onDebug(`_preloadAhead(${t}) limit=${e} trackCount=${this._tracks.length}`);for(let s=t+1;s<this._tracks.length&&s<e;s++){let r=this._tracks[s];if(r.isBufferLoaded)this.onDebug(`_preloadAhead: track ${s} already loaded`);else{this.onDebug(`_preloadAhead: starting preload for track ${s}`),r.preload();break}}}_cancelScheduledGapless(){if(this._scheduledNextIndex===null)return;let t=this._trackAt(this._scheduledNextIndex);t&&(t.cancelGaplessStart(),this.onDebug(`_cancelScheduledGapless: cancelled track ${this._scheduledNextIndex}`)),this._scheduledNextIndex=null}_tryScheduleGapless(t){let e=et();if(!e||this.webAudioIsDisabled)return;let s=t+1;if(s>=this._tracks.length)return;let r=this._tracks[t],i=this._tracks[s];if(!r.isBufferLoaded||!i.isBufferLoaded||this._scheduledNextIndex===s||!r.isPlaying)return;let o=this._computeTrackEndTime(r);o!==null&&(o<e.currentTime+.01||(i.scheduleGaplessStart(o),this._scheduledNextIndex=s))}_computeTrackEndTime(t){let e=et();if(!e||!t.isBufferLoaded)return null;let s=t.duration;if(isNaN(s))return null;if(t.scheduledStartContextTime!==null)return t.scheduledStartContextTime+s;let r=s-t.currentTime;return r<=0?null:e.currentTime+r}};export{_t as Queue,_t as default};
|
|
4
4
|
//# sourceMappingURL=index.mjs.map
|