@banou/ripple 0.0.1 → 0.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.
@@ -1 +1 @@
1
- import{k as s}from"./index-8227e1be.js";import{C as n,R as i}from"./index-9a320571.js";(async()=>{let e;globalThis.addEventListener("connect",async o=>{const{resolvers:a}=await import("./io-worker-67a3c2ed.js").then(async m=>{await m.__tla;return m}),{ports:[r]}=o;n({key:"shared-worker-fkn-api",target:r,resolvers:a}),r.start(),e||i(r,{key:"shared-worker-fkn-port"})("getApiTargetPort").then(t=>{s(t),e=t})})})();
1
+ import{k as s}from"./index-8227e1be.js";import{C as n,R as i}from"./index-9a320571.js";(async()=>{let e;globalThis.addEventListener("connect",async o=>{const{resolvers:a}=await import("./io-worker-682dbf74.js").then(async m=>{await m.__tla;return m}),{ports:[r]}=o;n({key:"shared-worker-fkn-api",target:r,resolvers:a}),r.start(),e||i(r,{key:"shared-worker-fkn-port"})("getApiTargetPort").then(t=>{s(t),e=t})})})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@banou/ripple",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "type": "module",
5
5
  "main": "build/index.js",
6
6
  "keywords": [
@@ -11,14 +11,17 @@
11
11
  "build"
12
12
  ],
13
13
  "scripts": {
14
- "_dev": "vite --port 5678",
14
+ "___dev": "vite --port 5678",
15
15
  "dev": "vite --port 4560",
16
- "build": "vite build && npm run copy-libav && npm run copy-libass && npm run copy-html",
16
+ "__dev": "shx rm -rf ./build && shx mkdir ./build && npm run copy-libav && npm run copy-libass && concurrently \"vite --port 4560\" \"vite build --mode development --watch\"",
17
+ "_dev": "shx rm -rf ./build && shx mkdir ./build && npm run copy-libav && npm run copy-html && npm run copy-libass && concurrently \"serve -s -C -p 4560 build\" \"vite build --mode development --watch\"",
18
+ "serve": "serve -s -C -p 4560 build",
19
+ "build": "shx rm -rf build/ && vite build && npm run copy-libav && npm run copy-libass && npm run copy-html",
17
20
  "copy-libav": "shx cp node_modules/libav-wasm/build/worker.js build/libav-worker.js && shx cp node_modules/libav-wasm/build/libav.wasm build/libav.wasm",
18
21
  "copy-libass": "shx cp node_modules/jassub/dist/jassub-worker.js build/jassub-worker.js && shx cp node_modules/jassub/dist/jassub-worker-modern.wasm build/jassub-worker-modern.wasm",
19
22
  "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
20
23
  "preview": "vite preview",
21
- "copy-html": "shx cp src/index.html build/index.html",
24
+ "copy-html": "shx cp src/index.html build/index.html && shx cp src/app.webmanifest build/app.webmanifest && copyfiles -u 2 ./src/assets/* build/assets",
22
25
  "copy-media-player": "copyfiles -u 4 ./node_modules/@banou/media-player/build/* build/tmp && shx rm build/tmp/index.js && shx mv build/tmp/* build && shx rm -rf build/tmp",
23
26
  "build-deps": "npm run build-deps-media-player && npm run build-deps-fkn-lib",
24
27
  "build-deps-local": "npm run build-deps-media-player && npm run build-deps-fkn-lib-local",
@@ -28,7 +31,7 @@
28
31
  "remove-build-deps": "shx rm -rf node_modules/@banou/media-player"
29
32
  },
30
33
  "dependencies": {
31
- "@banou/media-player": "^0.0.0",
34
+ "@banou/media-player": "^0.0.1",
32
35
  "@emotion/react": "^11.11.1",
33
36
  "@fkn/lib": "^0.0.1",
34
37
  "@hookform/resolvers": "^3.3.2",
@@ -48,8 +51,7 @@
48
51
  "react-hook-form": "^7.48.2",
49
52
  "react-router": "^6.16.0",
50
53
  "react-router-dom": "^6.16.0",
51
- "rxdb": "^15.0.0-beta.42",
52
- "rxdb-hooks": "^5.0.2",
54
+ "rxdb": "^14.17.1",
53
55
  "rxjs": "^7.8.1",
54
56
  "webtorrent": "^2.1.25",
55
57
  "xstate": "^5.0.0-beta.47",
@@ -63,12 +65,14 @@
63
65
  "@types/wicg-file-system-access": "^2023.10.1",
64
66
  "@typescript-eslint/eslint-plugin": "^6.0.0",
65
67
  "@typescript-eslint/parser": "^6.0.0",
68
+ "concurrently": "^8.2.2",
66
69
  "copyfiles": "^2.4.1",
67
70
  "eslint": "^8.45.0",
68
71
  "eslint-plugin-react-hooks": "^4.6.0",
69
72
  "eslint-plugin-react-refresh": "^0.4.3",
70
73
  "node-stdlib-browser": "^1.2.0",
71
74
  "rollup-plugin-polyfill-node": "^0.13.0",
75
+ "serve": "^14.2.1",
72
76
  "shx": "^0.3.4",
73
77
  "typescript": "^5.2.2",
74
78
  "vite": "^4.4.5",
@@ -1,3 +0,0 @@
1
- import{R as z,D as B}from"./index-9a320571.js";import{m as S,n as Pt,s as Tt,o as ue,d as bt,p as fe,c as le,q as he,v as nt,t as pe,__tla as __tla_0}from"./settings-bc96f65e.js";import{v as ye,P as ge}from"./index-8227e1be.js";let oe,On,Fn;let __tla=Promise.all([(()=>{try{return __tla_0}catch{}})()]).then(async()=>{function me(){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 ve(){const t=me();if(t.__xstate__)return t.__xstate__}const Ee=t=>{if(typeof window>"u")return;const e=ve();e&&e.register(t)};class Rt{constructor(e){this._process=e,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(e){const n={value:e,next:null};if(this._current){this._last.next=n,this._last=n;return}this._current=n,this._last=n,this._active&&this.flush()}flush(){for(;this._current;){const e=this._current;this._process(e.value),this._current=e.next}this._last=null}}const Y=".",Se="",Ut="",we="#",_e="*",Ht="xstate.init",Te="xstate.error",N="xstate.stop";function be(t,e){const n=e?`#${e}`:"";return{type:`xstate.after(${t})${n}`}}function rt(t,e){return{type:`xstate.done.state.${t}`,output:e}}function Re(t,e){return{type:`xstate.done.actor.${t}`,output:e}}function O(t,e){return{type:`xstate.error.actor.${t}`,data:e}}function Bt(t){return{type:Ht,input:t}}function x(t){setTimeout(()=>{throw t})}const De=(()=>typeof Symbol=="function"&&Symbol.observable||"@@observable")();let xe=0;function Ie(t){const e=new Map,n=new Map,s=new WeakMap,i=new Set,r={_bookId:()=>`x:${xe++}`,_register:(o,a)=>(e.set(o,a),o),_unregister:o=>{e.delete(o.sessionId);const a=s.get(o);a!==void 0&&(n.delete(a),s.delete(o))},get:o=>n.get(o),_set:(o,a)=>{const c=n.get(o);if(c&&c!==a)throw new Error(`Actor with system ID '${o}' already exists.`);n.set(o,a),s.set(a,o)},inspect:o=>{i.add(o)},_sendInspectionEvent:o=>{const a={...o,rootId:t.sessionId};i.forEach(c=>c.next?.(a))},_relay:(o,a,c)=>{r._sendInspectionEvent({type:"@xstate.event",sourceRef:o,actorRef:a,event:c}),a._send(c)}};return r}function Wt(t,e){const n=Dt(t),s=Dt(e);return typeof s=="string"?typeof n=="string"?s===n:!1:typeof n=="string"?n in s:Object.keys(n).every(i=>i in s?Wt(n[i],s[i]):!1)}function Jt(t){try{return Kt(t)?t:t.split(Y)}catch{throw new Error(`'${t}' is not a valid state path.`)}}function Dt(t){if(cn(t))return t.value;if(typeof t!="string")return t;const e=Jt(t);return Ae(e)}function Ae(t){if(t.length===1)return t[0];const e={};let n=e;for(let s=0;s<t.length-1;s++)if(s===t.length-2)n[t[s]]=t[s+1];else{const i=n;n={},i[t[s]]=n}return e}function xt(t,e){const n={},s=Object.keys(t);for(let i=0;i<s.length;i++){const r=s[i];n[r]=e(t[r],r,t,i)}return n}function zt(t){return[].concat(...t)}function Gt(t){return Kt(t)?t:[t]}function w(t){return t===void 0?[]:Gt(t)}function ot(t,e,n,s){return typeof t=="function"?t({context:e,event:n,self:s}):t}function Kt(t){return Array.isArray(t)}function ke(t){return t.type.startsWith("xstate.error.actor")}function A(t){return Gt(t).map(e=>typeof e>"u"||typeof e=="string"?{target:e}:e)}function Vt(t){if(!(t===void 0||t===Se))return w(t)}function It(t,e,n){const s=typeof t=="object",i=s?t:void 0;return{next:(s?t.next:t)?.bind(i),error:(s?t.error:e)?.bind(i),complete:(s?t.complete:n)?.bind(i)}}function At(t,e){return`${t}[${e}]`}function ft(t,e){if(e.startsWith("xstate#")){const[,n]=e.match(/\[(\d+)\]$/),i=t.getStateNodeById(e.slice(7,-(n.length+2))).config.invoke;return(Array.isArray(i)?i[n]:i).src}return t.implementations.actors[e]}function Oe(t){return[...new Set(zt([...t._nodes.map(e=>e.ownEvents)]))]}const lt=1;let m=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const $e={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class Me{constructor(e,n){this.logic=e,this._state=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new Rt(this._process.bind(this)),this.delayedEventsMap={},this.observers=new Set,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=[];const s={...$e,...n},{clock:i,logger:r,parent:o,syncSnapshot:a,id:c,systemId:u,inspect:l}=s;this.system=o?.system??Ie(this),l&&!o&&this.system.inspect(It(l)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=r,this.clock=i,this._parent=o,this._syncSnapshot=a,this.options=s,this.src=s.src??e,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:f=>{this._deferred.push(f)},system:this.system,stopChild:f=>{if(f._parent!==this)throw new Error(`Cannot stop child actor ${f.id} of ${this.id} because it is not a child`);f._stop()}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),u&&(this._systemId=u,this.system._set(u,this)),this._initState(n?.state),u&&this._state.status!=="active"&&this.system._unregister(this)}_initState(e){this._state=e?this.logic.restoreState?this.logic.restoreState(e,this._actorScope):e:this.logic.getInitialState(this._actorScope,this.options?.input)}update(e,n){this._state=e;let s;for(;s=this._deferred.shift();)s();for(const i of this.observers)try{i.next?.(e)}catch(r){x(r)}switch(this._state.status){case"done":this._stopProcedure(),this._complete(),this._doneEvent=Re(this.id,this._state.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._stopProcedure(),this._error(this._state.error),this._parent&&this.system._relay(this,this._parent,O(this.id,this._state.error));break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:n,snapshot:e})}subscribe(e,n,s){const i=It(e,n,s);if(this._processingStatus!==m.Stopped)this.observers.add(i);else try{i.complete?.()}catch(r){x(r)}return{unsubscribe:()=>{this.observers.delete(i)}}}start(){if(this._processingStatus===m.Running)return this;this._syncSnapshot&&this.subscribe({next:s=>{s.status==="active"&&this._parent.send({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;const e=Bt(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:e}),this._state.status){case"done":this.update(this._state,e);case"error":return this}if(this.logic.start)try{this.logic.start(this._state,this._actorScope)}catch(s){return this._stopProcedure(),this._error(s),this._parent?.send(O(this.id,s)),this}return this.update(this._state,e),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(e){let n,s;try{n=this.logic.transition(this._state,e,this._actorScope)}catch(i){s={err:i}}if(s){const{err:i}=s;this._stopProcedure(),this._error(i),this._parent?.send(O(this.id,i));return}this.update(n,e),e.type===N&&(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:N}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const e of this.observers)try{e.complete?.()}catch(n){x(n)}this.observers.clear()}_error(e){if(!this.observers.size){this._parent||x(e);return}let n=!1;for(const s of this.observers){const i=s.error;n||=!i;try{i?.(e)}catch(r){x(r)}}this.observers.clear(),n&&x(e)}_stopProcedure(){if(this._processingStatus!==m.Running)return this;for(const e of Object.keys(this.delayedEventsMap))this.clock.clearTimeout(this.delayedEventsMap[e]);return this.mailbox.clear(),this.mailbox=new Rt(this._process.bind(this)),this._processingStatus=m.Stopped,this.system._unregister(this),this}_send(e){this._processingStatus!==m.Stopped&&this.mailbox.enqueue(e)}send(e){this.system._relay(void 0,this,e)}delaySend(e){const{event:n,id:s,delay:i}=e,r=this.clock.setTimeout(()=>{this.system._relay(this,e.to??this,n)},i);s&&(this.delayedEventsMap[s]=r)}cancel(e){this.clock.clearTimeout(this.delayedEventsMap[e]),delete this.delayedEventsMap[e]}attachDevTools(){const{devTools:e}=this.options;e&&(typeof e=="function"?e:Ee)(this)}toJSON(){return{xstate$$type:lt,id:this.id}}getPersistedState(e){return this.logic.getPersistedState(this._state,e)}[De](){return this}getSnapshot(){return this._state}}function j(t,e){return new Me(t,e)}function Le(t,e,n,s,{sendId:i}){const r=typeof i=="function"?i(n,s):i;return[e,r]}function Fe(t,e){t.self.cancel(e)}function Ce(t){function e(n,s){}return e.type="xstate.cancel",e.sendId=t,e.resolve=Le,e.execute=Fe,e}function Ne(t,e,n,s,{id:i,systemId:r,src:o,input:a,syncSnapshot:c}){const u=typeof o=="string"?ft(e.machine,o):o,l=typeof i=="function"?i(n):i;let f;return u&&(f=j(u,{id:l,src:o,parent:t?.self,syncSnapshot:c,systemId:r,input:typeof a=="function"?a({context:e.context,event:n.event,self:t?.self}):a})),[R(e,{children:{...e.children,[l]:f}}),{id:i,actorRef:f}]}function je(t,{id:e,actorRef:n}){n&&t.defer(()=>{if(n._processingStatus!==m.Stopped)try{n.start?.()}catch(s){t.self.send(O(e,s));return}})}function Pe(...[t,{id:e,systemId:n,input:s,syncSnapshot:i=!1}={}]){function r(o,a){}return r.type="xstate.spawnChild",r.id=e,r.systemId=n,r.src=t,r.input=s,r.syncSnapshot=i,r.resolve=Ne,r.execute=je,r}function Ue(t,e,n,s,{actorRef:i}){const r=typeof i=="function"?i(n,s):i,o=typeof r=="string"?e.children[r]:r;let a=e.children;return o&&(a={...a},delete a[o.id]),[R(e,{children:a}),o]}function He(t,e){if(e){if(t.system._unregister(e),e._processingStatus!==m.Running){t.stopChild(e);return}t.defer(()=>{t.stopChild(e)})}}function qt(t){function e(n,s){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=Ue,e.execute=He,e}function Be(t,{context:e,event:n},{guards:s}){return s.some(i=>X(i,e,n,t))}function kt(t){function e(n,s){return!1}return e.check=Be,e.guards=t,e}function X(t,e,n,s){const{machine:i}=s,r=typeof t=="function",o=r?t:i.implementations.guards[typeof t=="string"?t:t.type];if(!r&&!o)throw new Error(`Guard '${typeof t=="string"?t:t.type}' is not implemented.'.`);if(typeof o!="function")return X(o,e,n,s);const a={context:e,event:n},c=r||typeof t=="string"?void 0:"params"in t?typeof t.params=="function"?t.params({context:e,event:n}):t.params:void 0;return"check"in o?o.check(s,a,o):o(a,c)}const ht=t=>t.type==="atomic"||t.type==="final";function $(t){return Object.values(t.states).filter(e=>e.type!=="history")}function U(t,e){const n=[];if(e===t)return n;let s=t.parent;for(;s&&s!==e;)n.push(s),s=s.parent;return n}function G(t){const e=new Set(t),n=Xt(e);for(const s of e)if(s.type==="compound"&&(!n.get(s)||!n.get(s).length))Ot(s).forEach(i=>e.add(i));else if(s.type==="parallel"){for(const i of $(s))if(i.type!=="history"&&!e.has(i)){const r=Ot(i);for(const o of r)e.add(o)}}for(const s of e){let i=s.parent;for(;i;)e.add(i),i=i.parent}return e}function Yt(t,e){const n=e.get(t);if(!n)return{};if(t.type==="compound"){const i=n[0];if(i){if(ht(i))return i.key}else return{}}const s={};for(const i of n)s[i.key]=Yt(i,e);return s}function Xt(t){const e=new Map;for(const n of t)e.has(n)||e.set(n,[]),n.parent&&(e.has(n.parent)||e.set(n.parent,[]),e.get(n.parent).push(n));return e}function Zt(t,e){const n=G(e);return Yt(t,Xt(n))}function pt(t,e){return e.type==="compound"?$(e).some(n=>n.type==="final"&&t.has(n)):e.type==="parallel"?$(e).every(n=>pt(t,n)):e.type==="final"}const Z=t=>t[0]===we;function We(t,e){return t.transitions.get(e)||[...t.transitions.keys()].filter(s=>{if(s===_e)return!0;if(!s.endsWith(".*"))return!1;const i=s.split("."),r=e.split(".");for(let o=0;o<i.length;o++){const a=i[o],c=r[o];if(a==="*")return o===i.length-1;if(a!==c)return!1}return!0}).sort((s,i)=>i.length-s.length).flatMap(s=>t.transitions.get(s))}function Je(t){const e=t.config.after;if(!e)return[];const n=(i,r)=>{const o=typeof i=="function"?`${t.id}:delay[${r}]`:i,a=be(o,t.id),c=a.type;return t.entry.push(mn(a,{id:c,delay:i})),t.exit.push(Ce(c)),c};return Object.keys(e).flatMap((i,r)=>{const o=e[i],a=typeof o=="string"?{target:o}:o,c=isNaN(+i)?i:+i,u=n(c,r);return w(a).map(l=>({...l,event:u,delay:c}))}).map(i=>{const{delay:r}=i;return{...T(t,i.event,i),delay:r}})}function T(t,e,n){const s=Vt(n.target),i=n.reenter??!1,r=Ke(t,s),o={...n,actions:w(n.actions),guard:n.guard,target:r,source:t,reenter:i,eventType:e,toJSON:()=>({...o,source:`#${t.id}`,target:r?r.map(a=>`#${a.id}`):void 0})};return o}function ze(t){const e=new Map;if(t.config.on)for(const n of Object.keys(t.config.on)){if(n===Ut)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const s=t.config.on[n];e.set(n,A(s).map(i=>T(t,n,i)))}if(t.config.onDone){const n=`xstate.done.state.${t.id}`;e.set(n,A(t.config.onDone).map(s=>T(t,n,s)))}for(const n of t.invoke){if(n.onDone){const s=`xstate.done.actor.${n.id}`;e.set(s,A(n.onDone).map(i=>T(t,s,i)))}if(n.onError){const s=`xstate.error.actor.${n.id}`;e.set(s,A(n.onError).map(i=>T(t,s,i)))}if(n.onSnapshot){const s=`xstate.snapshot.${n.id}`;e.set(s,A(n.onSnapshot).map(i=>T(t,s,i)))}}for(const n of t.after){let s=e.get(n.eventType);s||(s=[],e.set(n.eventType,s)),s.push(n)}return e}function Ge(t,e){const n=typeof e=="string"?t.states[e]:e?t.states[e.target]:void 0;if(!n&&e)throw new Error(`Initial state node "${e}" not found on parent state node #${t.id}`);const s={source:t,actions:!e||typeof e=="string"?[]:w(e.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...s,source:`#${t.id}`,target:n?[`#${n.id}`]:[]})};return s}function Ke(t,e){if(e!==void 0)return e.map(n=>{if(typeof n!="string")return n;if(Z(n))return t.machine.getStateNodeById(n);const s=n[0]===Y;if(s&&!t.parent)return K(t,n.slice(1));const i=s?t.key+n:n;if(t.parent)try{return K(t.parent,i)}catch(r){throw new Error(`Invalid transition definition for state node '${t.id}':
2
- ${r.message}`)}else throw new Error(`Invalid target: "${n}" is not a valid target from the root node. Did you mean ".${n}"?`)})}function Qt(t){const e=Vt(t.config.target);return e?{target:e.map(n=>typeof n=="string"?K(t.parent,n):n)}:t.parent.initial}function b(t){return t.type==="history"}function Ot(t){const e=te(t);for(const n of e)for(const s of U(n,t))e.add(s);return e}function te(t){const e=new Set;function n(s){if(!e.has(s)){if(e.add(s),s.type==="compound")n(s.initial.target[0]);else if(s.type==="parallel")for(const i of $(s))n(i)}}return n(t),e}function M(t,e){if(Z(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const n=t.states[e];if(!n)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return n}function K(t,e){if(typeof e=="string"&&Z(e))try{return t.machine.getStateNodeById(e)}catch{}const n=Jt(e).slice();let s=t;for(;n.length;){const i=n.shift();if(!i.length)break;s=M(s,i)}return s}function V(t,e){if(typeof e=="string")return[t,t.states[e]];const n=Object.keys(e),s=n.map(i=>M(t,i)).filter(Boolean);return[t.machine.root,t].concat(s,n.reduce((i,r)=>{const o=M(t,r);if(!o)return i;const a=V(o,e[r]);return i.concat(a)},[]))}function Ve(t,e,n,s){const r=M(t,e).next(n,s);return!r||!r.length?t.next(n,s):r}function qe(t,e,n,s){const i=Object.keys(e),r=M(t,i[0]),o=yt(r,e[i[0]],n,s);return!o||!o.length?t.next(n,s):o}function Ye(t,e,n,s){const i=[];for(const r of Object.keys(e)){const o=e[r];if(!o)continue;const a=M(t,r),c=yt(a,o,n,s);c&&i.push(...c)}return i.length?i:t.next(n,s)}function yt(t,e,n,s){return typeof e=="string"?Ve(t,e,n,s):Object.keys(e).length===1?qe(t,e,n,s):Ye(t,e,n,s)}function Xe(t){return Object.keys(t.states).map(e=>t.states[e]).filter(e=>e.type==="history")}function _(t,e){let n=t;for(;n.parent&&n.parent!==e;)n=n.parent;return n.parent===e}function Ze(t,e){const n=new Set(t),s=new Set(e);for(const i of n)if(s.has(i))return!0;for(const i of s)if(n.has(i))return!0;return!1}function ee(t,e,n){const s=new Set;for(const i of t){let r=!1;const o=new Set;for(const a of s)if(Ze(at([i],e,n),at([a],e,n)))if(_(i.source,a.source))o.add(a);else{r=!0;break}if(!r){for(const a of o)s.delete(a);s.add(i)}}return Array.from(s)}function Qe(t){const[e,...n]=t;for(const s of U(e,void 0))if(n.every(i=>_(i,s)))return s}function gt(t,e){if(!t.target)return[];const n=new Set;for(const s of t.target)if(b(s))if(e[s.id])for(const i of e[s.id])n.add(i);else for(const i of gt(Qt(s),e))n.add(i);else n.add(s);return[...n]}function ne(t,e){const n=gt(t,e);if(!n)return;if(!t.reenter&&n.every(i=>i===t.source||_(i,t.source)))return t.source;const s=Qe(n.concat(t.source));if(s)return s;if(!t.reenter)return t.source.machine.root}function at(t,e,n){const s=new Set;for(const i of t)if(i.target?.length){const r=ne(i,n);i.reenter&&i.source===r&&s.add(r);for(const o of e)_(o,r)&&s.add(o)}return[...s]}function tn(t,e){if(t.length!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;return!0}function ct(t,e,n,s,i,r){if(!t.length)return e;const o=new Set(e._nodes);let a=e.historyValue;const c=ee(t,o,a);let u=e;i||([u,a]=rn(u,s,n,c,o,a,r)),u=L(u,s,n,c.flatMap(f=>f.actions),r),u=nn(u,s,n,c,o,r,a,i);const l=[...o];u.status==="done"&&(u=L(u,s,n,l.sort((f,d)=>d.order-f.order).flatMap(f=>f.exit),r));try{return a===e.historyValue&&tn(e._nodes,o)?u:R(u,{_nodes:l,historyValue:a})}catch(f){throw f}}function en(t,e,n,s,i){if(!s.output)return;const r=rt(i.id,i.output&&i.parent?ot(i.output,t.context,e,n.self):void 0);return ot(s.output,t.context,r,n.self)}function nn(t,e,n,s,i,r,o,a){let c=t;const u=new Set,l=new Set;sn(s,o,l,u),a&&l.add(t.machine.root);const f=new Set;for(const d of[...u].sort((h,p)=>h.order-p.order)){i.add(d);const h=[];h.push(...d.entry);for(const p of d.invoke)h.push(Pe(p.src,{...p,syncSnapshot:!!p.onSnapshot}));if(l.has(d)){const p=d.initial.actions;h.push(...p)}if(c=L(c,e,n,h,r,d.invoke.map(p=>p.id)),d.type==="final"){const p=d.parent;let g=p?.type==="parallel"?p:p?.parent,v=g||d;for(p?.type==="compound"&&r.push(rt(p.id,d.output?ot(d.output,c.context,e,n.self):void 0));g?.type==="parallel"&&!f.has(g)&&pt(i,g);)f.add(g),r.push(rt(g.id)),v=g,g=g.parent;if(g)continue;c=R(c,{status:"done",output:en(c,e,n,c.machine.root,v)})}}return c}function sn(t,e,n,s){for(const i of t){const r=ne(i,e);for(const a of i.target||[])!b(a)&&(i.source!==a||i.source!==r||i.reenter)&&(s.add(a),n.add(a)),k(a,e,n,s);const o=gt(i,e);for(const a of o){const c=U(a,r);r?.type==="parallel"&&c.push(r),se(s,e,n,c,!i.source.parent&&i.reenter?void 0:r)}}}function k(t,e,n,s){if(b(t))if(e[t.id]){const i=e[t.id];for(const r of i)s.add(r),k(r,e,n,s);for(const r of i)st(r,t.parent,s,e,n)}else{const i=Qt(t);for(const r of i.target)s.add(r),i===t.parent?.initial&&n.add(t.parent),k(r,e,n,s);for(const r of i.target)st(r,t,s,e,n)}else if(t.type==="compound"){const[i]=t.initial.target;b(i)||(s.add(i),n.add(i)),k(i,e,n,s),st(i,t,s,e,n)}else if(t.type==="parallel")for(const i of $(t).filter(r=>!b(r)))[...s].some(r=>_(r,i))||(b(i)||(s.add(i),n.add(i)),k(i,e,n,s))}function se(t,e,n,s,i){for(const r of s)if((!i||_(r,i))&&t.add(r),r.type==="parallel")for(const o of $(r).filter(a=>!b(a)))[...t].some(a=>_(a,o))||(t.add(o),k(o,e,n,t))}function st(t,e,n,s,i){se(n,s,i,U(t,e))}function rn(t,e,n,s,i,r,o){let a=t;const c=at(s,i,r);c.sort((l,f)=>f.order-l.order);let u;for(const l of c)for(const f of Xe(l)){let d;f.history==="deep"?d=h=>ht(h)&&_(h,l):d=h=>h.parent===l,u??={...r},u[f.id]=Array.from(i).filter(d)}for(const l of c)a=L(a,e,n,[...l.exit,...l.invoke.map(f=>qt(f.id))],o),i.delete(l);return[a,u||r]}function ie(t,e,n,s,i,r){const{machine:o}=t;let a=t;for(const c of s){const u=typeof c=="function",l=u?c:(o.implementations.actions[typeof c=="string"?c:c.type]);if(!l)continue;const f={context:a.context,event:e,self:n?.self,system:n?.system},d=u||typeof c=="string"?void 0:"params"in c?typeof c.params=="function"?c.params({context:a.context,event:e}):c.params:void 0;if(!("resolve"in l)){n?.self._processingStatus===m.Running?l(f,d):n?.defer(()=>{l(f,d)});continue}const h=l,[p,g,v]=h.resolve(n,a,f,d,l,i);a=p,"retryResolve"in h&&r?.push([h,g]),"execute"in h&&(n?.self._processingStatus===m.Running?h.execute(n,g):n?.defer(h.execute.bind(null,n,g))),v&&(a=ie(a,e,n,v,i,r))}return a}function L(t,e,n,s,i,r){const o=r?[]:void 0,a=ie(t,e,n,s,{internalQueue:i,deferredActorIds:r},o);return o?.forEach(([c,u])=>{c.retryResolve(n,a,u)}),a}function it(t,e,n,s=[]){let i=t;const r=[];if(e.type===N)return i=R($t(i,e,n),{status:"stopped"}),r.push(i),{state:i,microstates:r};let o=e;if(o.type!==Ht){const c=Mt(o,i);i=ct(c,t,n,o,!1,s),r.push(i)}let a=!0;for(;i.status==="active";){let c=a?on(i,o):[];const u=c.length?i:void 0;if(!c.length){if(!s.length)break;o=s.shift(),c=Mt(o,i)}i=ct(c,i,n,o,!1,s),a=i!==u,r.push(i)}return i.status!=="active"&&$t(i,o,n),{state:i,microstates:r}}function $t(t,e,n){return L(t,e,n,Object.values(t.children).map(s=>qt(s)),[])}function Mt(t,e){return e.machine.getTransitionData(e,t)}function on(t,e){const n=new Set,s=t._nodes.filter(ht);for(const i of s)t:for(const r of[i].concat(U(i,void 0)))if(r.always){for(const o of r.always)if(o.guard===void 0||X(o.guard,t.context,e,t)){n.add(o);break t}}return ee(Array.from(n),new Set(t._nodes),t.historyValue)}function an(t,e){const n=G(V(t,e));return Zt(t,[...n])}function cn(t){return!!t&&typeof t=="object"&&"machine"in t&&"value"in t}const dn=function(e){return Wt(e,this.value)},un=function(e){return this.tags.has(e)},fn=function(e){const n=this.machine.getTransitionData(this,e);return!!n?.length&&n.some(s=>s.target!==void 0||s.actions.length)},ln=function(){const{_nodes:e,tags:n,machine:s,getMeta:i,toJSON:r,can:o,hasTag:a,matches:c,...u}=this;return{...u,tags:Array.from(n)}},hn=function(){return this._nodes.reduce((e,n)=>(n.meta!==void 0&&(e[n.id]=n.meta),e),{})};function W(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:Zt(e.root,t._nodes),tags:new Set(zt(t._nodes.map(n=>n.tags))),children:t.children,historyValue:t.historyValue||{},matches:dn,hasTag:un,can:fn,getMeta:hn,toJSON:ln}}function R(t,e={}){return W({...t,...e},t.machine)}function pn(t,e){const{_nodes:n,tags:s,machine:i,children:r,context:o,can:a,hasTag:c,matches:u,getMeta:l,toJSON:f,...d}=t,h={};for(const g in r){const v=r[g];h[g]={state:v.getPersistedState(e),src:v.src,systemId:v._systemId,syncSnapshot:v._syncSnapshot}}return{...d,context:re(o),children:h}}function re(t){let e;for(const n in t){const s=t[n];if(s&&typeof s=="object")if("sessionId"in s&&"send"in s&&"ref"in s)e??=Array.isArray(t)?t.slice():{...t},e[n]={xstate$$type:lt,id:s.id};else{const i=re(s);i!==s&&(e??=Array.isArray(t)?t.slice():{...t},e[n]=i)}}return e??t}function yn(t,e,n,s,{event:i,id:r,delay:o},{internalQueue:a}){const c=e.machine.implementations.delays;if(typeof i=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${i}" }) instead`);const u=typeof i=="function"?i(n,s):i;let l;if(typeof o=="string"){const f=c&&c[o];l=typeof f=="function"?f(n,s):f}else l=typeof o=="function"?o(n,s):o;return typeof l!="number"&&a.push(u),[e,{event:u,id:r,delay:l}]}function gn(t,e){if(typeof e.delay=="number"){t.self.delaySend(e);return}}function mn(t,e){function n(s,i){}return n.type="xstate.raise",n.event=t,n.id=e?.id,n.delay=e?.delay,n.resolve=yn,n.execute=gn,n}function P(t){const e="$$xstate.next",n="$$xstate.error",s="$$xstate.complete";return{config:t,transition:(r,o,{self:a,id:c,defer:u,system:l})=>{if(r.status!=="active")return r;switch(o.type){case e:return{...r,context:o.data};case n:return{...r,status:"error",error:o.data,input:void 0,_subscription:void 0};case s:return{...r,status:"done",input:void 0,_subscription:void 0};case N:return r._subscription.unsubscribe(),{...r,status:"stopped",input:void 0,_subscription:void 0};default:return r}},getInitialState:(r,o)=>({status:"active",output:void 0,error:void 0,context:void 0,input:o,_subscription:void 0}),start:(r,{self:o,system:a})=>{r.status!=="done"&&(r._subscription=t({input:r.input,system:a,self:o}).subscribe({next:c=>{a._relay(o,o,{type:e,data:c})},error:c=>{a._relay(o,o,{type:n,data:c})},complete:()=>{a._relay(o,o,{type:s})}}))},getPersistedState:({_subscription:r,...o})=>o,restoreState:r=>({...r,_subscription:void 0})}}const Lt="$$xstate.resolve",Ft="$$xstate.reject";function J(t){return{config:t,transition:(n,s)=>{if(n.status!=="active")return n;switch(s.type){case Lt:{const i=s.data;return{...n,status:"done",output:i,input:void 0}}case Ft:return{...n,status:"error",error:s.data,input:void 0};case N:return{...n,status:"stopped",input:void 0};default:return n}},start:(n,{self:s,system:i})=>{if(n.status!=="active")return;Promise.resolve(t({input:n.input,system:i,self:s})).then(o=>{s.getSnapshot().status==="active"&&i._relay(s,s,{type:Lt,data:o})},o=>{s.getSnapshot().status==="active"&&i._relay(s,s,{type:Ft,data:o})})},getInitialState:(n,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedState:n=>n,restoreState:n=>n}}function vn(t,{machine:e,context:n},s,i){const r=(o,a={})=>{const{systemId:c,input:u}=a;if(typeof o=="string"){const l=ft(e,o);if(!l)throw new Error(`Actor logic '${o}' not implemented in machine '${e.id}'`);const f=j(l,{id:a.id,parent:t.self,syncSnapshot:a.syncSnapshot,input:typeof u=="function"?u({context:n,event:s,self:t.self}):u,src:o,systemId:c});return i[f.id]=f,f}else return j(o,{id:a.id,parent:t.self,syncSnapshot:a.syncSnapshot,input:a.input,src:o,systemId:c})};return(o,a)=>{const c=r(o,a);return i[c.id]=c,t.defer(()=>{if(c._processingStatus!==m.Stopped)try{c.start?.()}catch(u){t.self.send(O(c.id,u));return}}),c}}function En(t,e,n,s,{assignment:i}){if(!e.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const r={},o={context:e.context,event:n.event,spawn:vn(t,e,n.event,r),self:t?.self,system:t?.system};let a={};if(typeof i=="function")a=i(o,s);else for(const u of Object.keys(i)){const l=i[u];a[u]=typeof l=="function"?l(o,s):l}const c=Object.assign({},e.context,a);return[R(e,{context:c,children:Object.keys(r).length?{...e.children,...r}:e.children})]}function y(t){function e(n,s){}return e.type="xstate.assign",e.assignment=t,e.resolve=En,e}let dt=function(t){return t.Parent="#_parent",t.Internal="#_internal",t}({});function Sn(t,e,n,s,{to:i,event:r,id:o,delay:a},c){const u=e.machine.implementations.delays;if(typeof r=="string")throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${r}" }) instead`);const l=typeof r=="function"?r(n,s):r;let f;if(typeof a=="string"){const p=u&&u[a];f=typeof p=="function"?p(n,s):p}else f=typeof a=="function"?a(n,s):a;const d=typeof i=="function"?i(n,s):i;let h;if(typeof d=="string"){if(d===dt.Parent?h=t?.self._parent:d===dt.Internal?h=t?.self:d.startsWith("#_")?h=e.children[d.slice(2)]:h=c.deferredActorIds?.includes(d)?d:e.children[d],!h)throw new Error(`Unable to send event to actor '${d}' from machine '${e.machine.id}'.`)}else h=d||t?.self;return[e,{to:h,event:l,id:o,delay:f}]}function wn(t,e,n){typeof n.to=="string"&&(n.to=e.children[n.to])}function _n(t,e){if(typeof e.delay=="number"){t.self.delaySend(e);return}t.defer(()=>{const{to:n,event:s}=e;t?.system._relay(t.self,n,s.type===Te?O(t.self.id,s.data):s)})}function Tn(t,e,n){function s(i,r){}return s.type="xstate.sendTo",s.to=t,s.event=e,s.id=n?.id,s.delay=n?.delay,s.resolve=Sn,s.retryResolve=wn,s.execute=_n,s}function C(t,e){return Tn(dt.Parent,t,e)}const Ct=new WeakMap;function I(t,e,n){let s=Ct.get(t);return s?e in s||(s[e]=n()):(s={[e]:n()},Ct.set(t,s)),s[e]}const bn={},F=t=>typeof t=="string"?{type:t}:typeof t=="function"?"resolve"in t?{type:t.type}:{type:t.name}:t;class mt{constructor(e,n){if(this.config=e,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=n._parent,this.key=n._key,this.machine=n._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(Y),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?xt(this.config.states,(s,i)=>new mt(s,{_parent:this,_key:i,_machine:this.machine})):bn,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=w(this.config.entry).slice(),this.exit=w(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=w(e.tags).slice()}_initialize(){this.transitions=ze(this),this.config.always&&(this.always=A(this.config.always).map(e=>T(this,Ut,e))),Object.keys(this.states).forEach(e=>{this.states[e]._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(F),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(e=>`#${e.id}`),source:`#${this.id}`,actions:this.initial.actions.map(F),eventType:null})}:void 0,history:this.history,states:xt(this.states,e=>e.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(e=>({...e,actions:e.actions.map(F)})),entry:this.entry.map(F),exit:this.exit.map(F),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 I(this,"invoke",()=>w(this.config.invoke).map((e,n)=>{const{src:s,systemId:i}=e,r=e.id||At(this.id,n),o=typeof s=="string"?s:`xstate#${At(this.id,n)}`;return{...e,src:o,id:r,systemId:i,toJSON(){const{onDone:a,onError:c,...u}=e;return{...u,type:"xstate.invoke",src:o,id:r}}}}))}get on(){return I(this,"on",()=>[...this.transitions].flatMap(([n,s])=>s.map(i=>[n,i])).reduce((n,[s,i])=>(n[s]=n[s]||[],n[s].push(i),n),{}))}get after(){return I(this,"delayedTransitions",()=>Je(this))}get initial(){return I(this,"initial",()=>Ge(this,this.config.initial))}next(e,n){const s=n.type,i=[];let r;const o=I(this,`candidates-${s}`,()=>We(this,s));for(const a of o){const{guard:c}=a,u=e.context;let l=!1;try{l=!c||X(c,u,n,e)}catch(f){const d=typeof c=="string"?c:typeof c=="object"?c.type:void 0;throw new Error(`Unable to evaluate guard ${d?`'${d}' `:""}in transition for event '${s}' in state node '${this.id}':
3
- ${f.message}`)}if(l){i.push(...a.actions),r=a;break}}return r?[r]:void 0}get events(){return I(this,"events",()=>{const{states:e}=this,n=new Set(this.ownEvents);if(e)for(const s of Object.keys(e)){const i=e[s];if(i.states)for(const r of i.events)n.add(`${r}`)}return Array.from(n)})}get ownEvents(){const e=new Set([...this.transitions.keys()].filter(n=>this.transitions.get(n).some(s=>!(!s.target&&!s.actions.length&&!s.reenter))));return Array.from(e)}}const Rn="#";class vt{constructor(e,n){this.config=e,this.version=void 0,this.implementations=void 0,this.types=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.__TResolvedTypesMeta=void 0,this.id=e.id||"(machine)",this.implementations={actors:n?.actors??{},actions:n?.actions??{},delays:n?.delays??{},guards:n?.guards??{}},this.version=this.config.version,this.types=this.config.types??{},this.transition=this.transition.bind(this),this.getInitialState=this.getInitialState.bind(this),this.restoreState=this.restoreState.bind(this),this.start=this.start.bind(this),this.root=new mt(e,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(e){const{actions:n,guards:s,actors:i,delays:r}=this.implementations;return new vt(this.config,{actions:{...n,...e.actions},guards:{...s,...e.guards},actors:{...i,...e.actors},delays:{...r,...e.delays}})}resolveState(e){const n=an(this.root,e.value),s=G(V(this.root,n));return W({_nodes:[...s],context:e.context||{},children:{},status:pt(s,this.root)?"done":e.status||"active",output:e.output,error:e.error,historyValue:e.historyValue},this)}transition(e,n,s){if(ke(n)&&!Oe(e).some(r=>r===n.type))return R(e,{status:"error",error:n.data});const{state:i}=it(e,n,s);return i}microstep(e,n,s){return it(e,n,s).microstates}getTransitionData(e,n){return yt(this.root,e.value,e,n)||[]}getPreInitialState(e,n,s){const{context:i}=this.config,r=W({context:typeof i!="function"&&i?i:{},_nodes:[this.root],children:{},status:"active"},this);return typeof i=="function"?L(r,n,e,[y(({spawn:a,event:c})=>i({spawn:a,input:c.input}))],s):r}getInitialState(e,n){const s=Bt(n),i=[],r=this.getPreInitialState(e,s,i),o=ct([{target:[...te(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],r,e,s,!0,i),{state:a}=it(o,s,e,i);return a}start(e){Object.values(e.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(e){const n=e.split(Y),s=n.slice(1),i=Z(n[0])?n[0].slice(Rn.length):n[0],r=this.idMap.get(i);if(!r)throw new Error(`Child state node '#${i}' does not exist on machine '${this.id}'`);return K(r,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedState(e,n){return pn(e,n)}restoreState(e,n){const s={},i=e.children;Object.keys(i).forEach(c=>{const u=i[c],l=u.state,f=u.src,d=typeof f=="string"?ft(this,f):f;if(!d)return;const h=j(d,{id:c,parent:n?.self,syncSnapshot:u.syncSnapshot,state:l,src:f,systemId:u.systemId});s[c]=h});const r=W({...e,children:s,_nodes:Array.from(G(V(this.root,e.value)))},this);let o=new Set;function a(c,u){if(!o.has(c)){o.add(c);for(let l in c){const f=c[l];if(f&&typeof f=="object"){if("xstate$$type"in f&&f.xstate$$type===lt){c[l]=u[f.id];continue}a(f,u)}}}}return a(r.context,s),r}}function Et(t,e){return new vt(t,e)}const Dn=(t,e)=>new ReadableStream({start(){this.reader=t.getReader()},async pull(n){const s=Date.now(),{done:i,value:r}=await this.reader.read();if(i){n.close();return}n.enqueue(r);const a=Date.now()-s,u=r.length/(e()??Number.MAX_VALUE)*1e3-a;u>0&&await new Promise(l=>setTimeout(l,u))},cancel(){this.reader?.cancel()}}),xn=t=>{if(t.length===0)return[];const e=t.sort((s,i)=>s.start-i.start),n=[e[0]];for(let s=1;s<e.length;s++){const i=e[s],r=n[n.length-1];i.start<=r.end+1?r.end=Math.max(r.end,i.end):n.push(i)}return n},Nt=5e3,In=Et({initial:"checkingFile",context:({input:t})=>({settingsDbDocument:t.settingsDbDocument,document:t.document,file:t.file,downloadedRanges:t.file.downloadedRanges??[],downloaded:t.file.downloaded??0,progress:t.file.progress??0,selected:t.file.selected??!1,priority:t.file.priority??0,length:t.file.length??0,offset:t.file.offset??0,path:t.file.path??"",pathArray:t.file.pathArray,name:t.file.name??"",index:t.file.index,status:t.file.status??"checking",streamBandwithLogs:t.file.streamBandwithLogs??[],downloadSpeed:t.file.downloadSpeed??0}),on:{"FILE.PAUSE":{target:".paused"},"FILE.RESUME":{target:".downloading"}},states:{checkingFile:{entry:C({type:"FILE.CHECKING_FILE"}),always:{target:"downloading",guard:({context:t})=>t?.selected===!0}},downloading:{entry:C({type:"FILE.DOWNLOADING"}),invoke:{input:t=>t,src:P(t=>new S.Observable(e=>{const n={input:t.input.context},s=n.input.document;if(n.input.file.selected===!1)return e.complete();const r=n.input.file.downloadedRanges.sort((f,d)=>f.start-d.start).at(0)?.end||0;if(r===n.input.file.length){e.complete();return}let o=[...n.input.streamBandwithLogs],a=[...n.input.file.downloadedRanges.map(f=>({...f}))],c=!1,u,l=new Promise((f,d)=>{u=f});return ye({magnet:s.state.magnet,path:n.input.file.pathArray.join("/"),offset:r}).then(async f=>{const d=await n.input.settingsDbDocument.getLatest();let h=d.downloadSpeedLimitEnabled,p=d.downloadSpeedLimit;d.$.subscribe(H=>{h=H.downloadSpeedLimitEnabled,p=H.downloadSpeedLimit});const v=Dn(f.body,()=>h?p:Number.MAX_VALUE).getReader(),{write:ae,close:Q}=await z(oe(),{key:"io-worker"})("openWriteStream",{filePath:`${n.input.document.infoHash}/${n.input.file.path}`,offset:r,size:n.input.file.length});u(Q);const St=async()=>{if(t.self.getSnapshot().status!=="active")return;if(c)return await v.cancel(),await Q(),e.error(err);const{done:H,value:wt}=await v.read();if(H)return await Q(),e.complete();const tt=wt.byteLength;try{await ae(wt.buffer)}catch(E){return e.error(E)}const et=a?.find(E=>E.start<=r&&E.end>=r);et?et.end=et.end+tt:a=[...a,{start:r,end:r+tt}],a=xn(a),o=[...o,{timestamp:Date.now(),byteLength:tt}];const ce=o.filter(E=>E.timestamp>Date.now()-Nt).sort((E,D)=>E.timestamp-D.timestamp),_t=a.reduce((E,D)=>E+(D.end-D.start),0),de=ce.reduce((E,D)=>E+D.byteLength,0)/Nt*1e3;e.next({type:"FILE.DOWNLOADING_UPDATE",value:{downloadedRanges:a,downloaded:_t,progress:_t/n.input.file.length,status:"downloading",streamBandwithLogs:[...o],downloadSpeed:de}}),c||St()};St()}).catch(f=>{u(void 0),console.log("downloadFile err",f),e.error(f)}),()=>{c=!0,l.then(f=>f?.())}})),onSnapshot:{guard:({event:t})=>t.snapshot.context?.type==="FILE.DOWNLOADING_UPDATE",actions:y(({event:t})=>({downloadedRanges:t.snapshot.context.value.downloadedRanges,downloaded:t.snapshot.context.value.downloaded,progress:t.snapshot.context.value.progress,status:t.snapshot.context.value.status,streamBandwithLogs:t.snapshot.context.value.streamBandwithLogs,downloadSpeed:t.snapshot.context.value.downloadSpeed}))},onDone:{target:"finished"}},on:{"FILE.PAUSE":{target:"paused",actions:y({status:"paused"})}}},paused:{entry:[C({type:"FILE.PAUSED"}),y({status:"paused"})],on:{"FILE.RESUME":{target:"downloading",actions:y({status:"downloading"})}}},finished:{entry:[C({type:"FILE.FINISHED"}),y({status:"finished",downloaded:({context:t})=>t.length,progress:1,downloadedRanges:({context:t})=>[{start:0,end:t.length}]})]}}}),jt=Et({initial:"init",context:({input:t})=>({settingsDbDocument:t.settingsDbDocument,infoHash:t.infoHash,magnet:t.magnet,torrentFile:t.torrentFile,shouldRemoveFiles:!1,lastEvent:null,document:t.document,dbDocument:t.dbDocument,files:[]}),types:{events:{}},always:[{actions:[async({context:t,event:e,self:n})=>{const s=t.files.map(d=>d.getSnapshot().context);if(!t.document||!t.dbDocument||e.type==="TORRENT.REMOVE-AND-KEEP-FILES"||e.type==="TORRENT.REMOVE-AND-DELETE-FILES")return;const i={...t.document,state:{...t.document.state,torrentFile:t.document.state.torrentFile&&Pt(t.document.state.torrentFile)}},r=n.getSnapshot().value,o=s.reduce((d,h)=>d+h.length,0),a=s.reduce((d,h)=>d+h.downloaded,0),c=r==="downloading"?s.reduce((d,h)=>d+h.downloadSpeed,0):0,u=(o-a)/c,{infoHash:l,...f}=Tt({state:{name:i.state.name,status:r,progress:s.filter(d=>d.selected).reduce((d,h)=>d+h.progress,0)/s.filter(d=>d.selected).length,size:i.state.size,peers:i.state.peers,proxy:i.state.proxy,p2p:i.state.p2p,addedAt:i.state.addedAt,remainingTime:u,peersCount:i.state.peersCount,seedersCount:i.state.seedersCount,leechersCount:i.state.leechersCount,downloaded:a,uploaded:s.reduce((d,h)=>d+h.uploaded,0),downloadSpeed:c,uploadSpeed:s.reduce((d,h)=>d+h.uploadSpeed,0),ratio:i.state.ratio,files:s.map((d,h)=>({index:h,name:d.name,path:d.path,pathArray:d.pathArray,offset:d.offset,length:d.length,downloaded:d.downloaded,progress:d.progress,selected:d.selected,priority:d.priority,downloadedRanges:d.downloadedRanges.map(p=>({start:p.start,end:p.end})),downloadSpeed:d.downloadSpeed,streamBandwithLogs:d.streamBandwithLogs.map(p=>({byteLength:p.byteLength,timestamp:p.timestamp}))})),streamBandwithLogs:s.reduce((d,h)=>d.concat(h.streamBandwithLogs),[]).sort((d,h)=>d.timestamp-h.timestamp),magnet:i.state.magnet,torrentFile:ue(i.state.torrentFile)},options:i.options&&{paused:i.options.paused}});await t.dbDocument.incrementalUpdate({$set:{...f}})},y(({event:t})=>({lastEvent:t}))],guard:({context:t,event:e})=>t.lastEvent!==e}],on:{"FILE.CHECKING":".checkingFiles","FILE.FINISHED":{guard:({context:t})=>t.files.every(e=>e.getSnapshot().value==="finished"),target:".finished"},"TORRENT.PAUSE":{actions:y({files:({context:t})=>(t.files.forEach(e=>e.send({type:"FILE.PAUSE"})),t.files)})},"TORRENT.RESUME":{actions:y({files:({context:t})=>(t.files.forEach(e=>e.send({type:"FILE.RESUME"})),t.files)})},"TORRENT.REMOVE-AND-DELETE-FILES":{actions:[y({shouldRemoveFiles:()=>!0})],target:".removing"},"TORRENT.REMOVE-AND-KEEP-FILES":{actions:[y({shouldRemoveFiles:()=>!1})],target:".removing"}},states:{init:{invoke:{input:({context:t,event:e})=>({context:t,data:e}),src:J(async({input:t})=>{const{context:e,data:{input:n}}=t;if(e.dbDocument)return e.dbDocument;const s=await bt.torrents.findOne(n.infoHash).exec();if(s)return s;const i=n.torrentFile?.infoBuffer?n.torrentFile:await ge({magnet:n.magnet}).then(o=>o.arrayBuffer()).then(o=>fe(le.Buffer.from(o))),r=Tt({infoHash:i.infoHash,state:{magnet:n.magnet?n.magnet:he(n.torrentFile),torrentFile:i}});return bt.torrents.insert(r)}),onDone:{target:"checkingFiles",actions:[y({document:({event:t})=>t.output.toJSON(),dbDocument:({event:t})=>t.output,files:({spawn:t,event:e,context:n})=>e.output.state.files.filter(s=>s.selected).map(s=>t(In,{id:`torrent-${e.output.infoHash}-${s.path}`,input:{settingsDbDocument:n.settingsDbDocument,document:e.output.toJSON(),file:s},syncSnapshot:!0}))})]}}},checkingFiles:{invoke:{src:J(async()=>{}),onDone:[{target:"downloadingMetadata",guard:({context:t})=>!t.torrentFile},{guard:kt([({context:t})=>t.document.state.stats==="finished",({context:t})=>t.torrent&&t.files.every(e=>e.getSnapshot().value==="finished")]),target:"finished"},{target:"downloading",guard:kt([({context:t})=>t.document.state.status==="downloading",({context:t})=>t.torrentFile])}]}},downloadingMetadata:{invoke:{input:({context:t})=>t,src:P(t=>t.input.document.$),onSnapshot:{target:"downloading",guard:({event:t})=>t.snapshot.context?.state?.torrentFile!==void 0}}},downloading:{invoke:{input:({context:t})=>t,src:P(({input:t,...e})=>S.from([]))},on:{"FILES.FINISHED":"finished","TORRENT.PAUSE":{target:"paused",actions:y({files:({context:t,event:e})=>(t.files.forEach(n=>n.send({type:"FILE.PAUSE"})),t.files)})}}},paused:{on:{"TORRENT.RESUME":{target:"downloading",actions:y({files:({context:t,event:e})=>(t.files.forEach(n=>n.send({type:"FILE.RESUME"})),t.files)})}}},finished:{},removing:{invoke:{input:({context:t,self:e})=>({context:t,self:e}),src:J(async({input:t})=>{if(t.context.dbDocument){const n=async()=>{try{await (await t.context.dbDocument.getLatest()).remove()}catch{await new Promise(i=>setTimeout(i,100)),await n()}};n()}return t.context.files.forEach(n=>t.self._actorScope.stopChild(n)),await (await (await navigator.storage.getDirectory()).getDirectoryHandle("torrents")).removeEntry(t.context.infoHash,{recursive:!0}),t.context.document}),onDone:{actions:[y({document:()=>{},dbDocument:()=>{},files:[]}),C(({context:t})=>({type:"TORRENT.REMOVED",input:{infoHash:t.infoHash}}))]}}}}}),An=()=>pe.find().exec(),kn=Et({id:"torrentManager",initial:"init",context:{settingsDbDocument:void 0,torrents:[],workerReady:!1},types:{events:{}},on:{"WORKER.DISCONNECTED":{actions:y({workerReady:!1})},"WORKER.READY":{actions:y({workerReady:!0})}},states:{init:{invoke:{src:J(async()=>{const[t,e]=await Promise.all([nt(),An()]);return{settingsDbDocument:t,torrentDbDocuments:e}}),onDone:{target:"waitingForDocuments",actions:y({settingsDbDocument:({event:t})=>t.output.settingsDbDocument,torrents:({spawn:t,event:e})=>e.output.torrentDbDocuments.map(n=>t(jt,{id:`torrent-${n.infoHash}`,input:{settingsDbDocument:e.output.settingsDbDocument,infoHash:n.infoHash,magnet:n.state.magnet,torrentFile:n.state.torrentFile,document:n.toJSON(),dbDocument:n},syncSnapshot:!0}))})}}},waitingForDocuments:{always:{target:"idle",guard:({context:t})=>t.workerReady}},idle:{invoke:{input:({context:t})=>t,src:P(({input:t})=>(t.torrents.filter(e=>e.getSnapshot().value!=="finished").forEach(e=>e.send({type:"TORRENT.RESUME"})),S.from(nt()).pipe(S.mergeMap(e=>e?.$),S.filter(e=>e?.paused),S.first()))),onDone:{target:"paused"}},on:{"TORRENT.ADD":{actions:y({torrents:({spawn:t,context:e,event:n})=>[...e.torrents,t(jt,{id:`torrent-${n.input.infoHash}`,input:{settingsDbDocument:e.settingsDbDocument,...n.input},syncSnapshot:!0})]})},"TORRENT.PAUSE":{actions:y({torrents:({context:t,event:e})=>(t.torrents.find(s=>s.id===`torrent-${e.output.infoHash}`)?.send({type:"TORRENT.PAUSE"}),t.torrents)})},"TORRENT.RESUME":{actions:y({torrents:({context:t,event:e})=>(t.torrents.find(s=>s.id===`torrent-${e.output.infoHash}`)?.send({type:"TORRENT.RESUME"}),t.torrents)})},"TORRENT.REMOVE-AND-DELETE-FILES":{actions:({context:t,event:e})=>{t.torrents.find(s=>s.id===`torrent-${e.input.infoHash}`)?.send({type:"TORRENT.REMOVE-AND-DELETE-FILES"})}},"TORRENT.REMOVE-AND-KEEP-FILES":{actions:({context:t,event:e})=>{t.torrents.find(s=>s.id===`torrent-${e.input.infoHash}`)?.send({type:"TORRENT.REMOVE-AND-KEEP-FILES"})}},"TORRENT.REMOVED":{actions:y({torrents:({context:t,event:e})=>t.torrents.filter(n=>n.id!==`torrent-${e.input.infoHash}`)})},PAUSE:{actions:y({torrents:({context:t})=>(t.torrents.filter(e=>e.getSnapshot().value!=="finished").forEach(e=>e.send({type:"TORRENT.PAUSE"})),t.torrents)}),target:"paused"}}},paused:{invoke:{id:"paused status watch",input:({context:t})=>t,src:P(({input:t})=>(t.torrents.filter(e=>e.getSnapshot().value!=="finished").forEach(e=>e.send({type:"TORRENT.PAUSE"})),S.from(nt()).pipe(S.mergeMap(e=>e?.$),S.filter(e=>!e?.paused),S.first()))),onDone:{target:"idle"}},on:{RESUME:{actions:y({torrents:({context:t})=>(t.torrents.filter(e=>e.getSnapshot().value!=="finished").forEach(e=>e.send({type:"TORRENT.RESUME"})),t.torrents)}),target:"idle"}}}}}),q=j(kn).start();let ut;oe=()=>ut;On=B(async({workerPort:t})=>{ut&&q.send({type:"WORKER.DISCONNECTED"}),ut=t,await new Promise((e,n)=>{const s=setInterval(()=>{z(t,{key:"torrent-manager"})("ping").then(i=>{clearInterval(s),e(void 0)})},100);z(t,{key:"torrent-manager"})("ping").then(i=>{clearInterval(s),e(void 0)}),setTimeout(()=>{clearInterval(s),n()},1e3)}),q.send({type:"WORKER.READY"})});Fn={newLeader:On,addTorrent:B(async({infoHash:t,magnet:e,torrentFile:n})=>{q.send({type:"TORRENT.ADD",input:{infoHash:t,magnet:e,torrentFile:n&&Pt(n)}})}),removeTorrent:B(async({infoHash:t,removeFiles:e})=>{q.send({type:e?"TORRENT.REMOVE-AND-DELETE-FILES":"TORRENT.REMOVE-AND-KEEP-FILES",input:{infoHash:t}})}),readTorrentFile:B(({infoHash:t,filePath:e,offset:n,size:s})=>z(oe(),{key:"io-worker"})("readTorrentFile",{infoHash:t,filePath:e,offset:n,size:s}))}});export{oe as getIoWorkerPort,On as newLeader,Fn as resolvers,__tla};