nmea-web-serial 1.1.2 → 1.1.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/README.md CHANGED
@@ -17,10 +17,10 @@ npm install nmea-web-serial
17
17
  The simplest way to use the library is with the client API, which provides a clean abstraction over the state machine:
18
18
 
19
19
  ```typescript
20
- import { createNavigationNmeaClient } from 'nmea-web-serial'
20
+ import { NavigationNmeaClient } from 'nmea-web-serial'
21
21
 
22
22
  // Create a client for navigation data
23
- const client = createNavigationNmeaClient({
23
+ const client = new NavigationNmeaClient({
24
24
  baudRate: 4800,
25
25
  enableLogging: false,
26
26
  onData: (navigationData) => {
@@ -62,12 +62,12 @@ The client API provides a simple, framework-agnostic interface for managing NMEA
62
62
 
63
63
  ### Navigation Client
64
64
 
65
- For navigation-focused use cases, use `createNavigationNmeaClient`:
65
+ For navigation-focused use cases, use `NavigationNmeaClient`:
66
66
 
67
67
  ```typescript
68
- import { createNavigationNmeaClient } from 'nmea-web-serial'
68
+ import { NavigationNmeaClient } from 'nmea-web-serial'
69
69
 
70
- const client = createNavigationNmeaClient({
70
+ const client = new NavigationNmeaClient({
71
71
  // Optional: baud rate (default: 4800)
72
72
  baudRate: 4800,
73
73
 
@@ -1,4 +1,4 @@
1
1
  "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function Tn(){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 In(){const e=Tn();if(e.__xstate__)return e.__xstate__}const wn=e=>{if(typeof window>"u")return;const t=In();t&&t.register(e)};class dt{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const n={value:t,next:null};if(this._current){this._last.next=n,this._last=n;return}this._current=n,this._last=n,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const zt=".",Pn="",Jt="",kn="#",Dn="*",Zt="xstate.init",En="xstate.error",we="xstate.stop";function An(e,t){return{type:`xstate.after.${e}.${t}`}}function Ke(e,t){return{type:`xstate.done.state.${e}`,output:t}}function Mn(e,t){return{type:`xstate.done.actor.${e}`,output:t,actorId:e}}function Yt(e,t){return{type:`xstate.error.actor.${e}`,error:t,actorId:e}}function Xt(e){return{type:Zt,input:e}}function j(e){setTimeout(()=>{throw e})}const On=typeof Symbol=="function"&&Symbol.observable||"@@observable";function Qt(e,t){const n=ft(e),r=ft(t);return typeof r=="string"?typeof n=="string"?r===n:!1:typeof n=="string"?n in r:Object.keys(n).every(i=>i in r?Qt(n[i],r[i]):!1)}function Qe(e){if(en(e))return e;const t=[];let n="";for(let r=0;r<e.length;r++){switch(e.charCodeAt(r)){case 92:n+=e[r+1],r++;continue;case 46:t.push(n),n="";continue}n+=e[r]}return t.push(n),t}function ft(e){if(ur(e))return e.value;if(typeof e!="string")return e;const t=Qe(e);return Fn(t)}function Fn(e){if(e.length===1)return e[0];const t={};let n=t;for(let r=0;r<e.length-1;r++)if(r===e.length-2)n[e[r]]=e[r+1];else{const i=n;n={},i[e[r]]=n}return t}function lt(e,t){const n={},r=Object.keys(e);for(let i=0;i<r.length;i++){const o=r[i];n[o]=t(e[o],o,e,i)}return n}function $t(e){return en(e)?e:[e]}function x(e){return e===void 0?[]:$t(e)}function ze(e,t,n,r){return typeof e=="function"?e({context:t,event:n,self:r}):e}function en(e){return Array.isArray(e)}function Cn(e){return e.type.startsWith("xstate.error.actor")}function Z(e){return $t(e).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function tn(e){if(!(e===void 0||e===Pn))return x(e)}function Je(e,t,n){const r=typeof e=="object",i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}function ht(e,t){return`${t}.${e}`}function $e(e,t){const n=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return e.implementations.actors[t];const[,r,i]=n,s=e.getStateNodeById(i).config.invoke;return(Array.isArray(s)?s[r]:s).src}function pt(e,t){return`${e.sessionId}.${t}`}let Nn=0;function Rn(e,t){const n=new Map,r=new Map,i=new WeakMap,o=new Set,s={},{clock:a,logger:c}=t,u={schedule:(d,p,g,y,I=Math.random().toString(36).slice(2))=>{const C={source:d,target:p,event:g,delay:y,id:I,startedAt:Date.now()},N=pt(d,I);l._snapshot._scheduledEvents[N]=C;const V=a.setTimeout(()=>{delete s[N],delete l._snapshot._scheduledEvents[N],l._relay(d,p,g)},y);s[N]=V},cancel:(d,p)=>{const g=pt(d,p),y=s[g];delete s[g],delete l._snapshot._scheduledEvents[g],y!==void 0&&a.clearTimeout(y)},cancelAll:d=>{for(const p in l._snapshot._scheduledEvents){const g=l._snapshot._scheduledEvents[p];g.source===d&&u.cancel(d,g.id)}}},f=d=>{if(!o.size)return;const p={...d,rootId:e.sessionId};o.forEach(g=>g.next?.(p))},l={_snapshot:{_scheduledEvents:(t?.snapshot&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${Nn++}`,_register:(d,p)=>(n.set(d,p),d),_unregister:d=>{n.delete(d.sessionId);const p=i.get(d);p!==void 0&&(r.delete(p),i.delete(d))},get:d=>r.get(d),getAll:()=>Object.fromEntries(r.entries()),_set:(d,p)=>{const g=r.get(d);if(g&&g!==p)throw new Error(`Actor with system ID '${d}' already exists.`);r.set(d,p),i.set(p,d)},inspect:d=>{const p=Je(d);return o.add(p),{unsubscribe(){o.delete(p)}}},_sendInspectionEvent:f,_relay:(d,p,g)=>{l._sendInspectionEvent({type:"@xstate.event",sourceRef:d,actorRef:p,event:g}),p._send(g)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...l._snapshot._scheduledEvents}}),start:()=>{const d=l._snapshot._scheduledEvents;l._snapshot._scheduledEvents={};for(const p in d){const{source:g,target:y,event:I,delay:C,id:N}=d[p];u.schedule(g,y,I,C,N)}},_clock:a,_logger:c};return l}let He=!1;const et=1;let A=(function(e){return e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped",e})({});const jn={clock:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},logger:console.log.bind(console),devTools:!1};class Gn{constructor(t,n){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new dt(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=A.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 r={...jn,...n},{clock:i,logger:o,parent:s,syncSnapshot:a,id:c,systemId:u,inspect:f}=r;this.system=s?s.system:Rn(this,{clock:i,logger:o}),f&&!s&&this.system.inspect(Je(f)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=n?.logger??this.system._logger,this.clock=n?.clock??this.system._clock,this._parent=s,this._syncSnapshot=a,this.options=r,this.src=r.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:l=>{this._deferred.push(l)},system:this.system,stopChild:l=>{if(l._parent!==this)throw new Error(`Cannot stop child actor ${l.id} of ${this.id} because it is not a child`);l._stop()},emit:l=>{const d=this.eventListeners.get(l.type),p=this.eventListeners.get("*");if(!d&&!p)return;const g=[...d?d.values():[],...p?p.values():[]];for(const y of g)try{y(l)}catch(I){j(I)}},actionExecutor:l=>{const d=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:l.type,params:l.params}}),!l.exec)return;const p=He;try{He=!0,l.exec(l.info,l.params)}finally{He=p}};this._processingStatus===A.Running?d():this._deferred.push(d)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),u&&(this.systemId=u,this.system._set(u,this)),this._initState(n?.snapshot??n?.state),u&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(n){this._snapshot={status:"error",output:void 0,error:n}}}update(t,n){this._snapshot=t;let r;for(;r=this._deferred.shift();)try{r()}catch(i){this._deferred.length=0,this._snapshot={...t,status:"error",error:i}}switch(this._snapshot.status){case"active":for(const i of this.observers)try{i.next?.(t)}catch(o){j(o)}break;case"done":for(const i of this.observers)try{i.next?.(t)}catch(o){j(o)}this._stopProcedure(),this._complete(),this._doneEvent=Mn(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:n,snapshot:t})}subscribe(t,n,r){const i=Je(t,n,r);if(this._processingStatus!==A.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{i.complete?.()}catch(o){j(o)}break;case"error":{const o=this._snapshot.error;if(!i.error)j(o);else try{i.error(o)}catch(s){j(s)}break}}return{unsubscribe:()=>{this.observers.delete(i)}}}on(t,n){let r=this.eventListeners.get(t);r||(r=new Set,this.eventListeners.set(t,r));const i=n.bind(void 0);return r.add(i),{unsubscribe:()=>{r.delete(i)}}}start(){if(this._processingStatus===A.Running)return this;this._syncSnapshot&&this.subscribe({next:r=>{r.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:r})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=A.Running;const t=Xt(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t}),this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(r){return this._snapshot={...this._snapshot,status:"error",error:r},this._error(r),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let n,r;try{n=this.logic.transition(this._snapshot,t,this._actorScope)}catch(i){r={err:i}}if(r){const{err:i}=r;this._snapshot={...this._snapshot,status:"error",error:i},this._error(i);return}this.update(n,t),t.type===we&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===A.Stopped?this:(this.mailbox.clear(),this._processingStatus===A.NotStarted?(this._processingStatus=A.Stopped,this):(this.mailbox.enqueue({type:we}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(n){j(n)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||j(t);return}let n=!1;for(const r of this.observers){const i=r.error;n||=!i;try{i?.(t)}catch(o){j(o)}}this.observers.clear(),n&&j(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,Yt(this.id,t))}_stopProcedure(){return this._processingStatus!==A.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new dt(this._process.bind(this)),this._processingStatus=A.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==A.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;t&&(typeof t=="function"?t:wn)(this)}toJSON(){return{xstate$$type:et,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[On](){return this}getSnapshot(){return this._snapshot}}function Pe(e,...[t]){return new Gn(e,t)}function Ln(e,t,n,r,{sendId:i}){const o=typeof i=="function"?i(n,r):i;return[t,{sendId:o},void 0]}function xn(e,t){e.defer(()=>{e.system.scheduler.cancel(e.self,t.sendId)})}function tt(e){function t(n,r){}return t.type="xstate.cancel",t.sendId=e,t.resolve=Ln,t.execute=xn,t}function qn(e,t,n,r,{id:i,systemId:o,src:s,input:a,syncSnapshot:c}){const u=typeof s=="string"?$e(t.machine,s):s,f=typeof i=="function"?i(n):i;let l,d;return u&&(d=typeof a=="function"?a({context:t.context,event:n.event,self:e.self}):a,l=Pe(u,{id:f,src:s,parent:e.self,syncSnapshot:c,systemId:o,input:d})),[U(t,{children:{...t.children,[f]:l}}),{id:i,systemId:o,actorRef:l,src:s,input:d},void 0]}function Wn(e,{actorRef:t}){t&&e.defer(()=>{t._processingStatus!==A.Stopped&&t.start()})}function nt(...[e,{id:t,systemId:n,input:r,syncSnapshot:i=!1}={}]){function o(s,a){}return o.type="xstate.spawnChild",o.id=t,o.systemId=n,o.src=e,o.input=r,o.syncSnapshot=i,o.resolve=qn,o.execute=Wn,o}function Bn(e,t,n,r,{actorRef:i}){const o=typeof i=="function"?i(n,r):i,s=typeof o=="string"?t.children[o]:o;let a=t.children;return s&&(a={...a},delete a[s.id]),[U(t,{children:a}),s,void 0]}function Hn(e,t){if(t){if(e.system._unregister(t),t._processingStatus!==A.Running){e.stopChild(t);return}e.defer(()=>{e.stopChild(t)})}}function Ce(e){function t(n,r){}return t.type="xstate.stopChild",t.actorRef=e,t.resolve=Bn,t.execute=Hn,t}function Ne(e,t,n,r){const{machine:i}=r,o=typeof e=="function",s=o?e:i.implementations.guards[typeof e=="string"?e:e.type];if(!o&&!s)throw new Error(`Guard '${typeof e=="string"?e:e.type}' is not implemented.'.`);if(typeof s!="function")return Ne(s,t,n,r);const a={context:t,event:n},c=o||typeof e=="string"?void 0:"params"in e?typeof e.params=="function"?e.params({context:t,event:n}):e.params:void 0;return"check"in s?s.check(r,a,s):s(a,c)}const rt=e=>e.type==="atomic"||e.type==="final";function X(e){return Object.values(e.states).filter(t=>t.type!=="history")}function ke(e,t){const n=[];if(t===e)return n;let r=e.parent;for(;r&&r!==t;)n.push(r),r=r.parent;return n}function Ae(e){const t=new Set(e),n=rn(t);for(const r of t)if(r.type==="compound"&&(!n.get(r)||!n.get(r).length))gt(r).forEach(i=>t.add(i));else if(r.type==="parallel"){for(const i of X(r))if(i.type!=="history"&&!t.has(i)){const o=gt(i);for(const s of o)t.add(s)}}for(const r of t){let i=r.parent;for(;i;)t.add(i),i=i.parent}return t}function nn(e,t){const n=t.get(e);if(!n)return{};if(e.type==="compound"){const i=n[0];if(i){if(rt(i))return i.key}else return{}}const r={};for(const i of n)r[i.key]=nn(i,t);return r}function rn(e){const t=new Map;for(const n of e)t.has(n)||t.set(n,[]),n.parent&&(t.has(n.parent)||t.set(n.parent,[]),t.get(n.parent).push(n));return t}function sn(e,t){const n=Ae(t);return nn(e,rn(n))}function st(e,t){return t.type==="compound"?X(t).some(n=>n.type==="final"&&e.has(n)):t.type==="parallel"?X(t).every(n=>st(e,n)):t.type==="final"}const Re=e=>e[0]===kn;function Un(e,t){return e.transitions.get(t)||[...e.transitions.keys()].filter(r=>{if(r===Dn)return!0;if(!r.endsWith(".*"))return!1;const i=r.split("."),o=t.split(".");for(let s=0;s<i.length;s++){const a=i[s],c=o[s];if(a==="*")return s===i.length-1;if(a!==c)return!1}return!0}).sort((r,i)=>i.length-r.length).flatMap(r=>e.transitions.get(r))}function Vn(e){const t=e.config.after;if(!t)return[];const n=i=>{const o=An(i,e.id),s=o.type;return e.entry.push(at(o,{id:s,delay:i})),e.exit.push(tt(s)),s};return Object.keys(t).flatMap(i=>{const o=t[i],s=typeof o=="string"?{target:o}:o,a=Number.isNaN(+i)?i:+i,c=n(a);return x(s).map(u=>({...u,event:c,delay:a}))}).map(i=>{const{delay:o}=i;return{...B(e,i.event,i),delay:o}})}function B(e,t,n){const r=tn(n.target),i=n.reenter??!1,o=Jn(e,r),s={...n,actions:x(n.actions),guard:n.guard,target:o,source:e,reenter:i,eventType:t,toJSON:()=>({...s,source:`#${e.id}`,target:o?o.map(a=>`#${a.id}`):void 0})};return s}function Kn(e){const t=new Map;if(e.config.on)for(const n of Object.keys(e.config.on)){if(n===Jt)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const r=e.config.on[n];t.set(n,Z(r).map(i=>B(e,n,i)))}if(e.config.onDone){const n=`xstate.done.state.${e.id}`;t.set(n,Z(e.config.onDone).map(r=>B(e,n,r)))}for(const n of e.invoke){if(n.onDone){const r=`xstate.done.actor.${n.id}`;t.set(r,Z(n.onDone).map(i=>B(e,r,i)))}if(n.onError){const r=`xstate.error.actor.${n.id}`;t.set(r,Z(n.onError).map(i=>B(e,r,i)))}if(n.onSnapshot){const r=`xstate.snapshot.${n.id}`;t.set(r,Z(n.onSnapshot).map(i=>B(e,r,i)))}}for(const n of e.after){let r=t.get(n.eventType);r||(r=[],t.set(n.eventType,r)),r.push(n)}return t}function zn(e,t){const n=typeof t=="string"?e.states[t]:t?e.states[t.target]:void 0;if(!n&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${e.id}`);const r={source:e,actions:!t||typeof t=="string"?[]:x(t.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...r,source:`#${e.id}`,target:n?[`#${n.id}`]:[]})};return r}function Jn(e,t){if(t!==void 0)return t.map(n=>{if(typeof n!="string")return n;if(Re(n))return e.machine.getStateNodeById(n);const r=n[0]===zt;if(r&&!e.parent)return Me(e,n.slice(1));const i=r?e.key+n:n;if(e.parent)try{return Me(e.parent,i)}catch(o){throw new Error(`Invalid transition definition for state node '${e.id}':
2
2
  ${o.message}`)}else throw new Error(`Invalid target: "${n}" is not a valid target from the root node. Did you mean ".${n}"?`)})}function on(e){const t=tn(e.config.target);return t?{target:t.map(n=>typeof n=="string"?Me(e.parent,n):n)}:e.parent.initial}function H(e){return e.type==="history"}function gt(e){const t=an(e);for(const n of t)for(const r of ke(n,e))t.add(r);return t}function an(e){const t=new Set;function n(r){if(!t.has(r)){if(t.add(r),r.type==="compound")n(r.initial.target[0]);else if(r.type==="parallel")for(const i of X(r))n(i)}}return n(e),t}function Q(e,t){if(Re(t))return e.machine.getStateNodeById(t);if(!e.states)throw new Error(`Unable to retrieve child state '${t}' from '${e.id}'; no child states exist.`);const n=e.states[t];if(!n)throw new Error(`Child state '${t}' does not exist on '${e.id}'`);return n}function Me(e,t){if(typeof t=="string"&&Re(t))try{return e.machine.getStateNodeById(t)}catch{}const n=Qe(t).slice();let r=e;for(;n.length;){const i=n.shift();if(!i.length)break;r=Q(r,i)}return r}function Oe(e,t){if(typeof t=="string"){const i=e.states[t];if(!i)throw new Error(`State '${t}' does not exist on '${e.id}'`);return[e,i]}const n=Object.keys(t),r=n.map(i=>Q(e,i)).filter(Boolean);return[e.machine.root,e].concat(r,n.reduce((i,o)=>{const s=Q(e,o);if(!s)return i;const a=Oe(s,t[o]);return i.concat(a)},[]))}function Zn(e,t,n,r){const o=Q(e,t).next(n,r);return!o||!o.length?e.next(n,r):o}function Yn(e,t,n,r){const i=Object.keys(t),o=Q(e,i[0]),s=it(o,t[i[0]],n,r);return!s||!s.length?e.next(n,r):s}function Xn(e,t,n,r){const i=[];for(const o of Object.keys(t)){const s=t[o];if(!s)continue;const a=Q(e,o),c=it(a,s,n,r);c&&i.push(...c)}return i.length?i:e.next(n,r)}function it(e,t,n,r){return typeof t=="string"?Zn(e,t,n,r):Object.keys(t).length===1?Yn(e,t,n,r):Xn(e,t,n,r)}function Qn(e){return Object.keys(e.states).map(t=>e.states[t]).filter(t=>t.type==="history")}function q(e,t){let n=e;for(;n.parent&&n.parent!==t;)n=n.parent;return n.parent===t}function $n(e,t){const n=new Set(e),r=new Set(t);for(const i of n)if(r.has(i))return!0;for(const i of r)if(n.has(i))return!0;return!1}function cn(e,t,n){const r=new Set;for(const i of e){let o=!1;const s=new Set;for(const a of r)if($n(Ze([i],t,n),Ze([a],t,n)))if(q(i.source,a.source))s.add(a);else{o=!0;break}if(!o){for(const a of s)r.delete(a);r.add(i)}}return Array.from(r)}function er(e){const[t,...n]=e;for(const r of ke(t,void 0))if(n.every(i=>q(i,r)))return r}function ot(e,t){if(!e.target)return[];const n=new Set;for(const r of e.target)if(H(r))if(t[r.id])for(const i of t[r.id])n.add(i);else for(const i of ot(on(r),t))n.add(i);else n.add(r);return[...n]}function un(e,t){const n=ot(e,t);if(!n)return;if(!e.reenter&&n.every(i=>i===e.source||q(i,e.source)))return e.source;const r=er(n.concat(e.source));if(r)return r;if(!e.reenter)return e.source.machine.root}function Ze(e,t,n){const r=new Set;for(const i of e)if(i.target?.length){const o=un(i,n);i.reenter&&i.source===o&&r.add(o);for(const s of t)q(s,o)&&r.add(s)}return[...r]}function tr(e,t){if(e.length!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function Ye(e,t,n,r,i,o){if(!e.length)return t;const s=new Set(t._nodes);let a=t.historyValue;const c=cn(e,s,a);let u=t;i||([u,a]=ir(u,r,n,c,s,a,o,n.actionExecutor)),u=$(u,r,n,c.flatMap(l=>l.actions),o,void 0),u=rr(u,r,n,c,s,o,a,i);const f=[...s];u.status==="done"&&(u=$(u,r,n,f.sort((l,d)=>d.order-l.order).flatMap(l=>l.exit),o,void 0));try{return a===t.historyValue&&tr(t._nodes,s)?u:U(u,{_nodes:f,historyValue:a})}catch(l){throw l}}function nr(e,t,n,r,i){if(r.output===void 0)return;const o=Ke(i.id,i.output!==void 0&&i.parent?ze(i.output,e.context,t,n.self):void 0);return ze(r.output,e.context,o,n.self)}function rr(e,t,n,r,i,o,s,a){let c=e;const u=new Set,f=new Set;sr(r,s,f,u),a&&f.add(e.machine.root);const l=new Set;for(const d of[...u].sort((p,g)=>p.order-g.order)){i.add(d);const p=[];p.push(...d.entry);for(const g of d.invoke)p.push(nt(g.src,{...g,syncSnapshot:!!g.onSnapshot}));if(f.has(d)){const g=d.initial.actions;p.push(...g)}if(c=$(c,t,n,p,o,d.invoke.map(g=>g.id)),d.type==="final"){const g=d.parent;let y=g?.type==="parallel"?g:g?.parent,I=y||d;for(g?.type==="compound"&&o.push(Ke(g.id,d.output!==void 0?ze(d.output,c.context,t,n.self):void 0));y?.type==="parallel"&&!l.has(y)&&st(i,y);)l.add(y),o.push(Ke(y.id)),I=y,y=y.parent;if(y)continue;c=U(c,{status:"done",output:nr(c,t,n,c.machine.root,I)})}}return c}function sr(e,t,n,r){for(const i of e){const o=un(i,t);for(const a of i.target||[])!H(a)&&(i.source!==a||i.source!==o||i.reenter)&&(r.add(a),n.add(a)),Y(a,t,n,r);const s=ot(i,t);for(const a of s){const c=ke(a,o);o?.type==="parallel"&&c.push(o),dn(r,t,n,c,!i.source.parent&&i.reenter?void 0:o)}}}function Y(e,t,n,r){if(H(e))if(t[e.id]){const i=t[e.id];for(const o of i)r.add(o),Y(o,t,n,r);for(const o of i)Ue(o,e.parent,r,t,n)}else{const i=on(e);for(const o of i.target)r.add(o),i===e.parent?.initial&&n.add(e.parent),Y(o,t,n,r);for(const o of i.target)Ue(o,e.parent,r,t,n)}else if(e.type==="compound"){const[i]=e.initial.target;H(i)||(r.add(i),n.add(i)),Y(i,t,n,r),Ue(i,e,r,t,n)}else if(e.type==="parallel")for(const i of X(e).filter(o=>!H(o)))[...r].some(o=>q(o,i))||(H(i)||(r.add(i),n.add(i)),Y(i,t,n,r))}function dn(e,t,n,r,i){for(const o of r)if((!i||q(o,i))&&e.add(o),o.type==="parallel")for(const s of X(o).filter(a=>!H(a)))[...e].some(a=>q(a,s))||(e.add(s),Y(s,t,n,e))}function Ue(e,t,n,r,i){dn(n,r,i,ke(e,t))}function ir(e,t,n,r,i,o,s,a){let c=e;const u=Ze(r,i,o);u.sort((l,d)=>d.order-l.order);let f;for(const l of u)for(const d of Qn(l)){let p;d.history==="deep"?p=g=>rt(g)&&q(g,l):p=g=>g.parent===l,f??={...o},f[d.id]=Array.from(i).filter(p)}for(const l of u)c=$(c,t,n,[...l.exit,...l.invoke.map(d=>Ce(d.id))],s,void 0),i.delete(l);return[c,f||o]}function or(e,t){return e.implementations.actions[t]}function fn(e,t,n,r,i,o){const{machine:s}=e;let a=e;for(const c of r){const u=typeof c=="function",f=u?c:or(s,typeof c=="string"?c:c.type),l={context:a.context,event:t,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:t}):c.params:void 0;if(!f||!("resolve"in f)){n.actionExecutor({type:typeof c=="string"?c:typeof c=="object"?c.type:c.name||"(anonymous)",info:l,params:d,exec:f});continue}const p=f,[g,y,I]=p.resolve(n,a,l,d,f,i);a=g,"retryResolve"in p&&o?.push([p,y]),"execute"in p&&n.actionExecutor({type:p.type,info:l,params:y,exec:p.execute.bind(null,n,y)}),I&&(a=fn(a,t,n,I,i,o))}return a}function $(e,t,n,r,i,o){const s=o?[]:void 0,a=fn(e,t,n,r,{internalQueue:i,deferredActorIds:o},s);return s?.forEach(([c,u])=>{c.retryResolve(n,a,u)}),a}function Ve(e,t,n,r){let i=e;const o=[];function s(u,f,l){n.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:n.self,event:f,snapshot:u,_transitions:l}),o.push(u)}if(t.type===we)return i=U(vt(i,t,n),{status:"stopped"}),s(i,t,[]),{snapshot:i,microstates:o};let a=t;if(a.type!==Zt){const u=a,f=Cn(u),l=mt(u,i);if(f&&!l.length)return i=U(e,{status:"error",error:u.error}),s(i,u,[]),{snapshot:i,microstates:o};i=Ye(l,e,n,a,!1,r),s(i,u,l)}let c=!0;for(;i.status==="active";){let u=c?ar(i,a):[];const f=u.length?i:void 0;if(!u.length){if(!r.length)break;a=r.shift(),u=mt(a,i)}i=Ye(u,i,n,a,!1,r),c=i!==f,s(i,a,u)}return i.status!=="active"&&vt(i,a,n),{snapshot:i,microstates:o}}function vt(e,t,n){return $(e,t,n,Object.values(e.children).map(r=>Ce(r)),[],void 0)}function mt(e,t){return t.machine.getTransitionData(t,e)}function ar(e,t){const n=new Set,r=e._nodes.filter(rt);for(const i of r)e:for(const o of[i].concat(ke(i,void 0)))if(o.always){for(const s of o.always)if(s.guard===void 0||Ne(s.guard,e.context,t,e)){n.add(s);break e}}return cn(Array.from(n),new Set(e._nodes),e.historyValue)}function cr(e,t){const n=Ae(Oe(e,t));return sn(e,[...n])}function ur(e){return!!e&&typeof e=="object"&&"machine"in e&&"value"in e}const dr=function(t){return Qt(t,this.value)},fr=function(t){return this.tags.has(t)},lr=function(t){const n=this.machine.getTransitionData(this,t);return!!n?.length&&n.some(r=>r.target!==void 0||r.actions.length)},hr=function(){const{_nodes:t,tags:n,machine:r,getMeta:i,toJSON:o,can:s,hasTag:a,matches:c,...u}=this;return{...u,tags:Array.from(n)}},pr=function(){return this._nodes.reduce((t,n)=>(n.meta!==void 0&&(t[n.id]=n.meta),t),{})};function Ee(e,t){return{status:e.status,output:e.output,error:e.error,machine:t,context:e.context,_nodes:e._nodes,value:sn(t.root,e._nodes),tags:new Set(e._nodes.flatMap(n=>n.tags)),children:e.children,historyValue:e.historyValue||{},matches:dr,hasTag:fr,can:lr,getMeta:pr,toJSON:hr}}function U(e,t={}){return Ee({...e,...t},e.machine)}function gr(e){if(typeof e!="object"||e===null)return{};const t={};for(const n in e){const r=e[n];Array.isArray(r)&&(t[n]=r.map(i=>({id:i.id})))}return t}function vr(e,t){const{_nodes:n,tags:r,machine:i,children:o,context:s,can:a,hasTag:c,matches:u,getMeta:f,toJSON:l,...d}=e,p={};for(const y in o){const I=o[y];p[y]={snapshot:I.getPersistedSnapshot(t),src:I.src,systemId:I.systemId,syncSnapshot:I._syncSnapshot}}return{...d,context:ln(s),children:p,historyValue:gr(d.historyValue)}}function ln(e){let t;for(const n in e){const r=e[n];if(r&&typeof r=="object")if("sessionId"in r&&"send"in r&&"ref"in r)t??=Array.isArray(e)?e.slice():{...e},t[n]={xstate$$type:et,id:r.id};else{const i=ln(r);i!==r&&(t??=Array.isArray(e)?e.slice():{...e},t[n]=i)}}return t??e}function mr(e,t,n,r,{event:i,id:o,delay:s},{internalQueue:a}){const 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`);const u=typeof i=="function"?i(n,r):i;let f;if(typeof s=="string"){const l=c&&c[s];f=typeof l=="function"?l(n,r):l}else f=typeof s=="function"?s(n,r):s;return typeof f!="number"&&a.push(u),[t,{event:u,id:o,delay:f},void 0]}function yr(e,t){const{event:n,delay:r,id:i}=t;if(typeof r=="number"){e.defer(()=>{const o=e.self;e.system.scheduler.schedule(o,o,n,r,i)});return}}function at(e,t){function n(r,i){}return n.type="xstate.raise",n.event=e,n.id=t?.id,n.delay=t?.delay,n.resolve=mr,n.execute=yr,n}const yt=new WeakMap;function Sr(e){return{config:e,start:(n,r)=>{const{self:i,system:o,emit:s}=r,a={receivers:void 0,dispose:void 0};yt.set(i,a),a.dispose=e({input:n.input,system:o,self:i,sendBack:c=>{i.getSnapshot().status!=="stopped"&&i._parent&&o._relay(i,i._parent,c)},receive:c=>{a.receivers??=new Set,a.receivers.add(c)},emit:s})},transition:(n,r,i)=>{const o=yt.get(i.self);return r.type===we?(n={...n,status:"stopped",error:void 0},o.dispose?.(),n):(o.receivers?.forEach(s=>s(r)),n)},getInitialSnapshot:(n,r)=>({status:"active",output:void 0,error:void 0,input:r}),getPersistedSnapshot:n=>n,restoreSnapshot:n=>n}}const St="xstate.promise.resolve",_t="xstate.promise.reject",De=new WeakMap;function hn(e){return{config:e,transition:(n,r,i)=>{if(n.status!=="active")return n;switch(r.type){case St:{const o=r.data;return{...n,status:"done",output:o,input:void 0}}case _t:return{...n,status:"error",error:r.data,input:void 0};case we:return De.get(i.self)?.abort(),{...n,status:"stopped",input:void 0};default:return n}},start:(n,{self:r,system:i,emit:o})=>{if(n.status!=="active")return;const s=new AbortController;De.set(r,s),Promise.resolve(e({input:n.input,system:i,self:r,signal:s.signal,emit:o})).then(c=>{r.getSnapshot().status==="active"&&(De.delete(r),i._relay(r,r,{type:St,data:c}))},c=>{r.getSnapshot().status==="active"&&(De.delete(r),i._relay(r,r,{type:_t,data:c}))})},getInitialSnapshot:(n,r)=>({status:"active",output:void 0,error:void 0,input:r}),getPersistedSnapshot:n=>n,restoreSnapshot:n=>n}}function _r(e,{machine:t,context:n},r,i){const o=(s,a)=>{if(typeof s=="string"){const c=$e(t,s);if(!c)throw new Error(`Actor logic '${s}' not implemented in machine '${t.id}'`);const u=Pe(c,{id:a?.id,parent:e.self,syncSnapshot:a?.syncSnapshot,input:typeof a?.input=="function"?a.input({context:n,event:r,self:e.self}):a?.input,src:s,systemId:a?.systemId});return i[u.id]=u,u}else return Pe(s,{id:a?.id,parent:e.self,syncSnapshot:a?.syncSnapshot,input:a?.input,src:s,systemId:a?.systemId})};return(s,a)=>{const c=o(s,a);return i[c.id]=c,e.defer(()=>{c._processingStatus!==A.Stopped&&c.start()}),c}}function br(e,t,n,r,{assignment:i}){if(!t.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const o={},s={context:t.context,event:n.event,spawn:_r(e,t,n.event,o),self:e.self,system:e.system};let a={};if(typeof i=="function")a=i(s,r);else for(const u of Object.keys(i)){const f=i[u];a[u]=typeof f=="function"?f(s,r):f}const c=Object.assign({},t.context,a);return[U(t,{context:c,children:Object.keys(o).length?{...t.children,...o}:t.children}),void 0,void 0]}function F(e){function t(n,r){}return t.type="xstate.assign",t.assignment=e,t.resolve=br,t}const bt=new WeakMap;function J(e,t,n){let r=bt.get(e);return r?t in r||(r[t]=n()):(r={[t]:n()},bt.set(e,r)),r[t]}const Tr={},te=e=>typeof e=="string"?{type:e}:typeof e=="function"?"resolve"in e?{type:e.type}:{type:e.name}:e;class Fe{constructor(t,n){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=n._parent,this.key=n._key,this.machine=n._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(zt),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?lt(this.config.states,(r,i)=>new Fe(r,{_parent:this,_key:i,_machine:this.machine})):Tr,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=x(this.config.entry).slice(),this.exit=x(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=x(t.tags).slice()}_initialize(){this.transitions=Kn(this),this.config.always&&(this.always=Z(this.config.always).map(t=>B(this,Jt,t))),Object.keys(this.states).forEach(t=>{this.states[t]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(te),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(te),eventType:null})}:void 0,history:this.history,states:lt(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(te)})),entry:this.entry.map(te),exit:this.exit.map(te),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 J(this,"invoke",()=>x(this.config.invoke).map((t,n)=>{const{src:r,systemId:i}=t,o=t.id??ht(this.id,n),s=typeof r=="string"?r:`xstate.invoke.${ht(this.id,n)}`;return{...t,src:s,id:o,systemId:i,toJSON(){const{onDone:a,onError:c,...u}=t;return{...u,type:"xstate.invoke",src:s,id:o}}}}))}get on(){return J(this,"on",()=>[...this.transitions].flatMap(([n,r])=>r.map(i=>[n,i])).reduce((n,[r,i])=>(n[r]=n[r]||[],n[r].push(i),n),{}))}get after(){return J(this,"delayedTransitions",()=>Vn(this))}get initial(){return J(this,"initial",()=>zn(this,this.config.initial))}next(t,n){const r=n.type,i=[];let o;const s=J(this,`candidates-${r}`,()=>Un(this,r));for(const a of s){const{guard:c}=a,u=t.context;let f=!1;try{f=!c||Ne(c,u,n,t)}catch(l){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 '${r}' in state node '${this.id}':
3
3
  ${l.message}`)}if(f){i.push(...a.actions),o=a;break}}return o?[o]:void 0}get events(){return J(this,"events",()=>{const{states:t}=this,n=new Set(this.ownEvents);if(t)for(const r of Object.keys(t)){const i=t[r];if(i.states)for(const o of i.events)n.add(`${o}`)}return Array.from(n)})}get ownEvents(){const t=new Set([...this.transitions.keys()].filter(n=>this.transitions.get(n).some(r=>!(!r.target&&!r.actions.length&&!r.reenter))));return Array.from(t)}}const Ir="#";class ct{constructor(t,n){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:n?.actors??{},actions:n?.actions??{},delays:n?.delays??{},guards:n?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new Fe(t,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:n,guards:r,actors:i,delays:o}=this.implementations;return new ct(this.config,{actions:{...n,...t.actions},guards:{...r,...t.guards},actors:{...i,...t.actors},delays:{...o,...t.delays}})}resolveState(t){const n=cr(this.root,t.value),r=Ae(Oe(this.root,n));return Ee({_nodes:[...r],context:t.context||{},children:{},status:st(r,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,n,r){return Ve(t,n,r,[]).snapshot}microstep(t,n,r){return Ve(t,n,r,[]).microstates}getTransitionData(t,n){return it(this.root,t.value,t,n)||[]}getPreInitialState(t,n,r){const{context:i}=this.config,o=Ee({context:typeof i!="function"&&i?i:{},_nodes:[this.root],children:{},status:"active"},this);return typeof i=="function"?$(o,n,t,[F(({spawn:a,event:c,self:u})=>i({spawn:a,input:c.input,self:u}))],r,void 0):o}getInitialSnapshot(t,n){const r=Xt(n),i=[],o=this.getPreInitialState(t,r,i),s=Ye([{target:[...an(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],o,t,r,!0,i),{snapshot:a}=Ve(s,r,t,i);return a}start(t){Object.values(t.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(t){const n=Qe(t),r=n.slice(1),i=Re(n[0])?n[0].slice(Ir.length):n[0],o=this.idMap.get(i);if(!o)throw new Error(`Child state node '#${i}' does not exist on machine '${this.id}'`);return Me(o,r)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,n){return vr(t,n)}restoreSnapshot(t,n){const r={},i=t.children;Object.keys(i).forEach(l=>{const d=i[l],p=d.snapshot,g=d.src,y=typeof g=="string"?$e(this,g):g;if(!y)return;const I=Pe(y,{id:l,parent:n.self,syncSnapshot:d.syncSnapshot,snapshot:p,src:g,systemId:d.systemId});r[l]=I});function o(l,d){if(d instanceof Fe)return d;try{return l.machine.getStateNodeById(d.id)}catch{}}function s(l,d){if(!d||typeof d!="object")return{};const p={};for(const g in d){const y=d[g];for(const I of y){const C=o(l,I);C&&(p[g]??=[],p[g].push(C))}}return p}const a=s(this.root,t.historyValue),c=Ee({...t,children:r,_nodes:Array.from(Ae(Oe(this.root,t.value))),historyValue:a},this),u=new Set;function f(l,d){if(!u.has(l)){u.add(l);for(const p in l){const g=l[p];if(g&&typeof g=="object"){if("xstate$$type"in g&&g.xstate$$type===et){l[p]=d[g.id];continue}f(g,d)}}}}return f(c.context,r),c}}function wr(e,t,n,r,{event:i}){const o=typeof i=="function"?i(n,r):i;return[t,{event:o},void 0]}function Pr(e,{event:t}){e.defer(()=>e.emit(t))}function pn(e){function t(n,r){}return t.type="xstate.emit",t.event=e,t.resolve=wr,t.execute=Pr,t}let Xe=(function(e){return e.Parent="#_parent",e.Internal="#_internal",e})({});function kr(e,t,n,r,{to:i,event:o,id:s,delay:a},c){const u=t.machine.implementations.delays;if(typeof o=="string")throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${o}" }) instead`);const f=typeof o=="function"?o(n,r):o;let l;if(typeof a=="string"){const g=u&&u[a];l=typeof g=="function"?g(n,r):g}else l=typeof a=="function"?a(n,r):a;const d=typeof i=="function"?i(n,r):i;let p;if(typeof d=="string"){if(d===Xe.Parent?p=e.self._parent:d===Xe.Internal?p=e.self:d.startsWith("#_")?p=t.children[d.slice(2)]:p=c.deferredActorIds?.includes(d)?d:t.children[d],!p)throw new Error(`Unable to send event to actor '${d}' from machine '${t.machine.id}'.`)}else p=d||e.self;return[t,{to:p,targetId:typeof d=="string"?d:void 0,event:f,id:s,delay:l},void 0]}function Dr(e,t,n){typeof n.to=="string"&&(n.to=t.children[n.to])}function Er(e,t){e.defer(()=>{const{to:n,event:r,delay:i,id:o}=t;if(typeof i=="number"){e.system.scheduler.schedule(e.self,n,r,i,o);return}e.system._relay(e.self,n,r.type===En?Yt(e.self.id,r.data):r)})}function je(e,t,n){function r(i,o){}return r.type="xstate.sendTo",r.to=e,r.event=t,r.id=n?.id,r.delay=n?.delay,r.resolve=kr,r.retryResolve=Dr,r.execute=Er,r}function Ar(e,t){return je(Xe.Parent,e,t)}function Mr(e,t,n,r,{collect:i}){const o=[],s=function(c){o.push(c)};return s.assign=(...a)=>{o.push(F(...a))},s.cancel=(...a)=>{o.push(tt(...a))},s.raise=(...a)=>{o.push(at(...a))},s.sendTo=(...a)=>{o.push(je(...a))},s.sendParent=(...a)=>{o.push(Ar(...a))},s.spawnChild=(...a)=>{o.push(nt(...a))},s.stopChild=(...a)=>{o.push(Ce(...a))},s.emit=(...a)=>{o.push(pn(...a))},i({context:n.context,event:n.event,enqueue:s,check:a=>Ne(a,t.context,n.event,t),self:e.self,system:e.system},r),[t,void 0,o]}function Or(e){function t(n,r){}return t.type="xstate.enqueueActions",t.collect=e,t.resolve=Mr,t}function Fr(e,t,n,r,{value:i,label:o}){return[t,{value:typeof i=="function"?i(n,r):i,label:o},void 0]}function Cr({logger:e},{value:t,label:n}){n?e(n,t):e(t)}function Nr(e=({context:n,event:r})=>({context:n,event:r}),t){function n(r,i){}return n.type="xstate.log",n.value=e,n.label=t,n.resolve=Fr,n.execute=Cr,n}function Rr(e,t){return new ct(e,t)}function gn({schemas:e,actors:t,actions:n,guards:r,delays:i}){return{assign:F,sendTo:je,raise:at,log:Nr,cancel:tt,stopChild:Ce,enqueueActions:Or,emit:pn,spawnChild:nt,createStateConfig:o=>o,createAction:o=>o,createMachine:o=>Rr({...o,schemas:e},{actors:t,actions:n,guards:r,delays:i}),extend:o=>gn({schemas:e,actors:t,actions:{...n,...o.actions},guards:{...r,...o.guards},delays:{...i,...o.delays}})}}class vn{actor;subscription=null;options;constructor(t,n){this.options=n,this.actor=Pe(t),this.setupSubscriptions(),n?.enableLogging!==void 0&&this.setLogging(n.enableLogging),n?.baudRate!==void 0&&this.setBaudRate(n.baudRate),this.actor.start()}setupSubscriptions(){this.subscription=this.actor.subscribe(t=>{if(this.options?.onData&&t.context.data!==void 0&&this.options.onData(t.context.data),this.options?.onStateChange){const n=t.value==="connected";this.options.onStateChange(n)}this.options?.onError&&t.context.error&&this.options.onError(t.context.error)})}get data(){return this.actor.getSnapshot().context.data}get isConnected(){return this.actor.getSnapshot().value==="connected"}get isConnecting(){return this.actor.getSnapshot().value==="connecting"}get error(){return this.actor.getSnapshot().context.error}connect(){this.actor.send({type:"CONNECT"})}disconnect(){this.actor.send({type:"DISCONNECT"})}setLogging(t){this.actor.send({type:"SET_LOGGING",enabled:t})}setBaudRate(t){this.actor.send({type:"SET_BAUD_RATE",baudRate:t})}get machine(){return this.actor}dispose(){this.subscription&&(this.subscription.unsubscribe(),this.subscription=null),this.actor.stop()}}var O={},ne={},T={},Tt;function P(){if(Tt)return T;Tt=1,Object.defineProperty(T,"__esModule",{value:!0});var e=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];function t(h){var v=h>>4&15,m=h>>0&15;return e[v]+e[m]}T.toHexString=t;function n(h,v,m){for(var S=typeof h=="string"?h:h.toFixed(0);S.length<v;)S=m+S;return S}T.padLeft=n;function r(h){var v=h.split("*"),m=v[0],S=v[1],D=i(m),M=parseInt(S,16);return D===M}T.validNmeaChecksum=r;function i(h){for(var v=h.charCodeAt(1),m=2;m<h.length;m+=1)v=v^h.charCodeAt(m);return v=v&255,v}T.computeNmeaChecksum=i;function o(h){return"*"+t(i(h))}T.createNmeaChecksumFooter=o;function s(h){return h+o(h)}T.appendChecksumFooter=s;function a(h,v){return h===void 0?"":h.toFixed(v)}T.encodeFixed=a;function c(h){if(h===void 0)return",";var v;h<0?(v="S",h=-h):v="N";var m=Math.floor(h),S=n(m,2,"0"),D=h-m,M=D*60,R=n(M.toFixed(6),9,"0");return S=S+R+","+v,S}T.encodeLatitude=c;function u(h){if(h===void 0)return",";var v;h<0?(v="W",h=-h):v="E";var m=Math.floor(h),S=n(m,3,"0"),D=h-m,M=D*60,R=n(M.toFixed(6),9,"0");return S=S+R+","+v,S}T.encodeLongitude=u;function f(h){return h===void 0?",":h.toFixed(1)+",M"}T.encodeAltitude=f;function l(h){return h===void 0?"":h.toFixed(1)}T.encodeAltitudeNoUnits=l;function d(h){return h===void 0?",":h.toFixed(1)+",M"}T.encodeGeoidalSeperation=d;function p(h){return h===void 0?"":h.toFixed(1)}T.encodeGeoidalSeperationNoUnits=p;function g(h){return h===void 0?"":n(h.toFixed(2),6,"0")}T.encodeDegrees=g;function y(h){if(h===void 0)return"";var v=h.getUTCFullYear(),m=h.getUTCMonth()+1,S=h.getUTCDate();return n(S,2,"0")+n(m,2,"0")+v.toFixed(0).substr(2)}T.encodeDate=y;function I(h){if(h===void 0)return"";var v=h.getUTCHours(),m=h.getUTCMinutes(),S=h.getUTCSeconds();return n(v,2,"0")+n(m,2,"0")+n(S,2,"0")}T.encodeTime=I;function C(h){return h===void 0?"":h.toString()}T.encodeValue=C;function N(h){return h===""?0:parseFloat(h)}T.parseFloatSafe=N;function V(h){return h===""?0:parseInt(h,10)}T.parseIntSafe=V;function Le(h){if(h===void 0)return"";var v=parseFloat(h);return v===NaN?h:v}T.parseNumberOrString=Le;function ee(h){var v=h.indexOf(".");if(v<0)return 0;var m,S;return v>=3?(m=h.substring(0,v-2),S=h.substring(v-2)):(m="0",S=h),parseFloat(m)+parseFloat(S)/60}T.parseDmCoordinate=ee;function xe(h,v){var m=v==="N"?1:-1;return ee(h)*m}T.parseLatitude=xe;function qe(h,v){var m=v==="E"?1:-1;return ee(h)*m}T.parseLongitude=qe;function We(h,v){if(h==="")return new Date(0);var m=new Date;if(v){var S=v.slice(4),D=parseInt(v.slice(2,4),10)-1,M=v.slice(0,2);S.length===4?m.setUTCFullYear(Number(S),Number(D),Number(M)):m.setUTCFullYear(+("20"+S),Number(D),Number(M))}m.setUTCHours(Number(h.slice(0,2))),m.setUTCMinutes(Number(h.slice(2,4))),m.setUTCSeconds(Number(h.slice(4,6)));var R=h.slice(7),K=R.length,W=0;return K!==0&&(W=parseFloat(R)*Math.pow(10,3-K)),m.setUTCMilliseconds(Number(W)),m}T.parseTime=We;function Be(h,v){var m=parseInt(h.slice(0,2),10),S=parseInt(h.slice(2,4),10),D=parseInt(h.slice(4,6),10);D<73?D=D+2e3:D=D+1900;var M=parseInt(v.slice(0,2),10),R=parseInt(v.slice(2,4),10),K=parseInt(v.slice(4,6),10),W=0;return v.length===9&&(W=parseInt(v.slice(7,9),10)*10),new Date(Date.UTC(D,S-1,m,M,R,K,W))}return T.parseDatetime=Be,T}var re={},It;function w(){if(It)return re;It=1,Object.defineProperty(re,"__esModule",{value:!0});function e(n,r,i){return{sentenceId:r,talkerId:n.talkerId,chxOk:n.chxOk,sentenceName:i}}re.initStubFields=e;function t(n,r){var i,o;return n.charAt(1)==="P"?(i="P",o=n.substr(2)):(i=n.substr(1,2),o=n.substr(3)),{talkerId:i,sentenceId:o,chxOk:r||void 0}}return re.parseStub=t,re}var wt;function jr(){return wt||(wt=1,(function(e){var t=ne&&ne.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="APB",e.sentenceName='Autopilot sentence "B"';function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{status1:s[1],status2:s[2],xteMagn:n.parseFloatSafe(s[3]),steerDir:s[4],xteUnit:s[5],arrivalCircleStatus:s[6],arrivalPerpendicularStatus:s[7],bearingOrig2Dest:n.parseFloatSafe(s[8]),bearingOrig2DestType:s[9],waypoint:s[10],bearing2Dest:n.parseFloatSafe(s[11]),bearingDestType:s[12],heading2steer:n.parseFloatSafe(s[13]),headingDestType:s[14]})}e.decodeSentence=i})(ne)),ne}var se={},Pt;function Gr(){return Pt||(Pt=1,(function(e){var t=se&&se.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="BWC",e.sentenceName="Bearing and distance to waypoint - great circle";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{time:n.parseTime(s[1]),bearingLatitude:n.parseLatitude(s[2],s[3]),bearingLongitude:n.parseLongitude(s[4],s[5]),bearingTrue:n.parseFloatSafe(s[6]),bearingMagnetic:n.parseFloatSafe(s[8]),distanceNm:n.parseFloatSafe(s[10]),waypointId:s[12],faaMode:s[13]})}e.decodeSentence=i})(se)),se}var ie={},kt;function Lr(){return kt||(kt=1,(function(e){var t=ie&&ie.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="DBT",e.sentenceName="Depth below transducer";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{depthFeet:n.parseFloatSafe(a[1]),depthMeters:n.parseFloatSafe(a[3]),depthFathoms:n.parseFloatSafe(a[5])})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeFixed(s.depthFeet,2)),c.push("f"),c.push(n.encodeFixed(s.depthMeters,2)),c.push("M"),c.push(n.encodeFixed(s.depthFathoms,2)),c.push("F");var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(ie)),ie}var oe={},Dt;function xr(){return Dt||(Dt=1,(function(e){var t=oe&&oe.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="DTM",e.sentenceName="Datum reference";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{datumCode:o(a[1]),datumSubcode:a[2]||void 0,offsetLatitude:n.parseLatitude(a[3],a[4]),offsetLongitude:n.parseLongitude(a[5],a[6]),offsetAltitudeMeters:n.parseFloatSafe(a[7]),datumName:o(a[8])})}e.decodeSentence=i;function o(s){return s==="W84"?"W84":s==="W72"?"W72":s==="S85"?"S85":s==="P90"?"P90":s==="999"?"999":""}})(oe)),oe}var ae={},Et;function qr(){return Et||(Et=1,(function(e){var t=ae&&ae.__assign||function(){return t=Object.assign||function(a){for(var c,u=1,f=arguments.length;u<f;u++){c=arguments[u];for(var l in c)Object.prototype.hasOwnProperty.call(c,l)&&(a[l]=c[l])}return a},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GGA",e.sentenceName="Global positioning system fix data";var i=["none","fix","delta","pps","rtk","frtk","estimated","manual","simulation"];function o(a,c){return t(t({},r.initStubFields(a,e.sentenceId,e.sentenceName)),{time:n.parseTime(c[1]),latitude:n.parseLatitude(c[2],c[3]),longitude:n.parseLongitude(c[4],c[5]),fixType:i[n.parseIntSafe(c[6])],satellitesInView:n.parseIntSafe(c[7]),horizontalDilution:n.parseFloatSafe(c[8]),altitudeMeters:n.parseFloatSafe(c[9]),geoidalSeperation:n.parseFloatSafe(c[11]),differentialAge:n.parseFloatSafe(c[13]),differentialRefStn:c[14]})}e.decodeSentence=o;function s(a,c){var u=["$"+c+e.sentenceId];u.push(n.encodeTime(a.time)),u.push(n.encodeLatitude(a.latitude)),u.push(n.encodeLongitude(a.longitude)),u.push(n.encodeValue(i.indexOf(a.fixType))),u.push(n.encodeValue(a.satellitesInView)),u.push(n.encodeFixed(a.horizontalDilution,1)),u.push(n.encodeAltitude(a.altitudeMeters)),u.push(n.encodeGeoidalSeperation(a.geoidalSeperation)),u.push(n.encodeFixed(a.differentialAge,2)),u.push(n.encodeValue(a.differentialRefStn));var f=u.join(",");return f+n.createNmeaChecksumFooter(f)}e.encodePacket=s})(ae)),ae}var ce={},At;function Wr(){return At||(At=1,(function(e){var t=ce&&ce.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GLL",e.sentenceName="Geographic position - latitude and longitude";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{latitude:n.parseLatitude(a[1],a[2]),longitude:n.parseLongitude(a[3],a[4]),time:n.parseTime(a[5]),status:a[6]==="A"?"valid":"invalid",faaMode:a[7]})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeLatitude(s.latitude)),c.push(n.encodeLongitude(s.longitude)),c.push(n.encodeTime(s.time)),c.push(s.status==="valid"?"A":"V"),s.faaMode&&c.push(s.faaMode);var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(ce)),ce}var ue={},Mt;function Br(){return Mt||(Mt=1,(function(e){var t=ue&&ue.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GNS",e.sentenceName="GNSS fix data";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{time:n.parseTime(a[1]),latitude:n.parseLatitude(a[2],a[3]),longitude:n.parseLongitude(a[4],a[5]),modeIndicator:a[6],satellitesInView:n.parseIntSafe(a[7]),horizontalDilution:n.parseFloatSafe(a[8]),altitudeMeters:n.parseFloatSafe(a[9]),geoidalSeperation:n.parseFloatSafe(a[10]),differentialAge:n.parseFloatSafe(a[11]),differentialRefStn:a[12]})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeTime(s.time)),c.push(n.encodeLatitude(s.latitude)),c.push(n.encodeLongitude(s.longitude)),c.push(s.modeIndicator),c.push(n.encodeValue(s.satellitesInView)),c.push(n.encodeFixed(s.horizontalDilution,1)),c.push(n.encodeAltitudeNoUnits(s.altitudeMeters)),c.push(n.encodeGeoidalSeperationNoUnits(s.geoidalSeperation)),c.push(n.encodeFixed(s.differentialAge,2)),c.push(n.encodeValue(s.differentialRefStn));var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(ue)),ue}var de={},Ot;function Hr(){return Ot||(Ot=1,(function(e){var t=de&&de.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GSA",e.sentenceName="Active satellites and dilution of precision";var i=["unknown","none","2D","3D"];function o(s,a){for(var c=[],u=3;u<15;u++)a[u]&&c.push(+a[u]);return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{selectionMode:a[1]==="A"?"automatic":"manual",fixMode:i[n.parseIntSafe(a[2])],satellites:c,PDOP:n.parseFloatSafe(a[15]),HDOP:n.parseFloatSafe(a[16]),VDOP:n.parseFloatSafe(a[17])})}e.decodeSentence=o})(de)),de}var fe={},Ft;function Ur(){return Ft||(Ft=1,(function(e){var t=fe&&fe.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GST",e.sentenceName="GPS pseudorange noise statistics";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{time:n.parseTime(s[1]),totalRms:n.parseFloatSafe(s[2]),semiMajorError:n.parseFloatSafe(s[3]),semiMinorError:n.parseFloatSafe(s[4]),orientationOfSemiMajorError:n.parseFloatSafe(s[5]),latitudeError:n.parseFloatSafe(s[6]),longitudeError:n.parseFloatSafe(s[7]),altitudeError:n.parseFloatSafe(s[8])})}e.decodeSentence=i})(fe)),fe}var le={},Ct;function Vr(){return Ct||(Ct=1,(function(e){var t=le&&le.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GSV",e.sentenceName="Satellites in view";function i(o,s){for(var a=(s.length-4)/4,c=[],u=0;u<a;u++){var f=u*4+4;c.push({prnNumber:n.parseIntSafe(s[f]),elevationDegrees:n.parseIntSafe(s[f+1]),azimuthTrue:n.parseIntSafe(s[f+2]),SNRdB:n.parseIntSafe(s[f+3])})}return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{numberOfMessages:n.parseIntSafe(s[1]),messageNumber:n.parseIntSafe(s[2]),satellitesInView:n.parseIntSafe(s[3]),satellites:c})}e.decodeSentence=i})(le)),le}var he={},Nt;function Kr(){return Nt||(Nt=1,(function(e){var t=he&&he.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="HDG",e.sentenceName="Heading - deviation and variation";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{heading:n.parseFloatSafe(s[1]),deviation:n.parseFloatSafe(s[2]),deviationDirection:s[3]==="E"?"E":s[3]==="W"?"W":"",variation:n.parseFloatSafe(s[4]),variationDirection:s[5]==="E"?"E":s[5]==="W"?"W":""})}e.decodeSentence=i})(he)),he}var pe={},Rt;function zr(){return Rt||(Rt=1,(function(e){var t=pe&&pe.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="HDM",e.sentenceName="Heading - magnetic";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{heading:n.parseFloatSafe(a[1])})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeFixed(s.heading,1)),c.push("M");var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(pe)),pe}var ge={},jt;function Jr(){return jt||(jt=1,(function(e){var t=ge&&ge.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="HDT",e.sentenceName="Heading - true";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{heading:n.parseFloatSafe(a[1])})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeFixed(s.heading,1)),c.push("T");var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(ge)),ge}var ve={},Gt;function Zr(){return Gt||(Gt=1,(function(e){var t=ve&&ve.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="MTK",e.sentenceName="Configuration packet";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{packetType:n.parseIntSafe(s.sentenceId.substr(3)),data:a.slice(1).map(n.parseNumberOrString)})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId+n.padLeft(s.packetType,3,"0")];c=c.concat(s.data.toString());var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(ve)),ve}var me={},Lt;function Yr(){return Lt||(Lt=1,(function(e){var t=me&&me.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="MWV",e.sentenceName="Wind speed and angle";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{windAngle:n.parseFloatSafe(a[1]),reference:a[2]==="R"?"relative":"true",speed:n.parseFloatSafe(a[3]),units:a[4]==="K"?"K":a[4]==="M"?"M":"N",status:a[5]==="A"?"valid":"invalid"})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeDegrees(s.windAngle)),c.push(s.reference==="relative"?"R":"T"),c.push(n.encodeFixed(s.speed,2)),c.push(s.units==="K"?"K":s.units==="M"?"M":"N"),c.push(s.status==="valid"?"A":"V");var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(me)),me}var ye={},xt;function Xr(){return xt||(xt=1,(function(e){var t=ye&&ye.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="RDID",e.sentenceName="RDI proprietary heading, pitch, and roll";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{roll:n.parseFloatSafe(s[1]),pitch:n.parseFloatSafe(s[2]),heading:n.parseFloatSafe(s[3])})}e.decodeSentence=i})(ye)),ye}var Se={},qt;function Qr(){return qt||(qt=1,(function(e){var t=Se&&Se.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="RMC",e.sentenceName="Recommended minimum navigation information";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{datetime:n.parseDatetime(s[9],s[1]),status:s[2]==="A"?"valid":"warning",latitude:n.parseLatitude(s[3],s[4]),longitude:n.parseLongitude(s[5],s[6]),speedKnots:n.parseFloatSafe(s[7]),trackTrue:n.parseFloatSafe(s[8]),variation:n.parseFloatSafe(s[10]),variationPole:s[11]==="E"?"E":s[11]==="W"?"W":"",faaMode:s[12]})}e.decodeSentence=i})(Se)),Se}var _e={},Wt;function $r(){return Wt||(Wt=1,(function(e){var t=_e&&_e.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="VHW",e.sentenceName="Water speed and heading";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{degreesTrue:n.parseFloatSafe(s[1]),degreesMagnetic:n.parseFloatSafe(s[3]),speedKnots:n.parseFloatSafe(s[5]),speedKmph:n.parseFloatSafe(s[7])})}e.decodeSentence=i})(_e)),_e}var be={},Bt;function es(){return Bt||(Bt=1,(function(e){var t=be&&be.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="VTG",e.sentenceName="Track made good and ground speed";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{trackTrue:n.parseFloatSafe(a[1]),trackMagnetic:n.parseFloatSafe(a[3]),speedKnots:n.parseFloatSafe(a[5]),speedKmph:n.parseFloatSafe(a[7]),faaMode:a[9]})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeDegrees(s.trackTrue)),c.push("T"),c.push(n.encodeDegrees(s.trackMagnetic)),c.push("M"),c.push(n.encodeFixed(s.speedKnots,2)),c.push("N"),s.speedKmph?(c.push(n.encodeFixed(s.speedKmph,2)),c.push("K")):(c.push(""),c.push("")),s.faaMode&&c.push(s.faaMode);var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(be)),be}var Te={},Ht;function ts(){return Ht||(Ht=1,(function(e){var t=Te&&Te.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="ZDA",e.sentenceName="UTC, day, month, year, and local time zone";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{datetime:n.parseTime(s[1],s.slice(2,5).join("")),localZoneHours:n.parseIntSafe(s[5]),localZoneMinutes:n.parseIntSafe(s[6])})}e.decodeSentence=i})(Te)),Te}var Ie={},Ut;function mn(){return Ut||(Ut=1,(function(e){var t=Ie&&Ie.__assign||function(){return t=Object.assign||function(i){for(var o,s=1,a=arguments.length;s<a;s++){o=arguments[s];for(var c in o)Object.prototype.hasOwnProperty.call(o,c)&&(i[c]=o[c])}return i},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=w();e.sentenceId="?";function r(i,o){return t(t({},n.initStubFields(i,e.sentenceId)),{originalPacketId:i.sentenceId,dataFields:o.slice(1)})}e.decodeSentence=r})(Ie)),Ie}var Vt;function ns(){if(Vt)return O;Vt=1;var e=O&&O.__extends||(function(){var _=function(b,k){return _=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(E,L){E.__proto__=L}||function(E,L){for(var z in L)L.hasOwnProperty(z)&&(E[z]=L[z])},_(b,k)};return function(b,k){_(b,k);function E(){this.constructor=b}b.prototype=k===null?Object.create(k):(E.prototype=k.prototype,new E)}})();Object.defineProperty(O,"__esModule",{value:!0});var t=jr(),n=Gr(),r=Lr(),i=xr(),o=qr(),s=Wr(),a=Br(),c=Hr(),u=Ur(),f=Vr(),l=Kr(),d=zr(),p=Jr(),g=Zr(),y=Yr(),I=Xr(),C=Qr(),N=$r(),V=es(),Le=ts(),ee=w(),xe=mn(),qe=P(),We={APB:t.decodeSentence,BWC:n.decodeSentence,DBT:r.decodeSentence,DTM:i.decodeSentence,GGA:o.decodeSentence,GLL:s.decodeSentence,GNS:a.decodeSentence,GSA:c.decodeSentence,GST:u.decodeSentence,GSV:f.decodeSentence,HDG:l.decodeSentence,HDM:d.decodeSentence,HDT:p.decodeSentence,MTK:g.decodeSentence,MWV:y.decodeSentence,RDID:I.decodeSentence,RMC:C.decodeSentence,VHW:N.decodeSentence,VTG:V.decodeSentence,ZDA:Le.decodeSentence},Be={DBT:r.encodePacket,GGA:o.encodePacket,GLL:s.encodePacket,GNS:a.encodePacket,HDM:d.encodePacket,HDT:p.encodePacket,MTK:g.encodePacket,MWV:y.encodePacket,VTG:V.encodePacket},h=(function(){function _(b){b===void 0&&(b=!1),this.ableToParseBadChecksum=b}return _.getParser=function(b){return b.sentenceId.substr(0,3)==="MTK"?g.decodeSentence:We[b.sentenceId]},_.prototype.assemble=function(b,k){var E=_.getParser(b);return E?E(b,k):this.assembleCustomPacket(b,k)},_.prototype.assembleCustomPacket=function(b,k){return null},_})();O.DefaultPacketFactory=h;var v=new h;function m(_,b){var k=!0;if(!qe.validNmeaChecksum(_)){if(!b.ableToParseBadChecksum)throw Error('Invalid sentence: "'+_+'".');k=!1}var E=_.split("*")[0].split(","),L=ee.parseStub(E[0],k),z=b.assemble(L,E);if(!z)throw Error('No known parser for sentence ID "'+L.sentenceId+'".');return z}O.parseGenericPacket=m;function S(_){return m(_,v)}O.parseNmeaSentence=S;function D(_,b){if(b===void 0&&(b="P"),_===void 0)throw new Error("Packet must be given.");var k=Be[_.sentenceId];if(k)return k(_,b);throw Error('No known encoder for sentence ID "'+_.sentenceId+'"')}O.encodeNmeaPacket=D;var M=(function(_){e(b,_);function b(){return _.call(this,!0)||this}return b.prototype.assembleCustomPacket=function(k,E){return xe.decodeSentence(k,E)},b})(h);O.UnsafePacketFactory=M;var R=new M;function K(_){return m(_,R)}O.parseUnsafeNmeaSentence=K;function W(_){return _.sentenceId==="?"?_.originalPacketId:_.sentenceId}return O.getUnsafePacketId=W,O}var Ge=ns(),rs=mn(),ut=w();function G(e){return e===""?0:Number.parseFloat(e)}const ss="DBK",is="Depth Below Keel";function os(e,t){return{...ut.initStubFields(e,ss,is),depthFeet:G(t[1]),depthMeters:G(t[3]),depthFathoms:G(t[5])}}const as="DBS",cs="Depth Below Surface";function us(e,t){return{...ut.initStubFields(e,as,cs),depthFeet:G(t[1]),depthMeters:G(t[3]),depthFathoms:G(t[5])}}const ds="DPT",fs="Depth of Water";function ls(e,t){return{...ut.initStubFields(e,ds,fs),depthMeters:G(t[1]),offsetMeters:G(t[2]),maximumRangeScale:G(t[3])}}function yn(e,t){switch(e.talkerId){case"DBS":return us(e,t);case"DBK":return os(e,t);case"DPT":return ls(e,t);default:return null}}class hs extends Ge.DefaultPacketFactory{assembleCustomPacket(t,n){return yn(t,n)}}const ps=new hs;function gs(e){return Ge.parseGenericPacket(e,ps)}class vs extends Ge.DefaultPacketFactory{constructor(){super(!0)}assembleCustomPacket(t,n){const r=yn(t,n);return r||rs.decodeSentence(t,n)}}const ms=new vs;function Sn(e){return Ge.parseGenericPacket(e,ms)}function Kt(e,t){return!t||t.length===0?!0:e!==void 0&&t.includes(e)}class ys{container;constructor(){this.container=""}transform(t,n){this.container+=t;const r=this.container.split(`\r
4
- `),i=r.pop();this.container=i??"",r.forEach(o=>{o.length>0&&n.enqueue(o)})}flush(t){this.container=""}}const Ss=hn(async({input:e})=>{if(!navigator.serial)throw new Error("Web Serial API is not supported in this browser.");console.log("Requesting serial port...");const t=await navigator.serial.requestPort();if(console.log(`Opening port at ${e.baudRate} baud...`),t.readable||t.writable){console.log("Port is already open, closing first...");try{await t.close()}catch(n){console.warn("Error closing already-open port:",n)}}return await t.open({baudRate:e.baudRate}),console.log("Port open."),t}),_s=hn(async({input:e})=>{if(e.port)try{(e.port.readable||e.port.writable)&&(await e.port.close(),console.log("Port closed successfully."))}catch(t){console.warn("Error closing port:",t)}}),bs=Sr(({input:e,sendBack:t,receive:n})=>{const{port:r}=e;if(!r||!r.readable){t({type:"SERIAL.ERROR",error:"Invalid port context."});return}const i=new ys,s=r.readable.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform:i.transform.bind(i),flush:i.flush.bind(i)})).getReader();let a=!0;async function c(){try{for(;a;){const{value:u,done:f}=await s.read();if(f)break;if(u&&u.length>0)try{const l=Sn(u);if(l.sentenceId==="?")continue;t({type:"SERIAL.DATA",data:l})}catch(l){const d=l instanceof Error?l.message:String(l);console.warn("Failed to parse NMEA sentence:",u,d),t({type:"SERIAL.ERROR",error:`Parser Error: ${d}`})}}}catch(u){if(console.error("Read loop error:",u),a){const f=u instanceof Error?u.message:String(u);t({type:"FATAL_ERROR",error:f})}}finally{console.log("Read loop finished."),t({type:"SERIAL.DISCONNECTED"})}}return c(),n(u=>{u.type==="STOP"&&(console.log("Received STOP, cancelling reader..."),a=!1,s.cancel().catch(()=>{}))}),()=>{console.log("Cleaning up stream reader actor..."),a=!1,s&&s.cancel().catch(()=>{})}});function _n(e){const{adapter:t,allowedSentenceIds:n,initialData:r,initialPackets:i}=e;return gn({actors:{connectToSerial:Ss,readNmeaStream:bs,closePort:_s},actions:{setPort:F((o,s)=>({port:s.port,error:null})),setError:F((o,s)=>{const a=s.error;let c;return typeof a=="string"?c=a:a instanceof Error?c=a.message||"Failed to connect.":c=String(a)||"Failed to connect.",{error:c}}),logParsedData:({context:o},s)=>{if(!o.enableLogging)return;const c=s.packet.sentenceId;Kt(c,n)&&console.log(`${c} Packet:`,s.packet)},storePacket:F(({context:o},s)=>{const c=s.packet.sentenceId;if(c&&Kt(c,n)){const u={...o.packets,[c]:s.packet};return{packets:u,data:t(u),error:null}}return{packets:o.packets,data:t(o.packets),error:null}}),clearError:F((o,s)=>({error:s.error})),setFatalError:F((o,s)=>({error:s.error})),disconnect:F({port:null,error:null,packets:i,data:r}),setLogging:F((o,s)=>({enableLogging:s.enabled})),setBaudRate:F((o,s)=>({baudRate:s.baudRate}))}}).createMachine({id:"nmea",initial:"disconnected",context:{port:null,error:null,packets:i,data:r,enableLogging:!1,baudRate:4800},on:{SET_LOGGING:{actions:{type:"setLogging",params:({event:o})=>({enabled:o.enabled})}}},states:{disconnected:{on:{CONNECT:"connecting",SET_BAUD_RATE:{actions:{type:"setBaudRate",params:({event:o})=>({baudRate:o.baudRate})}}}},connecting:{invoke:{id:"connectToSerial",src:"connectToSerial",input:({context:o})=>({baudRate:o.baudRate}),onDone:{target:"connected",actions:{type:"setPort",params:({event:o})=>({port:o.output})}},onError:{target:"error",actions:{type:"setError",params:({event:o})=>({error:o.error})}}}},connected:{on:{"SERIAL.DATA":{actions:[{type:"logParsedData",params:({event:o})=>({packet:o.data})},{type:"storePacket",params:({event:o})=>({packet:o.data})}]},"SERIAL.ERROR":{actions:{type:"clearError",params:({event:o})=>({error:o.error})}},FATAL_ERROR:{target:"error",actions:{type:"setFatalError",params:({event:o})=>({error:o.error})}},"SERIAL.DISCONNECTED":{target:"disconnecting"},DISCONNECT:{actions:je("streamReader",{type:"STOP"})}},invoke:{id:"streamReader",src:"readNmeaStream",input:({context:o})=>({port:o.port})}},disconnecting:{invoke:{id:"closePort",src:"closePort",input:({context:o})=>({port:o.port}),onDone:{target:"disconnected",actions:"disconnect"},onError:{target:"disconnected",actions:"disconnect"}}},error:{on:{CONNECT:"connecting"}}}})}function Ts(e,t,n){return e&&e.fixType!=="none"?{latitude:e.latitude,longitude:e.longitude,source:"GGA",fixType:e.fixType,altitudeMeters:e.altitudeMeters,satellitesInView:e.satellitesInView,horizontalDilution:e.horizontalDilution}:t&&t.status==="valid"?{latitude:t.latitude,longitude:t.longitude,source:"RMC",status:t.status}:n&&n.status==="valid"?{latitude:n.latitude,longitude:n.longitude,source:"GLL",status:"valid"}:null}function Is(e,t,n,r){if(e){const i=new Date(e.datetime),o=e.localZoneHours*60+e.localZoneMinutes;return i.setMinutes(i.getMinutes()+o),{utc:e.datetime,local:i,source:"ZDA"}}return t&&t.fixType!=="none"?{utc:t.time,local:null,source:"GGA"}:n&&n.status==="valid"?{utc:n.datetime,local:null,source:"RMC"}:r&&r.status==="valid"?{utc:r.time,local:null,source:"GLL"}:null}function ws(e,t){return e?{knots:e.speedKnots,source:"VTG"}:t&&t.status==="valid"?{knots:t.speedKnots,source:"RMC"}:null}function Ps(e){return e.variationDirection==="W"?-e.variation:(e.variationDirection==="E",e.variation)}function ks(e,t,n,r){if(e&&e.heading!==void 0)return{degreesTrue:e.heading,source:"HDT",isDerived:!1};if(t&&t.heading!==void 0){const o=Ps(t);return{degreesTrue:t.heading+o,source:"HDG",isDerived:!1}}const i=n?.trackTrue??r?.trackTrue;return i!==void 0?{degreesTrue:i,source:"COG",isDerived:!0}:null}function Ds(e,t,n,r){return e&&e.depthMeters!==void 0?{meters:e.depthMeters,source:"DPT"}:t?{meters:t.depthMeters,source:"DBT"}:n&&n.depthMeters!==void 0?{meters:n.depthMeters,source:"DBS"}:r&&r.depthMeters!==void 0?{meters:r.depthMeters,source:"DBK"}:null}function Es(e){const t=Is(e.ZDA,e.GGA,e.RMC,e.GLL),n=Ts(e.GGA,e.RMC,e.GLL),r=ws(e.VTG,e.RMC),i=ks(e.HDT,e.HDG,e.RMC,e.VTG),o=Ds(e.DPT,e.DBT,e.DBS,e.DBK);return{time:t,position:n,speed:r,heading:i,depth:o}}const As=["GGA","RMC","GLL","VTG","HDT","HDG","DPT","DBT","DBS","DBK","ZDA"];function Ms(){return e=>Es(e)}const Os={time:null,position:null,speed:null,heading:null,depth:null},Fs={};function Cs(){return{adapter:Ms(),allowedSentenceIds:As,initialData:Os,initialPackets:Fs}}function bn(){return _n(Cs())}function Ns(e){const t=bn();return new vn(t,{enableLogging:e?.enableLogging,baudRate:e?.baudRate,onData:e?.onData,onStateChange:e?.onStateChange,onError:e?.onError})}exports.NmeaClient=vn;exports.createNavigationNmeaClient=Ns;exports.createNavigationNmeaMachine=bn;exports.createNmeaMachine=_n;exports.parseNmeaSentence=gs;exports.parseUnsafeNmeaSentence=Sn;
4
+ `),i=r.pop();this.container=i??"",r.forEach(o=>{o.length>0&&n.enqueue(o)})}flush(t){this.container=""}}const Ss=hn(async({input:e})=>{if(!navigator.serial)throw new Error("Web Serial API is not supported in this browser.");console.log("Requesting serial port...");const t=await navigator.serial.requestPort();if(console.log(`Opening port at ${e.baudRate} baud...`),t.readable||t.writable){console.log("Port is already open, closing first...");try{await t.close()}catch(n){console.warn("Error closing already-open port:",n)}}return await t.open({baudRate:e.baudRate}),console.log("Port open."),t}),_s=hn(async({input:e})=>{if(e.port)try{(e.port.readable||e.port.writable)&&(await e.port.close(),console.log("Port closed successfully."))}catch(t){console.warn("Error closing port:",t)}}),bs=Sr(({input:e,sendBack:t,receive:n})=>{const{port:r}=e;if(!r||!r.readable){t({type:"SERIAL.ERROR",error:"Invalid port context."});return}const i=new ys,s=r.readable.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform:i.transform.bind(i),flush:i.flush.bind(i)})).getReader();let a=!0;async function c(){try{for(;a;){const{value:u,done:f}=await s.read();if(f)break;if(u&&u.length>0)try{const l=Sn(u);if(l.sentenceId==="?")continue;t({type:"SERIAL.DATA",data:l})}catch(l){const d=l instanceof Error?l.message:String(l);console.warn("Failed to parse NMEA sentence:",u,d),t({type:"SERIAL.ERROR",error:`Parser Error: ${d}`})}}}catch(u){if(console.error("Read loop error:",u),a){const f=u instanceof Error?u.message:String(u);t({type:"FATAL_ERROR",error:f})}}finally{console.log("Read loop finished."),t({type:"SERIAL.DISCONNECTED"})}}return c(),n(u=>{u.type==="STOP"&&(console.log("Received STOP, cancelling reader..."),a=!1,s.cancel().catch(()=>{}))}),()=>{console.log("Cleaning up stream reader actor..."),a=!1,s&&s.cancel().catch(()=>{})}});function _n(e){const{adapter:t,allowedSentenceIds:n,initialData:r,initialPackets:i}=e;return gn({actors:{connectToSerial:Ss,readNmeaStream:bs,closePort:_s},actions:{setPort:F((o,s)=>({port:s.port,error:null})),setError:F((o,s)=>{const a=s.error;let c;return typeof a=="string"?c=a:a instanceof Error?c=a.message||"Failed to connect.":c=String(a)||"Failed to connect.",{error:c}}),logParsedData:({context:o},s)=>{if(!o.enableLogging)return;const c=s.packet.sentenceId;Kt(c,n)&&console.log(`${c} Packet:`,s.packet)},storePacket:F(({context:o},s)=>{const c=s.packet.sentenceId;if(c&&Kt(c,n)){const u={...o.packets,[c]:s.packet};return{packets:u,data:t(u),error:null}}return{packets:o.packets,data:t(o.packets),error:null}}),clearError:F((o,s)=>({error:s.error})),setFatalError:F((o,s)=>({error:s.error})),disconnect:F({port:null,error:null,packets:i,data:r}),setLogging:F((o,s)=>({enableLogging:s.enabled})),setBaudRate:F((o,s)=>({baudRate:s.baudRate}))}}).createMachine({id:"nmea",initial:"disconnected",context:{port:null,error:null,packets:i,data:r,enableLogging:!1,baudRate:4800},on:{SET_LOGGING:{actions:{type:"setLogging",params:({event:o})=>({enabled:o.enabled})}}},states:{disconnected:{on:{CONNECT:"connecting",SET_BAUD_RATE:{actions:{type:"setBaudRate",params:({event:o})=>({baudRate:o.baudRate})}}}},connecting:{invoke:{id:"connectToSerial",src:"connectToSerial",input:({context:o})=>({baudRate:o.baudRate}),onDone:{target:"connected",actions:{type:"setPort",params:({event:o})=>({port:o.output})}},onError:{target:"error",actions:{type:"setError",params:({event:o})=>({error:o.error})}}}},connected:{on:{"SERIAL.DATA":{actions:[{type:"logParsedData",params:({event:o})=>({packet:o.data})},{type:"storePacket",params:({event:o})=>({packet:o.data})}]},"SERIAL.ERROR":{actions:{type:"clearError",params:({event:o})=>({error:o.error})}},FATAL_ERROR:{target:"error",actions:{type:"setFatalError",params:({event:o})=>({error:o.error})}},"SERIAL.DISCONNECTED":{target:"disconnecting"},DISCONNECT:{actions:je("streamReader",{type:"STOP"})}},invoke:{id:"streamReader",src:"readNmeaStream",input:({context:o})=>({port:o.port})}},disconnecting:{invoke:{id:"closePort",src:"closePort",input:({context:o})=>({port:o.port}),onDone:{target:"disconnected",actions:"disconnect"},onError:{target:"disconnected",actions:"disconnect"}}},error:{on:{CONNECT:"connecting"}}}})}function Ts(e,t,n){return e&&e.fixType!=="none"?{latitude:e.latitude,longitude:e.longitude,source:"GGA",fixType:e.fixType,altitudeMeters:e.altitudeMeters,satellitesInView:e.satellitesInView,horizontalDilution:e.horizontalDilution}:t&&t.status==="valid"?{latitude:t.latitude,longitude:t.longitude,source:"RMC",status:t.status}:n&&n.status==="valid"?{latitude:n.latitude,longitude:n.longitude,source:"GLL",status:"valid"}:null}function Is(e,t,n,r){if(e){const i=new Date(e.datetime),o=e.localZoneHours*60+e.localZoneMinutes;return i.setMinutes(i.getMinutes()+o),{utc:e.datetime,local:i,source:"ZDA"}}return t&&t.fixType!=="none"?{utc:t.time,local:null,source:"GGA"}:n&&n.status==="valid"?{utc:n.datetime,local:null,source:"RMC"}:r&&r.status==="valid"?{utc:r.time,local:null,source:"GLL"}:null}function ws(e,t){return e?{knots:e.speedKnots,source:"VTG"}:t&&t.status==="valid"?{knots:t.speedKnots,source:"RMC"}:null}function Ps(e){return e.variationDirection==="W"?-e.variation:(e.variationDirection==="E",e.variation)}function ks(e,t,n,r){if(e&&e.heading!==void 0)return{degreesTrue:e.heading,source:"HDT",isDerived:!1};if(t&&t.heading!==void 0){const o=Ps(t);return{degreesTrue:t.heading+o,source:"HDG",isDerived:!1}}const i=n?.trackTrue??r?.trackTrue;return i!==void 0?{degreesTrue:i,source:"COG",isDerived:!0}:null}function Ds(e,t,n,r){return e&&e.depthMeters!==void 0?{meters:e.depthMeters,source:"DPT"}:t?{meters:t.depthMeters,source:"DBT"}:n&&n.depthMeters!==void 0?{meters:n.depthMeters,source:"DBS"}:r&&r.depthMeters!==void 0?{meters:r.depthMeters,source:"DBK"}:null}function Es(e){const t=Is(e.ZDA,e.GGA,e.RMC,e.GLL),n=Ts(e.GGA,e.RMC,e.GLL),r=ws(e.VTG,e.RMC),i=ks(e.HDT,e.HDG,e.RMC,e.VTG),o=Ds(e.DPT,e.DBT,e.DBS,e.DBK);return{time:t,position:n,speed:r,heading:i,depth:o}}const As=["GGA","RMC","GLL","VTG","HDT","HDG","DPT","DBT","DBS","DBK","ZDA"];function Ms(){return e=>Es(e)}const Os={time:null,position:null,speed:null,heading:null,depth:null},Fs={};function Cs(){return{adapter:Ms(),allowedSentenceIds:As,initialData:Os,initialPackets:Fs}}function bn(){return _n(Cs())}class Ns extends vn{constructor(t){const n=bn();super(n,{enableLogging:t?.enableLogging,baudRate:t?.baudRate,onData:t?.onData,onStateChange:t?.onStateChange,onError:t?.onError})}}exports.NavigationNmeaClient=Ns;exports.NmeaClient=vn;exports.createNavigationNmeaMachine=bn;exports.createNmeaMachine=_n;exports.parseNmeaSentence=gs;exports.parseUnsafeNmeaSentence=Sn;
@@ -27,37 +27,27 @@ import { Values } from 'xstate';
27
27
  import { VTGPacket } from 'nmea-simple';
28
28
  import { ZDAPacket } from 'nmea-simple';
29
29
 
30
- /**
31
- * Simple client for navigation NMEA data.
32
- * Creates a machine and manages connection state automatically.
33
- *
34
- * @param options - Configuration options.
35
- * @returns A client instance for managing the NMEA connection.
36
- *
37
- * @example
38
- * ```typescript
39
- * const client = createNavigationNmeaClient({
40
- * enableLogging: true,
41
- * onData: (navigation) => {
42
- * console.log('Position:', navigation.position);
43
- * },
44
- * });
45
- *
46
- * client.connect();
47
- * ```
48
- */
49
- export declare function createNavigationNmeaClient(options?: NmeaClientOptions<NavigationData>): NmeaClient<NavigationData, StoredPackets>;
50
-
51
30
  /**
52
31
  * Convenience function to create a navigation-focused NMEA machine.
53
- * This is a pre-configured machine that computes navigation data from NMEA packets.
54
32
  *
55
- * @returns An NMEA machine configured for navigation data computation.
33
+ * This is a pre-configured machine that computes navigation data (position, time, speed, heading, depth)
34
+ * from NMEA packets. It uses the navigation adapter which automatically handles priority-based fallback
35
+ * between different sentence types.
56
36
  *
57
37
  * @example
58
38
  * ```typescript
59
39
  * const machine = createNavigationNmeaMachine();
40
+ * const actor = createActor(machine);
41
+ * actor.start();
42
+ * actor.send({ type: 'CONNECT' });
60
43
  * ```
44
+ *
45
+ * @returns An XState state machine configured for navigation data computation.
46
+ *
47
+ * @remarks
48
+ * The returned machine is an XState state machine. Use it with XState's `createActor` to create
49
+ * an actor instance, or use the {@link NavigationNmeaClient} class for a simpler API that doesn't
50
+ * require direct XState knowledge.
61
51
  */
62
52
  export declare function createNavigationNmeaMachine(): StateMachine<NmeaContext<NavigationData, StoredPackets>, {
63
53
  type: "CONNECT";
@@ -588,10 +578,8 @@ readonly CONNECT: "connecting";
588
578
  /**
589
579
  * Factory function to create an NMEA state machine with a generic adapter pattern.
590
580
  *
591
- * @template TData - The type of computed/translated data stored in context.
592
- * @template TPackets - The type of stored packets (typically a record of sentence ID to packet).
593
- * @param config - Configuration for the machine including adapter function and initial values.
594
- * @returns An XState machine configured with the provided adapter and types.
581
+ * Creates an XState state machine that manages serial port connections, parses NMEA sentences,
582
+ * and transforms them into your application's data format using the provided adapter function.
595
583
  *
596
584
  * @example
597
585
  * ```typescript
@@ -601,9 +589,23 @@ readonly CONNECT: "connecting";
601
589
  * initialData: { time: null, position: null },
602
590
  * initialPackets: {},
603
591
  * });
592
+ *
593
+ * const actor = createActor(machine);
594
+ * actor.start();
595
+ * actor.send({ type: 'CONNECT' });
604
596
  * ```
597
+ *
598
+ * @template TData - The type of computed/translated data stored in context.
599
+ * @template TPackets - The type of stored packets (typically a record of sentence ID to packet).
600
+ * @param config - Configuration for the machine including adapter function and initial values.
601
+ * @returns An XState state machine that can be used with `createActor` from XState.
602
+ *
603
+ * @remarks
604
+ * The returned machine is an XState state machine. Use it with XState's `createActor` to create
605
+ * an actor instance, or use the {@link NmeaClient} class for a simpler API that doesn't require
606
+ * direct XState knowledge.
605
607
  */
606
- export declare function createNmeaMachine<TData, TPackets extends Record<string, unknown>>(config: NmeaMachineConfig<TData, TPackets>): StateMachine<NmeaContext<TData, TPackets>, {
608
+ export declare function createNmeaMachine<TData, TPackets extends Record<string, PacketStub | undefined>>(config: NmeaMachineConfig<TData, TPackets>): StateMachine<NmeaContext<TData, TPackets>, {
607
609
  type: "CONNECT";
608
610
  } | {
609
611
  type: "DISCONNECT";
@@ -1131,19 +1133,19 @@ readonly CONNECT: "connecting";
1131
1133
 
1132
1134
  declare type CustomPackets = DBSPacket | DBKPacket | DPTPacket;
1133
1135
 
1134
- export declare interface DBKPacket extends PacketStub<typeof sentenceId_3> {
1136
+ declare interface DBKPacket extends PacketStub<typeof sentenceId_3> {
1135
1137
  depthFeet: number;
1136
1138
  depthMeters: number;
1137
1139
  depthFathoms: number;
1138
1140
  }
1139
1141
 
1140
- export declare interface DBSPacket extends PacketStub<typeof sentenceId_2> {
1142
+ declare interface DBSPacket extends PacketStub<typeof sentenceId_2> {
1141
1143
  depthFeet: number;
1142
1144
  depthMeters: number;
1143
1145
  depthFathoms: number;
1144
1146
  }
1145
1147
 
1146
- export declare interface DPTPacket extends PacketStub<typeof sentenceId> {
1148
+ declare interface DPTPacket extends PacketStub<typeof sentenceId> {
1147
1149
  depthMeters: number;
1148
1150
  offsetMeters: number;
1149
1151
  maximumRangeScale: number;
@@ -1185,11 +1187,36 @@ export declare interface NavigationData {
1185
1187
  } | null;
1186
1188
  }
1187
1189
 
1190
+ /**
1191
+ * Simple client for navigation NMEA data.
1192
+ * Creates a machine and manages connection state automatically.
1193
+ *
1194
+ * @example
1195
+ * ```typescript
1196
+ * const client = new NavigationNmeaClient({
1197
+ * enableLogging: true,
1198
+ * onData: (navigation) => {
1199
+ * console.log('Position:', navigation.position);
1200
+ * },
1201
+ * });
1202
+ *
1203
+ * client.connect();
1204
+ * ```
1205
+ */
1206
+ export declare class NavigationNmeaClient extends NmeaClient<NavigationData, StoredPackets> {
1207
+ /**
1208
+ * Creates a new navigation NMEA client.
1209
+ *
1210
+ * @param options - Optional configuration and callbacks.
1211
+ */
1212
+ constructor(options?: NmeaClientOptions<NavigationData>);
1213
+ }
1214
+
1188
1215
  /**
1189
1216
  * Simple client for managing NMEA connections.
1190
1217
  * Abstracts away XState details while still exposing the machine for advanced use.
1191
1218
  */
1192
- export declare class NmeaClient<TData, TPackets extends Record<string, unknown>> {
1219
+ export declare class NmeaClient<TData, TPackets extends Record<string, PacketStub | undefined>> {
1193
1220
  private actor;
1194
1221
  private subscription;
1195
1222
  private options?;
@@ -1265,7 +1292,7 @@ export declare interface NmeaClientOptions<TData = unknown> {
1265
1292
  * @template TData - The type of computed/translated data.
1266
1293
  * @template TPackets - The type of stored packets.
1267
1294
  */
1268
- export declare interface NmeaContext<TData, TPackets extends Record<string, unknown>> {
1295
+ declare interface NmeaContext<TData, TPackets extends Record<string, PacketStub | undefined>> {
1269
1296
  /** The active Web Serial port connection, or null if disconnected. */
1270
1297
  port: SerialPort | null;
1271
1298
  /** Current error message, or null if no error. */
@@ -1283,7 +1310,7 @@ export declare interface NmeaContext<TData, TPackets extends Record<string, unkn
1283
1310
  /**
1284
1311
  * Events that the NMEA state machine can handle.
1285
1312
  */
1286
- export declare type NmeaEvent = {
1313
+ declare type NmeaEvent = {
1287
1314
  type: 'CONNECT';
1288
1315
  } | {
1289
1316
  type: 'DISCONNECT';
@@ -1313,14 +1340,14 @@ export declare type NmeaEvent = {
1313
1340
  * @template TData - The type of computed/translated data.
1314
1341
  * @template TPackets - The type of stored packets.
1315
1342
  */
1316
- export declare type NmeaMachineActor<TData, TPackets extends Record<string, unknown>> = ActorRefFrom<ReturnType<typeof createNmeaMachine<TData, TPackets>>>;
1343
+ export declare type NmeaMachineActor<TData, TPackets extends Record<string, PacketStub | undefined>> = ActorRefFrom<ReturnType<typeof createNmeaMachine<TData, TPackets>>>;
1317
1344
 
1318
1345
  /**
1319
1346
  * Configuration for creating an NMEA machine.
1320
1347
  * @template TData - The type of computed/translated data stored in context.
1321
1348
  * @template TPackets - The type of stored packets (typically a record of sentence ID to packet).
1322
1349
  */
1323
- export declare interface NmeaMachineConfig<TData, TPackets extends Record<string, unknown>> {
1350
+ export declare interface NmeaMachineConfig<TData, TPackets extends Record<string, PacketStub | undefined>> {
1324
1351
  /** Function that transforms stored packets into the computed data type. */
1325
1352
  adapter: (packets: TPackets) => TData;
1326
1353
  /** Optional list of sentence IDs to filter and store. If not provided, all parsed sentences are stored. */
@@ -1331,8 +1358,6 @@ export declare interface NmeaMachineConfig<TData, TPackets extends Record<string
1331
1358
  initialPackets: TPackets;
1332
1359
  }
1333
1360
 
1334
- export { Packet }
1335
-
1336
1361
  export declare function parseNmeaSentence(sentence: string): ExtendedNmeaPacket;
1337
1362
 
1338
1363
  export declare function parseUnsafeNmeaSentence(sentence: string): ExtendedNmeaPacket | UnknownPacket;
@@ -1346,7 +1371,7 @@ declare const sentenceId_3: "DBK";
1346
1371
  /**
1347
1372
  * Types for stored packets by sentence type.
1348
1373
  */
1349
- export declare interface StoredPackets extends Record<string, unknown> {
1374
+ export declare interface StoredPackets extends Record<string, PacketStub | undefined> {
1350
1375
  GGA?: GGAPacket;
1351
1376
  RMC?: RMCPacket;
1352
1377
  GLL?: GLLPacket;
@@ -1,4 +1,4 @@
1
1
  var NmeaWebSerial=(function(L){"use strict";function In(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function wn(){const e=In();if(e.__xstate__)return e.__xstate__}const Pn=e=>{if(typeof window>"u")return;const t=wn();t&&t.register(e)};class ft{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const n={value:t,next:null};if(this._current){this._last.next=n,this._last=n;return}this._current=n,this._last=n,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const lt=".",kn="",ht="",Dn="#",En="*",pt="xstate.init",An="xstate.error",te="xstate.stop";function Mn(e,t){return{type:`xstate.after.${e}.${t}`}}function xe(e,t){return{type:`xstate.done.state.${e}`,output:t}}function On(e,t){return{type:`xstate.done.actor.${e}`,output:t,actorId:e}}function gt(e,t){return{type:`xstate.error.actor.${e}`,error:t,actorId:e}}function vt(e){return{type:pt,input:e}}function C(e){setTimeout(()=>{throw e})}const Fn=typeof Symbol=="function"&&Symbol.observable||"@@observable";function mt(e,t){const n=yt(e),r=yt(t);return typeof r=="string"?typeof n=="string"?r===n:!1:typeof n=="string"?n in r:Object.keys(n).every(i=>i in r?mt(n[i],r[i]):!1)}function qe(e){if(bt(e))return e;const t=[];let n="";for(let r=0;r<e.length;r++){switch(e.charCodeAt(r)){case 92:n+=e[r+1],r++;continue;case 46:t.push(n),n="";continue}n+=e[r]}return t.push(n),t}function yt(e){if(dr(e))return e.value;if(typeof e!="string")return e;const t=qe(e);return Cn(t)}function Cn(e){if(e.length===1)return e[0];const t={};let n=t;for(let r=0;r<e.length-1;r++)if(r===e.length-2)n[e[r]]=e[r+1];else{const i=n;n={},i[e[r]]=n}return t}function St(e,t){const n={},r=Object.keys(e);for(let i=0;i<r.length;i++){const o=r[i];n[o]=t(e[o],o,e,i)}return n}function _t(e){return bt(e)?e:[e]}function x(e){return e===void 0?[]:_t(e)}function We(e,t,n,r){return typeof e=="function"?e({context:t,event:n,self:r}):e}function bt(e){return Array.isArray(e)}function Nn(e){return e.type.startsWith("xstate.error.actor")}function K(e){return _t(e).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function Tt(e){if(!(e===void 0||e===kn))return x(e)}function Be(e,t,n){const r=typeof e=="object",i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}function It(e,t){return`${t}.${e}`}function He(e,t){const n=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return e.implementations.actors[t];const[,r,i]=n,s=e.getStateNodeById(i).config.invoke;return(Array.isArray(s)?s[r]:s).src}function wt(e,t){return`${e.sessionId}.${t}`}let Rn=0;function jn(e,t){const n=new Map,r=new Map,i=new WeakMap,o=new Set,s={},{clock:a,logger:c}=t,u={schedule:(d,p,g,y,I=Math.random().toString(36).slice(2))=>{const N={source:d,target:p,event:g,delay:y,id:I,startedAt:Date.now()},R=wt(d,I);l._snapshot._scheduledEvents[R]=N;const Q=a.setTimeout(()=>{delete s[R],delete l._snapshot._scheduledEvents[R],l._relay(d,p,g)},y);s[R]=Q},cancel:(d,p)=>{const g=wt(d,p),y=s[g];delete s[g],delete l._snapshot._scheduledEvents[g],y!==void 0&&a.clearTimeout(y)},cancelAll:d=>{for(const p in l._snapshot._scheduledEvents){const g=l._snapshot._scheduledEvents[p];g.source===d&&u.cancel(d,g.id)}}},f=d=>{if(!o.size)return;const p={...d,rootId:e.sessionId};o.forEach(g=>g.next?.(p))},l={_snapshot:{_scheduledEvents:(t?.snapshot&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${Rn++}`,_register:(d,p)=>(n.set(d,p),d),_unregister:d=>{n.delete(d.sessionId);const p=i.get(d);p!==void 0&&(r.delete(p),i.delete(d))},get:d=>r.get(d),getAll:()=>Object.fromEntries(r.entries()),_set:(d,p)=>{const g=r.get(d);if(g&&g!==p)throw new Error(`Actor with system ID '${d}' already exists.`);r.set(d,p),i.set(p,d)},inspect:d=>{const p=Be(d);return o.add(p),{unsubscribe(){o.delete(p)}}},_sendInspectionEvent:f,_relay:(d,p,g)=>{l._sendInspectionEvent({type:"@xstate.event",sourceRef:d,actorRef:p,event:g}),p._send(g)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...l._snapshot._scheduledEvents}}),start:()=>{const d=l._snapshot._scheduledEvents;l._snapshot._scheduledEvents={};for(const p in d){const{source:g,target:y,event:I,delay:N,id:R}=d[p];u.schedule(g,y,I,N,R)}},_clock:a,_logger:c};return l}let Ue=!1;const Ve=1;let E=(function(e){return e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped",e})({});const Gn={clock:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},logger:console.log.bind(console),devTools:!1};class Ln{constructor(t,n){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new ft(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=E.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 r={...Gn,...n},{clock:i,logger:o,parent:s,syncSnapshot:a,id:c,systemId:u,inspect:f}=r;this.system=s?s.system:jn(this,{clock:i,logger:o}),f&&!s&&this.system.inspect(Be(f)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=n?.logger??this.system._logger,this.clock=n?.clock??this.system._clock,this._parent=s,this._syncSnapshot=a,this.options=r,this.src=r.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:l=>{this._deferred.push(l)},system:this.system,stopChild:l=>{if(l._parent!==this)throw new Error(`Cannot stop child actor ${l.id} of ${this.id} because it is not a child`);l._stop()},emit:l=>{const d=this.eventListeners.get(l.type),p=this.eventListeners.get("*");if(!d&&!p)return;const g=[...d?d.values():[],...p?p.values():[]];for(const y of g)try{y(l)}catch(I){C(I)}},actionExecutor:l=>{const d=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:l.type,params:l.params}}),!l.exec)return;const p=Ue;try{Ue=!0,l.exec(l.info,l.params)}finally{Ue=p}};this._processingStatus===E.Running?d():this._deferred.push(d)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),u&&(this.systemId=u,this.system._set(u,this)),this._initState(n?.snapshot??n?.state),u&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(n){this._snapshot={status:"error",output:void 0,error:n}}}update(t,n){this._snapshot=t;let r;for(;r=this._deferred.shift();)try{r()}catch(i){this._deferred.length=0,this._snapshot={...t,status:"error",error:i}}switch(this._snapshot.status){case"active":for(const i of this.observers)try{i.next?.(t)}catch(o){C(o)}break;case"done":for(const i of this.observers)try{i.next?.(t)}catch(o){C(o)}this._stopProcedure(),this._complete(),this._doneEvent=On(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:n,snapshot:t})}subscribe(t,n,r){const i=Be(t,n,r);if(this._processingStatus!==E.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{i.complete?.()}catch(o){C(o)}break;case"error":{const o=this._snapshot.error;if(!i.error)C(o);else try{i.error(o)}catch(s){C(s)}break}}return{unsubscribe:()=>{this.observers.delete(i)}}}on(t,n){let r=this.eventListeners.get(t);r||(r=new Set,this.eventListeners.set(t,r));const i=n.bind(void 0);return r.add(i),{unsubscribe:()=>{r.delete(i)}}}start(){if(this._processingStatus===E.Running)return this;this._syncSnapshot&&this.subscribe({next:r=>{r.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:r})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=E.Running;const t=vt(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t}),this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(r){return this._snapshot={...this._snapshot,status:"error",error:r},this._error(r),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let n,r;try{n=this.logic.transition(this._snapshot,t,this._actorScope)}catch(i){r={err:i}}if(r){const{err:i}=r;this._snapshot={...this._snapshot,status:"error",error:i},this._error(i);return}this.update(n,t),t.type===te&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===E.Stopped?this:(this.mailbox.clear(),this._processingStatus===E.NotStarted?(this._processingStatus=E.Stopped,this):(this.mailbox.enqueue({type:te}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(n){C(n)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||C(t);return}let n=!1;for(const r of this.observers){const i=r.error;n||=!i;try{i?.(t)}catch(o){C(o)}}this.observers.clear(),n&&C(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,gt(this.id,t))}_stopProcedure(){return this._processingStatus!==E.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new ft(this._process.bind(this)),this._processingStatus=E.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==E.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;t&&(typeof t=="function"?t:Pn)(this)}toJSON(){return{xstate$$type:Ve,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[Fn](){return this}getSnapshot(){return this._snapshot}}function ne(e,...[t]){return new Ln(e,t)}function xn(e,t,n,r,{sendId:i}){const o=typeof i=="function"?i(n,r):i;return[t,{sendId:o},void 0]}function qn(e,t){e.defer(()=>{e.system.scheduler.cancel(e.self,t.sendId)})}function Ke(e){function t(n,r){}return t.type="xstate.cancel",t.sendId=e,t.resolve=xn,t.execute=qn,t}function Wn(e,t,n,r,{id:i,systemId:o,src:s,input:a,syncSnapshot:c}){const u=typeof s=="string"?He(t.machine,s):s,f=typeof i=="function"?i(n):i;let l,d;return u&&(d=typeof a=="function"?a({context:t.context,event:n.event,self:e.self}):a,l=ne(u,{id:f,src:s,parent:e.self,syncSnapshot:c,systemId:o,input:d})),[U(t,{children:{...t.children,[f]:l}}),{id:i,systemId:o,actorRef:l,src:s,input:d},void 0]}function Bn(e,{actorRef:t}){t&&e.defer(()=>{t._processingStatus!==E.Stopped&&t.start()})}function ze(...[e,{id:t,systemId:n,input:r,syncSnapshot:i=!1}={}]){function o(s,a){}return o.type="xstate.spawnChild",o.id=t,o.systemId=n,o.src=e,o.input=r,o.syncSnapshot=i,o.resolve=Wn,o.execute=Bn,o}function Hn(e,t,n,r,{actorRef:i}){const o=typeof i=="function"?i(n,r):i,s=typeof o=="string"?t.children[o]:o;let a=t.children;return s&&(a={...a},delete a[s.id]),[U(t,{children:a}),s,void 0]}function Un(e,t){if(t){if(e.system._unregister(t),t._processingStatus!==E.Running){e.stopChild(t);return}e.defer(()=>{e.stopChild(t)})}}function Ee(e){function t(n,r){}return t.type="xstate.stopChild",t.actorRef=e,t.resolve=Hn,t.execute=Un,t}function Ae(e,t,n,r){const{machine:i}=r,o=typeof e=="function",s=o?e:i.implementations.guards[typeof e=="string"?e:e.type];if(!o&&!s)throw new Error(`Guard '${typeof e=="string"?e:e.type}' is not implemented.'.`);if(typeof s!="function")return Ae(s,t,n,r);const a={context:t,event:n},c=o||typeof e=="string"?void 0:"params"in e?typeof e.params=="function"?e.params({context:t,event:n}):e.params:void 0;return"check"in s?s.check(r,a,s):s(a,c)}const Je=e=>e.type==="atomic"||e.type==="final";function z(e){return Object.values(e.states).filter(t=>t.type!=="history")}function re(e,t){const n=[];if(t===e)return n;let r=e.parent;for(;r&&r!==t;)n.push(r),r=r.parent;return n}function Me(e){const t=new Set(e),n=kt(t);for(const r of t)if(r.type==="compound"&&(!n.get(r)||!n.get(r).length))At(r).forEach(i=>t.add(i));else if(r.type==="parallel"){for(const i of z(r))if(i.type!=="history"&&!t.has(i)){const o=At(i);for(const s of o)t.add(s)}}for(const r of t){let i=r.parent;for(;i;)t.add(i),i=i.parent}return t}function Pt(e,t){const n=t.get(e);if(!n)return{};if(e.type==="compound"){const i=n[0];if(i){if(Je(i))return i.key}else return{}}const r={};for(const i of n)r[i.key]=Pt(i,t);return r}function kt(e){const t=new Map;for(const n of e)t.has(n)||t.set(n,[]),n.parent&&(t.has(n.parent)||t.set(n.parent,[]),t.get(n.parent).push(n));return t}function Dt(e,t){const n=Me(t);return Pt(e,kt(n))}function Ze(e,t){return t.type==="compound"?z(t).some(n=>n.type==="final"&&e.has(n)):t.type==="parallel"?z(t).every(n=>Ze(e,n)):t.type==="final"}const Oe=e=>e[0]===Dn;function Vn(e,t){return e.transitions.get(t)||[...e.transitions.keys()].filter(r=>{if(r===En)return!0;if(!r.endsWith(".*"))return!1;const i=r.split("."),o=t.split(".");for(let s=0;s<i.length;s++){const a=i[s],c=o[s];if(a==="*")return s===i.length-1;if(a!==c)return!1}return!0}).sort((r,i)=>i.length-r.length).flatMap(r=>e.transitions.get(r))}function Kn(e){const t=e.config.after;if(!t)return[];const n=i=>{const o=Mn(i,e.id),s=o.type;return e.entry.push(nt(o,{id:s,delay:i})),e.exit.push(Ke(s)),s};return Object.keys(t).flatMap(i=>{const o=t[i],s=typeof o=="string"?{target:o}:o,a=Number.isNaN(+i)?i:+i,c=n(a);return x(s).map(u=>({...u,event:c,delay:a}))}).map(i=>{const{delay:o}=i;return{...B(e,i.event,i),delay:o}})}function B(e,t,n){const r=Tt(n.target),i=n.reenter??!1,o=Zn(e,r),s={...n,actions:x(n.actions),guard:n.guard,target:o,source:e,reenter:i,eventType:t,toJSON:()=>({...s,source:`#${e.id}`,target:o?o.map(a=>`#${a.id}`):void 0})};return s}function zn(e){const t=new Map;if(e.config.on)for(const n of Object.keys(e.config.on)){if(n===ht)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const r=e.config.on[n];t.set(n,K(r).map(i=>B(e,n,i)))}if(e.config.onDone){const n=`xstate.done.state.${e.id}`;t.set(n,K(e.config.onDone).map(r=>B(e,n,r)))}for(const n of e.invoke){if(n.onDone){const r=`xstate.done.actor.${n.id}`;t.set(r,K(n.onDone).map(i=>B(e,r,i)))}if(n.onError){const r=`xstate.error.actor.${n.id}`;t.set(r,K(n.onError).map(i=>B(e,r,i)))}if(n.onSnapshot){const r=`xstate.snapshot.${n.id}`;t.set(r,K(n.onSnapshot).map(i=>B(e,r,i)))}}for(const n of e.after){let r=t.get(n.eventType);r||(r=[],t.set(n.eventType,r)),r.push(n)}return t}function Jn(e,t){const n=typeof t=="string"?e.states[t]:t?e.states[t.target]:void 0;if(!n&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${e.id}`);const r={source:e,actions:!t||typeof t=="string"?[]:x(t.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...r,source:`#${e.id}`,target:n?[`#${n.id}`]:[]})};return r}function Zn(e,t){if(t!==void 0)return t.map(n=>{if(typeof n!="string")return n;if(Oe(n))return e.machine.getStateNodeById(n);const r=n[0]===lt;if(r&&!e.parent)return Fe(e,n.slice(1));const i=r?e.key+n:n;if(e.parent)try{return Fe(e.parent,i)}catch(o){throw new Error(`Invalid transition definition for state node '${e.id}':
2
2
  ${o.message}`)}else throw new Error(`Invalid target: "${n}" is not a valid target from the root node. Did you mean ".${n}"?`)})}function Et(e){const t=Tt(e.config.target);return t?{target:t.map(n=>typeof n=="string"?Fe(e.parent,n):n)}:e.parent.initial}function H(e){return e.type==="history"}function At(e){const t=Mt(e);for(const n of t)for(const r of re(n,e))t.add(r);return t}function Mt(e){const t=new Set;function n(r){if(!t.has(r)){if(t.add(r),r.type==="compound")n(r.initial.target[0]);else if(r.type==="parallel")for(const i of z(r))n(i)}}return n(e),t}function J(e,t){if(Oe(t))return e.machine.getStateNodeById(t);if(!e.states)throw new Error(`Unable to retrieve child state '${t}' from '${e.id}'; no child states exist.`);const n=e.states[t];if(!n)throw new Error(`Child state '${t}' does not exist on '${e.id}'`);return n}function Fe(e,t){if(typeof t=="string"&&Oe(t))try{return e.machine.getStateNodeById(t)}catch{}const n=qe(t).slice();let r=e;for(;n.length;){const i=n.shift();if(!i.length)break;r=J(r,i)}return r}function Ce(e,t){if(typeof t=="string"){const i=e.states[t];if(!i)throw new Error(`State '${t}' does not exist on '${e.id}'`);return[e,i]}const n=Object.keys(t),r=n.map(i=>J(e,i)).filter(Boolean);return[e.machine.root,e].concat(r,n.reduce((i,o)=>{const s=J(e,o);if(!s)return i;const a=Ce(s,t[o]);return i.concat(a)},[]))}function Yn(e,t,n,r){const o=J(e,t).next(n,r);return!o||!o.length?e.next(n,r):o}function Xn(e,t,n,r){const i=Object.keys(t),o=J(e,i[0]),s=Ye(o,t[i[0]],n,r);return!s||!s.length?e.next(n,r):s}function Qn(e,t,n,r){const i=[];for(const o of Object.keys(t)){const s=t[o];if(!s)continue;const a=J(e,o),c=Ye(a,s,n,r);c&&i.push(...c)}return i.length?i:e.next(n,r)}function Ye(e,t,n,r){return typeof t=="string"?Yn(e,t,n,r):Object.keys(t).length===1?Xn(e,t,n,r):Qn(e,t,n,r)}function $n(e){return Object.keys(e.states).map(t=>e.states[t]).filter(t=>t.type==="history")}function q(e,t){let n=e;for(;n.parent&&n.parent!==t;)n=n.parent;return n.parent===t}function er(e,t){const n=new Set(e),r=new Set(t);for(const i of n)if(r.has(i))return!0;for(const i of r)if(n.has(i))return!0;return!1}function Ot(e,t,n){const r=new Set;for(const i of e){let o=!1;const s=new Set;for(const a of r)if(er(Qe([i],t,n),Qe([a],t,n)))if(q(i.source,a.source))s.add(a);else{o=!0;break}if(!o){for(const a of s)r.delete(a);r.add(i)}}return Array.from(r)}function tr(e){const[t,...n]=e;for(const r of re(t,void 0))if(n.every(i=>q(i,r)))return r}function Xe(e,t){if(!e.target)return[];const n=new Set;for(const r of e.target)if(H(r))if(t[r.id])for(const i of t[r.id])n.add(i);else for(const i of Xe(Et(r),t))n.add(i);else n.add(r);return[...n]}function Ft(e,t){const n=Xe(e,t);if(!n)return;if(!e.reenter&&n.every(i=>i===e.source||q(i,e.source)))return e.source;const r=tr(n.concat(e.source));if(r)return r;if(!e.reenter)return e.source.machine.root}function Qe(e,t,n){const r=new Set;for(const i of e)if(i.target?.length){const o=Ft(i,n);i.reenter&&i.source===o&&r.add(o);for(const s of t)q(s,o)&&r.add(s)}return[...r]}function nr(e,t){if(e.length!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function $e(e,t,n,r,i,o){if(!e.length)return t;const s=new Set(t._nodes);let a=t.historyValue;const c=Ot(e,s,a);let u=t;i||([u,a]=or(u,r,n,c,s,a,o,n.actionExecutor)),u=Y(u,r,n,c.flatMap(l=>l.actions),o,void 0),u=sr(u,r,n,c,s,o,a,i);const f=[...s];u.status==="done"&&(u=Y(u,r,n,f.sort((l,d)=>d.order-l.order).flatMap(l=>l.exit),o,void 0));try{return a===t.historyValue&&nr(t._nodes,s)?u:U(u,{_nodes:f,historyValue:a})}catch(l){throw l}}function rr(e,t,n,r,i){if(r.output===void 0)return;const o=xe(i.id,i.output!==void 0&&i.parent?We(i.output,e.context,t,n.self):void 0);return We(r.output,e.context,o,n.self)}function sr(e,t,n,r,i,o,s,a){let c=e;const u=new Set,f=new Set;ir(r,s,f,u),a&&f.add(e.machine.root);const l=new Set;for(const d of[...u].sort((p,g)=>p.order-g.order)){i.add(d);const p=[];p.push(...d.entry);for(const g of d.invoke)p.push(ze(g.src,{...g,syncSnapshot:!!g.onSnapshot}));if(f.has(d)){const g=d.initial.actions;p.push(...g)}if(c=Y(c,t,n,p,o,d.invoke.map(g=>g.id)),d.type==="final"){const g=d.parent;let y=g?.type==="parallel"?g:g?.parent,I=y||d;for(g?.type==="compound"&&o.push(xe(g.id,d.output!==void 0?We(d.output,c.context,t,n.self):void 0));y?.type==="parallel"&&!l.has(y)&&Ze(i,y);)l.add(y),o.push(xe(y.id)),I=y,y=y.parent;if(y)continue;c=U(c,{status:"done",output:rr(c,t,n,c.machine.root,I)})}}return c}function ir(e,t,n,r){for(const i of e){const o=Ft(i,t);for(const a of i.target||[])!H(a)&&(i.source!==a||i.source!==o||i.reenter)&&(r.add(a),n.add(a)),Z(a,t,n,r);const s=Xe(i,t);for(const a of s){const c=re(a,o);o?.type==="parallel"&&c.push(o),Ct(r,t,n,c,!i.source.parent&&i.reenter?void 0:o)}}}function Z(e,t,n,r){if(H(e))if(t[e.id]){const i=t[e.id];for(const o of i)r.add(o),Z(o,t,n,r);for(const o of i)et(o,e.parent,r,t,n)}else{const i=Et(e);for(const o of i.target)r.add(o),i===e.parent?.initial&&n.add(e.parent),Z(o,t,n,r);for(const o of i.target)et(o,e.parent,r,t,n)}else if(e.type==="compound"){const[i]=e.initial.target;H(i)||(r.add(i),n.add(i)),Z(i,t,n,r),et(i,e,r,t,n)}else if(e.type==="parallel")for(const i of z(e).filter(o=>!H(o)))[...r].some(o=>q(o,i))||(H(i)||(r.add(i),n.add(i)),Z(i,t,n,r))}function Ct(e,t,n,r,i){for(const o of r)if((!i||q(o,i))&&e.add(o),o.type==="parallel")for(const s of z(o).filter(a=>!H(a)))[...e].some(a=>q(a,s))||(e.add(s),Z(s,t,n,e))}function et(e,t,n,r,i){Ct(n,r,i,re(e,t))}function or(e,t,n,r,i,o,s,a){let c=e;const u=Qe(r,i,o);u.sort((l,d)=>d.order-l.order);let f;for(const l of u)for(const d of $n(l)){let p;d.history==="deep"?p=g=>Je(g)&&q(g,l):p=g=>g.parent===l,f??={...o},f[d.id]=Array.from(i).filter(p)}for(const l of u)c=Y(c,t,n,[...l.exit,...l.invoke.map(d=>Ee(d.id))],s,void 0),i.delete(l);return[c,f||o]}function ar(e,t){return e.implementations.actions[t]}function Nt(e,t,n,r,i,o){const{machine:s}=e;let a=e;for(const c of r){const u=typeof c=="function",f=u?c:ar(s,typeof c=="string"?c:c.type),l={context:a.context,event:t,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:t}):c.params:void 0;if(!f||!("resolve"in f)){n.actionExecutor({type:typeof c=="string"?c:typeof c=="object"?c.type:c.name||"(anonymous)",info:l,params:d,exec:f});continue}const p=f,[g,y,I]=p.resolve(n,a,l,d,f,i);a=g,"retryResolve"in p&&o?.push([p,y]),"execute"in p&&n.actionExecutor({type:p.type,info:l,params:y,exec:p.execute.bind(null,n,y)}),I&&(a=Nt(a,t,n,I,i,o))}return a}function Y(e,t,n,r,i,o){const s=o?[]:void 0,a=Nt(e,t,n,r,{internalQueue:i,deferredActorIds:o},s);return s?.forEach(([c,u])=>{c.retryResolve(n,a,u)}),a}function tt(e,t,n,r){let i=e;const o=[];function s(u,f,l){n.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:n.self,event:f,snapshot:u,_transitions:l}),o.push(u)}if(t.type===te)return i=U(Rt(i,t,n),{status:"stopped"}),s(i,t,[]),{snapshot:i,microstates:o};let a=t;if(a.type!==pt){const u=a,f=Nn(u),l=jt(u,i);if(f&&!l.length)return i=U(e,{status:"error",error:u.error}),s(i,u,[]),{snapshot:i,microstates:o};i=$e(l,e,n,a,!1,r),s(i,u,l)}let c=!0;for(;i.status==="active";){let u=c?cr(i,a):[];const f=u.length?i:void 0;if(!u.length){if(!r.length)break;a=r.shift(),u=jt(a,i)}i=$e(u,i,n,a,!1,r),c=i!==f,s(i,a,u)}return i.status!=="active"&&Rt(i,a,n),{snapshot:i,microstates:o}}function Rt(e,t,n){return Y(e,t,n,Object.values(e.children).map(r=>Ee(r)),[],void 0)}function jt(e,t){return t.machine.getTransitionData(t,e)}function cr(e,t){const n=new Set,r=e._nodes.filter(Je);for(const i of r)e:for(const o of[i].concat(re(i,void 0)))if(o.always){for(const s of o.always)if(s.guard===void 0||Ae(s.guard,e.context,t,e)){n.add(s);break e}}return Ot(Array.from(n),new Set(e._nodes),e.historyValue)}function ur(e,t){const n=Me(Ce(e,t));return Dt(e,[...n])}function dr(e){return!!e&&typeof e=="object"&&"machine"in e&&"value"in e}const fr=function(t){return mt(t,this.value)},lr=function(t){return this.tags.has(t)},hr=function(t){const n=this.machine.getTransitionData(this,t);return!!n?.length&&n.some(r=>r.target!==void 0||r.actions.length)},pr=function(){const{_nodes:t,tags:n,machine:r,getMeta:i,toJSON:o,can:s,hasTag:a,matches:c,...u}=this;return{...u,tags:Array.from(n)}},gr=function(){return this._nodes.reduce((t,n)=>(n.meta!==void 0&&(t[n.id]=n.meta),t),{})};function Ne(e,t){return{status:e.status,output:e.output,error:e.error,machine:t,context:e.context,_nodes:e._nodes,value:Dt(t.root,e._nodes),tags:new Set(e._nodes.flatMap(n=>n.tags)),children:e.children,historyValue:e.historyValue||{},matches:fr,hasTag:lr,can:hr,getMeta:gr,toJSON:pr}}function U(e,t={}){return Ne({...e,...t},e.machine)}function vr(e){if(typeof e!="object"||e===null)return{};const t={};for(const n in e){const r=e[n];Array.isArray(r)&&(t[n]=r.map(i=>({id:i.id})))}return t}function mr(e,t){const{_nodes:n,tags:r,machine:i,children:o,context:s,can:a,hasTag:c,matches:u,getMeta:f,toJSON:l,...d}=e,p={};for(const y in o){const I=o[y];p[y]={snapshot:I.getPersistedSnapshot(t),src:I.src,systemId:I.systemId,syncSnapshot:I._syncSnapshot}}return{...d,context:Gt(s),children:p,historyValue:vr(d.historyValue)}}function Gt(e){let t;for(const n in e){const r=e[n];if(r&&typeof r=="object")if("sessionId"in r&&"send"in r&&"ref"in r)t??=Array.isArray(e)?e.slice():{...e},t[n]={xstate$$type:Ve,id:r.id};else{const i=Gt(r);i!==r&&(t??=Array.isArray(e)?e.slice():{...e},t[n]=i)}}return t??e}function yr(e,t,n,r,{event:i,id:o,delay:s},{internalQueue:a}){const 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`);const u=typeof i=="function"?i(n,r):i;let f;if(typeof s=="string"){const l=c&&c[s];f=typeof l=="function"?l(n,r):l}else f=typeof s=="function"?s(n,r):s;return typeof f!="number"&&a.push(u),[t,{event:u,id:o,delay:f},void 0]}function Sr(e,t){const{event:n,delay:r,id:i}=t;if(typeof r=="number"){e.defer(()=>{const o=e.self;e.system.scheduler.schedule(o,o,n,r,i)});return}}function nt(e,t){function n(r,i){}return n.type="xstate.raise",n.event=e,n.id=t?.id,n.delay=t?.delay,n.resolve=yr,n.execute=Sr,n}const Lt=new WeakMap;function _r(e){return{config:e,start:(n,r)=>{const{self:i,system:o,emit:s}=r,a={receivers:void 0,dispose:void 0};Lt.set(i,a),a.dispose=e({input:n.input,system:o,self:i,sendBack:c=>{i.getSnapshot().status!=="stopped"&&i._parent&&o._relay(i,i._parent,c)},receive:c=>{a.receivers??=new Set,a.receivers.add(c)},emit:s})},transition:(n,r,i)=>{const o=Lt.get(i.self);return r.type===te?(n={...n,status:"stopped",error:void 0},o.dispose?.(),n):(o.receivers?.forEach(s=>s(r)),n)},getInitialSnapshot:(n,r)=>({status:"active",output:void 0,error:void 0,input:r}),getPersistedSnapshot:n=>n,restoreSnapshot:n=>n}}const xt="xstate.promise.resolve",qt="xstate.promise.reject",Re=new WeakMap;function Wt(e){return{config:e,transition:(n,r,i)=>{if(n.status!=="active")return n;switch(r.type){case xt:{const o=r.data;return{...n,status:"done",output:o,input:void 0}}case qt:return{...n,status:"error",error:r.data,input:void 0};case te:return Re.get(i.self)?.abort(),{...n,status:"stopped",input:void 0};default:return n}},start:(n,{self:r,system:i,emit:o})=>{if(n.status!=="active")return;const s=new AbortController;Re.set(r,s),Promise.resolve(e({input:n.input,system:i,self:r,signal:s.signal,emit:o})).then(c=>{r.getSnapshot().status==="active"&&(Re.delete(r),i._relay(r,r,{type:xt,data:c}))},c=>{r.getSnapshot().status==="active"&&(Re.delete(r),i._relay(r,r,{type:qt,data:c}))})},getInitialSnapshot:(n,r)=>({status:"active",output:void 0,error:void 0,input:r}),getPersistedSnapshot:n=>n,restoreSnapshot:n=>n}}function br(e,{machine:t,context:n},r,i){const o=(s,a)=>{if(typeof s=="string"){const c=He(t,s);if(!c)throw new Error(`Actor logic '${s}' not implemented in machine '${t.id}'`);const u=ne(c,{id:a?.id,parent:e.self,syncSnapshot:a?.syncSnapshot,input:typeof a?.input=="function"?a.input({context:n,event:r,self:e.self}):a?.input,src:s,systemId:a?.systemId});return i[u.id]=u,u}else return ne(s,{id:a?.id,parent:e.self,syncSnapshot:a?.syncSnapshot,input:a?.input,src:s,systemId:a?.systemId})};return(s,a)=>{const c=o(s,a);return i[c.id]=c,e.defer(()=>{c._processingStatus!==E.Stopped&&c.start()}),c}}function Tr(e,t,n,r,{assignment:i}){if(!t.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const o={},s={context:t.context,event:n.event,spawn:br(e,t,n.event,o),self:e.self,system:e.system};let a={};if(typeof i=="function")a=i(s,r);else for(const u of Object.keys(i)){const f=i[u];a[u]=typeof f=="function"?f(s,r):f}const c=Object.assign({},t.context,a);return[U(t,{context:c,children:Object.keys(o).length?{...t.children,...o}:t.children}),void 0,void 0]}function F(e){function t(n,r){}return t.type="xstate.assign",t.assignment=e,t.resolve=Tr,t}const Bt=new WeakMap;function X(e,t,n){let r=Bt.get(e);return r?t in r||(r[t]=n()):(r={[t]:n()},Bt.set(e,r)),r[t]}const Ir={},se=e=>typeof e=="string"?{type:e}:typeof e=="function"?"resolve"in e?{type:e.type}:{type:e.name}:e;class je{constructor(t,n){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=n._parent,this.key=n._key,this.machine=n._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(lt),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?St(this.config.states,(r,i)=>new je(r,{_parent:this,_key:i,_machine:this.machine})):Ir,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=x(this.config.entry).slice(),this.exit=x(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=x(t.tags).slice()}_initialize(){this.transitions=zn(this),this.config.always&&(this.always=K(this.config.always).map(t=>B(this,ht,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(se),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(se),eventType:null})}:void 0,history:this.history,states:St(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(se)})),entry:this.entry.map(se),exit:this.exit.map(se),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 X(this,"invoke",()=>x(this.config.invoke).map((t,n)=>{const{src:r,systemId:i}=t,o=t.id??It(this.id,n),s=typeof r=="string"?r:`xstate.invoke.${It(this.id,n)}`;return{...t,src:s,id:o,systemId:i,toJSON(){const{onDone:a,onError:c,...u}=t;return{...u,type:"xstate.invoke",src:s,id:o}}}}))}get on(){return X(this,"on",()=>[...this.transitions].flatMap(([n,r])=>r.map(i=>[n,i])).reduce((n,[r,i])=>(n[r]=n[r]||[],n[r].push(i),n),{}))}get after(){return X(this,"delayedTransitions",()=>Kn(this))}get initial(){return X(this,"initial",()=>Jn(this,this.config.initial))}next(t,n){const r=n.type,i=[];let o;const s=X(this,`candidates-${r}`,()=>Vn(this,r));for(const a of s){const{guard:c}=a,u=t.context;let f=!1;try{f=!c||Ae(c,u,n,t)}catch(l){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 '${r}' in state node '${this.id}':
3
3
  ${l.message}`)}if(f){i.push(...a.actions),o=a;break}}return o?[o]:void 0}get events(){return X(this,"events",()=>{const{states:t}=this,n=new Set(this.ownEvents);if(t)for(const r of Object.keys(t)){const i=t[r];if(i.states)for(const o of i.events)n.add(`${o}`)}return Array.from(n)})}get ownEvents(){const t=new Set([...this.transitions.keys()].filter(n=>this.transitions.get(n).some(r=>!(!r.target&&!r.actions.length&&!r.reenter))));return Array.from(t)}}const wr="#";class rt{constructor(t,n){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:n?.actors??{},actions:n?.actions??{},delays:n?.delays??{},guards:n?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new je(t,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:n,guards:r,actors:i,delays:o}=this.implementations;return new rt(this.config,{actions:{...n,...t.actions},guards:{...r,...t.guards},actors:{...i,...t.actors},delays:{...o,...t.delays}})}resolveState(t){const n=ur(this.root,t.value),r=Me(Ce(this.root,n));return Ne({_nodes:[...r],context:t.context||{},children:{},status:Ze(r,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,n,r){return tt(t,n,r,[]).snapshot}microstep(t,n,r){return tt(t,n,r,[]).microstates}getTransitionData(t,n){return Ye(this.root,t.value,t,n)||[]}getPreInitialState(t,n,r){const{context:i}=this.config,o=Ne({context:typeof i!="function"&&i?i:{},_nodes:[this.root],children:{},status:"active"},this);return typeof i=="function"?Y(o,n,t,[F(({spawn:a,event:c,self:u})=>i({spawn:a,input:c.input,self:u}))],r,void 0):o}getInitialSnapshot(t,n){const r=vt(n),i=[],o=this.getPreInitialState(t,r,i),s=$e([{target:[...Mt(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],o,t,r,!0,i),{snapshot:a}=tt(s,r,t,i);return a}start(t){Object.values(t.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(t){const n=qe(t),r=n.slice(1),i=Oe(n[0])?n[0].slice(wr.length):n[0],o=this.idMap.get(i);if(!o)throw new Error(`Child state node '#${i}' does not exist on machine '${this.id}'`);return Fe(o,r)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,n){return mr(t,n)}restoreSnapshot(t,n){const r={},i=t.children;Object.keys(i).forEach(l=>{const d=i[l],p=d.snapshot,g=d.src,y=typeof g=="string"?He(this,g):g;if(!y)return;const I=ne(y,{id:l,parent:n.self,syncSnapshot:d.syncSnapshot,snapshot:p,src:g,systemId:d.systemId});r[l]=I});function o(l,d){if(d instanceof je)return d;try{return l.machine.getStateNodeById(d.id)}catch{}}function s(l,d){if(!d||typeof d!="object")return{};const p={};for(const g in d){const y=d[g];for(const I of y){const N=o(l,I);N&&(p[g]??=[],p[g].push(N))}}return p}const a=s(this.root,t.historyValue),c=Ne({...t,children:r,_nodes:Array.from(Me(Ce(this.root,t.value))),historyValue:a},this),u=new Set;function f(l,d){if(!u.has(l)){u.add(l);for(const p in l){const g=l[p];if(g&&typeof g=="object"){if("xstate$$type"in g&&g.xstate$$type===Ve){l[p]=d[g.id];continue}f(g,d)}}}}return f(c.context,r),c}}function Pr(e,t,n,r,{event:i}){const o=typeof i=="function"?i(n,r):i;return[t,{event:o},void 0]}function kr(e,{event:t}){e.defer(()=>e.emit(t))}function Ht(e){function t(n,r){}return t.type="xstate.emit",t.event=e,t.resolve=Pr,t.execute=kr,t}let st=(function(e){return e.Parent="#_parent",e.Internal="#_internal",e})({});function Dr(e,t,n,r,{to:i,event:o,id:s,delay:a},c){const u=t.machine.implementations.delays;if(typeof o=="string")throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${o}" }) instead`);const f=typeof o=="function"?o(n,r):o;let l;if(typeof a=="string"){const g=u&&u[a];l=typeof g=="function"?g(n,r):g}else l=typeof a=="function"?a(n,r):a;const d=typeof i=="function"?i(n,r):i;let p;if(typeof d=="string"){if(d===st.Parent?p=e.self._parent:d===st.Internal?p=e.self:d.startsWith("#_")?p=t.children[d.slice(2)]:p=c.deferredActorIds?.includes(d)?d:t.children[d],!p)throw new Error(`Unable to send event to actor '${d}' from machine '${t.machine.id}'.`)}else p=d||e.self;return[t,{to:p,targetId:typeof d=="string"?d:void 0,event:f,id:s,delay:l},void 0]}function Er(e,t,n){typeof n.to=="string"&&(n.to=t.children[n.to])}function Ar(e,t){e.defer(()=>{const{to:n,event:r,delay:i,id:o}=t;if(typeof i=="number"){e.system.scheduler.schedule(e.self,n,r,i,o);return}e.system._relay(e.self,n,r.type===An?gt(e.self.id,r.data):r)})}function Ge(e,t,n){function r(i,o){}return r.type="xstate.sendTo",r.to=e,r.event=t,r.id=n?.id,r.delay=n?.delay,r.resolve=Dr,r.retryResolve=Er,r.execute=Ar,r}function Mr(e,t){return Ge(st.Parent,e,t)}function Or(e,t,n,r,{collect:i}){const o=[],s=function(c){o.push(c)};return s.assign=(...a)=>{o.push(F(...a))},s.cancel=(...a)=>{o.push(Ke(...a))},s.raise=(...a)=>{o.push(nt(...a))},s.sendTo=(...a)=>{o.push(Ge(...a))},s.sendParent=(...a)=>{o.push(Mr(...a))},s.spawnChild=(...a)=>{o.push(ze(...a))},s.stopChild=(...a)=>{o.push(Ee(...a))},s.emit=(...a)=>{o.push(Ht(...a))},i({context:n.context,event:n.event,enqueue:s,check:a=>Ae(a,t.context,n.event,t),self:e.self,system:e.system},r),[t,void 0,o]}function Fr(e){function t(n,r){}return t.type="xstate.enqueueActions",t.collect=e,t.resolve=Or,t}function Cr(e,t,n,r,{value:i,label:o}){return[t,{value:typeof i=="function"?i(n,r):i,label:o},void 0]}function Nr({logger:e},{value:t,label:n}){n?e(n,t):e(t)}function Rr(e=({context:n,event:r})=>({context:n,event:r}),t){function n(r,i){}return n.type="xstate.log",n.value=e,n.label=t,n.resolve=Cr,n.execute=Nr,n}function jr(e,t){return new rt(e,t)}function Ut({schemas:e,actors:t,actions:n,guards:r,delays:i}){return{assign:F,sendTo:Ge,raise:nt,log:Rr,cancel:Ke,stopChild:Ee,enqueueActions:Fr,emit:Ht,spawnChild:ze,createStateConfig:o=>o,createAction:o=>o,createMachine:o=>jr({...o,schemas:e},{actors:t,actions:n,guards:r,delays:i}),extend:o=>Ut({schemas:e,actors:t,actions:{...n,...o.actions},guards:{...r,...o.guards},delays:{...i,...o.delays}})}}class Vt{actor;subscription=null;options;constructor(t,n){this.options=n,this.actor=ne(t),this.setupSubscriptions(),n?.enableLogging!==void 0&&this.setLogging(n.enableLogging),n?.baudRate!==void 0&&this.setBaudRate(n.baudRate),this.actor.start()}setupSubscriptions(){this.subscription=this.actor.subscribe(t=>{if(this.options?.onData&&t.context.data!==void 0&&this.options.onData(t.context.data),this.options?.onStateChange){const n=t.value==="connected";this.options.onStateChange(n)}this.options?.onError&&t.context.error&&this.options.onError(t.context.error)})}get data(){return this.actor.getSnapshot().context.data}get isConnected(){return this.actor.getSnapshot().value==="connected"}get isConnecting(){return this.actor.getSnapshot().value==="connecting"}get error(){return this.actor.getSnapshot().context.error}connect(){this.actor.send({type:"CONNECT"})}disconnect(){this.actor.send({type:"DISCONNECT"})}setLogging(t){this.actor.send({type:"SET_LOGGING",enabled:t})}setBaudRate(t){this.actor.send({type:"SET_BAUD_RATE",baudRate:t})}get machine(){return this.actor}dispose(){this.subscription&&(this.subscription.unsubscribe(),this.subscription=null),this.actor.stop()}}var O={},ie={},b={},Kt;function P(){if(Kt)return b;Kt=1,Object.defineProperty(b,"__esModule",{value:!0});var e=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];function t(h){var v=h>>4&15,m=h>>0&15;return e[v]+e[m]}b.toHexString=t;function n(h,v,m){for(var S=typeof h=="string"?h:h.toFixed(0);S.length<v;)S=m+S;return S}b.padLeft=n;function r(h){var v=h.split("*"),m=v[0],S=v[1],D=i(m),M=parseInt(S,16);return D===M}b.validNmeaChecksum=r;function i(h){for(var v=h.charCodeAt(1),m=2;m<h.length;m+=1)v=v^h.charCodeAt(m);return v=v&255,v}b.computeNmeaChecksum=i;function o(h){return"*"+t(i(h))}b.createNmeaChecksumFooter=o;function s(h){return h+o(h)}b.appendChecksumFooter=s;function a(h,v){return h===void 0?"":h.toFixed(v)}b.encodeFixed=a;function c(h){if(h===void 0)return",";var v;h<0?(v="S",h=-h):v="N";var m=Math.floor(h),S=n(m,2,"0"),D=h-m,M=D*60,j=n(M.toFixed(6),9,"0");return S=S+j+","+v,S}b.encodeLatitude=c;function u(h){if(h===void 0)return",";var v;h<0?(v="W",h=-h):v="E";var m=Math.floor(h),S=n(m,3,"0"),D=h-m,M=D*60,j=n(M.toFixed(6),9,"0");return S=S+j+","+v,S}b.encodeLongitude=u;function f(h){return h===void 0?",":h.toFixed(1)+",M"}b.encodeAltitude=f;function l(h){return h===void 0?"":h.toFixed(1)}b.encodeAltitudeNoUnits=l;function d(h){return h===void 0?",":h.toFixed(1)+",M"}b.encodeGeoidalSeperation=d;function p(h){return h===void 0?"":h.toFixed(1)}b.encodeGeoidalSeperationNoUnits=p;function g(h){return h===void 0?"":n(h.toFixed(2),6,"0")}b.encodeDegrees=g;function y(h){if(h===void 0)return"";var v=h.getUTCFullYear(),m=h.getUTCMonth()+1,S=h.getUTCDate();return n(S,2,"0")+n(m,2,"0")+v.toFixed(0).substr(2)}b.encodeDate=y;function I(h){if(h===void 0)return"";var v=h.getUTCHours(),m=h.getUTCMinutes(),S=h.getUTCSeconds();return n(v,2,"0")+n(m,2,"0")+n(S,2,"0")}b.encodeTime=I;function N(h){return h===void 0?"":h.toString()}b.encodeValue=N;function R(h){return h===""?0:parseFloat(h)}b.parseFloatSafe=R;function Q(h){return h===""?0:parseInt(h,10)}b.parseIntSafe=Q;function ot(h){if(h===void 0)return"";var v=parseFloat(h);return v===NaN?h:v}b.parseNumberOrString=ot;function De(h){var v=h.indexOf(".");if(v<0)return 0;var m,S;return v>=3?(m=h.substring(0,v-2),S=h.substring(v-2)):(m="0",S=h),parseFloat(m)+parseFloat(S)/60}b.parseDmCoordinate=De;function at(h,v){var m=v==="N"?1:-1;return De(h)*m}b.parseLatitude=at;function ct(h,v){var m=v==="E"?1:-1;return De(h)*m}b.parseLongitude=ct;function ut(h,v){if(h==="")return new Date(0);var m=new Date;if(v){var S=v.slice(4),D=parseInt(v.slice(2,4),10)-1,M=v.slice(0,2);S.length===4?m.setUTCFullYear(Number(S),Number(D),Number(M)):m.setUTCFullYear(+("20"+S),Number(D),Number(M))}m.setUTCHours(Number(h.slice(0,2))),m.setUTCMinutes(Number(h.slice(2,4))),m.setUTCSeconds(Number(h.slice(4,6)));var j=h.slice(7),$=j.length,V=0;return $!==0&&(V=parseFloat(j)*Math.pow(10,3-$)),m.setUTCMilliseconds(Number(V)),m}b.parseTime=ut;function dt(h,v){var m=parseInt(h.slice(0,2),10),S=parseInt(h.slice(2,4),10),D=parseInt(h.slice(4,6),10);D<73?D=D+2e3:D=D+1900;var M=parseInt(v.slice(0,2),10),j=parseInt(v.slice(2,4),10),$=parseInt(v.slice(4,6),10),V=0;return v.length===9&&(V=parseInt(v.slice(7,9),10)*10),new Date(Date.UTC(D,S-1,m,M,j,$,V))}return b.parseDatetime=dt,b}var oe={},zt;function w(){if(zt)return oe;zt=1,Object.defineProperty(oe,"__esModule",{value:!0});function e(n,r,i){return{sentenceId:r,talkerId:n.talkerId,chxOk:n.chxOk,sentenceName:i}}oe.initStubFields=e;function t(n,r){var i,o;return n.charAt(1)==="P"?(i="P",o=n.substr(2)):(i=n.substr(1,2),o=n.substr(3)),{talkerId:i,sentenceId:o,chxOk:r||void 0}}return oe.parseStub=t,oe}var Jt;function Gr(){return Jt||(Jt=1,(function(e){var t=ie&&ie.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="APB",e.sentenceName='Autopilot sentence "B"';function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{status1:s[1],status2:s[2],xteMagn:n.parseFloatSafe(s[3]),steerDir:s[4],xteUnit:s[5],arrivalCircleStatus:s[6],arrivalPerpendicularStatus:s[7],bearingOrig2Dest:n.parseFloatSafe(s[8]),bearingOrig2DestType:s[9],waypoint:s[10],bearing2Dest:n.parseFloatSafe(s[11]),bearingDestType:s[12],heading2steer:n.parseFloatSafe(s[13]),headingDestType:s[14]})}e.decodeSentence=i})(ie)),ie}var ae={},Zt;function Lr(){return Zt||(Zt=1,(function(e){var t=ae&&ae.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="BWC",e.sentenceName="Bearing and distance to waypoint - great circle";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{time:n.parseTime(s[1]),bearingLatitude:n.parseLatitude(s[2],s[3]),bearingLongitude:n.parseLongitude(s[4],s[5]),bearingTrue:n.parseFloatSafe(s[6]),bearingMagnetic:n.parseFloatSafe(s[8]),distanceNm:n.parseFloatSafe(s[10]),waypointId:s[12],faaMode:s[13]})}e.decodeSentence=i})(ae)),ae}var ce={},Yt;function xr(){return Yt||(Yt=1,(function(e){var t=ce&&ce.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="DBT",e.sentenceName="Depth below transducer";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{depthFeet:n.parseFloatSafe(a[1]),depthMeters:n.parseFloatSafe(a[3]),depthFathoms:n.parseFloatSafe(a[5])})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeFixed(s.depthFeet,2)),c.push("f"),c.push(n.encodeFixed(s.depthMeters,2)),c.push("M"),c.push(n.encodeFixed(s.depthFathoms,2)),c.push("F");var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(ce)),ce}var ue={},Xt;function qr(){return Xt||(Xt=1,(function(e){var t=ue&&ue.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="DTM",e.sentenceName="Datum reference";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{datumCode:o(a[1]),datumSubcode:a[2]||void 0,offsetLatitude:n.parseLatitude(a[3],a[4]),offsetLongitude:n.parseLongitude(a[5],a[6]),offsetAltitudeMeters:n.parseFloatSafe(a[7]),datumName:o(a[8])})}e.decodeSentence=i;function o(s){return s==="W84"?"W84":s==="W72"?"W72":s==="S85"?"S85":s==="P90"?"P90":s==="999"?"999":""}})(ue)),ue}var de={},Qt;function Wr(){return Qt||(Qt=1,(function(e){var t=de&&de.__assign||function(){return t=Object.assign||function(a){for(var c,u=1,f=arguments.length;u<f;u++){c=arguments[u];for(var l in c)Object.prototype.hasOwnProperty.call(c,l)&&(a[l]=c[l])}return a},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GGA",e.sentenceName="Global positioning system fix data";var i=["none","fix","delta","pps","rtk","frtk","estimated","manual","simulation"];function o(a,c){return t(t({},r.initStubFields(a,e.sentenceId,e.sentenceName)),{time:n.parseTime(c[1]),latitude:n.parseLatitude(c[2],c[3]),longitude:n.parseLongitude(c[4],c[5]),fixType:i[n.parseIntSafe(c[6])],satellitesInView:n.parseIntSafe(c[7]),horizontalDilution:n.parseFloatSafe(c[8]),altitudeMeters:n.parseFloatSafe(c[9]),geoidalSeperation:n.parseFloatSafe(c[11]),differentialAge:n.parseFloatSafe(c[13]),differentialRefStn:c[14]})}e.decodeSentence=o;function s(a,c){var u=["$"+c+e.sentenceId];u.push(n.encodeTime(a.time)),u.push(n.encodeLatitude(a.latitude)),u.push(n.encodeLongitude(a.longitude)),u.push(n.encodeValue(i.indexOf(a.fixType))),u.push(n.encodeValue(a.satellitesInView)),u.push(n.encodeFixed(a.horizontalDilution,1)),u.push(n.encodeAltitude(a.altitudeMeters)),u.push(n.encodeGeoidalSeperation(a.geoidalSeperation)),u.push(n.encodeFixed(a.differentialAge,2)),u.push(n.encodeValue(a.differentialRefStn));var f=u.join(",");return f+n.createNmeaChecksumFooter(f)}e.encodePacket=s})(de)),de}var fe={},$t;function Br(){return $t||($t=1,(function(e){var t=fe&&fe.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GLL",e.sentenceName="Geographic position - latitude and longitude";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{latitude:n.parseLatitude(a[1],a[2]),longitude:n.parseLongitude(a[3],a[4]),time:n.parseTime(a[5]),status:a[6]==="A"?"valid":"invalid",faaMode:a[7]})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeLatitude(s.latitude)),c.push(n.encodeLongitude(s.longitude)),c.push(n.encodeTime(s.time)),c.push(s.status==="valid"?"A":"V"),s.faaMode&&c.push(s.faaMode);var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(fe)),fe}var le={},en;function Hr(){return en||(en=1,(function(e){var t=le&&le.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GNS",e.sentenceName="GNSS fix data";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{time:n.parseTime(a[1]),latitude:n.parseLatitude(a[2],a[3]),longitude:n.parseLongitude(a[4],a[5]),modeIndicator:a[6],satellitesInView:n.parseIntSafe(a[7]),horizontalDilution:n.parseFloatSafe(a[8]),altitudeMeters:n.parseFloatSafe(a[9]),geoidalSeperation:n.parseFloatSafe(a[10]),differentialAge:n.parseFloatSafe(a[11]),differentialRefStn:a[12]})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeTime(s.time)),c.push(n.encodeLatitude(s.latitude)),c.push(n.encodeLongitude(s.longitude)),c.push(s.modeIndicator),c.push(n.encodeValue(s.satellitesInView)),c.push(n.encodeFixed(s.horizontalDilution,1)),c.push(n.encodeAltitudeNoUnits(s.altitudeMeters)),c.push(n.encodeGeoidalSeperationNoUnits(s.geoidalSeperation)),c.push(n.encodeFixed(s.differentialAge,2)),c.push(n.encodeValue(s.differentialRefStn));var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(le)),le}var he={},tn;function Ur(){return tn||(tn=1,(function(e){var t=he&&he.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GSA",e.sentenceName="Active satellites and dilution of precision";var i=["unknown","none","2D","3D"];function o(s,a){for(var c=[],u=3;u<15;u++)a[u]&&c.push(+a[u]);return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{selectionMode:a[1]==="A"?"automatic":"manual",fixMode:i[n.parseIntSafe(a[2])],satellites:c,PDOP:n.parseFloatSafe(a[15]),HDOP:n.parseFloatSafe(a[16]),VDOP:n.parseFloatSafe(a[17])})}e.decodeSentence=o})(he)),he}var pe={},nn;function Vr(){return nn||(nn=1,(function(e){var t=pe&&pe.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GST",e.sentenceName="GPS pseudorange noise statistics";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{time:n.parseTime(s[1]),totalRms:n.parseFloatSafe(s[2]),semiMajorError:n.parseFloatSafe(s[3]),semiMinorError:n.parseFloatSafe(s[4]),orientationOfSemiMajorError:n.parseFloatSafe(s[5]),latitudeError:n.parseFloatSafe(s[6]),longitudeError:n.parseFloatSafe(s[7]),altitudeError:n.parseFloatSafe(s[8])})}e.decodeSentence=i})(pe)),pe}var ge={},rn;function Kr(){return rn||(rn=1,(function(e){var t=ge&&ge.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GSV",e.sentenceName="Satellites in view";function i(o,s){for(var a=(s.length-4)/4,c=[],u=0;u<a;u++){var f=u*4+4;c.push({prnNumber:n.parseIntSafe(s[f]),elevationDegrees:n.parseIntSafe(s[f+1]),azimuthTrue:n.parseIntSafe(s[f+2]),SNRdB:n.parseIntSafe(s[f+3])})}return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{numberOfMessages:n.parseIntSafe(s[1]),messageNumber:n.parseIntSafe(s[2]),satellitesInView:n.parseIntSafe(s[3]),satellites:c})}e.decodeSentence=i})(ge)),ge}var ve={},sn;function zr(){return sn||(sn=1,(function(e){var t=ve&&ve.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="HDG",e.sentenceName="Heading - deviation and variation";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{heading:n.parseFloatSafe(s[1]),deviation:n.parseFloatSafe(s[2]),deviationDirection:s[3]==="E"?"E":s[3]==="W"?"W":"",variation:n.parseFloatSafe(s[4]),variationDirection:s[5]==="E"?"E":s[5]==="W"?"W":""})}e.decodeSentence=i})(ve)),ve}var me={},on;function Jr(){return on||(on=1,(function(e){var t=me&&me.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="HDM",e.sentenceName="Heading - magnetic";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{heading:n.parseFloatSafe(a[1])})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeFixed(s.heading,1)),c.push("M");var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(me)),me}var ye={},an;function Zr(){return an||(an=1,(function(e){var t=ye&&ye.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="HDT",e.sentenceName="Heading - true";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{heading:n.parseFloatSafe(a[1])})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeFixed(s.heading,1)),c.push("T");var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(ye)),ye}var Se={},cn;function Yr(){return cn||(cn=1,(function(e){var t=Se&&Se.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="MTK",e.sentenceName="Configuration packet";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{packetType:n.parseIntSafe(s.sentenceId.substr(3)),data:a.slice(1).map(n.parseNumberOrString)})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId+n.padLeft(s.packetType,3,"0")];c=c.concat(s.data.toString());var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(Se)),Se}var _e={},un;function Xr(){return un||(un=1,(function(e){var t=_e&&_e.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="MWV",e.sentenceName="Wind speed and angle";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{windAngle:n.parseFloatSafe(a[1]),reference:a[2]==="R"?"relative":"true",speed:n.parseFloatSafe(a[3]),units:a[4]==="K"?"K":a[4]==="M"?"M":"N",status:a[5]==="A"?"valid":"invalid"})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeDegrees(s.windAngle)),c.push(s.reference==="relative"?"R":"T"),c.push(n.encodeFixed(s.speed,2)),c.push(s.units==="K"?"K":s.units==="M"?"M":"N"),c.push(s.status==="valid"?"A":"V");var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(_e)),_e}var be={},dn;function Qr(){return dn||(dn=1,(function(e){var t=be&&be.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="RDID",e.sentenceName="RDI proprietary heading, pitch, and roll";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{roll:n.parseFloatSafe(s[1]),pitch:n.parseFloatSafe(s[2]),heading:n.parseFloatSafe(s[3])})}e.decodeSentence=i})(be)),be}var Te={},fn;function $r(){return fn||(fn=1,(function(e){var t=Te&&Te.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="RMC",e.sentenceName="Recommended minimum navigation information";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{datetime:n.parseDatetime(s[9],s[1]),status:s[2]==="A"?"valid":"warning",latitude:n.parseLatitude(s[3],s[4]),longitude:n.parseLongitude(s[5],s[6]),speedKnots:n.parseFloatSafe(s[7]),trackTrue:n.parseFloatSafe(s[8]),variation:n.parseFloatSafe(s[10]),variationPole:s[11]==="E"?"E":s[11]==="W"?"W":"",faaMode:s[12]})}e.decodeSentence=i})(Te)),Te}var Ie={},ln;function es(){return ln||(ln=1,(function(e){var t=Ie&&Ie.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="VHW",e.sentenceName="Water speed and heading";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{degreesTrue:n.parseFloatSafe(s[1]),degreesMagnetic:n.parseFloatSafe(s[3]),speedKnots:n.parseFloatSafe(s[5]),speedKmph:n.parseFloatSafe(s[7])})}e.decodeSentence=i})(Ie)),Ie}var we={},hn;function ts(){return hn||(hn=1,(function(e){var t=we&&we.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="VTG",e.sentenceName="Track made good and ground speed";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{trackTrue:n.parseFloatSafe(a[1]),trackMagnetic:n.parseFloatSafe(a[3]),speedKnots:n.parseFloatSafe(a[5]),speedKmph:n.parseFloatSafe(a[7]),faaMode:a[9]})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeDegrees(s.trackTrue)),c.push("T"),c.push(n.encodeDegrees(s.trackMagnetic)),c.push("M"),c.push(n.encodeFixed(s.speedKnots,2)),c.push("N"),s.speedKmph?(c.push(n.encodeFixed(s.speedKmph,2)),c.push("K")):(c.push(""),c.push("")),s.faaMode&&c.push(s.faaMode);var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(we)),we}var Pe={},pn;function ns(){return pn||(pn=1,(function(e){var t=Pe&&Pe.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="ZDA",e.sentenceName="UTC, day, month, year, and local time zone";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{datetime:n.parseTime(s[1],s.slice(2,5).join("")),localZoneHours:n.parseIntSafe(s[5]),localZoneMinutes:n.parseIntSafe(s[6])})}e.decodeSentence=i})(Pe)),Pe}var ke={},gn;function vn(){return gn||(gn=1,(function(e){var t=ke&&ke.__assign||function(){return t=Object.assign||function(i){for(var o,s=1,a=arguments.length;s<a;s++){o=arguments[s];for(var c in o)Object.prototype.hasOwnProperty.call(o,c)&&(i[c]=o[c])}return i},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=w();e.sentenceId="?";function r(i,o){return t(t({},n.initStubFields(i,e.sentenceId)),{originalPacketId:i.sentenceId,dataFields:o.slice(1)})}e.decodeSentence=r})(ke)),ke}var mn;function rs(){if(mn)return O;mn=1;var e=O&&O.__extends||(function(){var _=function(T,k){return _=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(A,W){A.__proto__=W}||function(A,W){for(var ee in W)W.hasOwnProperty(ee)&&(A[ee]=W[ee])},_(T,k)};return function(T,k){_(T,k);function A(){this.constructor=T}T.prototype=k===null?Object.create(k):(A.prototype=k.prototype,new A)}})();Object.defineProperty(O,"__esModule",{value:!0});var t=Gr(),n=Lr(),r=xr(),i=qr(),o=Wr(),s=Br(),a=Hr(),c=Ur(),u=Vr(),f=Kr(),l=zr(),d=Jr(),p=Zr(),g=Yr(),y=Xr(),I=Qr(),N=$r(),R=es(),Q=ts(),ot=ns(),De=w(),at=vn(),ct=P(),ut={APB:t.decodeSentence,BWC:n.decodeSentence,DBT:r.decodeSentence,DTM:i.decodeSentence,GGA:o.decodeSentence,GLL:s.decodeSentence,GNS:a.decodeSentence,GSA:c.decodeSentence,GST:u.decodeSentence,GSV:f.decodeSentence,HDG:l.decodeSentence,HDM:d.decodeSentence,HDT:p.decodeSentence,MTK:g.decodeSentence,MWV:y.decodeSentence,RDID:I.decodeSentence,RMC:N.decodeSentence,VHW:R.decodeSentence,VTG:Q.decodeSentence,ZDA:ot.decodeSentence},dt={DBT:r.encodePacket,GGA:o.encodePacket,GLL:s.encodePacket,GNS:a.encodePacket,HDM:d.encodePacket,HDT:p.encodePacket,MTK:g.encodePacket,MWV:y.encodePacket,VTG:Q.encodePacket},h=(function(){function _(T){T===void 0&&(T=!1),this.ableToParseBadChecksum=T}return _.getParser=function(T){return T.sentenceId.substr(0,3)==="MTK"?g.decodeSentence:ut[T.sentenceId]},_.prototype.assemble=function(T,k){var A=_.getParser(T);return A?A(T,k):this.assembleCustomPacket(T,k)},_.prototype.assembleCustomPacket=function(T,k){return null},_})();O.DefaultPacketFactory=h;var v=new h;function m(_,T){var k=!0;if(!ct.validNmeaChecksum(_)){if(!T.ableToParseBadChecksum)throw Error('Invalid sentence: "'+_+'".');k=!1}var A=_.split("*")[0].split(","),W=De.parseStub(A[0],k),ee=T.assemble(W,A);if(!ee)throw Error('No known parser for sentence ID "'+W.sentenceId+'".');return ee}O.parseGenericPacket=m;function S(_){return m(_,v)}O.parseNmeaSentence=S;function D(_,T){if(T===void 0&&(T="P"),_===void 0)throw new Error("Packet must be given.");var k=dt[_.sentenceId];if(k)return k(_,T);throw Error('No known encoder for sentence ID "'+_.sentenceId+'"')}O.encodeNmeaPacket=D;var M=(function(_){e(T,_);function T(){return _.call(this,!0)||this}return T.prototype.assembleCustomPacket=function(k,A){return at.decodeSentence(k,A)},T})(h);O.UnsafePacketFactory=M;var j=new M;function $(_){return m(_,j)}O.parseUnsafeNmeaSentence=$;function V(_){return _.sentenceId==="?"?_.originalPacketId:_.sentenceId}return O.getUnsafePacketId=V,O}var Le=rs(),ss=vn(),it=w();function G(e){return e===""?0:Number.parseFloat(e)}const is="DBK",os="Depth Below Keel";function as(e,t){return{...it.initStubFields(e,is,os),depthFeet:G(t[1]),depthMeters:G(t[3]),depthFathoms:G(t[5])}}const cs="DBS",us="Depth Below Surface";function ds(e,t){return{...it.initStubFields(e,cs,us),depthFeet:G(t[1]),depthMeters:G(t[3]),depthFathoms:G(t[5])}}const fs="DPT",ls="Depth of Water";function hs(e,t){return{...it.initStubFields(e,fs,ls),depthMeters:G(t[1]),offsetMeters:G(t[2]),maximumRangeScale:G(t[3])}}function yn(e,t){switch(e.talkerId){case"DBS":return ds(e,t);case"DBK":return as(e,t);case"DPT":return hs(e,t);default:return null}}class ps extends Le.DefaultPacketFactory{assembleCustomPacket(t,n){return yn(t,n)}}const gs=new ps;function vs(e){return Le.parseGenericPacket(e,gs)}class ms extends Le.DefaultPacketFactory{constructor(){super(!0)}assembleCustomPacket(t,n){const r=yn(t,n);return r||ss.decodeSentence(t,n)}}const ys=new ms;function Sn(e){return Le.parseGenericPacket(e,ys)}function _n(e,t){return!t||t.length===0?!0:e!==void 0&&t.includes(e)}class Ss{container;constructor(){this.container=""}transform(t,n){this.container+=t;const r=this.container.split(`\r
4
- `),i=r.pop();this.container=i??"",r.forEach(o=>{o.length>0&&n.enqueue(o)})}flush(t){this.container=""}}const _s=Wt(async({input:e})=>{if(!navigator.serial)throw new Error("Web Serial API is not supported in this browser.");console.log("Requesting serial port...");const t=await navigator.serial.requestPort();if(console.log(`Opening port at ${e.baudRate} baud...`),t.readable||t.writable){console.log("Port is already open, closing first...");try{await t.close()}catch(n){console.warn("Error closing already-open port:",n)}}return await t.open({baudRate:e.baudRate}),console.log("Port open."),t}),bs=Wt(async({input:e})=>{if(e.port)try{(e.port.readable||e.port.writable)&&(await e.port.close(),console.log("Port closed successfully."))}catch(t){console.warn("Error closing port:",t)}}),Ts=_r(({input:e,sendBack:t,receive:n})=>{const{port:r}=e;if(!r||!r.readable){t({type:"SERIAL.ERROR",error:"Invalid port context."});return}const i=new Ss,s=r.readable.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform:i.transform.bind(i),flush:i.flush.bind(i)})).getReader();let a=!0;async function c(){try{for(;a;){const{value:u,done:f}=await s.read();if(f)break;if(u&&u.length>0)try{const l=Sn(u);if(l.sentenceId==="?")continue;t({type:"SERIAL.DATA",data:l})}catch(l){const d=l instanceof Error?l.message:String(l);console.warn("Failed to parse NMEA sentence:",u,d),t({type:"SERIAL.ERROR",error:`Parser Error: ${d}`})}}}catch(u){if(console.error("Read loop error:",u),a){const f=u instanceof Error?u.message:String(u);t({type:"FATAL_ERROR",error:f})}}finally{console.log("Read loop finished."),t({type:"SERIAL.DISCONNECTED"})}}return c(),n(u=>{u.type==="STOP"&&(console.log("Received STOP, cancelling reader..."),a=!1,s.cancel().catch(()=>{}))}),()=>{console.log("Cleaning up stream reader actor..."),a=!1,s&&s.cancel().catch(()=>{})}});function bn(e){const{adapter:t,allowedSentenceIds:n,initialData:r,initialPackets:i}=e;return Ut({actors:{connectToSerial:_s,readNmeaStream:Ts,closePort:bs},actions:{setPort:F((o,s)=>({port:s.port,error:null})),setError:F((o,s)=>{const a=s.error;let c;return typeof a=="string"?c=a:a instanceof Error?c=a.message||"Failed to connect.":c=String(a)||"Failed to connect.",{error:c}}),logParsedData:({context:o},s)=>{if(!o.enableLogging)return;const c=s.packet.sentenceId;_n(c,n)&&console.log(`${c} Packet:`,s.packet)},storePacket:F(({context:o},s)=>{const c=s.packet.sentenceId;if(c&&_n(c,n)){const u={...o.packets,[c]:s.packet};return{packets:u,data:t(u),error:null}}return{packets:o.packets,data:t(o.packets),error:null}}),clearError:F((o,s)=>({error:s.error})),setFatalError:F((o,s)=>({error:s.error})),disconnect:F({port:null,error:null,packets:i,data:r}),setLogging:F((o,s)=>({enableLogging:s.enabled})),setBaudRate:F((o,s)=>({baudRate:s.baudRate}))}}).createMachine({id:"nmea",initial:"disconnected",context:{port:null,error:null,packets:i,data:r,enableLogging:!1,baudRate:4800},on:{SET_LOGGING:{actions:{type:"setLogging",params:({event:o})=>({enabled:o.enabled})}}},states:{disconnected:{on:{CONNECT:"connecting",SET_BAUD_RATE:{actions:{type:"setBaudRate",params:({event:o})=>({baudRate:o.baudRate})}}}},connecting:{invoke:{id:"connectToSerial",src:"connectToSerial",input:({context:o})=>({baudRate:o.baudRate}),onDone:{target:"connected",actions:{type:"setPort",params:({event:o})=>({port:o.output})}},onError:{target:"error",actions:{type:"setError",params:({event:o})=>({error:o.error})}}}},connected:{on:{"SERIAL.DATA":{actions:[{type:"logParsedData",params:({event:o})=>({packet:o.data})},{type:"storePacket",params:({event:o})=>({packet:o.data})}]},"SERIAL.ERROR":{actions:{type:"clearError",params:({event:o})=>({error:o.error})}},FATAL_ERROR:{target:"error",actions:{type:"setFatalError",params:({event:o})=>({error:o.error})}},"SERIAL.DISCONNECTED":{target:"disconnecting"},DISCONNECT:{actions:Ge("streamReader",{type:"STOP"})}},invoke:{id:"streamReader",src:"readNmeaStream",input:({context:o})=>({port:o.port})}},disconnecting:{invoke:{id:"closePort",src:"closePort",input:({context:o})=>({port:o.port}),onDone:{target:"disconnected",actions:"disconnect"},onError:{target:"disconnected",actions:"disconnect"}}},error:{on:{CONNECT:"connecting"}}}})}function Is(e,t,n){return e&&e.fixType!=="none"?{latitude:e.latitude,longitude:e.longitude,source:"GGA",fixType:e.fixType,altitudeMeters:e.altitudeMeters,satellitesInView:e.satellitesInView,horizontalDilution:e.horizontalDilution}:t&&t.status==="valid"?{latitude:t.latitude,longitude:t.longitude,source:"RMC",status:t.status}:n&&n.status==="valid"?{latitude:n.latitude,longitude:n.longitude,source:"GLL",status:"valid"}:null}function ws(e,t,n,r){if(e){const i=new Date(e.datetime),o=e.localZoneHours*60+e.localZoneMinutes;return i.setMinutes(i.getMinutes()+o),{utc:e.datetime,local:i,source:"ZDA"}}return t&&t.fixType!=="none"?{utc:t.time,local:null,source:"GGA"}:n&&n.status==="valid"?{utc:n.datetime,local:null,source:"RMC"}:r&&r.status==="valid"?{utc:r.time,local:null,source:"GLL"}:null}function Ps(e,t){return e?{knots:e.speedKnots,source:"VTG"}:t&&t.status==="valid"?{knots:t.speedKnots,source:"RMC"}:null}function ks(e){return e.variationDirection==="W"?-e.variation:(e.variationDirection==="E",e.variation)}function Ds(e,t,n,r){if(e&&e.heading!==void 0)return{degreesTrue:e.heading,source:"HDT",isDerived:!1};if(t&&t.heading!==void 0){const o=ks(t);return{degreesTrue:t.heading+o,source:"HDG",isDerived:!1}}const i=n?.trackTrue??r?.trackTrue;return i!==void 0?{degreesTrue:i,source:"COG",isDerived:!0}:null}function Es(e,t,n,r){return e&&e.depthMeters!==void 0?{meters:e.depthMeters,source:"DPT"}:t?{meters:t.depthMeters,source:"DBT"}:n&&n.depthMeters!==void 0?{meters:n.depthMeters,source:"DBS"}:r&&r.depthMeters!==void 0?{meters:r.depthMeters,source:"DBK"}:null}function As(e){const t=ws(e.ZDA,e.GGA,e.RMC,e.GLL),n=Is(e.GGA,e.RMC,e.GLL),r=Ps(e.VTG,e.RMC),i=Ds(e.HDT,e.HDG,e.RMC,e.VTG),o=Es(e.DPT,e.DBT,e.DBS,e.DBK);return{time:t,position:n,speed:r,heading:i,depth:o}}const Ms=["GGA","RMC","GLL","VTG","HDT","HDG","DPT","DBT","DBS","DBK","ZDA"];function Os(){return e=>As(e)}const Fs={time:null,position:null,speed:null,heading:null,depth:null},Cs={};function Ns(){return{adapter:Os(),allowedSentenceIds:Ms,initialData:Fs,initialPackets:Cs}}function Tn(){return bn(Ns())}function Rs(e){const t=Tn();return new Vt(t,{enableLogging:e?.enableLogging,baudRate:e?.baudRate,onData:e?.onData,onStateChange:e?.onStateChange,onError:e?.onError})}return L.NmeaClient=Vt,L.createNavigationNmeaClient=Rs,L.createNavigationNmeaMachine=Tn,L.createNmeaMachine=bn,L.parseNmeaSentence=vs,L.parseUnsafeNmeaSentence=Sn,Object.defineProperty(L,Symbol.toStringTag,{value:"Module"}),L})({});
4
+ `),i=r.pop();this.container=i??"",r.forEach(o=>{o.length>0&&n.enqueue(o)})}flush(t){this.container=""}}const _s=Wt(async({input:e})=>{if(!navigator.serial)throw new Error("Web Serial API is not supported in this browser.");console.log("Requesting serial port...");const t=await navigator.serial.requestPort();if(console.log(`Opening port at ${e.baudRate} baud...`),t.readable||t.writable){console.log("Port is already open, closing first...");try{await t.close()}catch(n){console.warn("Error closing already-open port:",n)}}return await t.open({baudRate:e.baudRate}),console.log("Port open."),t}),bs=Wt(async({input:e})=>{if(e.port)try{(e.port.readable||e.port.writable)&&(await e.port.close(),console.log("Port closed successfully."))}catch(t){console.warn("Error closing port:",t)}}),Ts=_r(({input:e,sendBack:t,receive:n})=>{const{port:r}=e;if(!r||!r.readable){t({type:"SERIAL.ERROR",error:"Invalid port context."});return}const i=new Ss,s=r.readable.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform:i.transform.bind(i),flush:i.flush.bind(i)})).getReader();let a=!0;async function c(){try{for(;a;){const{value:u,done:f}=await s.read();if(f)break;if(u&&u.length>0)try{const l=Sn(u);if(l.sentenceId==="?")continue;t({type:"SERIAL.DATA",data:l})}catch(l){const d=l instanceof Error?l.message:String(l);console.warn("Failed to parse NMEA sentence:",u,d),t({type:"SERIAL.ERROR",error:`Parser Error: ${d}`})}}}catch(u){if(console.error("Read loop error:",u),a){const f=u instanceof Error?u.message:String(u);t({type:"FATAL_ERROR",error:f})}}finally{console.log("Read loop finished."),t({type:"SERIAL.DISCONNECTED"})}}return c(),n(u=>{u.type==="STOP"&&(console.log("Received STOP, cancelling reader..."),a=!1,s.cancel().catch(()=>{}))}),()=>{console.log("Cleaning up stream reader actor..."),a=!1,s&&s.cancel().catch(()=>{})}});function bn(e){const{adapter:t,allowedSentenceIds:n,initialData:r,initialPackets:i}=e;return Ut({actors:{connectToSerial:_s,readNmeaStream:Ts,closePort:bs},actions:{setPort:F((o,s)=>({port:s.port,error:null})),setError:F((o,s)=>{const a=s.error;let c;return typeof a=="string"?c=a:a instanceof Error?c=a.message||"Failed to connect.":c=String(a)||"Failed to connect.",{error:c}}),logParsedData:({context:o},s)=>{if(!o.enableLogging)return;const c=s.packet.sentenceId;_n(c,n)&&console.log(`${c} Packet:`,s.packet)},storePacket:F(({context:o},s)=>{const c=s.packet.sentenceId;if(c&&_n(c,n)){const u={...o.packets,[c]:s.packet};return{packets:u,data:t(u),error:null}}return{packets:o.packets,data:t(o.packets),error:null}}),clearError:F((o,s)=>({error:s.error})),setFatalError:F((o,s)=>({error:s.error})),disconnect:F({port:null,error:null,packets:i,data:r}),setLogging:F((o,s)=>({enableLogging:s.enabled})),setBaudRate:F((o,s)=>({baudRate:s.baudRate}))}}).createMachine({id:"nmea",initial:"disconnected",context:{port:null,error:null,packets:i,data:r,enableLogging:!1,baudRate:4800},on:{SET_LOGGING:{actions:{type:"setLogging",params:({event:o})=>({enabled:o.enabled})}}},states:{disconnected:{on:{CONNECT:"connecting",SET_BAUD_RATE:{actions:{type:"setBaudRate",params:({event:o})=>({baudRate:o.baudRate})}}}},connecting:{invoke:{id:"connectToSerial",src:"connectToSerial",input:({context:o})=>({baudRate:o.baudRate}),onDone:{target:"connected",actions:{type:"setPort",params:({event:o})=>({port:o.output})}},onError:{target:"error",actions:{type:"setError",params:({event:o})=>({error:o.error})}}}},connected:{on:{"SERIAL.DATA":{actions:[{type:"logParsedData",params:({event:o})=>({packet:o.data})},{type:"storePacket",params:({event:o})=>({packet:o.data})}]},"SERIAL.ERROR":{actions:{type:"clearError",params:({event:o})=>({error:o.error})}},FATAL_ERROR:{target:"error",actions:{type:"setFatalError",params:({event:o})=>({error:o.error})}},"SERIAL.DISCONNECTED":{target:"disconnecting"},DISCONNECT:{actions:Ge("streamReader",{type:"STOP"})}},invoke:{id:"streamReader",src:"readNmeaStream",input:({context:o})=>({port:o.port})}},disconnecting:{invoke:{id:"closePort",src:"closePort",input:({context:o})=>({port:o.port}),onDone:{target:"disconnected",actions:"disconnect"},onError:{target:"disconnected",actions:"disconnect"}}},error:{on:{CONNECT:"connecting"}}}})}function Is(e,t,n){return e&&e.fixType!=="none"?{latitude:e.latitude,longitude:e.longitude,source:"GGA",fixType:e.fixType,altitudeMeters:e.altitudeMeters,satellitesInView:e.satellitesInView,horizontalDilution:e.horizontalDilution}:t&&t.status==="valid"?{latitude:t.latitude,longitude:t.longitude,source:"RMC",status:t.status}:n&&n.status==="valid"?{latitude:n.latitude,longitude:n.longitude,source:"GLL",status:"valid"}:null}function ws(e,t,n,r){if(e){const i=new Date(e.datetime),o=e.localZoneHours*60+e.localZoneMinutes;return i.setMinutes(i.getMinutes()+o),{utc:e.datetime,local:i,source:"ZDA"}}return t&&t.fixType!=="none"?{utc:t.time,local:null,source:"GGA"}:n&&n.status==="valid"?{utc:n.datetime,local:null,source:"RMC"}:r&&r.status==="valid"?{utc:r.time,local:null,source:"GLL"}:null}function Ps(e,t){return e?{knots:e.speedKnots,source:"VTG"}:t&&t.status==="valid"?{knots:t.speedKnots,source:"RMC"}:null}function ks(e){return e.variationDirection==="W"?-e.variation:(e.variationDirection==="E",e.variation)}function Ds(e,t,n,r){if(e&&e.heading!==void 0)return{degreesTrue:e.heading,source:"HDT",isDerived:!1};if(t&&t.heading!==void 0){const o=ks(t);return{degreesTrue:t.heading+o,source:"HDG",isDerived:!1}}const i=n?.trackTrue??r?.trackTrue;return i!==void 0?{degreesTrue:i,source:"COG",isDerived:!0}:null}function Es(e,t,n,r){return e&&e.depthMeters!==void 0?{meters:e.depthMeters,source:"DPT"}:t?{meters:t.depthMeters,source:"DBT"}:n&&n.depthMeters!==void 0?{meters:n.depthMeters,source:"DBS"}:r&&r.depthMeters!==void 0?{meters:r.depthMeters,source:"DBK"}:null}function As(e){const t=ws(e.ZDA,e.GGA,e.RMC,e.GLL),n=Is(e.GGA,e.RMC,e.GLL),r=Ps(e.VTG,e.RMC),i=Ds(e.HDT,e.HDG,e.RMC,e.VTG),o=Es(e.DPT,e.DBT,e.DBS,e.DBK);return{time:t,position:n,speed:r,heading:i,depth:o}}const Ms=["GGA","RMC","GLL","VTG","HDT","HDG","DPT","DBT","DBS","DBK","ZDA"];function Os(){return e=>As(e)}const Fs={time:null,position:null,speed:null,heading:null,depth:null},Cs={};function Ns(){return{adapter:Os(),allowedSentenceIds:Ms,initialData:Fs,initialPackets:Cs}}function Tn(){return bn(Ns())}class Rs extends Vt{constructor(t){const n=Tn();super(n,{enableLogging:t?.enableLogging,baudRate:t?.baudRate,onData:t?.onData,onStateChange:t?.onStateChange,onError:t?.onError})}}return L.NavigationNmeaClient=Rs,L.NmeaClient=Vt,L.createNavigationNmeaMachine=Tn,L.createNmeaMachine=bn,L.parseNmeaSentence=vs,L.parseUnsafeNmeaSentence=Sn,Object.defineProperty(L,Symbol.toStringTag,{value:"Module"}),L})({});
@@ -3756,19 +3756,26 @@ function Os() {
3756
3756
  function Fs() {
3757
3757
  return Ss(Os());
3758
3758
  }
3759
- function Rs(e) {
3760
- const t = Fs();
3761
- return new Fr(t, {
3762
- enableLogging: e?.enableLogging,
3763
- baudRate: e?.baudRate,
3764
- onData: e?.onData,
3765
- onStateChange: e?.onStateChange,
3766
- onError: e?.onError
3767
- });
3759
+ class Rs extends Fr {
3760
+ /**
3761
+ * Creates a new navigation NMEA client.
3762
+ *
3763
+ * @param options - Optional configuration and callbacks.
3764
+ */
3765
+ constructor(t) {
3766
+ const n = Fs();
3767
+ super(n, {
3768
+ enableLogging: t?.enableLogging,
3769
+ baudRate: t?.baudRate,
3770
+ onData: t?.onData,
3771
+ onStateChange: t?.onStateChange,
3772
+ onError: t?.onError
3773
+ });
3774
+ }
3768
3775
  }
3769
3776
  export {
3777
+ Rs as NavigationNmeaClient,
3770
3778
  Fr as NmeaClient,
3771
- Rs as createNavigationNmeaClient,
3772
3779
  Fs as createNavigationNmeaMachine,
3773
3780
  Ss as createNmeaMachine,
3774
3781
  Cs as parseNmeaSentence,
@@ -1,4 +1,4 @@
1
1
  (function(F,te){typeof exports=="object"&&typeof module<"u"?te(exports):typeof define=="function"&&define.amd?define(["exports"],te):(F=typeof globalThis<"u"?globalThis:F||self,te(F.NmeaWebSerial={}))})(this,(function(F){"use strict";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 wn(){const e=te();if(e.__xstate__)return e.__xstate__}const Pn=e=>{if(typeof window>"u")return;const t=wn();t&&t.register(e)};class lt{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const n={value:t,next:null};if(this._current){this._last.next=n,this._last=n;return}this._current=n,this._last=n,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const ht=".",kn="",pt="",Dn="#",En="*",gt="xstate.init",An="xstate.error",ne="xstate.stop";function Mn(e,t){return{type:`xstate.after.${e}.${t}`}}function qe(e,t){return{type:`xstate.done.state.${e}`,output:t}}function On(e,t){return{type:`xstate.done.actor.${e}`,output:t,actorId:e}}function vt(e,t){return{type:`xstate.error.actor.${e}`,error:t,actorId:e}}function mt(e){return{type:gt,input:e}}function N(e){setTimeout(()=>{throw e})}const Fn=typeof Symbol=="function"&&Symbol.observable||"@@observable";function yt(e,t){const n=St(e),r=St(t);return typeof r=="string"?typeof n=="string"?r===n:!1:typeof n=="string"?n in r:Object.keys(n).every(i=>i in r?yt(n[i],r[i]):!1)}function We(e){if(Tt(e))return e;const t=[];let n="";for(let r=0;r<e.length;r++){switch(e.charCodeAt(r)){case 92:n+=e[r+1],r++;continue;case 46:t.push(n),n="";continue}n+=e[r]}return t.push(n),t}function St(e){if(dr(e))return e.value;if(typeof e!="string")return e;const t=We(e);return Cn(t)}function Cn(e){if(e.length===1)return e[0];const t={};let n=t;for(let r=0;r<e.length-1;r++)if(r===e.length-2)n[e[r]]=e[r+1];else{const i=n;n={},i[e[r]]=n}return t}function _t(e,t){const n={},r=Object.keys(e);for(let i=0;i<r.length;i++){const o=r[i];n[o]=t(e[o],o,e,i)}return n}function bt(e){return Tt(e)?e:[e]}function x(e){return e===void 0?[]:bt(e)}function Be(e,t,n,r){return typeof e=="function"?e({context:t,event:n,self:r}):e}function Tt(e){return Array.isArray(e)}function Nn(e){return e.type.startsWith("xstate.error.actor")}function K(e){return bt(e).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function It(e){if(!(e===void 0||e===kn))return x(e)}function He(e,t,n){const r=typeof e=="object",i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}function wt(e,t){return`${t}.${e}`}function Ue(e,t){const n=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return e.implementations.actors[t];const[,r,i]=n,s=e.getStateNodeById(i).config.invoke;return(Array.isArray(s)?s[r]:s).src}function Pt(e,t){return`${e.sessionId}.${t}`}let Rn=0;function jn(e,t){const n=new Map,r=new Map,i=new WeakMap,o=new Set,s={},{clock:a,logger:c}=t,u={schedule:(d,p,g,y,I=Math.random().toString(36).slice(2))=>{const R={source:d,target:p,event:g,delay:y,id:I,startedAt:Date.now()},j=Pt(d,I);l._snapshot._scheduledEvents[j]=R;const Q=a.setTimeout(()=>{delete s[j],delete l._snapshot._scheduledEvents[j],l._relay(d,p,g)},y);s[j]=Q},cancel:(d,p)=>{const g=Pt(d,p),y=s[g];delete s[g],delete l._snapshot._scheduledEvents[g],y!==void 0&&a.clearTimeout(y)},cancelAll:d=>{for(const p in l._snapshot._scheduledEvents){const g=l._snapshot._scheduledEvents[p];g.source===d&&u.cancel(d,g.id)}}},f=d=>{if(!o.size)return;const p={...d,rootId:e.sessionId};o.forEach(g=>g.next?.(p))},l={_snapshot:{_scheduledEvents:(t?.snapshot&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${Rn++}`,_register:(d,p)=>(n.set(d,p),d),_unregister:d=>{n.delete(d.sessionId);const p=i.get(d);p!==void 0&&(r.delete(p),i.delete(d))},get:d=>r.get(d),getAll:()=>Object.fromEntries(r.entries()),_set:(d,p)=>{const g=r.get(d);if(g&&g!==p)throw new Error(`Actor with system ID '${d}' already exists.`);r.set(d,p),i.set(p,d)},inspect:d=>{const p=He(d);return o.add(p),{unsubscribe(){o.delete(p)}}},_sendInspectionEvent:f,_relay:(d,p,g)=>{l._sendInspectionEvent({type:"@xstate.event",sourceRef:d,actorRef:p,event:g}),p._send(g)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...l._snapshot._scheduledEvents}}),start:()=>{const d=l._snapshot._scheduledEvents;l._snapshot._scheduledEvents={};for(const p in d){const{source:g,target:y,event:I,delay:R,id:j}=d[p];u.schedule(g,y,I,R,j)}},_clock:a,_logger:c};return l}let Ve=!1;const Ke=1;let E=(function(e){return e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped",e})({});const Gn={clock:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},logger:console.log.bind(console),devTools:!1};class Ln{constructor(t,n){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new lt(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=E.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 r={...Gn,...n},{clock:i,logger:o,parent:s,syncSnapshot:a,id:c,systemId:u,inspect:f}=r;this.system=s?s.system:jn(this,{clock:i,logger:o}),f&&!s&&this.system.inspect(He(f)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=n?.logger??this.system._logger,this.clock=n?.clock??this.system._clock,this._parent=s,this._syncSnapshot=a,this.options=r,this.src=r.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:l=>{this._deferred.push(l)},system:this.system,stopChild:l=>{if(l._parent!==this)throw new Error(`Cannot stop child actor ${l.id} of ${this.id} because it is not a child`);l._stop()},emit:l=>{const d=this.eventListeners.get(l.type),p=this.eventListeners.get("*");if(!d&&!p)return;const g=[...d?d.values():[],...p?p.values():[]];for(const y of g)try{y(l)}catch(I){N(I)}},actionExecutor:l=>{const d=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:l.type,params:l.params}}),!l.exec)return;const p=Ve;try{Ve=!0,l.exec(l.info,l.params)}finally{Ve=p}};this._processingStatus===E.Running?d():this._deferred.push(d)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),u&&(this.systemId=u,this.system._set(u,this)),this._initState(n?.snapshot??n?.state),u&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(n){this._snapshot={status:"error",output:void 0,error:n}}}update(t,n){this._snapshot=t;let r;for(;r=this._deferred.shift();)try{r()}catch(i){this._deferred.length=0,this._snapshot={...t,status:"error",error:i}}switch(this._snapshot.status){case"active":for(const i of this.observers)try{i.next?.(t)}catch(o){N(o)}break;case"done":for(const i of this.observers)try{i.next?.(t)}catch(o){N(o)}this._stopProcedure(),this._complete(),this._doneEvent=On(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:n,snapshot:t})}subscribe(t,n,r){const i=He(t,n,r);if(this._processingStatus!==E.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{i.complete?.()}catch(o){N(o)}break;case"error":{const o=this._snapshot.error;if(!i.error)N(o);else try{i.error(o)}catch(s){N(s)}break}}return{unsubscribe:()=>{this.observers.delete(i)}}}on(t,n){let r=this.eventListeners.get(t);r||(r=new Set,this.eventListeners.set(t,r));const i=n.bind(void 0);return r.add(i),{unsubscribe:()=>{r.delete(i)}}}start(){if(this._processingStatus===E.Running)return this;this._syncSnapshot&&this.subscribe({next:r=>{r.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:r})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=E.Running;const t=mt(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(r){return this._snapshot={...this._snapshot,status:"error",error:r},this._error(r),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let n,r;try{n=this.logic.transition(this._snapshot,t,this._actorScope)}catch(i){r={err:i}}if(r){const{err:i}=r;this._snapshot={...this._snapshot,status:"error",error:i},this._error(i);return}this.update(n,t),t.type===ne&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===E.Stopped?this:(this.mailbox.clear(),this._processingStatus===E.NotStarted?(this._processingStatus=E.Stopped,this):(this.mailbox.enqueue({type:ne}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(n){N(n)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||N(t);return}let n=!1;for(const r of this.observers){const i=r.error;n||=!i;try{i?.(t)}catch(o){N(o)}}this.observers.clear(),n&&N(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,vt(this.id,t))}_stopProcedure(){return this._processingStatus!==E.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new lt(this._process.bind(this)),this._processingStatus=E.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==E.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;t&&(typeof t=="function"?t:Pn)(this)}toJSON(){return{xstate$$type:Ke,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[Fn](){return this}getSnapshot(){return this._snapshot}}function re(e,...[t]){return new Ln(e,t)}function xn(e,t,n,r,{sendId:i}){const o=typeof i=="function"?i(n,r):i;return[t,{sendId:o},void 0]}function qn(e,t){e.defer(()=>{e.system.scheduler.cancel(e.self,t.sendId)})}function ze(e){function t(n,r){}return t.type="xstate.cancel",t.sendId=e,t.resolve=xn,t.execute=qn,t}function Wn(e,t,n,r,{id:i,systemId:o,src:s,input:a,syncSnapshot:c}){const u=typeof s=="string"?Ue(t.machine,s):s,f=typeof i=="function"?i(n):i;let l,d;return u&&(d=typeof a=="function"?a({context:t.context,event:n.event,self:e.self}):a,l=re(u,{id:f,src:s,parent:e.self,syncSnapshot:c,systemId:o,input:d})),[U(t,{children:{...t.children,[f]:l}}),{id:i,systemId:o,actorRef:l,src:s,input:d},void 0]}function Bn(e,{actorRef:t}){t&&e.defer(()=>{t._processingStatus!==E.Stopped&&t.start()})}function Je(...[e,{id:t,systemId:n,input:r,syncSnapshot:i=!1}={}]){function o(s,a){}return o.type="xstate.spawnChild",o.id=t,o.systemId=n,o.src=e,o.input=r,o.syncSnapshot=i,o.resolve=Wn,o.execute=Bn,o}function Hn(e,t,n,r,{actorRef:i}){const o=typeof i=="function"?i(n,r):i,s=typeof o=="string"?t.children[o]:o;let a=t.children;return s&&(a={...a},delete a[s.id]),[U(t,{children:a}),s,void 0]}function Un(e,t){if(t){if(e.system._unregister(t),t._processingStatus!==E.Running){e.stopChild(t);return}e.defer(()=>{e.stopChild(t)})}}function Ae(e){function t(n,r){}return t.type="xstate.stopChild",t.actorRef=e,t.resolve=Hn,t.execute=Un,t}function Me(e,t,n,r){const{machine:i}=r,o=typeof e=="function",s=o?e:i.implementations.guards[typeof e=="string"?e:e.type];if(!o&&!s)throw new Error(`Guard '${typeof e=="string"?e:e.type}' is not implemented.'.`);if(typeof s!="function")return Me(s,t,n,r);const a={context:t,event:n},c=o||typeof e=="string"?void 0:"params"in e?typeof e.params=="function"?e.params({context:t,event:n}):e.params:void 0;return"check"in s?s.check(r,a,s):s(a,c)}const Ze=e=>e.type==="atomic"||e.type==="final";function z(e){return Object.values(e.states).filter(t=>t.type!=="history")}function se(e,t){const n=[];if(t===e)return n;let r=e.parent;for(;r&&r!==t;)n.push(r),r=r.parent;return n}function Oe(e){const t=new Set(e),n=Dt(t);for(const r of t)if(r.type==="compound"&&(!n.get(r)||!n.get(r).length))Mt(r).forEach(i=>t.add(i));else if(r.type==="parallel"){for(const i of z(r))if(i.type!=="history"&&!t.has(i)){const o=Mt(i);for(const s of o)t.add(s)}}for(const r of t){let i=r.parent;for(;i;)t.add(i),i=i.parent}return t}function kt(e,t){const n=t.get(e);if(!n)return{};if(e.type==="compound"){const i=n[0];if(i){if(Ze(i))return i.key}else return{}}const r={};for(const i of n)r[i.key]=kt(i,t);return r}function Dt(e){const t=new Map;for(const n of e)t.has(n)||t.set(n,[]),n.parent&&(t.has(n.parent)||t.set(n.parent,[]),t.get(n.parent).push(n));return t}function Et(e,t){const n=Oe(t);return kt(e,Dt(n))}function Ye(e,t){return t.type==="compound"?z(t).some(n=>n.type==="final"&&e.has(n)):t.type==="parallel"?z(t).every(n=>Ye(e,n)):t.type==="final"}const Fe=e=>e[0]===Dn;function Vn(e,t){return e.transitions.get(t)||[...e.transitions.keys()].filter(r=>{if(r===En)return!0;if(!r.endsWith(".*"))return!1;const i=r.split("."),o=t.split(".");for(let s=0;s<i.length;s++){const a=i[s],c=o[s];if(a==="*")return s===i.length-1;if(a!==c)return!1}return!0}).sort((r,i)=>i.length-r.length).flatMap(r=>e.transitions.get(r))}function Kn(e){const t=e.config.after;if(!t)return[];const n=i=>{const o=Mn(i,e.id),s=o.type;return e.entry.push(rt(o,{id:s,delay:i})),e.exit.push(ze(s)),s};return Object.keys(t).flatMap(i=>{const o=t[i],s=typeof o=="string"?{target:o}:o,a=Number.isNaN(+i)?i:+i,c=n(a);return x(s).map(u=>({...u,event:c,delay:a}))}).map(i=>{const{delay:o}=i;return{...B(e,i.event,i),delay:o}})}function B(e,t,n){const r=It(n.target),i=n.reenter??!1,o=Zn(e,r),s={...n,actions:x(n.actions),guard:n.guard,target:o,source:e,reenter:i,eventType:t,toJSON:()=>({...s,source:`#${e.id}`,target:o?o.map(a=>`#${a.id}`):void 0})};return s}function zn(e){const t=new Map;if(e.config.on)for(const n of Object.keys(e.config.on)){if(n===pt)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const r=e.config.on[n];t.set(n,K(r).map(i=>B(e,n,i)))}if(e.config.onDone){const n=`xstate.done.state.${e.id}`;t.set(n,K(e.config.onDone).map(r=>B(e,n,r)))}for(const n of e.invoke){if(n.onDone){const r=`xstate.done.actor.${n.id}`;t.set(r,K(n.onDone).map(i=>B(e,r,i)))}if(n.onError){const r=`xstate.error.actor.${n.id}`;t.set(r,K(n.onError).map(i=>B(e,r,i)))}if(n.onSnapshot){const r=`xstate.snapshot.${n.id}`;t.set(r,K(n.onSnapshot).map(i=>B(e,r,i)))}}for(const n of e.after){let r=t.get(n.eventType);r||(r=[],t.set(n.eventType,r)),r.push(n)}return t}function Jn(e,t){const n=typeof t=="string"?e.states[t]:t?e.states[t.target]:void 0;if(!n&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${e.id}`);const r={source:e,actions:!t||typeof t=="string"?[]:x(t.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...r,source:`#${e.id}`,target:n?[`#${n.id}`]:[]})};return r}function Zn(e,t){if(t!==void 0)return t.map(n=>{if(typeof n!="string")return n;if(Fe(n))return e.machine.getStateNodeById(n);const r=n[0]===ht;if(r&&!e.parent)return Ce(e,n.slice(1));const i=r?e.key+n:n;if(e.parent)try{return Ce(e.parent,i)}catch(o){throw new Error(`Invalid transition definition for state node '${e.id}':
2
2
  ${o.message}`)}else throw new Error(`Invalid target: "${n}" is not a valid target from the root node. Did you mean ".${n}"?`)})}function At(e){const t=It(e.config.target);return t?{target:t.map(n=>typeof n=="string"?Ce(e.parent,n):n)}:e.parent.initial}function H(e){return e.type==="history"}function Mt(e){const t=Ot(e);for(const n of t)for(const r of se(n,e))t.add(r);return t}function Ot(e){const t=new Set;function n(r){if(!t.has(r)){if(t.add(r),r.type==="compound")n(r.initial.target[0]);else if(r.type==="parallel")for(const i of z(r))n(i)}}return n(e),t}function J(e,t){if(Fe(t))return e.machine.getStateNodeById(t);if(!e.states)throw new Error(`Unable to retrieve child state '${t}' from '${e.id}'; no child states exist.`);const n=e.states[t];if(!n)throw new Error(`Child state '${t}' does not exist on '${e.id}'`);return n}function Ce(e,t){if(typeof t=="string"&&Fe(t))try{return e.machine.getStateNodeById(t)}catch{}const n=We(t).slice();let r=e;for(;n.length;){const i=n.shift();if(!i.length)break;r=J(r,i)}return r}function Ne(e,t){if(typeof t=="string"){const i=e.states[t];if(!i)throw new Error(`State '${t}' does not exist on '${e.id}'`);return[e,i]}const n=Object.keys(t),r=n.map(i=>J(e,i)).filter(Boolean);return[e.machine.root,e].concat(r,n.reduce((i,o)=>{const s=J(e,o);if(!s)return i;const a=Ne(s,t[o]);return i.concat(a)},[]))}function Yn(e,t,n,r){const o=J(e,t).next(n,r);return!o||!o.length?e.next(n,r):o}function Xn(e,t,n,r){const i=Object.keys(t),o=J(e,i[0]),s=Xe(o,t[i[0]],n,r);return!s||!s.length?e.next(n,r):s}function Qn(e,t,n,r){const i=[];for(const o of Object.keys(t)){const s=t[o];if(!s)continue;const a=J(e,o),c=Xe(a,s,n,r);c&&i.push(...c)}return i.length?i:e.next(n,r)}function Xe(e,t,n,r){return typeof t=="string"?Yn(e,t,n,r):Object.keys(t).length===1?Xn(e,t,n,r):Qn(e,t,n,r)}function $n(e){return Object.keys(e.states).map(t=>e.states[t]).filter(t=>t.type==="history")}function q(e,t){let n=e;for(;n.parent&&n.parent!==t;)n=n.parent;return n.parent===t}function er(e,t){const n=new Set(e),r=new Set(t);for(const i of n)if(r.has(i))return!0;for(const i of r)if(n.has(i))return!0;return!1}function Ft(e,t,n){const r=new Set;for(const i of e){let o=!1;const s=new Set;for(const a of r)if(er($e([i],t,n),$e([a],t,n)))if(q(i.source,a.source))s.add(a);else{o=!0;break}if(!o){for(const a of s)r.delete(a);r.add(i)}}return Array.from(r)}function tr(e){const[t,...n]=e;for(const r of se(t,void 0))if(n.every(i=>q(i,r)))return r}function Qe(e,t){if(!e.target)return[];const n=new Set;for(const r of e.target)if(H(r))if(t[r.id])for(const i of t[r.id])n.add(i);else for(const i of Qe(At(r),t))n.add(i);else n.add(r);return[...n]}function Ct(e,t){const n=Qe(e,t);if(!n)return;if(!e.reenter&&n.every(i=>i===e.source||q(i,e.source)))return e.source;const r=tr(n.concat(e.source));if(r)return r;if(!e.reenter)return e.source.machine.root}function $e(e,t,n){const r=new Set;for(const i of e)if(i.target?.length){const o=Ct(i,n);i.reenter&&i.source===o&&r.add(o);for(const s of t)q(s,o)&&r.add(s)}return[...r]}function nr(e,t){if(e.length!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function et(e,t,n,r,i,o){if(!e.length)return t;const s=new Set(t._nodes);let a=t.historyValue;const c=Ft(e,s,a);let u=t;i||([u,a]=or(u,r,n,c,s,a,o,n.actionExecutor)),u=Y(u,r,n,c.flatMap(l=>l.actions),o,void 0),u=sr(u,r,n,c,s,o,a,i);const f=[...s];u.status==="done"&&(u=Y(u,r,n,f.sort((l,d)=>d.order-l.order).flatMap(l=>l.exit),o,void 0));try{return a===t.historyValue&&nr(t._nodes,s)?u:U(u,{_nodes:f,historyValue:a})}catch(l){throw l}}function rr(e,t,n,r,i){if(r.output===void 0)return;const o=qe(i.id,i.output!==void 0&&i.parent?Be(i.output,e.context,t,n.self):void 0);return Be(r.output,e.context,o,n.self)}function sr(e,t,n,r,i,o,s,a){let c=e;const u=new Set,f=new Set;ir(r,s,f,u),a&&f.add(e.machine.root);const l=new Set;for(const d of[...u].sort((p,g)=>p.order-g.order)){i.add(d);const p=[];p.push(...d.entry);for(const g of d.invoke)p.push(Je(g.src,{...g,syncSnapshot:!!g.onSnapshot}));if(f.has(d)){const g=d.initial.actions;p.push(...g)}if(c=Y(c,t,n,p,o,d.invoke.map(g=>g.id)),d.type==="final"){const g=d.parent;let y=g?.type==="parallel"?g:g?.parent,I=y||d;for(g?.type==="compound"&&o.push(qe(g.id,d.output!==void 0?Be(d.output,c.context,t,n.self):void 0));y?.type==="parallel"&&!l.has(y)&&Ye(i,y);)l.add(y),o.push(qe(y.id)),I=y,y=y.parent;if(y)continue;c=U(c,{status:"done",output:rr(c,t,n,c.machine.root,I)})}}return c}function ir(e,t,n,r){for(const i of e){const o=Ct(i,t);for(const a of i.target||[])!H(a)&&(i.source!==a||i.source!==o||i.reenter)&&(r.add(a),n.add(a)),Z(a,t,n,r);const s=Qe(i,t);for(const a of s){const c=se(a,o);o?.type==="parallel"&&c.push(o),Nt(r,t,n,c,!i.source.parent&&i.reenter?void 0:o)}}}function Z(e,t,n,r){if(H(e))if(t[e.id]){const i=t[e.id];for(const o of i)r.add(o),Z(o,t,n,r);for(const o of i)tt(o,e.parent,r,t,n)}else{const i=At(e);for(const o of i.target)r.add(o),i===e.parent?.initial&&n.add(e.parent),Z(o,t,n,r);for(const o of i.target)tt(o,e.parent,r,t,n)}else if(e.type==="compound"){const[i]=e.initial.target;H(i)||(r.add(i),n.add(i)),Z(i,t,n,r),tt(i,e,r,t,n)}else if(e.type==="parallel")for(const i of z(e).filter(o=>!H(o)))[...r].some(o=>q(o,i))||(H(i)||(r.add(i),n.add(i)),Z(i,t,n,r))}function Nt(e,t,n,r,i){for(const o of r)if((!i||q(o,i))&&e.add(o),o.type==="parallel")for(const s of z(o).filter(a=>!H(a)))[...e].some(a=>q(a,s))||(e.add(s),Z(s,t,n,e))}function tt(e,t,n,r,i){Nt(n,r,i,se(e,t))}function or(e,t,n,r,i,o,s,a){let c=e;const u=$e(r,i,o);u.sort((l,d)=>d.order-l.order);let f;for(const l of u)for(const d of $n(l)){let p;d.history==="deep"?p=g=>Ze(g)&&q(g,l):p=g=>g.parent===l,f??={...o},f[d.id]=Array.from(i).filter(p)}for(const l of u)c=Y(c,t,n,[...l.exit,...l.invoke.map(d=>Ae(d.id))],s,void 0),i.delete(l);return[c,f||o]}function ar(e,t){return e.implementations.actions[t]}function Rt(e,t,n,r,i,o){const{machine:s}=e;let a=e;for(const c of r){const u=typeof c=="function",f=u?c:ar(s,typeof c=="string"?c:c.type),l={context:a.context,event:t,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:t}):c.params:void 0;if(!f||!("resolve"in f)){n.actionExecutor({type:typeof c=="string"?c:typeof c=="object"?c.type:c.name||"(anonymous)",info:l,params:d,exec:f});continue}const p=f,[g,y,I]=p.resolve(n,a,l,d,f,i);a=g,"retryResolve"in p&&o?.push([p,y]),"execute"in p&&n.actionExecutor({type:p.type,info:l,params:y,exec:p.execute.bind(null,n,y)}),I&&(a=Rt(a,t,n,I,i,o))}return a}function Y(e,t,n,r,i,o){const s=o?[]:void 0,a=Rt(e,t,n,r,{internalQueue:i,deferredActorIds:o},s);return s?.forEach(([c,u])=>{c.retryResolve(n,a,u)}),a}function nt(e,t,n,r){let i=e;const o=[];function s(u,f,l){n.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:n.self,event:f,snapshot:u,_transitions:l}),o.push(u)}if(t.type===ne)return i=U(jt(i,t,n),{status:"stopped"}),s(i,t,[]),{snapshot:i,microstates:o};let a=t;if(a.type!==gt){const u=a,f=Nn(u),l=Gt(u,i);if(f&&!l.length)return i=U(e,{status:"error",error:u.error}),s(i,u,[]),{snapshot:i,microstates:o};i=et(l,e,n,a,!1,r),s(i,u,l)}let c=!0;for(;i.status==="active";){let u=c?cr(i,a):[];const f=u.length?i:void 0;if(!u.length){if(!r.length)break;a=r.shift(),u=Gt(a,i)}i=et(u,i,n,a,!1,r),c=i!==f,s(i,a,u)}return i.status!=="active"&&jt(i,a,n),{snapshot:i,microstates:o}}function jt(e,t,n){return Y(e,t,n,Object.values(e.children).map(r=>Ae(r)),[],void 0)}function Gt(e,t){return t.machine.getTransitionData(t,e)}function cr(e,t){const n=new Set,r=e._nodes.filter(Ze);for(const i of r)e:for(const o of[i].concat(se(i,void 0)))if(o.always){for(const s of o.always)if(s.guard===void 0||Me(s.guard,e.context,t,e)){n.add(s);break e}}return Ft(Array.from(n),new Set(e._nodes),e.historyValue)}function ur(e,t){const n=Oe(Ne(e,t));return Et(e,[...n])}function dr(e){return!!e&&typeof e=="object"&&"machine"in e&&"value"in e}const fr=function(t){return yt(t,this.value)},lr=function(t){return this.tags.has(t)},hr=function(t){const n=this.machine.getTransitionData(this,t);return!!n?.length&&n.some(r=>r.target!==void 0||r.actions.length)},pr=function(){const{_nodes:t,tags:n,machine:r,getMeta:i,toJSON:o,can:s,hasTag:a,matches:c,...u}=this;return{...u,tags:Array.from(n)}},gr=function(){return this._nodes.reduce((t,n)=>(n.meta!==void 0&&(t[n.id]=n.meta),t),{})};function Re(e,t){return{status:e.status,output:e.output,error:e.error,machine:t,context:e.context,_nodes:e._nodes,value:Et(t.root,e._nodes),tags:new Set(e._nodes.flatMap(n=>n.tags)),children:e.children,historyValue:e.historyValue||{},matches:fr,hasTag:lr,can:hr,getMeta:gr,toJSON:pr}}function U(e,t={}){return Re({...e,...t},e.machine)}function vr(e){if(typeof e!="object"||e===null)return{};const t={};for(const n in e){const r=e[n];Array.isArray(r)&&(t[n]=r.map(i=>({id:i.id})))}return t}function mr(e,t){const{_nodes:n,tags:r,machine:i,children:o,context:s,can:a,hasTag:c,matches:u,getMeta:f,toJSON:l,...d}=e,p={};for(const y in o){const I=o[y];p[y]={snapshot:I.getPersistedSnapshot(t),src:I.src,systemId:I.systemId,syncSnapshot:I._syncSnapshot}}return{...d,context:Lt(s),children:p,historyValue:vr(d.historyValue)}}function Lt(e){let t;for(const n in e){const r=e[n];if(r&&typeof r=="object")if("sessionId"in r&&"send"in r&&"ref"in r)t??=Array.isArray(e)?e.slice():{...e},t[n]={xstate$$type:Ke,id:r.id};else{const i=Lt(r);i!==r&&(t??=Array.isArray(e)?e.slice():{...e},t[n]=i)}}return t??e}function yr(e,t,n,r,{event:i,id:o,delay:s},{internalQueue:a}){const 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`);const u=typeof i=="function"?i(n,r):i;let f;if(typeof s=="string"){const l=c&&c[s];f=typeof l=="function"?l(n,r):l}else f=typeof s=="function"?s(n,r):s;return typeof f!="number"&&a.push(u),[t,{event:u,id:o,delay:f},void 0]}function Sr(e,t){const{event:n,delay:r,id:i}=t;if(typeof r=="number"){e.defer(()=>{const o=e.self;e.system.scheduler.schedule(o,o,n,r,i)});return}}function rt(e,t){function n(r,i){}return n.type="xstate.raise",n.event=e,n.id=t?.id,n.delay=t?.delay,n.resolve=yr,n.execute=Sr,n}const xt=new WeakMap;function _r(e){return{config:e,start:(n,r)=>{const{self:i,system:o,emit:s}=r,a={receivers:void 0,dispose:void 0};xt.set(i,a),a.dispose=e({input:n.input,system:o,self:i,sendBack:c=>{i.getSnapshot().status!=="stopped"&&i._parent&&o._relay(i,i._parent,c)},receive:c=>{a.receivers??=new Set,a.receivers.add(c)},emit:s})},transition:(n,r,i)=>{const o=xt.get(i.self);return r.type===ne?(n={...n,status:"stopped",error:void 0},o.dispose?.(),n):(o.receivers?.forEach(s=>s(r)),n)},getInitialSnapshot:(n,r)=>({status:"active",output:void 0,error:void 0,input:r}),getPersistedSnapshot:n=>n,restoreSnapshot:n=>n}}const qt="xstate.promise.resolve",Wt="xstate.promise.reject",je=new WeakMap;function Bt(e){return{config:e,transition:(n,r,i)=>{if(n.status!=="active")return n;switch(r.type){case qt:{const o=r.data;return{...n,status:"done",output:o,input:void 0}}case Wt:return{...n,status:"error",error:r.data,input:void 0};case ne:return je.get(i.self)?.abort(),{...n,status:"stopped",input:void 0};default:return n}},start:(n,{self:r,system:i,emit:o})=>{if(n.status!=="active")return;const s=new AbortController;je.set(r,s),Promise.resolve(e({input:n.input,system:i,self:r,signal:s.signal,emit:o})).then(c=>{r.getSnapshot().status==="active"&&(je.delete(r),i._relay(r,r,{type:qt,data:c}))},c=>{r.getSnapshot().status==="active"&&(je.delete(r),i._relay(r,r,{type:Wt,data:c}))})},getInitialSnapshot:(n,r)=>({status:"active",output:void 0,error:void 0,input:r}),getPersistedSnapshot:n=>n,restoreSnapshot:n=>n}}function br(e,{machine:t,context:n},r,i){const o=(s,a)=>{if(typeof s=="string"){const c=Ue(t,s);if(!c)throw new Error(`Actor logic '${s}' not implemented in machine '${t.id}'`);const u=re(c,{id:a?.id,parent:e.self,syncSnapshot:a?.syncSnapshot,input:typeof a?.input=="function"?a.input({context:n,event:r,self:e.self}):a?.input,src:s,systemId:a?.systemId});return i[u.id]=u,u}else return re(s,{id:a?.id,parent:e.self,syncSnapshot:a?.syncSnapshot,input:a?.input,src:s,systemId:a?.systemId})};return(s,a)=>{const c=o(s,a);return i[c.id]=c,e.defer(()=>{c._processingStatus!==E.Stopped&&c.start()}),c}}function Tr(e,t,n,r,{assignment:i}){if(!t.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const o={},s={context:t.context,event:n.event,spawn:br(e,t,n.event,o),self:e.self,system:e.system};let a={};if(typeof i=="function")a=i(s,r);else for(const u of Object.keys(i)){const f=i[u];a[u]=typeof f=="function"?f(s,r):f}const c=Object.assign({},t.context,a);return[U(t,{context:c,children:Object.keys(o).length?{...t.children,...o}:t.children}),void 0,void 0]}function C(e){function t(n,r){}return t.type="xstate.assign",t.assignment=e,t.resolve=Tr,t}const Ht=new WeakMap;function X(e,t,n){let r=Ht.get(e);return r?t in r||(r[t]=n()):(r={[t]:n()},Ht.set(e,r)),r[t]}const Ir={},ie=e=>typeof e=="string"?{type:e}:typeof e=="function"?"resolve"in e?{type:e.type}:{type:e.name}:e;class Ge{constructor(t,n){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=n._parent,this.key=n._key,this.machine=n._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(ht),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?_t(this.config.states,(r,i)=>new Ge(r,{_parent:this,_key:i,_machine:this.machine})):Ir,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=x(this.config.entry).slice(),this.exit=x(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=x(t.tags).slice()}_initialize(){this.transitions=zn(this),this.config.always&&(this.always=K(this.config.always).map(t=>B(this,pt,t))),Object.keys(this.states).forEach(t=>{this.states[t]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(ie),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(ie),eventType:null})}:void 0,history:this.history,states:_t(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(ie)})),entry:this.entry.map(ie),exit:this.exit.map(ie),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return X(this,"invoke",()=>x(this.config.invoke).map((t,n)=>{const{src:r,systemId:i}=t,o=t.id??wt(this.id,n),s=typeof r=="string"?r:`xstate.invoke.${wt(this.id,n)}`;return{...t,src:s,id:o,systemId:i,toJSON(){const{onDone:a,onError:c,...u}=t;return{...u,type:"xstate.invoke",src:s,id:o}}}}))}get on(){return X(this,"on",()=>[...this.transitions].flatMap(([n,r])=>r.map(i=>[n,i])).reduce((n,[r,i])=>(n[r]=n[r]||[],n[r].push(i),n),{}))}get after(){return X(this,"delayedTransitions",()=>Kn(this))}get initial(){return X(this,"initial",()=>Jn(this,this.config.initial))}next(t,n){const r=n.type,i=[];let o;const s=X(this,`candidates-${r}`,()=>Vn(this,r));for(const a of s){const{guard:c}=a,u=t.context;let f=!1;try{f=!c||Me(c,u,n,t)}catch(l){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 '${r}' in state node '${this.id}':
3
3
  ${l.message}`)}if(f){i.push(...a.actions),o=a;break}}return o?[o]:void 0}get events(){return X(this,"events",()=>{const{states:t}=this,n=new Set(this.ownEvents);if(t)for(const r of Object.keys(t)){const i=t[r];if(i.states)for(const o of i.events)n.add(`${o}`)}return Array.from(n)})}get ownEvents(){const t=new Set([...this.transitions.keys()].filter(n=>this.transitions.get(n).some(r=>!(!r.target&&!r.actions.length&&!r.reenter))));return Array.from(t)}}const wr="#";class st{constructor(t,n){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:n?.actors??{},actions:n?.actions??{},delays:n?.delays??{},guards:n?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new Ge(t,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:n,guards:r,actors:i,delays:o}=this.implementations;return new st(this.config,{actions:{...n,...t.actions},guards:{...r,...t.guards},actors:{...i,...t.actors},delays:{...o,...t.delays}})}resolveState(t){const n=ur(this.root,t.value),r=Oe(Ne(this.root,n));return Re({_nodes:[...r],context:t.context||{},children:{},status:Ye(r,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,n,r){return nt(t,n,r,[]).snapshot}microstep(t,n,r){return nt(t,n,r,[]).microstates}getTransitionData(t,n){return Xe(this.root,t.value,t,n)||[]}getPreInitialState(t,n,r){const{context:i}=this.config,o=Re({context:typeof i!="function"&&i?i:{},_nodes:[this.root],children:{},status:"active"},this);return typeof i=="function"?Y(o,n,t,[C(({spawn:a,event:c,self:u})=>i({spawn:a,input:c.input,self:u}))],r,void 0):o}getInitialSnapshot(t,n){const r=mt(n),i=[],o=this.getPreInitialState(t,r,i),s=et([{target:[...Ot(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],o,t,r,!0,i),{snapshot:a}=nt(s,r,t,i);return a}start(t){Object.values(t.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(t){const n=We(t),r=n.slice(1),i=Fe(n[0])?n[0].slice(wr.length):n[0],o=this.idMap.get(i);if(!o)throw new Error(`Child state node '#${i}' does not exist on machine '${this.id}'`);return Ce(o,r)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,n){return mr(t,n)}restoreSnapshot(t,n){const r={},i=t.children;Object.keys(i).forEach(l=>{const d=i[l],p=d.snapshot,g=d.src,y=typeof g=="string"?Ue(this,g):g;if(!y)return;const I=re(y,{id:l,parent:n.self,syncSnapshot:d.syncSnapshot,snapshot:p,src:g,systemId:d.systemId});r[l]=I});function o(l,d){if(d instanceof Ge)return d;try{return l.machine.getStateNodeById(d.id)}catch{}}function s(l,d){if(!d||typeof d!="object")return{};const p={};for(const g in d){const y=d[g];for(const I of y){const R=o(l,I);R&&(p[g]??=[],p[g].push(R))}}return p}const a=s(this.root,t.historyValue),c=Re({...t,children:r,_nodes:Array.from(Oe(Ne(this.root,t.value))),historyValue:a},this),u=new Set;function f(l,d){if(!u.has(l)){u.add(l);for(const p in l){const g=l[p];if(g&&typeof g=="object"){if("xstate$$type"in g&&g.xstate$$type===Ke){l[p]=d[g.id];continue}f(g,d)}}}}return f(c.context,r),c}}function Pr(e,t,n,r,{event:i}){const o=typeof i=="function"?i(n,r):i;return[t,{event:o},void 0]}function kr(e,{event:t}){e.defer(()=>e.emit(t))}function Ut(e){function t(n,r){}return t.type="xstate.emit",t.event=e,t.resolve=Pr,t.execute=kr,t}let it=(function(e){return e.Parent="#_parent",e.Internal="#_internal",e})({});function Dr(e,t,n,r,{to:i,event:o,id:s,delay:a},c){const u=t.machine.implementations.delays;if(typeof o=="string")throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${o}" }) instead`);const f=typeof o=="function"?o(n,r):o;let l;if(typeof a=="string"){const g=u&&u[a];l=typeof g=="function"?g(n,r):g}else l=typeof a=="function"?a(n,r):a;const d=typeof i=="function"?i(n,r):i;let p;if(typeof d=="string"){if(d===it.Parent?p=e.self._parent:d===it.Internal?p=e.self:d.startsWith("#_")?p=t.children[d.slice(2)]:p=c.deferredActorIds?.includes(d)?d:t.children[d],!p)throw new Error(`Unable to send event to actor '${d}' from machine '${t.machine.id}'.`)}else p=d||e.self;return[t,{to:p,targetId:typeof d=="string"?d:void 0,event:f,id:s,delay:l},void 0]}function Er(e,t,n){typeof n.to=="string"&&(n.to=t.children[n.to])}function Ar(e,t){e.defer(()=>{const{to:n,event:r,delay:i,id:o}=t;if(typeof i=="number"){e.system.scheduler.schedule(e.self,n,r,i,o);return}e.system._relay(e.self,n,r.type===An?vt(e.self.id,r.data):r)})}function Le(e,t,n){function r(i,o){}return r.type="xstate.sendTo",r.to=e,r.event=t,r.id=n?.id,r.delay=n?.delay,r.resolve=Dr,r.retryResolve=Er,r.execute=Ar,r}function Mr(e,t){return Le(it.Parent,e,t)}function Or(e,t,n,r,{collect:i}){const o=[],s=function(c){o.push(c)};return s.assign=(...a)=>{o.push(C(...a))},s.cancel=(...a)=>{o.push(ze(...a))},s.raise=(...a)=>{o.push(rt(...a))},s.sendTo=(...a)=>{o.push(Le(...a))},s.sendParent=(...a)=>{o.push(Mr(...a))},s.spawnChild=(...a)=>{o.push(Je(...a))},s.stopChild=(...a)=>{o.push(Ae(...a))},s.emit=(...a)=>{o.push(Ut(...a))},i({context:n.context,event:n.event,enqueue:s,check:a=>Me(a,t.context,n.event,t),self:e.self,system:e.system},r),[t,void 0,o]}function Fr(e){function t(n,r){}return t.type="xstate.enqueueActions",t.collect=e,t.resolve=Or,t}function Cr(e,t,n,r,{value:i,label:o}){return[t,{value:typeof i=="function"?i(n,r):i,label:o},void 0]}function Nr({logger:e},{value:t,label:n}){n?e(n,t):e(t)}function Rr(e=({context:n,event:r})=>({context:n,event:r}),t){function n(r,i){}return n.type="xstate.log",n.value=e,n.label=t,n.resolve=Cr,n.execute=Nr,n}function jr(e,t){return new st(e,t)}function Vt({schemas:e,actors:t,actions:n,guards:r,delays:i}){return{assign:C,sendTo:Le,raise:rt,log:Rr,cancel:ze,stopChild:Ae,enqueueActions:Fr,emit:Ut,spawnChild:Je,createStateConfig:o=>o,createAction:o=>o,createMachine:o=>jr({...o,schemas:e},{actors:t,actions:n,guards:r,delays:i}),extend:o=>Vt({schemas:e,actors:t,actions:{...n,...o.actions},guards:{...r,...o.guards},delays:{...i,...o.delays}})}}class Kt{actor;subscription=null;options;constructor(t,n){this.options=n,this.actor=re(t),this.setupSubscriptions(),n?.enableLogging!==void 0&&this.setLogging(n.enableLogging),n?.baudRate!==void 0&&this.setBaudRate(n.baudRate),this.actor.start()}setupSubscriptions(){this.subscription=this.actor.subscribe(t=>{if(this.options?.onData&&t.context.data!==void 0&&this.options.onData(t.context.data),this.options?.onStateChange){const n=t.value==="connected";this.options.onStateChange(n)}this.options?.onError&&t.context.error&&this.options.onError(t.context.error)})}get data(){return this.actor.getSnapshot().context.data}get isConnected(){return this.actor.getSnapshot().value==="connected"}get isConnecting(){return this.actor.getSnapshot().value==="connecting"}get error(){return this.actor.getSnapshot().context.error}connect(){this.actor.send({type:"CONNECT"})}disconnect(){this.actor.send({type:"DISCONNECT"})}setLogging(t){this.actor.send({type:"SET_LOGGING",enabled:t})}setBaudRate(t){this.actor.send({type:"SET_BAUD_RATE",baudRate:t})}get machine(){return this.actor}dispose(){this.subscription&&(this.subscription.unsubscribe(),this.subscription=null),this.actor.stop()}}var O={},oe={},b={},zt;function P(){if(zt)return b;zt=1,Object.defineProperty(b,"__esModule",{value:!0});var e=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];function t(h){var v=h>>4&15,m=h>>0&15;return e[v]+e[m]}b.toHexString=t;function n(h,v,m){for(var S=typeof h=="string"?h:h.toFixed(0);S.length<v;)S=m+S;return S}b.padLeft=n;function r(h){var v=h.split("*"),m=v[0],S=v[1],D=i(m),M=parseInt(S,16);return D===M}b.validNmeaChecksum=r;function i(h){for(var v=h.charCodeAt(1),m=2;m<h.length;m+=1)v=v^h.charCodeAt(m);return v=v&255,v}b.computeNmeaChecksum=i;function o(h){return"*"+t(i(h))}b.createNmeaChecksumFooter=o;function s(h){return h+o(h)}b.appendChecksumFooter=s;function a(h,v){return h===void 0?"":h.toFixed(v)}b.encodeFixed=a;function c(h){if(h===void 0)return",";var v;h<0?(v="S",h=-h):v="N";var m=Math.floor(h),S=n(m,2,"0"),D=h-m,M=D*60,G=n(M.toFixed(6),9,"0");return S=S+G+","+v,S}b.encodeLatitude=c;function u(h){if(h===void 0)return",";var v;h<0?(v="W",h=-h):v="E";var m=Math.floor(h),S=n(m,3,"0"),D=h-m,M=D*60,G=n(M.toFixed(6),9,"0");return S=S+G+","+v,S}b.encodeLongitude=u;function f(h){return h===void 0?",":h.toFixed(1)+",M"}b.encodeAltitude=f;function l(h){return h===void 0?"":h.toFixed(1)}b.encodeAltitudeNoUnits=l;function d(h){return h===void 0?",":h.toFixed(1)+",M"}b.encodeGeoidalSeperation=d;function p(h){return h===void 0?"":h.toFixed(1)}b.encodeGeoidalSeperationNoUnits=p;function g(h){return h===void 0?"":n(h.toFixed(2),6,"0")}b.encodeDegrees=g;function y(h){if(h===void 0)return"";var v=h.getUTCFullYear(),m=h.getUTCMonth()+1,S=h.getUTCDate();return n(S,2,"0")+n(m,2,"0")+v.toFixed(0).substr(2)}b.encodeDate=y;function I(h){if(h===void 0)return"";var v=h.getUTCHours(),m=h.getUTCMinutes(),S=h.getUTCSeconds();return n(v,2,"0")+n(m,2,"0")+n(S,2,"0")}b.encodeTime=I;function R(h){return h===void 0?"":h.toString()}b.encodeValue=R;function j(h){return h===""?0:parseFloat(h)}b.parseFloatSafe=j;function Q(h){return h===""?0:parseInt(h,10)}b.parseIntSafe=Q;function at(h){if(h===void 0)return"";var v=parseFloat(h);return v===NaN?h:v}b.parseNumberOrString=at;function Ee(h){var v=h.indexOf(".");if(v<0)return 0;var m,S;return v>=3?(m=h.substring(0,v-2),S=h.substring(v-2)):(m="0",S=h),parseFloat(m)+parseFloat(S)/60}b.parseDmCoordinate=Ee;function ct(h,v){var m=v==="N"?1:-1;return Ee(h)*m}b.parseLatitude=ct;function ut(h,v){var m=v==="E"?1:-1;return Ee(h)*m}b.parseLongitude=ut;function dt(h,v){if(h==="")return new Date(0);var m=new Date;if(v){var S=v.slice(4),D=parseInt(v.slice(2,4),10)-1,M=v.slice(0,2);S.length===4?m.setUTCFullYear(Number(S),Number(D),Number(M)):m.setUTCFullYear(+("20"+S),Number(D),Number(M))}m.setUTCHours(Number(h.slice(0,2))),m.setUTCMinutes(Number(h.slice(2,4))),m.setUTCSeconds(Number(h.slice(4,6)));var G=h.slice(7),$=G.length,V=0;return $!==0&&(V=parseFloat(G)*Math.pow(10,3-$)),m.setUTCMilliseconds(Number(V)),m}b.parseTime=dt;function ft(h,v){var m=parseInt(h.slice(0,2),10),S=parseInt(h.slice(2,4),10),D=parseInt(h.slice(4,6),10);D<73?D=D+2e3:D=D+1900;var M=parseInt(v.slice(0,2),10),G=parseInt(v.slice(2,4),10),$=parseInt(v.slice(4,6),10),V=0;return v.length===9&&(V=parseInt(v.slice(7,9),10)*10),new Date(Date.UTC(D,S-1,m,M,G,$,V))}return b.parseDatetime=ft,b}var ae={},Jt;function w(){if(Jt)return ae;Jt=1,Object.defineProperty(ae,"__esModule",{value:!0});function e(n,r,i){return{sentenceId:r,talkerId:n.talkerId,chxOk:n.chxOk,sentenceName:i}}ae.initStubFields=e;function t(n,r){var i,o;return n.charAt(1)==="P"?(i="P",o=n.substr(2)):(i=n.substr(1,2),o=n.substr(3)),{talkerId:i,sentenceId:o,chxOk:r||void 0}}return ae.parseStub=t,ae}var Zt;function Gr(){return Zt||(Zt=1,(function(e){var t=oe&&oe.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="APB",e.sentenceName='Autopilot sentence "B"';function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{status1:s[1],status2:s[2],xteMagn:n.parseFloatSafe(s[3]),steerDir:s[4],xteUnit:s[5],arrivalCircleStatus:s[6],arrivalPerpendicularStatus:s[7],bearingOrig2Dest:n.parseFloatSafe(s[8]),bearingOrig2DestType:s[9],waypoint:s[10],bearing2Dest:n.parseFloatSafe(s[11]),bearingDestType:s[12],heading2steer:n.parseFloatSafe(s[13]),headingDestType:s[14]})}e.decodeSentence=i})(oe)),oe}var ce={},Yt;function Lr(){return Yt||(Yt=1,(function(e){var t=ce&&ce.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="BWC",e.sentenceName="Bearing and distance to waypoint - great circle";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{time:n.parseTime(s[1]),bearingLatitude:n.parseLatitude(s[2],s[3]),bearingLongitude:n.parseLongitude(s[4],s[5]),bearingTrue:n.parseFloatSafe(s[6]),bearingMagnetic:n.parseFloatSafe(s[8]),distanceNm:n.parseFloatSafe(s[10]),waypointId:s[12],faaMode:s[13]})}e.decodeSentence=i})(ce)),ce}var ue={},Xt;function xr(){return Xt||(Xt=1,(function(e){var t=ue&&ue.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="DBT",e.sentenceName="Depth below transducer";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{depthFeet:n.parseFloatSafe(a[1]),depthMeters:n.parseFloatSafe(a[3]),depthFathoms:n.parseFloatSafe(a[5])})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeFixed(s.depthFeet,2)),c.push("f"),c.push(n.encodeFixed(s.depthMeters,2)),c.push("M"),c.push(n.encodeFixed(s.depthFathoms,2)),c.push("F");var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(ue)),ue}var de={},Qt;function qr(){return Qt||(Qt=1,(function(e){var t=de&&de.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="DTM",e.sentenceName="Datum reference";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{datumCode:o(a[1]),datumSubcode:a[2]||void 0,offsetLatitude:n.parseLatitude(a[3],a[4]),offsetLongitude:n.parseLongitude(a[5],a[6]),offsetAltitudeMeters:n.parseFloatSafe(a[7]),datumName:o(a[8])})}e.decodeSentence=i;function o(s){return s==="W84"?"W84":s==="W72"?"W72":s==="S85"?"S85":s==="P90"?"P90":s==="999"?"999":""}})(de)),de}var fe={},$t;function Wr(){return $t||($t=1,(function(e){var t=fe&&fe.__assign||function(){return t=Object.assign||function(a){for(var c,u=1,f=arguments.length;u<f;u++){c=arguments[u];for(var l in c)Object.prototype.hasOwnProperty.call(c,l)&&(a[l]=c[l])}return a},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GGA",e.sentenceName="Global positioning system fix data";var i=["none","fix","delta","pps","rtk","frtk","estimated","manual","simulation"];function o(a,c){return t(t({},r.initStubFields(a,e.sentenceId,e.sentenceName)),{time:n.parseTime(c[1]),latitude:n.parseLatitude(c[2],c[3]),longitude:n.parseLongitude(c[4],c[5]),fixType:i[n.parseIntSafe(c[6])],satellitesInView:n.parseIntSafe(c[7]),horizontalDilution:n.parseFloatSafe(c[8]),altitudeMeters:n.parseFloatSafe(c[9]),geoidalSeperation:n.parseFloatSafe(c[11]),differentialAge:n.parseFloatSafe(c[13]),differentialRefStn:c[14]})}e.decodeSentence=o;function s(a,c){var u=["$"+c+e.sentenceId];u.push(n.encodeTime(a.time)),u.push(n.encodeLatitude(a.latitude)),u.push(n.encodeLongitude(a.longitude)),u.push(n.encodeValue(i.indexOf(a.fixType))),u.push(n.encodeValue(a.satellitesInView)),u.push(n.encodeFixed(a.horizontalDilution,1)),u.push(n.encodeAltitude(a.altitudeMeters)),u.push(n.encodeGeoidalSeperation(a.geoidalSeperation)),u.push(n.encodeFixed(a.differentialAge,2)),u.push(n.encodeValue(a.differentialRefStn));var f=u.join(",");return f+n.createNmeaChecksumFooter(f)}e.encodePacket=s})(fe)),fe}var le={},en;function Br(){return en||(en=1,(function(e){var t=le&&le.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GLL",e.sentenceName="Geographic position - latitude and longitude";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{latitude:n.parseLatitude(a[1],a[2]),longitude:n.parseLongitude(a[3],a[4]),time:n.parseTime(a[5]),status:a[6]==="A"?"valid":"invalid",faaMode:a[7]})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeLatitude(s.latitude)),c.push(n.encodeLongitude(s.longitude)),c.push(n.encodeTime(s.time)),c.push(s.status==="valid"?"A":"V"),s.faaMode&&c.push(s.faaMode);var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(le)),le}var he={},tn;function Hr(){return tn||(tn=1,(function(e){var t=he&&he.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GNS",e.sentenceName="GNSS fix data";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{time:n.parseTime(a[1]),latitude:n.parseLatitude(a[2],a[3]),longitude:n.parseLongitude(a[4],a[5]),modeIndicator:a[6],satellitesInView:n.parseIntSafe(a[7]),horizontalDilution:n.parseFloatSafe(a[8]),altitudeMeters:n.parseFloatSafe(a[9]),geoidalSeperation:n.parseFloatSafe(a[10]),differentialAge:n.parseFloatSafe(a[11]),differentialRefStn:a[12]})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeTime(s.time)),c.push(n.encodeLatitude(s.latitude)),c.push(n.encodeLongitude(s.longitude)),c.push(s.modeIndicator),c.push(n.encodeValue(s.satellitesInView)),c.push(n.encodeFixed(s.horizontalDilution,1)),c.push(n.encodeAltitudeNoUnits(s.altitudeMeters)),c.push(n.encodeGeoidalSeperationNoUnits(s.geoidalSeperation)),c.push(n.encodeFixed(s.differentialAge,2)),c.push(n.encodeValue(s.differentialRefStn));var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(he)),he}var pe={},nn;function Ur(){return nn||(nn=1,(function(e){var t=pe&&pe.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GSA",e.sentenceName="Active satellites and dilution of precision";var i=["unknown","none","2D","3D"];function o(s,a){for(var c=[],u=3;u<15;u++)a[u]&&c.push(+a[u]);return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{selectionMode:a[1]==="A"?"automatic":"manual",fixMode:i[n.parseIntSafe(a[2])],satellites:c,PDOP:n.parseFloatSafe(a[15]),HDOP:n.parseFloatSafe(a[16]),VDOP:n.parseFloatSafe(a[17])})}e.decodeSentence=o})(pe)),pe}var ge={},rn;function Vr(){return rn||(rn=1,(function(e){var t=ge&&ge.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GST",e.sentenceName="GPS pseudorange noise statistics";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{time:n.parseTime(s[1]),totalRms:n.parseFloatSafe(s[2]),semiMajorError:n.parseFloatSafe(s[3]),semiMinorError:n.parseFloatSafe(s[4]),orientationOfSemiMajorError:n.parseFloatSafe(s[5]),latitudeError:n.parseFloatSafe(s[6]),longitudeError:n.parseFloatSafe(s[7]),altitudeError:n.parseFloatSafe(s[8])})}e.decodeSentence=i})(ge)),ge}var ve={},sn;function Kr(){return sn||(sn=1,(function(e){var t=ve&&ve.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="GSV",e.sentenceName="Satellites in view";function i(o,s){for(var a=(s.length-4)/4,c=[],u=0;u<a;u++){var f=u*4+4;c.push({prnNumber:n.parseIntSafe(s[f]),elevationDegrees:n.parseIntSafe(s[f+1]),azimuthTrue:n.parseIntSafe(s[f+2]),SNRdB:n.parseIntSafe(s[f+3])})}return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{numberOfMessages:n.parseIntSafe(s[1]),messageNumber:n.parseIntSafe(s[2]),satellitesInView:n.parseIntSafe(s[3]),satellites:c})}e.decodeSentence=i})(ve)),ve}var me={},on;function zr(){return on||(on=1,(function(e){var t=me&&me.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="HDG",e.sentenceName="Heading - deviation and variation";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{heading:n.parseFloatSafe(s[1]),deviation:n.parseFloatSafe(s[2]),deviationDirection:s[3]==="E"?"E":s[3]==="W"?"W":"",variation:n.parseFloatSafe(s[4]),variationDirection:s[5]==="E"?"E":s[5]==="W"?"W":""})}e.decodeSentence=i})(me)),me}var ye={},an;function Jr(){return an||(an=1,(function(e){var t=ye&&ye.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="HDM",e.sentenceName="Heading - magnetic";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{heading:n.parseFloatSafe(a[1])})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeFixed(s.heading,1)),c.push("M");var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(ye)),ye}var Se={},cn;function Zr(){return cn||(cn=1,(function(e){var t=Se&&Se.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="HDT",e.sentenceName="Heading - true";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{heading:n.parseFloatSafe(a[1])})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeFixed(s.heading,1)),c.push("T");var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(Se)),Se}var _e={},un;function Yr(){return un||(un=1,(function(e){var t=_e&&_e.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="MTK",e.sentenceName="Configuration packet";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{packetType:n.parseIntSafe(s.sentenceId.substr(3)),data:a.slice(1).map(n.parseNumberOrString)})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId+n.padLeft(s.packetType,3,"0")];c=c.concat(s.data.toString());var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(_e)),_e}var be={},dn;function Xr(){return dn||(dn=1,(function(e){var t=be&&be.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="MWV",e.sentenceName="Wind speed and angle";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{windAngle:n.parseFloatSafe(a[1]),reference:a[2]==="R"?"relative":"true",speed:n.parseFloatSafe(a[3]),units:a[4]==="K"?"K":a[4]==="M"?"M":"N",status:a[5]==="A"?"valid":"invalid"})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeDegrees(s.windAngle)),c.push(s.reference==="relative"?"R":"T"),c.push(n.encodeFixed(s.speed,2)),c.push(s.units==="K"?"K":s.units==="M"?"M":"N"),c.push(s.status==="valid"?"A":"V");var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(be)),be}var Te={},fn;function Qr(){return fn||(fn=1,(function(e){var t=Te&&Te.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="RDID",e.sentenceName="RDI proprietary heading, pitch, and roll";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{roll:n.parseFloatSafe(s[1]),pitch:n.parseFloatSafe(s[2]),heading:n.parseFloatSafe(s[3])})}e.decodeSentence=i})(Te)),Te}var Ie={},ln;function $r(){return ln||(ln=1,(function(e){var t=Ie&&Ie.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="RMC",e.sentenceName="Recommended minimum navigation information";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{datetime:n.parseDatetime(s[9],s[1]),status:s[2]==="A"?"valid":"warning",latitude:n.parseLatitude(s[3],s[4]),longitude:n.parseLongitude(s[5],s[6]),speedKnots:n.parseFloatSafe(s[7]),trackTrue:n.parseFloatSafe(s[8]),variation:n.parseFloatSafe(s[10]),variationPole:s[11]==="E"?"E":s[11]==="W"?"W":"",faaMode:s[12]})}e.decodeSentence=i})(Ie)),Ie}var we={},hn;function es(){return hn||(hn=1,(function(e){var t=we&&we.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="VHW",e.sentenceName="Water speed and heading";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{degreesTrue:n.parseFloatSafe(s[1]),degreesMagnetic:n.parseFloatSafe(s[3]),speedKnots:n.parseFloatSafe(s[5]),speedKmph:n.parseFloatSafe(s[7])})}e.decodeSentence=i})(we)),we}var Pe={},pn;function ts(){return pn||(pn=1,(function(e){var t=Pe&&Pe.__assign||function(){return t=Object.assign||function(s){for(var a,c=1,u=arguments.length;c<u;c++){a=arguments[c];for(var f in a)Object.prototype.hasOwnProperty.call(a,f)&&(s[f]=a[f])}return s},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="VTG",e.sentenceName="Track made good and ground speed";function i(s,a){return t(t({},r.initStubFields(s,e.sentenceId,e.sentenceName)),{trackTrue:n.parseFloatSafe(a[1]),trackMagnetic:n.parseFloatSafe(a[3]),speedKnots:n.parseFloatSafe(a[5]),speedKmph:n.parseFloatSafe(a[7]),faaMode:a[9]})}e.decodeSentence=i;function o(s,a){var c=["$"+a+e.sentenceId];c.push(n.encodeDegrees(s.trackTrue)),c.push("T"),c.push(n.encodeDegrees(s.trackMagnetic)),c.push("M"),c.push(n.encodeFixed(s.speedKnots,2)),c.push("N"),s.speedKmph?(c.push(n.encodeFixed(s.speedKmph,2)),c.push("K")):(c.push(""),c.push("")),s.faaMode&&c.push(s.faaMode);var u=c.join(",");return u+n.createNmeaChecksumFooter(u)}e.encodePacket=o})(Pe)),Pe}var ke={},gn;function ns(){return gn||(gn=1,(function(e){var t=ke&&ke.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=P(),r=w();e.sentenceId="ZDA",e.sentenceName="UTC, day, month, year, and local time zone";function i(o,s){return t(t({},r.initStubFields(o,e.sentenceId,e.sentenceName)),{datetime:n.parseTime(s[1],s.slice(2,5).join("")),localZoneHours:n.parseIntSafe(s[5]),localZoneMinutes:n.parseIntSafe(s[6])})}e.decodeSentence=i})(ke)),ke}var De={},vn;function mn(){return vn||(vn=1,(function(e){var t=De&&De.__assign||function(){return t=Object.assign||function(i){for(var o,s=1,a=arguments.length;s<a;s++){o=arguments[s];for(var c in o)Object.prototype.hasOwnProperty.call(o,c)&&(i[c]=o[c])}return i},t.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var n=w();e.sentenceId="?";function r(i,o){return t(t({},n.initStubFields(i,e.sentenceId)),{originalPacketId:i.sentenceId,dataFields:o.slice(1)})}e.decodeSentence=r})(De)),De}var yn;function rs(){if(yn)return O;yn=1;var e=O&&O.__extends||(function(){var _=function(T,k){return _=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(A,W){A.__proto__=W}||function(A,W){for(var ee in W)W.hasOwnProperty(ee)&&(A[ee]=W[ee])},_(T,k)};return function(T,k){_(T,k);function A(){this.constructor=T}T.prototype=k===null?Object.create(k):(A.prototype=k.prototype,new A)}})();Object.defineProperty(O,"__esModule",{value:!0});var t=Gr(),n=Lr(),r=xr(),i=qr(),o=Wr(),s=Br(),a=Hr(),c=Ur(),u=Vr(),f=Kr(),l=zr(),d=Jr(),p=Zr(),g=Yr(),y=Xr(),I=Qr(),R=$r(),j=es(),Q=ts(),at=ns(),Ee=w(),ct=mn(),ut=P(),dt={APB:t.decodeSentence,BWC:n.decodeSentence,DBT:r.decodeSentence,DTM:i.decodeSentence,GGA:o.decodeSentence,GLL:s.decodeSentence,GNS:a.decodeSentence,GSA:c.decodeSentence,GST:u.decodeSentence,GSV:f.decodeSentence,HDG:l.decodeSentence,HDM:d.decodeSentence,HDT:p.decodeSentence,MTK:g.decodeSentence,MWV:y.decodeSentence,RDID:I.decodeSentence,RMC:R.decodeSentence,VHW:j.decodeSentence,VTG:Q.decodeSentence,ZDA:at.decodeSentence},ft={DBT:r.encodePacket,GGA:o.encodePacket,GLL:s.encodePacket,GNS:a.encodePacket,HDM:d.encodePacket,HDT:p.encodePacket,MTK:g.encodePacket,MWV:y.encodePacket,VTG:Q.encodePacket},h=(function(){function _(T){T===void 0&&(T=!1),this.ableToParseBadChecksum=T}return _.getParser=function(T){return T.sentenceId.substr(0,3)==="MTK"?g.decodeSentence:dt[T.sentenceId]},_.prototype.assemble=function(T,k){var A=_.getParser(T);return A?A(T,k):this.assembleCustomPacket(T,k)},_.prototype.assembleCustomPacket=function(T,k){return null},_})();O.DefaultPacketFactory=h;var v=new h;function m(_,T){var k=!0;if(!ut.validNmeaChecksum(_)){if(!T.ableToParseBadChecksum)throw Error('Invalid sentence: "'+_+'".');k=!1}var A=_.split("*")[0].split(","),W=Ee.parseStub(A[0],k),ee=T.assemble(W,A);if(!ee)throw Error('No known parser for sentence ID "'+W.sentenceId+'".');return ee}O.parseGenericPacket=m;function S(_){return m(_,v)}O.parseNmeaSentence=S;function D(_,T){if(T===void 0&&(T="P"),_===void 0)throw new Error("Packet must be given.");var k=ft[_.sentenceId];if(k)return k(_,T);throw Error('No known encoder for sentence ID "'+_.sentenceId+'"')}O.encodeNmeaPacket=D;var M=(function(_){e(T,_);function T(){return _.call(this,!0)||this}return T.prototype.assembleCustomPacket=function(k,A){return ct.decodeSentence(k,A)},T})(h);O.UnsafePacketFactory=M;var G=new M;function $(_){return m(_,G)}O.parseUnsafeNmeaSentence=$;function V(_){return _.sentenceId==="?"?_.originalPacketId:_.sentenceId}return O.getUnsafePacketId=V,O}var xe=rs(),ss=mn(),ot=w();function L(e){return e===""?0:Number.parseFloat(e)}const is="DBK",os="Depth Below Keel";function as(e,t){return{...ot.initStubFields(e,is,os),depthFeet:L(t[1]),depthMeters:L(t[3]),depthFathoms:L(t[5])}}const cs="DBS",us="Depth Below Surface";function ds(e,t){return{...ot.initStubFields(e,cs,us),depthFeet:L(t[1]),depthMeters:L(t[3]),depthFathoms:L(t[5])}}const fs="DPT",ls="Depth of Water";function hs(e,t){return{...ot.initStubFields(e,fs,ls),depthMeters:L(t[1]),offsetMeters:L(t[2]),maximumRangeScale:L(t[3])}}function Sn(e,t){switch(e.talkerId){case"DBS":return ds(e,t);case"DBK":return as(e,t);case"DPT":return hs(e,t);default:return null}}class ps extends xe.DefaultPacketFactory{assembleCustomPacket(t,n){return Sn(t,n)}}const gs=new ps;function vs(e){return xe.parseGenericPacket(e,gs)}class ms extends xe.DefaultPacketFactory{constructor(){super(!0)}assembleCustomPacket(t,n){const r=Sn(t,n);return r||ss.decodeSentence(t,n)}}const ys=new ms;function _n(e){return xe.parseGenericPacket(e,ys)}function bn(e,t){return!t||t.length===0?!0:e!==void 0&&t.includes(e)}class Ss{container;constructor(){this.container=""}transform(t,n){this.container+=t;const r=this.container.split(`\r
4
- `),i=r.pop();this.container=i??"",r.forEach(o=>{o.length>0&&n.enqueue(o)})}flush(t){this.container=""}}const _s=Bt(async({input:e})=>{if(!navigator.serial)throw new Error("Web Serial API is not supported in this browser.");console.log("Requesting serial port...");const t=await navigator.serial.requestPort();if(console.log(`Opening port at ${e.baudRate} baud...`),t.readable||t.writable){console.log("Port is already open, closing first...");try{await t.close()}catch(n){console.warn("Error closing already-open port:",n)}}return await t.open({baudRate:e.baudRate}),console.log("Port open."),t}),bs=Bt(async({input:e})=>{if(e.port)try{(e.port.readable||e.port.writable)&&(await e.port.close(),console.log("Port closed successfully."))}catch(t){console.warn("Error closing port:",t)}}),Ts=_r(({input:e,sendBack:t,receive:n})=>{const{port:r}=e;if(!r||!r.readable){t({type:"SERIAL.ERROR",error:"Invalid port context."});return}const i=new Ss,s=r.readable.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform:i.transform.bind(i),flush:i.flush.bind(i)})).getReader();let a=!0;async function c(){try{for(;a;){const{value:u,done:f}=await s.read();if(f)break;if(u&&u.length>0)try{const l=_n(u);if(l.sentenceId==="?")continue;t({type:"SERIAL.DATA",data:l})}catch(l){const d=l instanceof Error?l.message:String(l);console.warn("Failed to parse NMEA sentence:",u,d),t({type:"SERIAL.ERROR",error:`Parser Error: ${d}`})}}}catch(u){if(console.error("Read loop error:",u),a){const f=u instanceof Error?u.message:String(u);t({type:"FATAL_ERROR",error:f})}}finally{console.log("Read loop finished."),t({type:"SERIAL.DISCONNECTED"})}}return c(),n(u=>{u.type==="STOP"&&(console.log("Received STOP, cancelling reader..."),a=!1,s.cancel().catch(()=>{}))}),()=>{console.log("Cleaning up stream reader actor..."),a=!1,s&&s.cancel().catch(()=>{})}});function Tn(e){const{adapter:t,allowedSentenceIds:n,initialData:r,initialPackets:i}=e;return Vt({actors:{connectToSerial:_s,readNmeaStream:Ts,closePort:bs},actions:{setPort:C((o,s)=>({port:s.port,error:null})),setError:C((o,s)=>{const a=s.error;let c;return typeof a=="string"?c=a:a instanceof Error?c=a.message||"Failed to connect.":c=String(a)||"Failed to connect.",{error:c}}),logParsedData:({context:o},s)=>{if(!o.enableLogging)return;const c=s.packet.sentenceId;bn(c,n)&&console.log(`${c} Packet:`,s.packet)},storePacket:C(({context:o},s)=>{const c=s.packet.sentenceId;if(c&&bn(c,n)){const u={...o.packets,[c]:s.packet};return{packets:u,data:t(u),error:null}}return{packets:o.packets,data:t(o.packets),error:null}}),clearError:C((o,s)=>({error:s.error})),setFatalError:C((o,s)=>({error:s.error})),disconnect:C({port:null,error:null,packets:i,data:r}),setLogging:C((o,s)=>({enableLogging:s.enabled})),setBaudRate:C((o,s)=>({baudRate:s.baudRate}))}}).createMachine({id:"nmea",initial:"disconnected",context:{port:null,error:null,packets:i,data:r,enableLogging:!1,baudRate:4800},on:{SET_LOGGING:{actions:{type:"setLogging",params:({event:o})=>({enabled:o.enabled})}}},states:{disconnected:{on:{CONNECT:"connecting",SET_BAUD_RATE:{actions:{type:"setBaudRate",params:({event:o})=>({baudRate:o.baudRate})}}}},connecting:{invoke:{id:"connectToSerial",src:"connectToSerial",input:({context:o})=>({baudRate:o.baudRate}),onDone:{target:"connected",actions:{type:"setPort",params:({event:o})=>({port:o.output})}},onError:{target:"error",actions:{type:"setError",params:({event:o})=>({error:o.error})}}}},connected:{on:{"SERIAL.DATA":{actions:[{type:"logParsedData",params:({event:o})=>({packet:o.data})},{type:"storePacket",params:({event:o})=>({packet:o.data})}]},"SERIAL.ERROR":{actions:{type:"clearError",params:({event:o})=>({error:o.error})}},FATAL_ERROR:{target:"error",actions:{type:"setFatalError",params:({event:o})=>({error:o.error})}},"SERIAL.DISCONNECTED":{target:"disconnecting"},DISCONNECT:{actions:Le("streamReader",{type:"STOP"})}},invoke:{id:"streamReader",src:"readNmeaStream",input:({context:o})=>({port:o.port})}},disconnecting:{invoke:{id:"closePort",src:"closePort",input:({context:o})=>({port:o.port}),onDone:{target:"disconnected",actions:"disconnect"},onError:{target:"disconnected",actions:"disconnect"}}},error:{on:{CONNECT:"connecting"}}}})}function Is(e,t,n){return e&&e.fixType!=="none"?{latitude:e.latitude,longitude:e.longitude,source:"GGA",fixType:e.fixType,altitudeMeters:e.altitudeMeters,satellitesInView:e.satellitesInView,horizontalDilution:e.horizontalDilution}:t&&t.status==="valid"?{latitude:t.latitude,longitude:t.longitude,source:"RMC",status:t.status}:n&&n.status==="valid"?{latitude:n.latitude,longitude:n.longitude,source:"GLL",status:"valid"}:null}function ws(e,t,n,r){if(e){const i=new Date(e.datetime),o=e.localZoneHours*60+e.localZoneMinutes;return i.setMinutes(i.getMinutes()+o),{utc:e.datetime,local:i,source:"ZDA"}}return t&&t.fixType!=="none"?{utc:t.time,local:null,source:"GGA"}:n&&n.status==="valid"?{utc:n.datetime,local:null,source:"RMC"}:r&&r.status==="valid"?{utc:r.time,local:null,source:"GLL"}:null}function Ps(e,t){return e?{knots:e.speedKnots,source:"VTG"}:t&&t.status==="valid"?{knots:t.speedKnots,source:"RMC"}:null}function ks(e){return e.variationDirection==="W"?-e.variation:(e.variationDirection==="E",e.variation)}function Ds(e,t,n,r){if(e&&e.heading!==void 0)return{degreesTrue:e.heading,source:"HDT",isDerived:!1};if(t&&t.heading!==void 0){const o=ks(t);return{degreesTrue:t.heading+o,source:"HDG",isDerived:!1}}const i=n?.trackTrue??r?.trackTrue;return i!==void 0?{degreesTrue:i,source:"COG",isDerived:!0}:null}function Es(e,t,n,r){return e&&e.depthMeters!==void 0?{meters:e.depthMeters,source:"DPT"}:t?{meters:t.depthMeters,source:"DBT"}:n&&n.depthMeters!==void 0?{meters:n.depthMeters,source:"DBS"}:r&&r.depthMeters!==void 0?{meters:r.depthMeters,source:"DBK"}:null}function As(e){const t=ws(e.ZDA,e.GGA,e.RMC,e.GLL),n=Is(e.GGA,e.RMC,e.GLL),r=Ps(e.VTG,e.RMC),i=Ds(e.HDT,e.HDG,e.RMC,e.VTG),o=Es(e.DPT,e.DBT,e.DBS,e.DBK);return{time:t,position:n,speed:r,heading:i,depth:o}}const Ms=["GGA","RMC","GLL","VTG","HDT","HDG","DPT","DBT","DBS","DBK","ZDA"];function Os(){return e=>As(e)}const Fs={time:null,position:null,speed:null,heading:null,depth:null},Cs={};function Ns(){return{adapter:Os(),allowedSentenceIds:Ms,initialData:Fs,initialPackets:Cs}}function In(){return Tn(Ns())}function Rs(e){const t=In();return new Kt(t,{enableLogging:e?.enableLogging,baudRate:e?.baudRate,onData:e?.onData,onStateChange:e?.onStateChange,onError:e?.onError})}F.NmeaClient=Kt,F.createNavigationNmeaClient=Rs,F.createNavigationNmeaMachine=In,F.createNmeaMachine=Tn,F.parseNmeaSentence=vs,F.parseUnsafeNmeaSentence=_n,Object.defineProperty(F,Symbol.toStringTag,{value:"Module"})}));
4
+ `),i=r.pop();this.container=i??"",r.forEach(o=>{o.length>0&&n.enqueue(o)})}flush(t){this.container=""}}const _s=Bt(async({input:e})=>{if(!navigator.serial)throw new Error("Web Serial API is not supported in this browser.");console.log("Requesting serial port...");const t=await navigator.serial.requestPort();if(console.log(`Opening port at ${e.baudRate} baud...`),t.readable||t.writable){console.log("Port is already open, closing first...");try{await t.close()}catch(n){console.warn("Error closing already-open port:",n)}}return await t.open({baudRate:e.baudRate}),console.log("Port open."),t}),bs=Bt(async({input:e})=>{if(e.port)try{(e.port.readable||e.port.writable)&&(await e.port.close(),console.log("Port closed successfully."))}catch(t){console.warn("Error closing port:",t)}}),Ts=_r(({input:e,sendBack:t,receive:n})=>{const{port:r}=e;if(!r||!r.readable){t({type:"SERIAL.ERROR",error:"Invalid port context."});return}const i=new Ss,s=r.readable.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform:i.transform.bind(i),flush:i.flush.bind(i)})).getReader();let a=!0;async function c(){try{for(;a;){const{value:u,done:f}=await s.read();if(f)break;if(u&&u.length>0)try{const l=_n(u);if(l.sentenceId==="?")continue;t({type:"SERIAL.DATA",data:l})}catch(l){const d=l instanceof Error?l.message:String(l);console.warn("Failed to parse NMEA sentence:",u,d),t({type:"SERIAL.ERROR",error:`Parser Error: ${d}`})}}}catch(u){if(console.error("Read loop error:",u),a){const f=u instanceof Error?u.message:String(u);t({type:"FATAL_ERROR",error:f})}}finally{console.log("Read loop finished."),t({type:"SERIAL.DISCONNECTED"})}}return c(),n(u=>{u.type==="STOP"&&(console.log("Received STOP, cancelling reader..."),a=!1,s.cancel().catch(()=>{}))}),()=>{console.log("Cleaning up stream reader actor..."),a=!1,s&&s.cancel().catch(()=>{})}});function Tn(e){const{adapter:t,allowedSentenceIds:n,initialData:r,initialPackets:i}=e;return Vt({actors:{connectToSerial:_s,readNmeaStream:Ts,closePort:bs},actions:{setPort:C((o,s)=>({port:s.port,error:null})),setError:C((o,s)=>{const a=s.error;let c;return typeof a=="string"?c=a:a instanceof Error?c=a.message||"Failed to connect.":c=String(a)||"Failed to connect.",{error:c}}),logParsedData:({context:o},s)=>{if(!o.enableLogging)return;const c=s.packet.sentenceId;bn(c,n)&&console.log(`${c} Packet:`,s.packet)},storePacket:C(({context:o},s)=>{const c=s.packet.sentenceId;if(c&&bn(c,n)){const u={...o.packets,[c]:s.packet};return{packets:u,data:t(u),error:null}}return{packets:o.packets,data:t(o.packets),error:null}}),clearError:C((o,s)=>({error:s.error})),setFatalError:C((o,s)=>({error:s.error})),disconnect:C({port:null,error:null,packets:i,data:r}),setLogging:C((o,s)=>({enableLogging:s.enabled})),setBaudRate:C((o,s)=>({baudRate:s.baudRate}))}}).createMachine({id:"nmea",initial:"disconnected",context:{port:null,error:null,packets:i,data:r,enableLogging:!1,baudRate:4800},on:{SET_LOGGING:{actions:{type:"setLogging",params:({event:o})=>({enabled:o.enabled})}}},states:{disconnected:{on:{CONNECT:"connecting",SET_BAUD_RATE:{actions:{type:"setBaudRate",params:({event:o})=>({baudRate:o.baudRate})}}}},connecting:{invoke:{id:"connectToSerial",src:"connectToSerial",input:({context:o})=>({baudRate:o.baudRate}),onDone:{target:"connected",actions:{type:"setPort",params:({event:o})=>({port:o.output})}},onError:{target:"error",actions:{type:"setError",params:({event:o})=>({error:o.error})}}}},connected:{on:{"SERIAL.DATA":{actions:[{type:"logParsedData",params:({event:o})=>({packet:o.data})},{type:"storePacket",params:({event:o})=>({packet:o.data})}]},"SERIAL.ERROR":{actions:{type:"clearError",params:({event:o})=>({error:o.error})}},FATAL_ERROR:{target:"error",actions:{type:"setFatalError",params:({event:o})=>({error:o.error})}},"SERIAL.DISCONNECTED":{target:"disconnecting"},DISCONNECT:{actions:Le("streamReader",{type:"STOP"})}},invoke:{id:"streamReader",src:"readNmeaStream",input:({context:o})=>({port:o.port})}},disconnecting:{invoke:{id:"closePort",src:"closePort",input:({context:o})=>({port:o.port}),onDone:{target:"disconnected",actions:"disconnect"},onError:{target:"disconnected",actions:"disconnect"}}},error:{on:{CONNECT:"connecting"}}}})}function Is(e,t,n){return e&&e.fixType!=="none"?{latitude:e.latitude,longitude:e.longitude,source:"GGA",fixType:e.fixType,altitudeMeters:e.altitudeMeters,satellitesInView:e.satellitesInView,horizontalDilution:e.horizontalDilution}:t&&t.status==="valid"?{latitude:t.latitude,longitude:t.longitude,source:"RMC",status:t.status}:n&&n.status==="valid"?{latitude:n.latitude,longitude:n.longitude,source:"GLL",status:"valid"}:null}function ws(e,t,n,r){if(e){const i=new Date(e.datetime),o=e.localZoneHours*60+e.localZoneMinutes;return i.setMinutes(i.getMinutes()+o),{utc:e.datetime,local:i,source:"ZDA"}}return t&&t.fixType!=="none"?{utc:t.time,local:null,source:"GGA"}:n&&n.status==="valid"?{utc:n.datetime,local:null,source:"RMC"}:r&&r.status==="valid"?{utc:r.time,local:null,source:"GLL"}:null}function Ps(e,t){return e?{knots:e.speedKnots,source:"VTG"}:t&&t.status==="valid"?{knots:t.speedKnots,source:"RMC"}:null}function ks(e){return e.variationDirection==="W"?-e.variation:(e.variationDirection==="E",e.variation)}function Ds(e,t,n,r){if(e&&e.heading!==void 0)return{degreesTrue:e.heading,source:"HDT",isDerived:!1};if(t&&t.heading!==void 0){const o=ks(t);return{degreesTrue:t.heading+o,source:"HDG",isDerived:!1}}const i=n?.trackTrue??r?.trackTrue;return i!==void 0?{degreesTrue:i,source:"COG",isDerived:!0}:null}function Es(e,t,n,r){return e&&e.depthMeters!==void 0?{meters:e.depthMeters,source:"DPT"}:t?{meters:t.depthMeters,source:"DBT"}:n&&n.depthMeters!==void 0?{meters:n.depthMeters,source:"DBS"}:r&&r.depthMeters!==void 0?{meters:r.depthMeters,source:"DBK"}:null}function As(e){const t=ws(e.ZDA,e.GGA,e.RMC,e.GLL),n=Is(e.GGA,e.RMC,e.GLL),r=Ps(e.VTG,e.RMC),i=Ds(e.HDT,e.HDG,e.RMC,e.VTG),o=Es(e.DPT,e.DBT,e.DBS,e.DBK);return{time:t,position:n,speed:r,heading:i,depth:o}}const Ms=["GGA","RMC","GLL","VTG","HDT","HDG","DPT","DBT","DBS","DBK","ZDA"];function Os(){return e=>As(e)}const Fs={time:null,position:null,speed:null,heading:null,depth:null},Cs={};function Ns(){return{adapter:Os(),allowedSentenceIds:Ms,initialData:Fs,initialPackets:Cs}}function In(){return Tn(Ns())}class Rs extends Kt{constructor(t){const n=In();super(n,{enableLogging:t?.enableLogging,baudRate:t?.baudRate,onData:t?.onData,onStateChange:t?.onStateChange,onError:t?.onError})}}F.NavigationNmeaClient=Rs,F.NmeaClient=Kt,F.createNavigationNmeaMachine=In,F.createNmeaMachine=Tn,F.parseNmeaSentence=vs,F.parseUnsafeNmeaSentence=_n,Object.defineProperty(F,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nmea-web-serial",
3
3
  "type": "module",
4
- "version": "1.1.2",
4
+ "version": "1.1.3",
5
5
  "packageManager": "npm@10.8.2",
6
6
  "description": "NMEA 0183 sentence parser for the Web Serial API",
7
7
  "author": {