@camera.ui/browser 0.0.97 → 0.0.99
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle.js +1 -1
- package/dist/types/packages/client/browser/src/streaming/go2rts-session.d.ts +5 -1
- package/dist/types/packages/client/browser/src/types.d.ts +1 -1
- package/dist/types/packages/plugineer/src/polyglot/node/plugins/schema.d.ts +10 -2
- package/dist/types/server/src/api/database/index.d.ts +1 -1
- package/dist/types/server/src/api/database/types.d.ts +2 -1
- package/dist/types/server/src/api/go2rtc/api/streams.d.ts +1 -1
- package/dist/types/server/src/api/go2rtc/types.d.ts +2 -18
- package/dist/types/server/src/api/schemas/cameras.schema.d.ts +14 -0
- package/dist/types/server/src/api/types/index.d.ts +7 -0
- package/dist/types/server/src/api/utils/constants.d.ts +0 -2
- package/dist/types/server/src/api/websocket/nsp/server.d.ts +9 -4
- package/dist/types/server/src/api/websocket/types.d.ts +3 -3
- package/dist/types/server/src/services/logger/index.d.ts +6 -1
- package/dist/types/shared/types/index.d.ts +1 -0
- package/package.json +4 -4
package/dist/bundle.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var t={855:t=>{const e="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,s=()=>e.now(),n=t=>t===1/0||(t=>t&&t===Math.floor(t)&&t>0&&isFinite(t))(t);class r{constructor({max:t=1/0,ttl:e,updateAgeOnGet:s=!1,checkAgeOnGet:r=!1,noUpdateTTL:i=!1,dispose:o,noDisposeOnSet:a=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,void 0!==e&&!n(e))throw new TypeError("ttl must be positive integer or Infinity if set");if(!n(t))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=e,this.max=t,this.updateAgeOnGet=!!s,this.checkAgeOnGet=!!r,this.noUpdateTTL=!!i,this.noDisposeOnSet=!!a,void 0!==o){if("function"!=typeof o)throw new TypeError("dispose must be function if set");this.dispose=o}this.timer=void 0,this.timerExpiration=void 0}setTimer(t,e){if(this.timerExpiration<t)return;this.timer&&clearTimeout(this.timer);const n=setTimeout((()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(const t in this.expirations){this.setTimer(t,t-s());break}}),e);n.unref&&n.unref(),this.timerExpiration=t,this.timer=n}cancelTimer(){this.timer&&(clearTimeout(this.timer),this.timerExpiration=void 0,this.timer=void 0)}cancelTimers(){return process.emitWarning('TTLCache.cancelTimers has been renamed to TTLCache.cancelTimer (no "s"), and will be removed in the next major version update'),this.cancelTimer()}clear(){const t=this.dispose!==r.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(const[e,s]of t)this.dispose(s,e,"delete")}setTTL(t,e=this.ttl){const n=this.expirationMap.get(t);if(void 0!==n){const e=this.expirations[n];!e||e.length<=1?delete this.expirations[n]:this.expirations[n]=e.filter((e=>e!==t))}if(e!==1/0){const n=Math.floor(s()+e);this.expirationMap.set(t,n),this.expirations[n]||(this.expirations[n]=[],this.setTimer(n,e)),this.expirations[n].push(t)}else this.expirationMap.set(t,1/0)}set(t,e,{ttl:s=this.ttl,noUpdateTTL:r=this.noUpdateTTL,noDisposeOnSet:i=this.noDisposeOnSet}={}){if(!n(s))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(t)){r||this.setTTL(t,s);const n=this.data.get(t);n!==e&&(this.data.set(t,e),i||this.dispose(n,t,"set"))}else this.setTTL(t,s),this.data.set(t,e);for(;this.size>this.max;)this.purgeToCapacity();return this}has(t){return this.data.has(t)}getRemainingTTL(t){const e=this.expirationMap.get(t);return e===1/0?e:void 0!==e?Math.max(0,Math.ceil(e-s())):0}get(t,{updateAgeOnGet:e=this.updateAgeOnGet,ttl:s=this.ttl,checkAgeOnGet:n=this.checkAgeOnGet}={}){const r=this.data.get(t);if(!n||0!==this.getRemainingTTL(t))return e&&this.setTTL(t,s),r;this.delete(t)}dispose(t,e){}delete(t){const e=this.expirationMap.get(t);if(void 0!==e){const s=this.data.get(t);this.data.delete(t),this.expirationMap.delete(t);const n=this.expirations[e];return n&&(n.length<=1?delete this.expirations[e]:this.expirations[e]=n.filter((e=>e!==t))),this.dispose(s,t,"delete"),0===this.size&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(const t in this.expirations){const e=this.expirations[t];if(!(this.size-e.length>=this.max)){const t=this.size-this.max,s=[];for(const n of e.splice(0,t))s.push([n,this.data.get(n)]),this.data.delete(n),this.expirationMap.delete(n);for(const[t,e]of s)this.dispose(e,t,"evict");return}{delete this.expirations[t];const s=[];for(const t of e)s.push([t,this.data.get(t)]),this.data.delete(t),this.expirationMap.delete(t);for(const[t,e]of s)this.dispose(e,t,"evict")}}}get size(){return this.data.size}purgeStale(){const t=Math.ceil(s());for(const e in this.expirations){if("Infinity"===e||e>t)return;const s=[...this.expirations[e]||[]],n=[];delete this.expirations[e];for(const t of s)n.push([t,this.data.get(t)]),this.data.delete(t),this.expirationMap.delete(t);for(const[t,e]of n)this.dispose(e,t,"stale")}0===this.size&&this.cancelTimer()}*entries(){for(const t in this.expirations)for(const e of this.expirations[t])yield[e,this.data.get(e)]}*keys(){for(const t in this.expirations)for(const e of this.expirations[t])yield e}*values(){for(const t in this.expirations)for(const e of this.expirations[t])yield this.data.get(e)}[Symbol.iterator](){return this.entries()}}t.exports=r}},e={};function s(n){var r=e[n];if(void 0!==r)return r.exports;var i=e[n]={exports:{}};return t[n](i,i.exports,s),i.exports}s.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return s.d(e,{a:e}),e},s.d=(t,e)=>{for(var n in e)s.o(e,n)&&!s.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},s.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),s.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var n={};s.d(n,{j:()=>Qe});var r={};s.r(r),s.d(r,{Decoder:()=>Ve,Encoder:()=>Ne,PacketType:()=>Ie,protocol:()=>qe});class i{baseURL;abortControllers=new Set;constructor(t){this.baseURL=`${t}/api`}async request(t,e,s,n={}){const r=new AbortController;this.abortControllers.add(r);const i=setTimeout((()=>{r.abort(),this.abortControllers.delete(r)}),15e3);try{const i=await fetch(`${this.baseURL}${e}`,{method:t,headers:{"Content-Type":"application/json",...n.headers},body:s?JSON.stringify(s):void 0,signal:r.signal,...n});if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);return i}finally{clearTimeout(i),this.abortControllers.delete(r)}}get(t,e){return this.request("GET",t,void 0,e)}post(t,e,s){return this.request("POST",t,e,s)}}process.env.CAMERA_UI_RUNMODE,process.env.CAMERA_UI_RUNMODE,process.env.CAMERA_UI_RUNMODE,process.env.CAMERA_UI_AS_SERVICE;class o{subscriptions=[];additionalSubscriptions=[];addSubscriptions(...t){this.subscriptions.push(...t)}addAdditionalSubscriptions(...t){this.additionalSubscriptions.push(...t)}unsubscribe(){this.subscriptions.forEach((t=>t.unsubscribe()))}unsubscribeAdditional(){this.additionalSubscriptions.forEach((t=>t.unsubscribe()))}}function a(t,e,s=!1){if(t===e)return!0;if((void 0===t||void 0===e||null===t||null===e)&&(t||e))return!1;const n=t?.constructor.name,r=e?.constructor.name;if(n!==r)return!1;if("Array"===n&&"Array"===r){if(t.length!==e.length)return!1;if(s){const n=[...e];return t.every((t=>{const e=n.findIndex((e=>a(t,e,s)));return-1!==e&&(n.splice(e,1),!0)}))}{let n=!0;for(let r=0;r<t.length;r++)if(!a(t[r],e[r],s)){n=!1;break}return n}}if("Object"===n&&"Object"===r){let n=!0;const r=Object.keys(t),i=Object.keys(e);if(r.length!==i.length)return!1;for(let i=0;i<r.length;i++)if(t[r[i]]&&e[r[i]]){if(t[r[i]]===e[r[i]])continue;if(!t[r[i]]||"Array"!==t[r[i]].constructor.name&&"Object"!==t[r[i]].constructor.name){if(t[r[i]]!==e[r[i]]){n=!1;break}}else if(n=a(t[r[i]],e[r[i]],s),!n)break}else if(t[r[i]]&&!e[r[i]]||!t[r[i]]&&e[r[i]]){n=!1;break}return n}return t===e}function c(t){return JSON.parse(JSON.stringify(t))}var h=s(855),u=s.n(h),l=function(t,e){return l=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(t[s]=e[s])},l(t,e)};function p(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function s(){this.constructor=t}l(t,e),t.prototype=null===e?Object.create(e):(s.prototype=e.prototype,new s)}function d(t,e){var s,n,r,i={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(c){return function(a){if(s)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(i=0)),i;)try{if(s=1,n&&(r=2&a[0]?n.return:a[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,a[1])).done)return r;switch(n=0,r&&(a=[2&a[0],r.value]),a[0]){case 0:case 1:r=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,n=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!((r=(r=i.trys).length>0&&r[r.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]<r[3])){i.label=a[1];break}if(6===a[0]&&i.label<r[1]){i.label=r[1],r=a;break}if(r&&i.label<r[2]){i.label=r[2],i.ops.push(a);break}r[2]&&i.ops.pop(),i.trys.pop();continue}a=e.call(t,i)}catch(t){a=[6,t],n=0}finally{s=r=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function f(t){var e="function"==typeof Symbol&&Symbol.iterator,s=e&&t[e],n=0;if(s)return s.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function g(t,e){var s="function"==typeof Symbol&&t[Symbol.iterator];if(!s)return t;var n,r,i=s.call(t),o=[];try{for(;(void 0===e||e-- >0)&&!(n=i.next()).done;)o.push(n.value)}catch(t){r={error:t}}finally{try{n&&!n.done&&(s=i.return)&&s.call(i)}finally{if(r)throw r.error}}return o}function m(t,e,s){if(s||2===arguments.length)for(var n,r=0,i=e.length;r<i;r++)!n&&r in e||(n||(n=Array.prototype.slice.call(e,0,r)),n[r]=e[r]);return t.concat(n||Array.prototype.slice.call(e))}function y(t){return this instanceof y?(this.v=t,this):new y(t)}function b(t){return"function"==typeof t}function v(t){var e=t((function(t){Error.call(t),t.stack=(new Error).stack}));return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var w=v((function(t){return function(e){t(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map((function(t,e){return e+1+") "+t.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=e}}));function S(t,e){if(t){var s=t.indexOf(e);0<=s&&t.splice(s,1)}}var k=function(){function t(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var t,e,s,n,r;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var o=f(i),a=o.next();!a.done;a=o.next())a.value.remove(this)}catch(e){t={error:e}}finally{try{a&&!a.done&&(e=o.return)&&e.call(o)}finally{if(t)throw t.error}}else i.remove(this);var c=this.initialTeardown;if(b(c))try{c()}catch(t){r=t instanceof w?t.errors:[t]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var u=f(h),l=u.next();!l.done;l=u.next()){var p=l.value;try{E(p)}catch(t){r=null!=r?r:[],t instanceof w?r=m(m([],g(r)),g(t.errors)):r.push(t)}}}catch(t){s={error:t}}finally{try{l&&!l.done&&(n=u.return)&&n.call(u)}finally{if(s)throw s.error}}}if(r)throw new w(r)}},t.prototype.add=function(e){var s;if(e&&e!==this)if(this.closed)E(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=null!==(s=this._finalizers)&&void 0!==s?s:[]).push(e)}},t.prototype._hasParent=function(t){var e=this._parentage;return e===t||Array.isArray(e)&&e.includes(t)},t.prototype._addParent=function(t){var e=this._parentage;this._parentage=Array.isArray(e)?(e.push(t),e):e?[e,t]:t},t.prototype._removeParent=function(t){var e=this._parentage;e===t?this._parentage=null:Array.isArray(e)&&S(e,t)},t.prototype.remove=function(e){var s=this._finalizers;s&&S(s,e),e instanceof t&&e._removeParent(this)},t.EMPTY=function(){var e=new t;return e.closed=!0,e}(),t}(),x=k.EMPTY;function _(t){return t instanceof k||t&&"closed"in t&&b(t.remove)&&b(t.add)&&b(t.unsubscribe)}function E(t){b(t)?t():t.unsubscribe()}var T={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},O={setTimeout:function(t,e){for(var s=[],n=2;n<arguments.length;n++)s[n-2]=arguments[n];var r=O.delegate;return(null==r?void 0:r.setTimeout)?r.setTimeout.apply(r,m([t,e],g(s))):setTimeout.apply(void 0,m([t,e],g(s)))},clearTimeout:function(t){var e=O.delegate;return((null==e?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function C(t){O.setTimeout((function(){var e=T.onUnhandledError;if(!e)throw t;e(t)}))}function A(){}var R=B("C",void 0,void 0);function B(t,e,s){return{kind:t,value:e,error:s}}var j=null;function L(t){if(T.useDeprecatedSynchronousErrorHandling){var e=!j;if(e&&(j={errorThrown:!1,error:null}),t(),e){var s=j,n=s.errorThrown,r=s.error;if(j=null,n)throw r}}else t()}var M=function(t){function e(e){var s=t.call(this)||this;return s.isStopped=!1,e?(s.destination=e,_(e)&&e.add(s)):s.destination=V,s}return p(e,t),e.create=function(t,e,s){return new I(t,e,s)},e.prototype.next=function(t){this.isStopped?U(function(t){return B("N",t,void 0)}(t),this):this._next(t)},e.prototype.error=function(t){this.isStopped?U(B("E",void 0,t),this):(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped?U(R,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(k),P=Function.prototype.bind;function D(t,e){return P.call(t,e)}var q=function(){function t(t){this.partialObserver=t}return t.prototype.next=function(t){var e=this.partialObserver;if(e.next)try{e.next(t)}catch(t){N(t)}},t.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(t){N(t)}else N(t)},t.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(t){N(t)}},t}(),I=function(t){function e(e,s,n){var r,i,o=t.call(this)||this;return b(e)||!e?r={next:null!=e?e:void 0,error:null!=s?s:void 0,complete:null!=n?n:void 0}:o&&T.useDeprecatedNextContext?((i=Object.create(e)).unsubscribe=function(){return o.unsubscribe()},r={next:e.next&&D(e.next,i),error:e.error&&D(e.error,i),complete:e.complete&&D(e.complete,i)}):r=e,o.destination=new q(r),o}return p(e,t),e}(M);function N(t){var e;T.useDeprecatedSynchronousErrorHandling?(e=t,T.useDeprecatedSynchronousErrorHandling&&j&&(j.errorThrown=!0,j.error=e)):C(t)}function U(t,e){var s=T.onStoppedNotification;s&&O.setTimeout((function(){return s(t,e)}))}var V={closed:!0,next:A,error:function(t){throw t},complete:A},F="function"==typeof Symbol&&Symbol.observable||"@@observable";function W(t){return t}var z=function(){function t(t){t&&(this._subscribe=t)}return t.prototype.lift=function(e){var s=new t;return s.source=this,s.operator=e,s},t.prototype.subscribe=function(t,e,s){var n=this,r=function(t){return t&&t instanceof M||function(t){return t&&b(t.next)&&b(t.error)&&b(t.complete)}(t)&&_(t)}(t)?t:new I(t,e,s);return L((function(){var t=n,e=t.operator,s=t.source;r.add(e?e.call(r,s):s?n._subscribe(r):n._trySubscribe(r))})),r},t.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(e){t.error(e)}},t.prototype.forEach=function(t,e){var s=this;return new(e=H(e))((function(e,n){var r=new I({next:function(e){try{t(e)}catch(t){n(t),r.unsubscribe()}},error:n,complete:e});s.subscribe(r)}))},t.prototype._subscribe=function(t){var e;return null===(e=this.source)||void 0===e?void 0:e.subscribe(t)},t.prototype[F]=function(){return this},t.prototype.pipe=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return(0===(s=t).length?W:1===s.length?s[0]:function(t){return s.reduce((function(t,e){return e(t)}),t)})(this);var s},t.prototype.toPromise=function(t){var e=this;return new(t=H(t))((function(t,s){var n;e.subscribe((function(t){return n=t}),(function(t){return s(t)}),(function(){return t(n)}))}))},t.create=function(e){return new t(e)},t}();function H(t){var e;return null!==(e=null!=t?t:T.Promise)&&void 0!==e?e:Promise}var $=v((function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})),J=function(t){function e(){var e=t.call(this)||this;return e.closed=!1,e.currentObservers=null,e.observers=[],e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return p(e,t),e.prototype.lift=function(t){var e=new Y(this,this);return e.operator=t,e},e.prototype._throwIfClosed=function(){if(this.closed)throw new $},e.prototype.next=function(t){var e=this;L((function(){var s,n;if(e._throwIfClosed(),!e.isStopped){e.currentObservers||(e.currentObservers=Array.from(e.observers));try{for(var r=f(e.currentObservers),i=r.next();!i.done;i=r.next())i.value.next(t)}catch(t){s={error:t}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(s)throw s.error}}}}))},e.prototype.error=function(t){var e=this;L((function(){if(e._throwIfClosed(),!e.isStopped){e.hasError=e.isStopped=!0,e.thrownError=t;for(var s=e.observers;s.length;)s.shift().error(t)}}))},e.prototype.complete=function(){var t=this;L((function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var e=t.observers;e.length;)e.shift().complete()}}))},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return(null===(t=this.observers)||void 0===t?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(e){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,e)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var e=this,s=this,n=s.hasError,r=s.isStopped,i=s.observers;return n||r?x:(this.currentObservers=null,i.push(t),new k((function(){e.currentObservers=null,S(i,t)})))},e.prototype._checkFinalizedStatuses=function(t){var e=this,s=e.hasError,n=e.thrownError,r=e.isStopped;s?t.error(n):r&&t.complete()},e.prototype.asObservable=function(){var t=new z;return t.source=this,t},e.create=function(t,e){return new Y(t,e)},e}(z),Y=function(t){function e(e,s){var n=t.call(this)||this;return n.destination=e,n.source=s,n}return p(e,t),e.prototype.next=function(t){var e,s;null===(s=null===(e=this.destination)||void 0===e?void 0:e.next)||void 0===s||s.call(e,t)},e.prototype.error=function(t){var e,s;null===(s=null===(e=this.destination)||void 0===e?void 0:e.error)||void 0===s||s.call(e,t)},e.prototype.complete=function(){var t,e;null===(e=null===(t=this.destination)||void 0===t?void 0:t.complete)||void 0===e||e.call(t)},e.prototype._subscribe=function(t){var e,s;return null!==(s=null===(e=this.source)||void 0===e?void 0:e.subscribe(t))&&void 0!==s?s:x},e}(J),K=function(t){function e(e){var s=t.call(this)||this;return s._value=e,s}return p(e,t),Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(e){var s=t.prototype._subscribe.call(this,e);return!s.closed&&e.next(this._value),s},e.prototype.getValue=function(){var t=this,e=t.hasError,s=t.thrownError,n=t._value;if(e)throw s;return this._throwIfClosed(),n},e.prototype.next=function(e){t.prototype.next.call(this,this._value=e)},e}(J),G={now:function(){return(G.delegate||Date).now()},delegate:void 0},Q=function(t){function e(e,s,n){void 0===e&&(e=1/0),void 0===s&&(s=1/0),void 0===n&&(n=G);var r=t.call(this)||this;return r._bufferSize=e,r._windowTime=s,r._timestampProvider=n,r._buffer=[],r._infiniteTimeWindow=!0,r._infiniteTimeWindow=s===1/0,r._bufferSize=Math.max(1,e),r._windowTime=Math.max(1,s),r}return p(e,t),e.prototype.next=function(e){var s=this,n=s.isStopped,r=s._buffer,i=s._infiniteTimeWindow,o=s._timestampProvider,a=s._windowTime;n||(r.push(e),!i&&r.push(o.now()+a)),this._trimBuffer(),t.prototype.next.call(this,e)},e.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var e=this._innerSubscribe(t),s=this._infiniteTimeWindow,n=this._buffer.slice(),r=0;r<n.length&&!t.closed;r+=s?1:2)t.next(n[r]);return this._checkFinalizedStatuses(t),e},e.prototype._trimBuffer=function(){var t=this,e=t._bufferSize,s=t._timestampProvider,n=t._buffer,r=t._infiniteTimeWindow,i=(r?1:2)*e;if(e<1/0&&i<n.length&&n.splice(0,n.length-i),!r){for(var o=s.now(),a=0,c=1;c<n.length&&n[c]<=o;c+=2)a=c;a&&n.splice(0,a+1)}},e}(J);function X(t){return function(e){if(function(t){return b(null==t?void 0:t.lift)}(e))return e.lift((function(e){try{return t(e,this)}catch(t){this.error(t)}}));throw new TypeError("Unable to lift unknown Observable type")}}function Z(t,e,s,n,r){return new tt(t,e,s,n,r)}var tt=function(t){function e(e,s,n,r,i,o){var a=t.call(this,e)||this;return a.onFinalize=i,a.shouldUnsubscribe=o,a._next=s?function(t){try{s(t)}catch(t){e.error(t)}}:t.prototype._next,a._error=r?function(t){try{r(t)}catch(t){e.error(t)}finally{this.unsubscribe()}}:t.prototype._error,a._complete=n?function(){try{n()}catch(t){e.error(t)}finally{this.unsubscribe()}}:t.prototype._complete,a}return p(e,t),e.prototype.unsubscribe=function(){var e;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var s=this.closed;t.prototype.unsubscribe.call(this),!s&&(null===(e=this.onFinalize)||void 0===e||e.call(this))}},e}(M);function et(){return X((function(t,e){var s,n=!1;t.subscribe(Z(e,(function(t){var r=s;s=t,n&&e.next([r,t]),n=!0})))}))}function st(t,e){return X((function(s,n){var r=0;s.subscribe(Z(n,(function(s){return t.call(e,s,r++)&&n.next(s)})))}))}function nt(t,e){return X((function(s,n){var r=0;s.subscribe(Z(n,(function(s){n.next(t.call(e,s,r++))})))}))}var rt=function(t){return t&&"number"==typeof t.length&&"function"!=typeof t},it="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function ot(t){if(t instanceof z)return t;if(null!=t){if(function(t){return b(t[F])}(t))return r=t,new z((function(t){var e=r[F]();if(b(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(rt(t))return n=t,new z((function(t){for(var e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()}));if(function(t){return b(null==t?void 0:t.then)}(t))return s=t,new z((function(t){s.then((function(e){t.closed||(t.next(e),t.complete())}),(function(e){return t.error(e)})).then(null,C)}));if(function(t){return Symbol.asyncIterator&&b(null==t?void 0:t[Symbol.asyncIterator])}(t))return at(t);if(function(t){return b(null==t?void 0:t[it])}(t))return e=t,new z((function(t){var s,n;try{for(var r=f(e),i=r.next();!i.done;i=r.next()){var o=i.value;if(t.next(o),t.closed)return}}catch(t){s={error:t}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(s)throw s.error}}t.complete()}));if(function(t){return b(null==t?void 0:t.getReader)}(t))return at(function(t){return function(t,e,s){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,r=s.apply(t,e||[]),i=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",(function(t){return function(e){return Promise.resolve(e).then(t,h)}})),n[Symbol.asyncIterator]=function(){return this},n;function o(t,e){r[t]&&(n[t]=function(e){return new Promise((function(s,n){i.push([t,e,s,n])>1||a(t,e)}))},e&&(n[t]=e(n[t])))}function a(t,e){try{(s=r[t](e)).value instanceof y?Promise.resolve(s.value.v).then(c,h):u(i[0][2],s)}catch(t){u(i[0][3],t)}var s}function c(t){a("next",t)}function h(t){a("throw",t)}function u(t,e){t(e),i.shift(),i.length&&a(i[0][0],i[0][1])}}(this,arguments,(function(){var e,s,n;return d(this,(function(r){switch(r.label){case 0:e=t.getReader(),r.label=1;case 1:r.trys.push([1,,9,10]),r.label=2;case 2:return[4,y(e.read())];case 3:return s=r.sent(),n=s.value,s.done?[4,y(void 0)]:[3,5];case 4:return[2,r.sent()];case 5:return[4,y(n)];case 6:return[4,r.sent()];case 7:return r.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}}))}))}(t))}var e,s,n,r;throw function(t){return new TypeError("You provided "+(null!==t&&"object"==typeof t?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}(t)}function at(t){return new z((function(e){(function(t,e){var s,n,r,i,o,a,c,h;return o=this,a=void 0,h=function(){var o,a;return d(this,(function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),s=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,s=t[Symbol.asyncIterator];return s?s.call(t):(t=f(t),e={},n("next"),n("throw"),n("return"),e[Symbol.asyncIterator]=function(){return this},e);function n(s){e[s]=t[s]&&function(e){return new Promise((function(n,r){!function(t,e,s,n){Promise.resolve(n).then((function(e){t({value:e,done:s})}),e)}(n,r,(e=t[s](e)).done,e.value)}))}}}(t),c.label=1;case 1:return[4,s.next()];case 2:if((n=c.sent()).done)return[3,4];if(o=n.value,e.next(o),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),r={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),n&&!n.done&&(i=s.return)?[4,i.call(s)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(r)throw r.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}}))},new((c=void 0)||(c=Promise))((function(t,e){function s(t){try{r(h.next(t))}catch(t){e(t)}}function n(t){try{r(h.throw(t))}catch(t){e(t)}}function r(e){e.done?t(e.value):function(t){return t instanceof c?t:new c((function(e){e(t)}))}(e.value).then(s,n)}r((h=h.apply(o,a||[])).next())}))})(t,e).catch((function(t){return e.error(t)}))}))}function ct(t){void 0===t&&(t={});var e=t.connector,s=void 0===e?function(){return new J}:e,n=t.resetOnError,r=void 0===n||n,i=t.resetOnComplete,o=void 0===i||i,a=t.resetOnRefCountZero,c=void 0===a||a;return function(t){var e,n,i,a=0,h=!1,u=!1,l=function(){null==n||n.unsubscribe(),n=void 0},p=function(){l(),e=i=void 0,h=u=!1},d=function(){var t=e;p(),null==t||t.unsubscribe()};return X((function(t,f){a++,u||h||l();var g=i=null!=i?i:s();f.add((function(){0!=--a||u||h||(n=ht(d,c))})),g.subscribe(f),!e&&a>0&&(e=new I({next:function(t){return g.next(t)},error:function(t){u=!0,l(),n=ht(p,r,t),g.error(t)},complete:function(){h=!0,l(),n=ht(p,o),g.complete()}}),ot(t).subscribe(e))}))(t)}}function ht(t,e){for(var s=[],n=2;n<arguments.length;n++)s[n-2]=arguments[n];if(!0!==e){if(!1!==e){var r=new I({next:function(){r.unsubscribe(),t()}});return ot(e.apply(void 0,m([],g(s)))).subscribe(r)}}else t()}function ut(t,e,s){return void 0===s&&(s=1/0),b(e)?ut((function(s,n){return nt((function(t,r){return e(s,t,n,r)}))(ot(t(s,n)))}),s):("number"==typeof e&&(s=e),X((function(e,n){return function(t,e,s,n,r,i,o,a){var c=[],h=0,u=0,l=!1,p=function(){!l||c.length||h||e.complete()},d=function(t){return h<n?f(t):c.push(t)},f=function(t){h++;var r=!1;ot(s(t,u++)).subscribe(Z(e,(function(t){e.next(t)}),(function(){r=!0}),void 0,(function(){if(r)try{h--;for(var t=function(){var t=c.shift();f(t)};c.length&&h<n;)t();p()}catch(t){e.error(t)}})))};return t.subscribe(Z(e,d,(function(){l=!0,p()}))),function(){}}(e,n,t,s)})))}const lt=(t,e)=>{const[s,n,r,i]=t,[o,a,c,h]=e,u=Math.max(s,o),l=Math.max(n,a),p=Math.min(r,c),d=Math.min(i,h),f=Math.max(0,p-u)*Math.max(0,d-l);return f/((r-s)*(i-n)+(c-o)*(h-a)-f)},pt=(t,e)=>{const{origWidth:s,origHeight:n}=e,r=t.points.map((([t,e])=>[t*s/100,e*n/100]));return{...t,points:r}},dt=t=>{const{origWidth:e,origHeight:s,inputWidth:n,inputHeight:r}=t,[i,o,a,c]=t.boundingBox,h=i*e/n,u=o*s/r,l=a*e/n,p=c*s/r;return{...t,boundingBox:[h,u,l,p]}},ft=(t,e,s)=>{if(t.confidence<s.object.confidence)return!1;if(0===e.length)return!0;const[n,r,i,o]=t.boundingBox,a={xmin:n,ymin:r,xmax:i,ymax:o};let c=!1;for(const s of e){const e=pt(s,t);if(e.isPrivacyMask){if(mt(a,e.points)){c=!1;break}}else"include"===e.filter?"contain"===e.type?mt(a,e.points)&&(c=!0):"intersect"===e.type&&(gt(a,e.points)||mt(a,e.points))&&(c=!0):"exclude"===e.filter&&("contain"===e.type?mt(a,e.points)||(c=!0):"intersect"===e.type&&(gt(a,e.points)||mt(a,e.points)||(c=!0)))}return c},gt=(t,e)=>{const s=yt(t);for(const t of s)for(let s=0;s<e.length;s++){const n=[e[s],e[(s+1)%e.length]];if(bt(t,n))return!0}return!1},mt=(t,e)=>[[t.xmin,t.ymin],[t.xmax,t.ymin],[t.xmax,t.ymax],[t.xmin,t.ymax]].every((t=>vt(t,e))),yt=t=>{const{xmin:e,ymin:s,xmax:n,ymax:r}=t;return[[[e,s],[n,s]],[[n,s],[n,r]],[[n,r],[e,r]],[[e,r],[e,s]]]},bt=(t,e)=>{const s=(t,e,s)=>(s[1]-t[1])*(e[0]-t[0])>(e[1]-t[1])*(s[0]-t[0]);return n=t[0],r=t[1],s(n,i=e[0],o=e[1])!==s(r,i,o)&&s(n,r,i)!==s(n,r,o);var n,r,i,o},vt=(t,e)=>{const[s,n]=t;let r=!1,[i,o]=e[e.length-1];for(const[t,a]of e)a>n!=o>n&&s<(i-t)*(n-a)/(o-a)+t&&(r=!r),[i,o]=[t,a];return r};class wt extends o{logger;snapshotCache;cameraSubject;cameraState=new K(!1);lightState=new K(this.getLightState({state:!1},!0));motionState=new K(this.getMotionState({detections:[],state:!1},!0));audioState=new K(this.getAudioState({state:!1,db:0},!0));objectState=new K(this.getObjectState({detections:[]},!0));doorbellState=new K(this.getDoorbellState({state:!1},!0));sirenState=new K(this.getSirenState({state:!1,level:0},!0));batteryState=new K(this.getBatteryState({level:100,charging:!1,lowBattery:!1},!0));onConnected=this.createStateObservable(this.cameraState);onLightSwitched=this.createStateObservable(this.lightState);onMotionDetected=this.createStateObservable(this.motionState);onAudioDetected=this.createStateObservable(this.audioState);onObjectDetected=this.createStateObservable(this.objectState);onDoorbellPressed=this.createStateObservable(this.doorbellState);onSirenDetected=this.createStateObservable(this.sirenState);onBatteryChanged=this.createStateObservable(this.batteryState);get cameraObject(){return c(this.cameraSubject.getValue())}get id(){return this.cameraSubject.getValue()._id}get nativeId(){return this.cameraSubject.getValue().nativeId}get pluginId(){return this.cameraSubject.getValue().pluginId}get connected(){return this.cameraState.getValue()}get disabled(){return this.cameraSubject.getValue().disabled}get name(){return this.cameraSubject.getValue().name}get type(){return this.cameraSubject.getValue().type}get info(){return c(this.cameraSubject.getValue().info)}get isCloud(){return this.cameraSubject.getValue().isCloud}get hasLight(){return this.cameraSubject.getValue().hasLight}get hasSiren(){return this.cameraSubject.getValue().hasSiren}get hasBinarySensor(){return this.cameraSubject.getValue().hasBinarySensor}get hasBattery(){return this.cameraSubject.getValue().hasBattery}get hasMotionDetector(){return this.cameraSubject.getValue().hasMotionDetector}get hasAudioDetector(){return this.cameraSubject.getValue().hasAudioDetector}get hasObjectDetector(){return this.cameraSubject.getValue().hasObjectDetector}get hasPtz(){return this.cameraSubject.getValue().hasPtz}get hasPrebuffer(){return this.cameraSubject.getValue().hasPrebuffer}get snapshotTTL(){return this.cameraSubject.getValue().snapshotTTL}get activityZones(){return c(this.cameraSubject.getValue().activityZones)}get activitySettings(){return c(this.cameraSubject.getValue().activitySettings)}get frameWorkerSettings(){return c(this.cameraSubject.getValue().frameWorkerSettings)}get streamSource(){return this.highResolutionSource||this.midResolutionSource||this.lowResolutionSource}get snapshotSource(){return this.sources.find((t=>t.roles.includes("snapshot")&&!t.internal))}get highResolutionSource(){return this.sources.find((t=>t.roles.includes("high-resolution")&&!t.internal))}get midResolutionSource(){return this.sources.find((t=>t.roles.includes("mid-resolution")&&!t.internal))}get lowResolutionSource(){return this.sources.find((t=>t.roles.includes("low-resolution")&&!t.internal))}get ptz(){return this.ptzDelegate}constructor(t,e){super(),this.logger=e,this.cameraSubject=new K(t),this.updateCamera(t),this.snapshotCache=new(u())({max:100,ttl:1e3*this.snapshotTTL}),"native"===t.pluginId&&this.cameraState.next(!0)}getValue(t){switch(t){case"light":return c(this.lightState.getValue());case"motion":return c(this.motionState.getValue());case"audio":return c(this.audioState.getValue());case"object":return c(this.objectState.getValue());case"doorbell":return c(this.doorbellState.getValue());case"siren":return c(this.sirenState.getValue());case"battery":return c(this.batteryState.getValue());default:throw new Error(`Unknown state: ${t}`)}}async snapshot(t){this.snapshotCache.purgeStale();const e=this.snapshotSource||this.streamSource,s=e.urls.www.jpegSnapshot,n=this.snapshotCache.get(e._id);if(!t&&n)return this.logger.trace(this.name,"Snapshot requested (cached)"),n;this.logger.trace(this.name,"Snapshot requested (fetching)");try{if("native"!==this.cameraObject.pluginId){const t=await this.cameraDelegate.snapshot();if(t&&t.byteLength>0)return this.snapshotCache.set(e._id,t),t}const t=new AbortController,n=setTimeout((()=>t.abort()),5e3),r=await fetch(s,{signal:t.signal});if(clearTimeout(n),!r.ok)throw new Error("Status Code: "+r.status);const i=await r.arrayBuffer();return i.byteLength>0&&this.snapshotCache.set(e._id,i),i}catch{return}}onStateChange(t){return this[`${t}State`].pipe(et(),st((([e,s])=>"boolean"==typeof e||"boolean"==typeof s?e!==s:this.stateChanged(e,s,t))),nt((([t,e])=>({oldState:t,newState:e}))),ct({connector:()=>new Q(1)}))}onPropertyChange(t){return this.cameraSubject.pipe(et(),ut((([e,s])=>(Array.isArray(t)?t:[t]).map((t=>({property:t,oldData:e[t],newData:s[t]}))))),st((({oldData:t,newData:e})=>!a(t,e,!0))),ct({connector:()=>new Q(1)}))}removeAllListeners(){this.lightState.complete(),this.motionState.complete(),this.audioState.complete(),this.objectState.complete(),this.doorbellState.complete(),this.sirenState.complete(),this.batteryState.complete(),this.cameraSubject.complete(),this.cameraState.complete()}updateCamera(t){this.cameraSubject.next(t)}updateCameraState(t){this.cameraState.next(t)}updateStateInternal(t,e,s){let n,r=!1;if(s)r=!0,n=e;else{const s=this.checkStateInternal(t,e);r=s.changed,n=s.event}if(r)switch(t){case"light":this.lightState.next(this.getLightState(n));break;case"motion":this.motionState.next(this.getMotionState(n));break;case"audio":this.audioState.next(this.getAudioState(n));break;case"object":this.objectState.next(this.getObjectState(n));break;case"doorbell":this.doorbellState.next(this.getDoorbellState(n));break;case"siren":this.sirenState.next(this.getSirenState(n));break;case"battery":this.batteryState.next(this.getBatteryState(n));break;default:throw new Error(`Unknown state: ${t}`)}}checkStateInternal(t,e){let s,n=!1;switch(t){case"audio":const r=e;s=this.getAudioState(r),n=this.stateChanged(this.getValue("audio"),s,"audio");break;case"light":const i=e;s=this.getLightState(i),n=this.stateChanged(this.getValue("light"),s,"light");break;case"motion":const o=e;void 0!==o.state&&(o.detections=[]),o.detections=((t,e=.2)=>{if(0===t.length)return[];const s=[...t].sort(((t,e)=>{const s=(t.boundingBox[2]-t.boundingBox[0])*(t.boundingBox[3]-t.boundingBox[1]);return(e.boundingBox[2]-e.boundingBox[0])*(e.boundingBox[3]-e.boundingBox[1])-s})),n=[];for(;s.length>0;){let t={...s[0]};s.shift();const r=[];for(let n=0;n<s.length;n++)lt(t.boundingBox,s[n].boundingBox)>e&&r.push(n);if(r.length>0){const e=[t,...r.map((t=>s[t]))],n=[Math.min(...e.map((t=>t.boundingBox[0]))),Math.min(...e.map((t=>t.boundingBox[1]))),Math.max(...e.map((t=>t.boundingBox[2]))),Math.max(...e.map((t=>t.boundingBox[3])))],i=e.reduce(((t,e)=>t.confidence>e.confidence?t:e));t={...i,boundingBox:n,id:i.id||t.id};for(let t=r.length-1;t>=0;t--)s.splice(r[t],1)}n.push(t)}return n})(o.detections),o.detections=((t,e,s)=>{const n=[];for(const r of t)ft(dt(r),e,s)&&e.some((t=>!t.classes.length||t.classes.includes(r.label)))&&n.push(r);return n})(o.detections,this.activityZones,this.activitySettings),s=this.getMotionState(o),n=this.stateChanged(this.getValue("motion"),s,"motion");break;case"object":const a=e;a.detections=((t,e,s)=>{const n=[];for(const r of t)ft(dt(r),e,s)&&e.some((t=>!t.classes.length||t.classes.includes(r.label)))&&n.push(r);return n})(a.detections,this.activityZones,this.activitySettings),s=this.getObjectState(a),n=this.stateChanged(this.getValue("object"),s,"object");break;case"doorbell":const c=e;s=this.getDoorbellState(c),n=this.stateChanged(this.getValue("doorbell"),s,"doorbell");break;case"siren":const h=e;s=this.getSirenState(h),n=this.stateChanged(this.getValue("siren"),s,"siren");break;case"battery":const u=e;s=this.getBatteryState(u),n=this.stateChanged(this.getValue("battery"),s,"battery");break;default:throw new Error(`Unknown state: ${t}`)}return{changed:n,event:s}}stateChanged(t,e,s){if(!t||!e||!s)return!1;if("audio"==s){if(!this.hasAudioDetector)return!1;const s=t,n=e;return s.state!==n.state||s.db!==n.db}if("motion"==s){if(!this.hasMotionDetector)return!1;const s=t,n=e;return void 0!==n.state?s.state!==n.state:!a(s.detections,n.detections,!0)}if("object"==s){if(!this.hasObjectDetector)return!1;const s=e;return!a(t.detections,s.detections,!0)}if("siren"==s){if(!this.hasSiren)return!1;const s=t,n=e;return s.state!==n.state||s.level!==n.level}if("battery"==s){if(!this.hasBattery)return!1;const s=t,n=e;return s.level!==n.level||s.lowBattery!==n.lowBattery||s.charging!==n.charging}if("doorbell"==s){if(!this.hasBinarySensor)return!1;const s=e;return t.state!==s.state}if("light"==s){if(!this.hasLight)return!1;const s=e;return t.state!==s.state}return!1}getAudioState(t,e=!1){let s,n;if(!e){const t=this.getValue("audio");t.state?s=t:t.lastEvent?.state&&(s=t.lastEvent),s&&delete s.lastEvent}if(this.isStateEvent(t))n=t;else{const e={...t,timestamp:Date.now()};n={...e,db:e.db||s?.db||0,lastEvent:s||(e.state?e:void 0)}}return n}getMotionState(t,e=!1){let s,n;if(!e){const t=this.getValue("motion");t.detections.length?s=t:t.lastEvent?.detections.length&&(s=t.lastEvent),s&&delete s.lastEvent}if(this.isStateEvent(t))n=t;else{const e={...t,timestamp:Date.now()};n={...e,lastEvent:s||(e.detections.length?e:void 0)}}return n}getObjectState(t,e=!1){let s,n;if(!e){const t=this.getValue("object");t.detections.length?s=t:t.lastEvent?.detections.length&&(s=t.lastEvent),s&&delete s.lastEvent}if(this.isStateEvent(t))n=t;else{const e={...t,timestamp:Date.now()};n={...e,lastEvent:s||(e.detections.length?e:void 0)}}return n}getDoorbellState(t,e=!1){let s,n;if(!e){const t=this.getValue("doorbell");t.state?s=t:t.lastEvent?.state&&(s=t.lastEvent),s&&delete s.lastEvent}if(this.isStateEvent(t))n=t;else{const e={...t,timestamp:Date.now()};n={...e,lastEvent:s||(e.state?e:void 0)}}return n}getLightState(t,e=!1){let s,n;if(!e){const t=this.getValue("light");t.state?s=t:t.lastEvent?.state&&(s=t.lastEvent),s&&delete s.lastEvent}if(this.isStateEvent(t))n=t;else{const e={...t,timestamp:Date.now()};n={...e,lastEvent:s||(e.state?e:void 0)}}return n}getSirenState(t,e=!1){let s,n;if(!e){const t=this.getValue("siren");t.state?s=t:t.lastEvent?.state&&(s=t.lastEvent),s&&delete s.lastEvent}if(this.isStateEvent(t))n=t;else{const e={...t,timestamp:Date.now()};n={...e,level:e.level||s?.level||0,lastEvent:s||(e.state?e:void 0)}}return n}getBatteryState(t,e=!1){let s,n;if(!e){const e=this.getValue("battery");this.stateChanged(e,t,"battery")?s=e:e.lastEvent&&this.stateChanged(e.lastEvent,t,"battery")&&(s=e.lastEvent),s&&delete s.lastEvent}if(this.isStateEvent(t))n=t;else{const e={...t,timestamp:Date.now()};n={...e,charging:t.charging||s?.charging||!1,lowBattery:t.lowBattery||s?.lowBattery||!1,lastEvent:s||e}}return n}isStateEvent(t){return"timestamp"in t}createStateObservable(t){return t.pipe(ct({connector:()=>new Q(1)}))}}class St{delegate;onRequest;constructor(t){this.onRequest=t}async snapshot(){return this.delegate?this.delegate.snapshot():this._onRequest("snapshot",[],5e3)}_onRequest(t,e,s){return this.onRequest("cameraDelegate",t,e,s)}}class kt{delegate;onRequest;constructor(t){this.onRequest=t}async getPrebufferingState(t,e){return this.delegate?this.delegate.getPrebufferingState(t,e):this._onRequest("prebufferDelegate","getPrebufferingState",[t,e])}_onRequest(t,e,s,n){return this.onRequest(t,e,s,n)}}class xt{delegate;onRequest;constructor(t){this.onRequest=t}async moveAbsolute(t,e,s){return this.delegate?this.delegate.moveAbsolute(t,e,s):this._onRequest("moveAbsolute",[t,e,s])}async moveRelative(t,e,s){return this.delegate?this.delegate.moveRelative(t,e,s):this._onRequest("moveRelative",[t,e,s])}async moveContinuous(t,e,s){return this.delegate?this.delegate.moveContinuous(t,e,s):this._onRequest("moveContinuous",[t,e,s])}async stop(){return this.delegate?this.delegate.stop():this._onRequest("stop",[])}_onRequest(t,e,s){return this.onRequest("ptzDelegate",t,e,s)}}const _t=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)}));class Et extends EventTarget{cameraDevice;socketService;logger;options;videoPlayer;socket;streamId;hasBackchannel=!1;closed=!1;micTransceiver=null;pc=null;buf=new Uint8Array(2097152);mediaSource=null;sourceBuffer=null;bufLen=0;mseCodecs="";videoPlayerMp4;media=["video","audio","microphone"];codecList=[];reconnectTimeout;_finishLoading=!1;get mode(){return this.options.mode}webrtcReconnectTimeout;constructor(t,e,s,n){super(),this.options=n,this.videoPlayer=n.videoElement,this.cameraDevice=t,this.socketService=e,this.logger=s;const{socket:r}=this.socketService.getSocket(`${t.id}-go2rtcSession`,!0);this.socket=r,this.socket.connect(),this.streamId=_t(),this.createCodecsList()}connect(t){t&&(this.options.mode=t),console.log(this.cameraDevice.name,`Connecting... (${this.options.mode})`),this.socket.on("ws-open",this.onWsOpen.bind(this)),this.socket.on("ws-close",this.onWsClose.bind(this)),this.socket.on("ws-message",this.onWsMessage.bind(this)),this.socket.emit("ws-open",{id:this.streamId,cameraSource:this.options.sourceName,mode:this.options.mode})}disconnect(){console.log(this.cameraDevice.name,"Disconnecting..."),this.socket.removeListener("ws-open",this.onWsOpen.bind(this)),this.socket.removeListener("ws-close",this.onWsClose.bind(this)),this.socket.removeListener("ws-message",this.onWsMessage.bind(this)),this.socket.emit("ws-close",{id:this.streamId})}async reconnect(t){console.log(this.cameraDevice.name,"Reconnecting..."),this.dispatchEvent(new Event("reconnect")),this.close(),await new Promise((t=>setTimeout(t,100))),this.connect(t)}reset(){this._finishLoading=!1,this.pc?.getTransceivers().forEach((t=>t.sender?.track?.stop())),this.pc?.close(),this.pc=null,this.videoPlayerMp4?.remove(),this.videoPlayerMp4=void 0,this.videoPlayer.srcObject=null,this.videoPlayer.src="",this.videoPlayer.poster=""}close(){console.log(this.cameraDevice.name,"Closing..."),this.closed=!0,this.reset(),this.disconnect(),this.socket.emit("end"),this.socket.removeAllListeners()}onWsOpen({id:t}){if(t===this.streamId)switch(console.log(this.cameraDevice.name,"Connected"),this.options.mode){case"webrtc":case"webrtc/tcp":console.log(this.cameraDevice.name,"Requesting WebRTC session..."),this.requestWebrtc();break;case"mse":console.log(this.cameraDevice.name,"Requesting MSE session..."),this.requestMse();break;case"hls":console.log(this.cameraDevice.name,"Requesting HLS session..."),this.requestHls();break;case"mp4":console.log(this.cameraDevice.name,"Requesting MP4 session..."),this.requestMp4();break;case"mjpeg":console.log(this.cameraDevice.name,"Requesting MJPEG session..."),this.requestMjpeg();break;default:console.log(this.cameraDevice.name,"Unknown mode:",this.options.mode),this.dispatchEvent(new ErrorEvent("error",{message:"Unknown mode: "+this.options.mode}))}}onWsClose({id:t}){t===this.streamId&&(this.closed||void 0===this.options.reconnectInterval||(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=setTimeout((()=>{this.reconnect()}),this.options.reconnectInterval)))}onWsMessage({id:t,data:e}){if(t===this.streamId&&e.type)switch(e.type){case"mse":this.onMseData(e);break;case"hls":this.onHlsData(e);break;case"webrtc/candidate":case"webrtc/answer":this.onWebrtcData(e);break;case"mse-binary":this.onMseBuffer(e);break;case"mjpeg-binary":this.onMjpegBuffer(e);break;case"mp4-binary":this.onMp4Buffer(e);break;case"stream-info":this.onStreamInfo(e);break;case"error":this.dispatchEvent(new ErrorEvent("error",{error:e,message:e.value}))}}async requestWebrtc(){this.reset(),this.pc=new RTCPeerConnection({bundlePolicy:"max-bundle",iceServers:[{urls:"stun:stun.l.google.com:19302"}],sdpSemantics:"unified-plan"}),this.pc.addEventListener("icecandidate",(t=>{if("webrtc/tcp"===this.options.mode&&"udp"===t.candidate?.protocol)return;const e=t.candidate?.toJSON().candidate||"";this.socket.emit("stream-payload",{id:this.streamId,data:{type:"webrtc/candidate",value:e}})})),this.pc.addEventListener("connectionstatechange",(()=>{if(console.log(this.cameraDevice.name,"Connection state:",this.pc?.connectionState),"connected"===this.pc?.connectionState){const t=this.pc?.getTransceivers().filter((t=>"recvonly"===t.currentDirection)).map((t=>t.receiver.track));this.videoPlayer.srcObject=new MediaStream(t),this.finishLoading(),this.play(),this.disconnect()}else"failed"!==this.pc?.connectionState&&"disconnected"!==this.pc?.connectionState||(clearTimeout(this.webrtcReconnectTimeout),this.webrtcReconnectTimeout=setTimeout((()=>{"failed"!==this.pc?.connectionState&&"disconnected"!==this.pc?.connectionState||this.reconnect()}),1e3))})),this.pc.addTransceiver("video",{direction:"recvonly"}),this.pc.addTransceiver("audio",{direction:"recvonly"}),this.micTransceiver=this.pc.addTransceiver("audio",{direction:"sendonly"});const t=await this.pc.createOffer();await this.pc.setLocalDescription(t),console.log(this.cameraDevice.name,"Offer:",t.sdp),this.socket.emit("stream-payload",{id:this.streamId,data:{type:"webrtc/offer",value:t.sdp}})}async onWebrtcData(t){try{switch(t.type){case"webrtc/candidate":if("webrtc/tcp"===this.options.mode&&t.value.indexOf(" udp ")>0)return;await(this.pc?.addIceCandidate({candidate:t.value,sdpMid:"0"}));break;case"webrtc/answer":console.log(this.cameraDevice.name,"Answer:",t.value),await(this.pc?.setRemoteDescription({type:"answer",sdp:t.value}));break;case"error":if(console.log(this.cameraDevice.name,"WebRTC Error:",t.value),t.value.indexOf("webrtc/offer")<0)return;this.pc?.close()}}catch(t){this.dispatchEvent(new ErrorEvent("error",{error:t,message:t.message}))}}requestMse(){if(this.reset(),"ManagedMediaSource"in window){console.log(this.cameraDevice.name,"Using ManagedMediaSource");const t=window.ManagedMediaSource;this.mediaSource=new t,this.mediaSource.addEventListener("sourceopen",(()=>{this.socket.emit("stream-payload",{id:this.streamId,data:{type:"mse",value:this.parseCodecs(t.isTypeSupported)}})}),{once:!0}),this.videoPlayer.disableRemotePlayback=!0,this.videoPlayer.srcObject=this.mediaSource}else console.log(this.cameraDevice.name,"Using MediaSource"),this.mediaSource=new MediaSource,this.mediaSource.addEventListener("sourceopen",(()=>{URL.revokeObjectURL(this.videoPlayer.src),this.socket.emit("stream-payload",{id:this.streamId,data:{type:"mse",value:this.parseCodecs(MediaSource.isTypeSupported)}})}),{once:!0}),this.videoPlayer.src=URL.createObjectURL(this.mediaSource),this.videoPlayer.srcObject=null;this.play(),this.mseCodecs=""}onMseData(t){this.mediaSource&&(this.mseCodecs=t.value,this.bufLen=0,this.buf=new Uint8Array(2097152),this.sourceBuffer=this.mediaSource.addSourceBuffer(t.value),this.sourceBuffer.mode="segments",this.sourceBuffer.addEventListener("updateend",(()=>{if(!this.sourceBuffer?.updating)try{if(this.bufLen>0){const t=this.buf.slice(0,this.bufLen);this.bufLen=0,this.sourceBuffer?.appendBuffer(t)}else if(this.sourceBuffer?.buffered?.length){const t=this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)-15,e=this.sourceBuffer.buffered.start(0);t>e&&(this.sourceBuffer.remove(e,t),this.mediaSource?.setLiveSeekableRange(t,t+15))}}catch{}})))}async onMseBuffer(t){if("closed"!==this.mediaSource?.readyState)if(this.finishLoading(),this.sourceBuffer?.updating||this.bufLen>0){const e=new Uint8Array(t.value);this.buf.set(e,this.bufLen),this.bufLen+=e.byteLength}else try{this.sourceBuffer?.appendBuffer(t.value)}catch{}else this.closed||(this.closed=!0,this.dispatchEvent(new ErrorEvent("error",{message:"MediaSource closed"})),this.options.mode="webrtc",this.requestWebrtc())}requestMjpeg(){this.reset(),this.socket.emit("stream-payload",{id:this.streamId,data:{type:"mjpeg"}})}onMjpegBuffer(t){this.videoPlayer.controls=!1,this.videoPlayer.poster="data:image/jpeg;base64,"+this.btoaBinary(t.value),this.finishLoading()}requestMp4(){this.reset();const t=document.createElement("canvas");let e=null;this.videoPlayerMp4=document.createElement("video"),this.videoPlayerMp4.autoplay=!0,this.videoPlayerMp4.playsInline=!0,this.videoPlayerMp4.muted=!0,this.videoPlayerMp4.addEventListener("loadeddata",(()=>{this.videoPlayerMp4&&(e||(t.width=this.videoPlayerMp4.videoWidth,t.height=this.videoPlayerMp4.videoHeight,e=t.getContext("2d")),e?.drawImage(this.videoPlayerMp4,0,0,t.width,t.height),this.videoPlayer.controls=!1,this.videoPlayer.poster=t.toDataURL("image/jpeg"))}));const s=this.codecList.filter((t=>this.media.includes(t.indexOf("vc1")>0?"video":"audio"))).filter((t=>this.videoPlayer.canPlayType(`video/mp4; codecs="${t}"`))).join();console.log(this.cameraDevice.name,"Playable codecs (MP4):",s),this.socket.emit("stream-payload",{id:this.streamId,data:{type:"mp4",value:s}})}onMp4Buffer(t){this.finishLoading(),this.videoPlayerMp4&&(this.videoPlayerMp4.src="data:video/mp4;base64,"+this.btoaBinary(t.value))}requestHls(){this.reset();const t=this.parseCodecs((t=>this.videoPlayer.canPlayType(t)));console.log(this.cameraDevice.name,"Playable codecs (HLS):",t),this.socket.emit("stream-payload",{id:this.streamId,data:{type:"hls",value:t}})}onHlsData(t){const e="http"+t.wsURL.substring(2,t.wsURL.indexOf("/ws"))+"/hls/",s=t.value.replace("hls/",e),n="data:application/vnd.apple.mpegurl;base64,"+btoa(s.toString());this.videoPlayer.src=n,this.finishLoading(),this.play()}onStreamInfo(t){const e=t.value;e?.producers?.length&&(this.hasBackchannel=e.producers.some((t=>t.senders?.length)))}async play(){try{await this.videoPlayer.play()}catch(t){if(!this.videoPlayer.muted)return this.videoPlayer.muted=!0,this.play();this.logger.warn(this.cameraDevice.name,t)}}finishLoading(){this._finishLoading||(this._finishLoading=!0,this.dispatchEvent(new Event("finishLoading")))}createCodecsList(){const t=["avc1.640029","avc1.64002A","avc1.640033","hvc1.1.6.L153.B0","mp4a.40.2","mp4a.40.5","flac","opus"],e="undefined"==typeof window?null:navigator.userAgent.match(/Version\/(\d+).+Safari/);if(e?.[1]){const s=e[1]<"13"?"mp4a.40.2":e[1]<"14"?"flac":"opus";t.splice(t.indexOf(s))}this.codecList=t}parseCodecs(t){return this.codecList.filter((t=>this.media.includes(t.indexOf("vc1")>0?"video":"audio"))).filter((e=>t(`video/mp4; codecs="${e}"`))).join()}btoaBinary(t){const e=new Uint8Array(t),s=e.byteLength;let n="";for(let t=0;t<s;t++)n+=String.fromCharCode(e[t]);return window.btoa(n)}}class Tt extends wt{socketService;socket;pluginName="@camera.ui/client";subject;_started=!1;get started(){return this._started}cameraDelegate=new St(this.onRequest.bind(this));ptzDelegate=new xt(this.onRequest.bind(this));prebufferDelegate=new kt(this.onRequest.bind(this));get sources(){return this._sources.filter((t=>!t.internal))}get internalSources(){return this._sources.map((t=>({...t,type:t.name.endsWith(" AAC")?"aac":t.name.endsWith(" OPUS")?"opus":"pcma"}))).filter((t=>t.internal))}get _sources(){return JSON.parse(JSON.stringify(this.cameraSubject.getValue().sources)).map((t=>({...t,getPrebufferingState:e=>this.prebufferDelegate.getPrebufferingState(t.name,e),probeStream:()=>this.onRequest("cameraFn","probeStream",[t._id])})))}constructor(t,e,s){super(t,s),this.socketService=e;const{socket:n}=this.socketService.getSocket(this.id,!0);this.socket=n,this.socket.connect(),this.subject=`${this.pluginName}.camera.${this.id}`,this.listenToMessages()}async start(){this._started||(this._started=!0,await this.refreshStates(),this.socket.emit("joinRoomStates",this.id))}stop(){this._started=!1,this.socket.emit("leaveRoomStates",this.id)}close(){this.cleanup()}connect(){return this.onRequest("cameraFn","connect")}disconnect(){return this.onRequest("cameraFn","disconnect")}createSession(t){return new Et(this,this.socketService,this.logger,t)}async refreshStates(){const t=await this.onRequest("cameraFn","refreshStates");super.updateCamera(t.camera),super.updateCameraState(t.cameraState);for(const[e,s]of Object.entries(t.states))super.updateStateInternal(e,s,!0)}async cleanup(){this.stop(),this.removeAllListeners(),this.unsubscribe(),this.socket.removeAllListeners()}listenToMessages(){this.socket.emit("joinRoomDevice",this.id),this.socket.on("updateState",(t=>{t.cameraId===this.id&&super.updateStateInternal(t.stateName,t.data.newEvent,!0)})),this.socket.on("updateDevice",(t=>{if(t.cameraId===this.id)switch(t.type){case"removed":this.cleanup();break;case"updated":super.updateCamera(t.data);break;case"cameraState":super.updateCameraState(t.data)}}))}onRequest(t,e,s=[]){const n={requestId:_t(),targetId:this.subject,targetName:this.name,pluginId:this.pluginName,cameraId:this.id,type:"request",proxy:"camera",client:t,fn:e,args:s,timestamp:Date.now(),timeout:5e3};return new Promise(((t,e)=>{this.socket.emit("request",n,(s=>{s.error?e(s.error):t(s.response)}))}))}}class Ot{socketService;socket;logger;pluginName="@camera.ui/client";subject;constructor(t,e){this.socketService=t,this.socket=t.socket,this.logger=e,this.subject=`${this.pluginName}.coreManager`}async getFFmpegPath(){return this.onRequest("getFFmpegPath")}async getHwaccelInfo(){return this.onRequest("getHwaccelInfo")}async getServerAddresses(){return this.onRequest("getServerAddresses")}async getIceServers(){return this.onRequest("getIceServers")}onRequest(t,e){const s={requestId:_t(),targetId:this.subject,targetName:this.pluginName,pluginId:this.pluginName,type:"request",proxy:"core",client:"coreFn",fn:t,args:e||[],timestamp:Date.now(),timeout:5e3};return new Promise(((t,e)=>{this.socket.emit("request",s,(s=>{s.error?e(s.error):t(s.response)}))}))}}class Ct{socketService;socket;logger;pluginName="@camera.ui/client";subject;constructor(t,e){this.socketService=t,this.socket=t.socket,this.logger=e,this.subject=`${this.pluginName}.deviceManager`}async getCameraById(t){const e=await this.onRequest("getCameraById",[t]);if(e){const t=new Tt(e,this.socketService,this.logger);return await t.refreshStates(),t}}async getCameraByName(t){const e=await this.onRequest("getCameraByName",[t]);if(e){const t=new Tt(e,this.socketService,this.logger);return await t.refreshStates(),t}}onRequest(t,e){const s={requestId:_t(),targetId:this.subject,targetName:this.pluginName,pluginId:this.pluginName,type:"request",proxy:"device",client:"deviceFn",fn:t,args:e||[],timestamp:Date.now(),timeout:5e3};return new Promise(((t,e)=>{this.socket.emit("request",s,(s=>{s.error?e(s.error):t(s.response)}))}))}}const At=Object.create(null);At.open="0",At.close="1",At.ping="2",At.pong="3",At.message="4",At.upgrade="5",At.noop="6";const Rt=Object.create(null);Object.keys(At).forEach((t=>{Rt[At[t]]=t}));const Bt={type:"error",data:"parser error"},jt="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Lt="function"==typeof ArrayBuffer,Mt=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,Pt=({type:t,data:e},s,n)=>jt&&e instanceof Blob?s?n(e):Dt(e,n):Lt&&(e instanceof ArrayBuffer||Mt(e))?s?n(e):Dt(new Blob([e]),n):n(At[t]+(e||"")),Dt=(t,e)=>{const s=new FileReader;return s.onload=function(){const t=s.result.split(",")[1];e("b"+(t||""))},s.readAsDataURL(t)};function qt(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let It;const Nt="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)Nt["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const Ut="function"==typeof ArrayBuffer,Vt=(t,e)=>{if("string"!=typeof t)return{type:"message",data:Wt(t,e)};const s=t.charAt(0);return"b"===s?{type:"message",data:Ft(t.substring(1),e)}:Rt[s]?t.length>1?{type:Rt[s],data:t.substring(1)}:{type:Rt[s]}:Bt},Ft=(t,e)=>{if(Ut){const s=(t=>{let e,s,n,r,i,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);const h=new ArrayBuffer(o),u=new Uint8Array(h);for(e=0;e<a;e+=4)s=Nt[t.charCodeAt(e)],n=Nt[t.charCodeAt(e+1)],r=Nt[t.charCodeAt(e+2)],i=Nt[t.charCodeAt(e+3)],u[c++]=s<<2|n>>4,u[c++]=(15&n)<<4|r>>2,u[c++]=(3&r)<<6|63&i;return h})(t);return Wt(s,e)}return{base64:!0,data:t}},Wt=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,zt=String.fromCharCode(30);let Ht;function $t(t){return t.reduce(((t,e)=>t+e.length),0)}function Jt(t,e){if(t[0].length===e)return t.shift();const s=new Uint8Array(e);let n=0;for(let r=0;r<e;r++)s[r]=t[0][n++],n===t[0].length&&(t.shift(),n=0);return t.length&&n<t[0].length&&(t[0]=t[0].slice(n)),s}function Yt(t){if(t)return function(t){for(var e in Yt.prototype)t[e]=Yt.prototype[e];return t}(t)}Yt.prototype.on=Yt.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},Yt.prototype.once=function(t,e){function s(){this.off(t,s),e.apply(this,arguments)}return s.fn=e,this.on(t,s),this},Yt.prototype.off=Yt.prototype.removeListener=Yt.prototype.removeAllListeners=Yt.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var s,n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var r=0;r<n.length;r++)if((s=n[r])===e||s.fn===e){n.splice(r,1);break}return 0===n.length&&delete this._callbacks["$"+t],this},Yt.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),s=this._callbacks["$"+t],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(s){n=0;for(var r=(s=s.slice(0)).length;n<r;++n)s[n].apply(this,e)}return this},Yt.prototype.emitReserved=Yt.prototype.emit,Yt.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},Yt.prototype.hasListeners=function(t){return!!this.listeners(t).length};const Kt="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Gt(t,...e){return e.reduce(((e,s)=>(t.hasOwnProperty(s)&&(e[s]=t[s]),e)),{})}const Qt=Kt.setTimeout,Xt=Kt.clearTimeout;function Zt(t,e){e.useNativeTimers?(t.setTimeoutFn=Qt.bind(Kt),t.clearTimeoutFn=Xt.bind(Kt)):(t.setTimeoutFn=Kt.setTimeout.bind(Kt),t.clearTimeoutFn=Kt.clearTimeout.bind(Kt))}class te extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}class ee extends Yt{constructor(t){super(),this.writable=!1,Zt(this,t),this.opts=t,this.query=t.query,this.socket=t.socket}onError(t,e,s){return super.emitReserved("error",new te(t,e,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=Vt(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(t){const e=function(t){let e="";for(let s in t)t.hasOwnProperty(s)&&(e.length&&(e+="&"),e+=encodeURIComponent(s)+"="+encodeURIComponent(t[s]));return e}(t);return e.length?"?"+e:""}}const se="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),ne=64,re={};let ie,oe=0,ae=0;function ce(t){let e="";do{e=se[t%ne]+e,t=Math.floor(t/ne)}while(t>0);return e}function he(){const t=ce(+new Date);return t!==ie?(oe=0,ie=t):t+"."+ce(oe++)}for(;ae<ne;ae++)re[se[ae]]=ae;let ue=!1;try{ue="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const le=ue;function pe(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||le))return new XMLHttpRequest}catch(t){}if(!e)try{return new(Kt[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}function de(){}const fe=null!=new pe({xdomain:!1}).responseType;class ge extends Yt{constructor(t,e){super(),Zt(this,e),this.opts=e,this.method=e.method||"GET",this.uri=t,this.data=void 0!==e.data?e.data:null,this.create()}create(){var t;const e=Gt(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.opts.xd;const s=this.xhr=new pe(e);try{s.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let t in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(t)&&s.setRequestHeader(t,this.opts.extraHeaders[t])}}catch(t){}if("POST"===this.method)try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{s.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this.opts.cookieJar)||void 0===t||t.addCookies(s),"withCredentials"in s&&(s.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(s.timeout=this.opts.requestTimeout),s.onreadystatechange=()=>{var t;3===s.readyState&&(null===(t=this.opts.cookieJar)||void 0===t||t.parseCookies(s)),4===s.readyState&&(200===s.status||1223===s.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof s.status?s.status:0)}),0))},s.send(this.data)}catch(t){return void this.setTimeoutFn((()=>{this.onError(t)}),0)}"undefined"!=typeof document&&(this.index=ge.requestsCount++,ge.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=de,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete ge.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}function me(){for(let t in ge.requests)ge.requests.hasOwnProperty(t)&&ge.requests[t].abort()}ge.requestsCount=0,ge.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",me):"function"==typeof addEventListener&&addEventListener("onpagehide"in Kt?"pagehide":"unload",me,!1));const ye="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),be=Kt.WebSocket||Kt.MozWebSocket,ve="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),we={websocket:class extends ee{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),e=this.opts.protocols,s=ve?{}:Gt(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=ve?new be(t,e,s):e?new be(t,e):new be(t)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],n=e===t.length-1;Pt(s,this.supportsBinary,(t=>{try{this.ws.send(t)}catch(t){}n&&ye((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=he()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}check(){return!!be}},webtransport:class extends ee{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then((()=>{this.onClose()})).catch((t=>{this.onError("webtransport error",t)})),this.transport.ready.then((()=>{this.transport.createBidirectionalStream().then((t=>{const e=function(t,e){Ht||(Ht=new TextDecoder);const s=[];let n=0,r=-1,i=!1;return new TransformStream({transform(o,a){for(s.push(o);;){if(0===n){if($t(s)<1)break;const t=Jt(s,1);i=!(128&~t[0]),r=127&t[0],n=r<126?3:126===r?1:2}else if(1===n){if($t(s)<2)break;const t=Jt(s,2);r=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),n=3}else if(2===n){if($t(s)<8)break;const t=Jt(s,8),e=new DataView(t.buffer,t.byteOffset,t.length),i=e.getUint32(0);if(i>Math.pow(2,21)-1){a.enqueue(Bt);break}r=i*Math.pow(2,32)+e.getUint32(4),n=3}else{if($t(s)<r)break;const t=Jt(s,r);a.enqueue(Vt(i?t:Ht.decode(t),e)),n=0}if(0===r||r>t){a.enqueue(Bt);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(e).getReader(),n=new TransformStream({transform(t,e){!function(t,e){jt&&t.data instanceof Blob?t.data.arrayBuffer().then(qt).then(e):Lt&&(t.data instanceof ArrayBuffer||Mt(t.data))?e(qt(t.data)):Pt(t,!1,(t=>{It||(It=new TextEncoder),e(It.encode(t))}))}(t,(s=>{const n=s.length;let r;if(n<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,n);else if(n<65536){r=new Uint8Array(3);const t=new DataView(r.buffer);t.setUint8(0,126),t.setUint16(1,n)}else{r=new Uint8Array(9);const t=new DataView(r.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(n))}t.data&&"string"!=typeof t.data&&(r[0]|=128),e.enqueue(r),e.enqueue(s)}))}});n.readable.pipeTo(t.writable),this.writer=n.writable.getWriter();const r=()=>{s.read().then((({done:t,value:e})=>{t||(this.onPacket(e),r())})).catch((t=>{}))};r();const i={type:"open"};this.query.sid&&(i.data=`{"sid":"${this.query.sid}"}`),this.writer.write(i).then((()=>this.onOpen()))}))})))}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],n=e===t.length-1;this.writer.write(s).then((()=>{n&&ye((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var t;null===(t=this.transport)||void 0===t||t.close()}},polling:class extends ee{constructor(t){if(super(t),this.polling=!1,"undefined"!=typeof location){const e="https:"===location.protocol;let s=location.port;s||(s=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||s!==t.port}const e=t&&t.forceBase64;this.supportsBinary=fe&&!e,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this.polling||!this.writable){let t=0;this.polling&&(t++,this.once("pollComplete",(function(){--t||e()}))),this.writable||(t++,this.once("drain",(function(){--t||e()})))}else e()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const s=t.split(zt),n=[];for(let t=0;t<s.length;t++){const r=Vt(s[t],e);if(n.push(r),"error"===r.type)break}return n})(t,this.socket.binaryType).forEach((t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const s=t.length,n=new Array(s);let r=0;t.forEach(((t,i)=>{Pt(t,!1,(t=>{n[i]=t,++r===s&&e(n.join(zt))}))}))})(t,(t=>{this.doWrite(t,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=he()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}request(t={}){return Object.assign(t,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new ge(this.uri(),t)}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",((t,e)=>{this.onError("xhr post error",t,e)}))}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",((t,e)=>{this.onError("xhr poll error",t,e)})),this.pollXhr=t}}},Se=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ke=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function xe(t){if(t.length>2e3)throw"URI too long";const e=t,s=t.indexOf("["),n=t.indexOf("]");-1!=s&&-1!=n&&(t=t.substring(0,s)+t.substring(s,n).replace(/:/g,";")+t.substring(n,t.length));let r=Se.exec(t||""),i={},o=14;for(;o--;)i[ke[o]]=r[o]||"";return-1!=s&&-1!=n&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(t,e){const s=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||s.splice(0,1),"/"==e.slice(-1)&&s.splice(s.length-1,1),s}(0,i.path),i.queryKey=function(t,e){const s={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,n){e&&(s[e]=n)})),s}(0,i.query),i}class _e extends Yt{constructor(t,e={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],t&&"object"==typeof t&&(e=t,t=null),t?(t=xe(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=xe(e.host).host),Zt(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=e.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},s=t.split("&");for(let t=0,n=s.length;t<n;t++){let n=s[t].split("=");e[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return e}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new we[t](s)}open(){let t;if(this.opts.rememberUpgrade&&_e.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(t=>this.onClose("transport close",t)))}probe(t){let e=this.createTransport(t),s=!1;_e.priorWebsocketSuccess=!1;const n=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",(t=>{if(!s)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;_e.priorWebsocketSuccess="websocket"===e.name,this.transport.pause((()=>{s||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())}))}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}})))};function r(){s||(s=!0,h(),e.close(),e=null)}const i=t=>{const s=new Error("probe error: "+t);s.transport=e.name,r(),this.emitReserved("upgradeError",s)};function o(){i("transport closed")}function a(){i("socket closed")}function c(t){e&&t.name!==e.name&&r()}const h=()=>{e.removeListener("open",n),e.removeListener("error",i),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",n),e.once("error",i),e.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn((()=>{s||e.open()}),200):e.open()}onOpen(){if(this.readyState="open",_e.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let t=0;const e=this.upgrades.length;for(;t<e;t++)this.probe(this.upgrades[t])}}onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),this.resetPingTimeout(),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const e=new Error("server error");e.code=t.data,this.onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.upgrades=this.filterUpgrades(t.upgrades),this.pingInterval=t.pingInterval,this.pingTimeout=t.pingTimeout,this.maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s<this.writeBuffer.length;s++){const n=this.writeBuffer[s].data;if(n&&(t+="string"==typeof(e=n)?function(t){let e=0,s=0;for(let n=0,r=t.length;n<r;n++)e=t.charCodeAt(n),e<128?s+=1:e<2048?s+=2:e<55296||e>=57344?s+=3:(n++,s+=4);return s}(e):Math.ceil(1.33*(e.byteLength||e.size))),s>0&&t>this.maxPayload)return this.writeBuffer.slice(0,s);t+=2}var e;return this.writeBuffer}write(t,e,s){return this.sendPacket("message",t,e,s),this}send(t,e,s){return this.sendPacket("message",t,e,s),this}sendPacket(t,e,s,n){if("function"==typeof e&&(n=e,e=void 0),"function"==typeof s&&(n=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const r={type:t,data:e,options:s};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),n&&this.once("flush",n),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?s():t()})):this.upgrading?s():t()),this}onError(t){_e.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,e){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const e=[];let s=0;const n=t.length;for(;s<n;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}_e.protocol=4,_e.protocol;const Ee="function"==typeof ArrayBuffer,Te=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer,Oe=Object.prototype.toString,Ce="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Oe.call(Blob),Ae="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Oe.call(File);function Re(t){return Ee&&(t instanceof ArrayBuffer||Te(t))||Ce&&t instanceof Blob||Ae&&t instanceof File}function Be(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,s=t.length;e<s;e++)if(Be(t[e]))return!0;return!1}if(Re(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return Be(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&Be(t[e]))return!0;return!1}function je(t){const e=[],s=t.data,n=t;return n.data=Le(s,e),n.attachments=e.length,{packet:n,buffers:e}}function Le(t,e){if(!t)return t;if(Re(t)){const s={_placeholder:!0,num:e.length};return e.push(t),s}if(Array.isArray(t)){const s=new Array(t.length);for(let n=0;n<t.length;n++)s[n]=Le(t[n],e);return s}if("object"==typeof t&&!(t instanceof Date)){const s={};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(s[n]=Le(t[n],e));return s}return t}function Me(t,e){return t.data=Pe(t.data,e),delete t.attachments,t}function Pe(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let s=0;s<t.length;s++)t[s]=Pe(t[s],e);else if("object"==typeof t)for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=Pe(t[s],e));return t}const De=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],qe=5;var Ie;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(Ie||(Ie={}));class Ne{constructor(t){this.replacer=t}encode(t){return t.type!==Ie.EVENT&&t.type!==Ie.ACK||!Be(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===Ie.EVENT?Ie.BINARY_EVENT:Ie.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==Ie.BINARY_EVENT&&t.type!==Ie.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=je(t),s=this.encodeAsString(e.packet),n=e.buffers;return n.unshift(s),n}}function Ue(t){return"[object Object]"===Object.prototype.toString.call(t)}class Ve extends Yt{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const s=e.type===Ie.BINARY_EVENT;s||e.type===Ie.BINARY_ACK?(e.type=s?Ie.EVENT:Ie.ACK,this.reconstructor=new Fe(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!Re(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const s={type:Number(t.charAt(0))};if(void 0===Ie[s.type])throw new Error("unknown packet type "+s.type);if(s.type===Ie.BINARY_EVENT||s.type===Ie.BINARY_ACK){const n=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const r=t.substring(n,e);if(r!=Number(r)||"-"!==t.charAt(e))throw new Error("Illegal attachments");s.attachments=Number(r)}if("/"===t.charAt(e+1)){const n=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);s.nsp=t.substring(n,e)}else s.nsp="/";const n=t.charAt(e+1);if(""!==n&&Number(n)==n){const n=e+1;for(;++e;){const s=t.charAt(e);if(null==s||Number(s)!=s){--e;break}if(e===t.length)break}s.id=Number(t.substring(n,e+1))}if(t.charAt(++e)){const n=this.tryParse(t.substr(e));if(!Ve.isPayloadValid(s.type,n))throw new Error("invalid payload");s.data=n}return s}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case Ie.CONNECT:return Ue(e);case Ie.DISCONNECT:return void 0===e;case Ie.CONNECT_ERROR:return"string"==typeof e||Ue(e);case Ie.EVENT:case Ie.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===De.indexOf(e[0]));case Ie.ACK:case Ie.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Fe{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=Me(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function We(t,e,s){return t.on(e,s),function(){t.off(e,s)}}const ze=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class He extends Yt{constructor(t,e,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[We(t,"open",this.onopen.bind(this)),We(t,"packet",this.onpacket.bind(this)),We(t,"error",this.onerror.bind(this)),We(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){if(ze.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const s={type:Ie.EVENT,data:e,options:{}};if(s.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this._registerAckCallback(t,n),s.id=t}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!n||!this.connected)||(this.connected?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s)),this.flags={},this}_registerAckCallback(t,e){var s;const n=null!==(s=this.flags.timeout)&&void 0!==s?s:this._opts.ackTimeout;if(void 0===n)return void(this.acks[t]=e);const r=this.io.setTimeoutFn((()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))}),n),i=(...t)=>{this.io.clearTimeoutFn(r),e.apply(this,t)};i.withError=!0,this.acks[t]=i}emitWithAck(t,...e){return new Promise(((s,n)=>{const r=(t,e)=>t?n(t):s(e);r.withError=!0,e.push(r),this.emit(t,...e)}))}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push(((t,...n)=>{if(s===this._queue[0])return null!==t?s.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...n)),s.pending=!1,this._drainQueue()})),this._queue.push(s),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth((t=>{this._sendConnectPacket(t)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:Ie.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach((t=>{if(!this.sendBuffer.some((e=>String(e.id)===t))){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}}))}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case Ie.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ie.EVENT:case Ie.BINARY_EVENT:this.onevent(t);break;case Ie.ACK:case Ie.BINARY_ACK:this.onack(t);break;case Ie.DISCONNECT:this.ondisconnect();break;case Ie.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const s of e)s.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let s=!1;return function(...n){s||(s=!0,e.packet({type:Ie.ACK,id:t,data:n}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((t=>this.emitEvent(t))),this.receiveBuffer=[],this.sendBuffer.forEach((t=>{this.notifyOutgoingListeners(t),this.packet(t)})),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((t=>t())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Ie.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const s of e)s.apply(this,t.data)}}}function $e(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}$e.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),s=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+s:t-s}return 0|Math.min(t,this.max)},$e.prototype.reset=function(){this.attempts=0},$e.prototype.setMin=function(t){this.ms=t},$e.prototype.setMax=function(t){this.max=t},$e.prototype.setJitter=function(t){this.jitter=t};class Je extends Yt{constructor(t,e){var s;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,Zt(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(s=e.randomizationFactor)&&void 0!==s?s:.5),this.backoff=new $e({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const n=e.parser||r;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new _e(this.uri,this.opts);const e=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const n=We(e,"open",(function(){s.onopen(),t&&t()})),r=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},i=We(e,"error",r);if(!1!==this._timeout){const t=this._timeout,s=this.setTimeoutFn((()=>{n(),r(new Error("timeout")),e.close()}),t);this.opts.autoUnref&&s.unref(),this.subs.push((()=>{this.clearTimeoutFn(s)}))}return this.subs.push(n),this.subs.push(i),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(We(t,"ping",this.onping.bind(this)),We(t,"data",this.ondata.bind(this)),We(t,"error",this.onerror.bind(this)),We(t,"close",this.onclose.bind(this)),We(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){ye((()=>{this.emitReserved("packet",t)}),this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s?this._autoConnect&&!s.active&&s.connect():(s=new He(this,t,e),this.nsps[t]=s),s}_destroy(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let s=0;s<e.length;s++)this.engine.write(e[s],t.options)}cleanup(){this.subs.forEach((t=>t())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t,e){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn((()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open((e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()})))}),e);this.opts.autoUnref&&s.unref(),this.subs.push((()=>{this.clearTimeoutFn(s)}))}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Ye={};function Ke(t,e){"object"==typeof t&&(e=t,t=void 0);const s=function(t,e="",s){let n=t;s=s||"undefined"!=typeof location&&location,null==t&&(t=s.protocol+"//"+s.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?s.protocol+t:s.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==s?s.protocol+"//"+t:"https://"+t),n=xe(t)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const r=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+r+":"+n.port+e,n.href=n.protocol+"://"+r+(s&&s.port===n.port?"":":"+n.port),n}(t,(e=e||{}).path||"/socket.io"),n=s.source,r=s.id,i=s.path,o=Ye[r]&&i in Ye[r].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new Je(n,e):(Ye[r]||(Ye[r]=new Je(n,e)),a=Ye[r]),s.query&&!e.query&&(e.query=s.queryKey),a.socket(s.path,e)}Object.assign(Ke,{Manager:Je,Socket:He,io:Ke,connect:Ke});class Ge{socket;token;endpoint;socketList=new Map;constructor(t,e){this.endpoint=t.replace("https://","wss://").replace("http://","ws://"),this.token=e,this.socket=this.getSocket("default").socket,this.socket.connect()}close(){this.socket.emit("end"),this.socket.removeAllListeners(),this.socket.disconnect()}getSocket(t,e){return this.createManager(e)}createManager(t){const e=new Je(this.endpoint,{reconnection:!0,reconnectionDelay:500,rejectUnauthorized:!1,transports:["websocket"],forceNew:t}),s=e.socket("/proxy",{auth:{token:`Bearer ${this.token}`}});return{manager:e,socket:s}}}class Qe{api;socketService;config;logger;token;deviceManager;coreManager;constructor(t){this.config=t,this.logger=t.logger||{...console,attention:console.warn},this.api=new i(t.endpoint)}async connect(){return this.deviceManager&&this.coreManager||(this.cleanUpClient(),await this.login(),this.token=this.token||this.config.token,this.socketService=new Ge(this.config.endpoint,this.token),this.coreManager=new Ot(this.socketService,this.logger),this.deviceManager=new Ct(this.socketService,this.logger),this.checkSession()),{coreManager:this.coreManager,deviceManager:this.deviceManager}}async disconnect(){this.socketService?.close(),this.cleanUpClient(),this.config.username&&this.config.password&&await this.api.post("/auth/logout",void 0,{headers:{Authorization:`Bearer ${this.token}`}})}async updateCredentials(t){this.config={...this.config,...t},this.socketService&&await this.disconnect(),await this.connect()}async login(){if(this.config.username&&this.config.password)try{const t=await this.api.post("/auth/login",{username:this.config.username,password:this.config.password}),e=await t.json();this.token=e.access_token}catch(t){throw 401===t.response?.status?new Error("Invalid credentials"):new Error(`Failed to get token: ${t.message}`)}else if(this.config.token&&!this.config.skipCheck)try{await this.api.get("/auth/check",{headers:{Authorization:`Bearer ${this.config.token}`}})}catch(t){throw new Error(`Invalid token: ${t.message}`)}this.token=this.token||this.config.token}getDeviceManager(){return this.deviceManager}checkSession(){this.socketService?.socket.removeListener("invalidToken"),this.socketService?.socket.on("invalidToken",(async t=>{t===this.token&&await this.disconnect()}))}cleanUpClient(){this.deviceManager=void 0}}var Xe=n.j;export{Xe as CameraUiClient};
|
|
1
|
+
var t={855:t=>{const e="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,s=()=>e.now(),i=t=>t===1/0||(t=>t&&t===Math.floor(t)&&t>0&&isFinite(t))(t);class n{constructor({max:t=1/0,ttl:e,updateAgeOnGet:s=!1,checkAgeOnGet:n=!1,noUpdateTTL:r=!1,dispose:o,noDisposeOnSet:a=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,void 0!==e&&!i(e))throw new TypeError("ttl must be positive integer or Infinity if set");if(!i(t))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=e,this.max=t,this.updateAgeOnGet=!!s,this.checkAgeOnGet=!!n,this.noUpdateTTL=!!r,this.noDisposeOnSet=!!a,void 0!==o){if("function"!=typeof o)throw new TypeError("dispose must be function if set");this.dispose=o}this.timer=void 0,this.timerExpiration=void 0}setTimer(t,e){if(this.timerExpiration<t)return;this.timer&&clearTimeout(this.timer);const i=setTimeout((()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(const t in this.expirations){this.setTimer(t,t-s());break}}),e);i.unref&&i.unref(),this.timerExpiration=t,this.timer=i}cancelTimer(){this.timer&&(clearTimeout(this.timer),this.timerExpiration=void 0,this.timer=void 0)}cancelTimers(){return process.emitWarning('TTLCache.cancelTimers has been renamed to TTLCache.cancelTimer (no "s"), and will be removed in the next major version update'),this.cancelTimer()}clear(){const t=this.dispose!==n.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(const[e,s]of t)this.dispose(s,e,"delete")}setTTL(t,e=this.ttl){const i=this.expirationMap.get(t);if(void 0!==i){const e=this.expirations[i];!e||e.length<=1?delete this.expirations[i]:this.expirations[i]=e.filter((e=>e!==t))}if(e!==1/0){const i=Math.floor(s()+e);this.expirationMap.set(t,i),this.expirations[i]||(this.expirations[i]=[],this.setTimer(i,e)),this.expirations[i].push(t)}else this.expirationMap.set(t,1/0)}set(t,e,{ttl:s=this.ttl,noUpdateTTL:n=this.noUpdateTTL,noDisposeOnSet:r=this.noDisposeOnSet}={}){if(!i(s))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(t)){n||this.setTTL(t,s);const i=this.data.get(t);i!==e&&(this.data.set(t,e),r||this.dispose(i,t,"set"))}else this.setTTL(t,s),this.data.set(t,e);for(;this.size>this.max;)this.purgeToCapacity();return this}has(t){return this.data.has(t)}getRemainingTTL(t){const e=this.expirationMap.get(t);return e===1/0?e:void 0!==e?Math.max(0,Math.ceil(e-s())):0}get(t,{updateAgeOnGet:e=this.updateAgeOnGet,ttl:s=this.ttl,checkAgeOnGet:i=this.checkAgeOnGet}={}){const n=this.data.get(t);if(!i||0!==this.getRemainingTTL(t))return e&&this.setTTL(t,s),n;this.delete(t)}dispose(t,e){}delete(t){const e=this.expirationMap.get(t);if(void 0!==e){const s=this.data.get(t);this.data.delete(t),this.expirationMap.delete(t);const i=this.expirations[e];return i&&(i.length<=1?delete this.expirations[e]:this.expirations[e]=i.filter((e=>e!==t))),this.dispose(s,t,"delete"),0===this.size&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(const t in this.expirations){const e=this.expirations[t];if(!(this.size-e.length>=this.max)){const t=this.size-this.max,s=[];for(const i of e.splice(0,t))s.push([i,this.data.get(i)]),this.data.delete(i),this.expirationMap.delete(i);for(const[t,e]of s)this.dispose(e,t,"evict");return}{delete this.expirations[t];const s=[];for(const t of e)s.push([t,this.data.get(t)]),this.data.delete(t),this.expirationMap.delete(t);for(const[t,e]of s)this.dispose(e,t,"evict")}}}get size(){return this.data.size}purgeStale(){const t=Math.ceil(s());for(const e in this.expirations){if("Infinity"===e||e>t)return;const s=[...this.expirations[e]||[]],i=[];delete this.expirations[e];for(const t of s)i.push([t,this.data.get(t)]),this.data.delete(t),this.expirationMap.delete(t);for(const[t,e]of i)this.dispose(e,t,"stale")}0===this.size&&this.cancelTimer()}*entries(){for(const t in this.expirations)for(const e of this.expirations[t])yield[e,this.data.get(e)]}*keys(){for(const t in this.expirations)for(const e of this.expirations[t])yield e}*values(){for(const t in this.expirations)for(const e of this.expirations[t])yield this.data.get(e)}[Symbol.iterator](){return this.entries()}}t.exports=n}},e={};function s(i){var n=e[i];if(void 0!==n)return n.exports;var r=e[i]={exports:{}};return t[i](r,r.exports,s),r.exports}s.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return s.d(e,{a:e}),e},s.d=(t,e)=>{for(var i in e)s.o(e,i)&&!s.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},s.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),s.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var i={};s.d(i,{j:()=>Qe});var n={};s.r(n),s.d(n,{Decoder:()=>Ue,Encoder:()=>Ne,PacketType:()=>Ie,protocol:()=>qe});class r{baseURL;abortControllers=new Set;constructor(t){this.baseURL=`${t}/api`}async request(t,e,s,i={}){const n=new AbortController;this.abortControllers.add(n);const r=setTimeout((()=>{n.abort(),this.abortControllers.delete(n)}),15e3);try{const r=await fetch(`${this.baseURL}${e}`,{method:t,headers:{"Content-Type":"application/json",...i.headers},body:s?JSON.stringify(s):void 0,signal:n.signal,...i});if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);return r}finally{clearTimeout(r),this.abortControllers.delete(n)}}get(t,e){return this.request("GET",t,void 0,e)}post(t,e,s){return this.request("POST",t,e,s)}}process.env.CAMERA_UI_RUNMODE,process.env.CAMERA_UI_RUNMODE,process.env.CAMERA_UI_RUNMODE,process.env.CAMERA_UI_AS_SERVICE;class o{subscriptions=[];additionalSubscriptions=[];addSubscriptions(...t){this.subscriptions.push(...t)}addAdditionalSubscriptions(...t){this.additionalSubscriptions.push(...t)}unsubscribe(){this.subscriptions.forEach((t=>t.unsubscribe()))}unsubscribeAdditional(){this.additionalSubscriptions.forEach((t=>t.unsubscribe()))}}function a(t,e,s=!1){if(t===e)return!0;if((void 0===t||void 0===e||null===t||null===e)&&(t||e))return!1;const i=t?.constructor.name,n=e?.constructor.name;if(i!==n)return!1;if("Array"===i&&"Array"===n){if(t.length!==e.length)return!1;if(s){const i=[...e];return t.every((t=>{const e=i.findIndex((e=>a(t,e,s)));return-1!==e&&(i.splice(e,1),!0)}))}{let i=!0;for(let n=0;n<t.length;n++)if(!a(t[n],e[n],s)){i=!1;break}return i}}if("Object"===i&&"Object"===n){let i=!0;const n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(let r=0;r<n.length;r++)if(t[n[r]]&&e[n[r]]){if(t[n[r]]===e[n[r]])continue;if(!t[n[r]]||"Array"!==t[n[r]].constructor.name&&"Object"!==t[n[r]].constructor.name){if(t[n[r]]!==e[n[r]]){i=!1;break}}else if(i=a(t[n[r]],e[n[r]],s),!i)break}else if(t[n[r]]&&!e[n[r]]||!t[n[r]]&&e[n[r]]){i=!1;break}return i}return t===e}function c(t){return JSON.parse(JSON.stringify(t))}var h=s(855),u=s.n(h),l=function(t,e){return l=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(t[s]=e[s])},l(t,e)};function d(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function s(){this.constructor=t}l(t,e),t.prototype=null===e?Object.create(e):(s.prototype=e.prototype,new s)}function p(t,e){var s,i,n,r={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(c){return function(a){if(s)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(r=0)),r;)try{if(s=1,i&&(n=2&a[0]?i.return:a[0]?i.throw||((n=i.return)&&n.call(i),0):i.next)&&!(n=n.call(i,a[1])).done)return n;switch(i=0,n&&(a=[2&a[0],n.value]),a[0]){case 0:case 1:n=a;break;case 4:return r.label++,{value:a[1],done:!1};case 5:r.label++,i=a[1],a=[0];continue;case 7:a=r.ops.pop(),r.trys.pop();continue;default:if(!((n=(n=r.trys).length>0&&n[n.length-1])||6!==a[0]&&2!==a[0])){r=0;continue}if(3===a[0]&&(!n||a[1]>n[0]&&a[1]<n[3])){r.label=a[1];break}if(6===a[0]&&r.label<n[1]){r.label=n[1],n=a;break}if(n&&r.label<n[2]){r.label=n[2],r.ops.push(a);break}n[2]&&r.ops.pop(),r.trys.pop();continue}a=e.call(t,r)}catch(t){a=[6,t],i=0}finally{s=n=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function f(t){var e="function"==typeof Symbol&&Symbol.iterator,s=e&&t[e],i=0;if(s)return s.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function m(t,e){var s="function"==typeof Symbol&&t[Symbol.iterator];if(!s)return t;var i,n,r=s.call(t),o=[];try{for(;(void 0===e||e-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(t){n={error:t}}finally{try{i&&!i.done&&(s=r.return)&&s.call(r)}finally{if(n)throw n.error}}return o}function g(t,e,s){if(s||2===arguments.length)for(var i,n=0,r=e.length;n<r;n++)!i&&n in e||(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))}function y(t){return this instanceof y?(this.v=t,this):new y(t)}function b(t){return"function"==typeof t}function v(t){var e=t((function(t){Error.call(t),t.stack=(new Error).stack}));return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var w=v((function(t){return function(e){t(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map((function(t,e){return e+1+") "+t.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=e}}));function S(t,e){if(t){var s=t.indexOf(e);0<=s&&t.splice(s,1)}}var _=function(){function t(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var t,e,s,i,n;if(!this.closed){this.closed=!0;var r=this._parentage;if(r)if(this._parentage=null,Array.isArray(r))try{for(var o=f(r),a=o.next();!a.done;a=o.next())a.value.remove(this)}catch(e){t={error:e}}finally{try{a&&!a.done&&(e=o.return)&&e.call(o)}finally{if(t)throw t.error}}else r.remove(this);var c=this.initialTeardown;if(b(c))try{c()}catch(t){n=t instanceof w?t.errors:[t]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var u=f(h),l=u.next();!l.done;l=u.next()){var d=l.value;try{E(d)}catch(t){n=null!=n?n:[],t instanceof w?n=g(g([],m(n)),m(t.errors)):n.push(t)}}}catch(t){s={error:t}}finally{try{l&&!l.done&&(i=u.return)&&i.call(u)}finally{if(s)throw s.error}}}if(n)throw new w(n)}},t.prototype.add=function(e){var s;if(e&&e!==this)if(this.closed)E(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=null!==(s=this._finalizers)&&void 0!==s?s:[]).push(e)}},t.prototype._hasParent=function(t){var e=this._parentage;return e===t||Array.isArray(e)&&e.includes(t)},t.prototype._addParent=function(t){var e=this._parentage;this._parentage=Array.isArray(e)?(e.push(t),e):e?[e,t]:t},t.prototype._removeParent=function(t){var e=this._parentage;e===t?this._parentage=null:Array.isArray(e)&&S(e,t)},t.prototype.remove=function(e){var s=this._finalizers;s&&S(s,e),e instanceof t&&e._removeParent(this)},t.EMPTY=function(){var e=new t;return e.closed=!0,e}(),t}(),k=_.EMPTY;function x(t){return t instanceof _||t&&"closed"in t&&b(t.remove)&&b(t.add)&&b(t.unsubscribe)}function E(t){b(t)?t():t.unsubscribe()}var T={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},O={setTimeout:function(t,e){for(var s=[],i=2;i<arguments.length;i++)s[i-2]=arguments[i];var n=O.delegate;return(null==n?void 0:n.setTimeout)?n.setTimeout.apply(n,g([t,e],m(s))):setTimeout.apply(void 0,g([t,e],m(s)))},clearTimeout:function(t){var e=O.delegate;return((null==e?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function C(t){O.setTimeout((function(){var e=T.onUnhandledError;if(!e)throw t;e(t)}))}function R(){}var A=B("C",void 0,void 0);function B(t,e,s){return{kind:t,value:e,error:s}}var j=null;function L(t){if(T.useDeprecatedSynchronousErrorHandling){var e=!j;if(e&&(j={errorThrown:!1,error:null}),t(),e){var s=j,i=s.errorThrown,n=s.error;if(j=null,i)throw n}}else t()}var P=function(t){function e(e){var s=t.call(this)||this;return s.isStopped=!1,e?(s.destination=e,x(e)&&e.add(s)):s.destination=U,s}return d(e,t),e.create=function(t,e,s){return new I(t,e,s)},e.prototype.next=function(t){this.isStopped?F(function(t){return B("N",t,void 0)}(t),this):this._next(t)},e.prototype.error=function(t){this.isStopped?F(B("E",void 0,t),this):(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped?F(A,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(_),M=Function.prototype.bind;function D(t,e){return M.call(t,e)}var q=function(){function t(t){this.partialObserver=t}return t.prototype.next=function(t){var e=this.partialObserver;if(e.next)try{e.next(t)}catch(t){N(t)}},t.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(t){N(t)}else N(t)},t.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(t){N(t)}},t}(),I=function(t){function e(e,s,i){var n,r,o=t.call(this)||this;return b(e)||!e?n={next:null!=e?e:void 0,error:null!=s?s:void 0,complete:null!=i?i:void 0}:o&&T.useDeprecatedNextContext?((r=Object.create(e)).unsubscribe=function(){return o.unsubscribe()},n={next:e.next&&D(e.next,r),error:e.error&&D(e.error,r),complete:e.complete&&D(e.complete,r)}):n=e,o.destination=new q(n),o}return d(e,t),e}(P);function N(t){var e;T.useDeprecatedSynchronousErrorHandling?(e=t,T.useDeprecatedSynchronousErrorHandling&&j&&(j.errorThrown=!0,j.error=e)):C(t)}function F(t,e){var s=T.onStoppedNotification;s&&O.setTimeout((function(){return s(t,e)}))}var U={closed:!0,next:R,error:function(t){throw t},complete:R},V="function"==typeof Symbol&&Symbol.observable||"@@observable";function W(t){return t}var z=function(){function t(t){t&&(this._subscribe=t)}return t.prototype.lift=function(e){var s=new t;return s.source=this,s.operator=e,s},t.prototype.subscribe=function(t,e,s){var i=this,n=function(t){return t&&t instanceof P||function(t){return t&&b(t.next)&&b(t.error)&&b(t.complete)}(t)&&x(t)}(t)?t:new I(t,e,s);return L((function(){var t=i,e=t.operator,s=t.source;n.add(e?e.call(n,s):s?i._subscribe(n):i._trySubscribe(n))})),n},t.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(e){t.error(e)}},t.prototype.forEach=function(t,e){var s=this;return new(e=H(e))((function(e,i){var n=new I({next:function(e){try{t(e)}catch(t){i(t),n.unsubscribe()}},error:i,complete:e});s.subscribe(n)}))},t.prototype._subscribe=function(t){var e;return null===(e=this.source)||void 0===e?void 0:e.subscribe(t)},t.prototype[V]=function(){return this},t.prototype.pipe=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return(0===(s=t).length?W:1===s.length?s[0]:function(t){return s.reduce((function(t,e){return e(t)}),t)})(this);var s},t.prototype.toPromise=function(t){var e=this;return new(t=H(t))((function(t,s){var i;e.subscribe((function(t){return i=t}),(function(t){return s(t)}),(function(){return t(i)}))}))},t.create=function(e){return new t(e)},t}();function H(t){var e;return null!==(e=null!=t?t:T.Promise)&&void 0!==e?e:Promise}var $=v((function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})),Y=function(t){function e(){var e=t.call(this)||this;return e.closed=!1,e.currentObservers=null,e.observers=[],e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return d(e,t),e.prototype.lift=function(t){var e=new J(this,this);return e.operator=t,e},e.prototype._throwIfClosed=function(){if(this.closed)throw new $},e.prototype.next=function(t){var e=this;L((function(){var s,i;if(e._throwIfClosed(),!e.isStopped){e.currentObservers||(e.currentObservers=Array.from(e.observers));try{for(var n=f(e.currentObservers),r=n.next();!r.done;r=n.next())r.value.next(t)}catch(t){s={error:t}}finally{try{r&&!r.done&&(i=n.return)&&i.call(n)}finally{if(s)throw s.error}}}}))},e.prototype.error=function(t){var e=this;L((function(){if(e._throwIfClosed(),!e.isStopped){e.hasError=e.isStopped=!0,e.thrownError=t;for(var s=e.observers;s.length;)s.shift().error(t)}}))},e.prototype.complete=function(){var t=this;L((function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var e=t.observers;e.length;)e.shift().complete()}}))},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return(null===(t=this.observers)||void 0===t?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(e){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,e)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var e=this,s=this,i=s.hasError,n=s.isStopped,r=s.observers;return i||n?k:(this.currentObservers=null,r.push(t),new _((function(){e.currentObservers=null,S(r,t)})))},e.prototype._checkFinalizedStatuses=function(t){var e=this,s=e.hasError,i=e.thrownError,n=e.isStopped;s?t.error(i):n&&t.complete()},e.prototype.asObservable=function(){var t=new z;return t.source=this,t},e.create=function(t,e){return new J(t,e)},e}(z),J=function(t){function e(e,s){var i=t.call(this)||this;return i.destination=e,i.source=s,i}return d(e,t),e.prototype.next=function(t){var e,s;null===(s=null===(e=this.destination)||void 0===e?void 0:e.next)||void 0===s||s.call(e,t)},e.prototype.error=function(t){var e,s;null===(s=null===(e=this.destination)||void 0===e?void 0:e.error)||void 0===s||s.call(e,t)},e.prototype.complete=function(){var t,e;null===(e=null===(t=this.destination)||void 0===t?void 0:t.complete)||void 0===e||e.call(t)},e.prototype._subscribe=function(t){var e,s;return null!==(s=null===(e=this.source)||void 0===e?void 0:e.subscribe(t))&&void 0!==s?s:k},e}(Y),K=function(t){function e(e){var s=t.call(this)||this;return s._value=e,s}return d(e,t),Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(e){var s=t.prototype._subscribe.call(this,e);return!s.closed&&e.next(this._value),s},e.prototype.getValue=function(){var t=this,e=t.hasError,s=t.thrownError,i=t._value;if(e)throw s;return this._throwIfClosed(),i},e.prototype.next=function(e){t.prototype.next.call(this,this._value=e)},e}(Y),G={now:function(){return(G.delegate||Date).now()},delegate:void 0},Q=function(t){function e(e,s,i){void 0===e&&(e=1/0),void 0===s&&(s=1/0),void 0===i&&(i=G);var n=t.call(this)||this;return n._bufferSize=e,n._windowTime=s,n._timestampProvider=i,n._buffer=[],n._infiniteTimeWindow=!0,n._infiniteTimeWindow=s===1/0,n._bufferSize=Math.max(1,e),n._windowTime=Math.max(1,s),n}return d(e,t),e.prototype.next=function(e){var s=this,i=s.isStopped,n=s._buffer,r=s._infiniteTimeWindow,o=s._timestampProvider,a=s._windowTime;i||(n.push(e),!r&&n.push(o.now()+a)),this._trimBuffer(),t.prototype.next.call(this,e)},e.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var e=this._innerSubscribe(t),s=this._infiniteTimeWindow,i=this._buffer.slice(),n=0;n<i.length&&!t.closed;n+=s?1:2)t.next(i[n]);return this._checkFinalizedStatuses(t),e},e.prototype._trimBuffer=function(){var t=this,e=t._bufferSize,s=t._timestampProvider,i=t._buffer,n=t._infiniteTimeWindow,r=(n?1:2)*e;if(e<1/0&&r<i.length&&i.splice(0,i.length-r),!n){for(var o=s.now(),a=0,c=1;c<i.length&&i[c]<=o;c+=2)a=c;a&&i.splice(0,a+1)}},e}(Y);function X(t){return function(e){if(function(t){return b(null==t?void 0:t.lift)}(e))return e.lift((function(e){try{return t(e,this)}catch(t){this.error(t)}}));throw new TypeError("Unable to lift unknown Observable type")}}function Z(t,e,s,i,n){return new tt(t,e,s,i,n)}var tt=function(t){function e(e,s,i,n,r,o){var a=t.call(this,e)||this;return a.onFinalize=r,a.shouldUnsubscribe=o,a._next=s?function(t){try{s(t)}catch(t){e.error(t)}}:t.prototype._next,a._error=n?function(t){try{n(t)}catch(t){e.error(t)}finally{this.unsubscribe()}}:t.prototype._error,a._complete=i?function(){try{i()}catch(t){e.error(t)}finally{this.unsubscribe()}}:t.prototype._complete,a}return d(e,t),e.prototype.unsubscribe=function(){var e;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var s=this.closed;t.prototype.unsubscribe.call(this),!s&&(null===(e=this.onFinalize)||void 0===e||e.call(this))}},e}(P);function et(){return X((function(t,e){var s,i=!1;t.subscribe(Z(e,(function(t){var n=s;s=t,i&&e.next([n,t]),i=!0})))}))}function st(t,e){return X((function(s,i){var n=0;s.subscribe(Z(i,(function(s){return t.call(e,s,n++)&&i.next(s)})))}))}function it(t,e){return X((function(s,i){var n=0;s.subscribe(Z(i,(function(s){i.next(t.call(e,s,n++))})))}))}var nt=function(t){return t&&"number"==typeof t.length&&"function"!=typeof t},rt="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function ot(t){if(t instanceof z)return t;if(null!=t){if(function(t){return b(t[V])}(t))return n=t,new z((function(t){var e=n[V]();if(b(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(nt(t))return i=t,new z((function(t){for(var e=0;e<i.length&&!t.closed;e++)t.next(i[e]);t.complete()}));if(function(t){return b(null==t?void 0:t.then)}(t))return s=t,new z((function(t){s.then((function(e){t.closed||(t.next(e),t.complete())}),(function(e){return t.error(e)})).then(null,C)}));if(function(t){return Symbol.asyncIterator&&b(null==t?void 0:t[Symbol.asyncIterator])}(t))return at(t);if(function(t){return b(null==t?void 0:t[rt])}(t))return e=t,new z((function(t){var s,i;try{for(var n=f(e),r=n.next();!r.done;r=n.next()){var o=r.value;if(t.next(o),t.closed)return}}catch(t){s={error:t}}finally{try{r&&!r.done&&(i=n.return)&&i.call(n)}finally{if(s)throw s.error}}t.complete()}));if(function(t){return b(null==t?void 0:t.getReader)}(t))return at(function(t){return function(t,e,s){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,n=s.apply(t,e||[]),r=[];return i=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",(function(t){return function(e){return Promise.resolve(e).then(t,h)}})),i[Symbol.asyncIterator]=function(){return this},i;function o(t,e){n[t]&&(i[t]=function(e){return new Promise((function(s,i){r.push([t,e,s,i])>1||a(t,e)}))},e&&(i[t]=e(i[t])))}function a(t,e){try{(s=n[t](e)).value instanceof y?Promise.resolve(s.value.v).then(c,h):u(r[0][2],s)}catch(t){u(r[0][3],t)}var s}function c(t){a("next",t)}function h(t){a("throw",t)}function u(t,e){t(e),r.shift(),r.length&&a(r[0][0],r[0][1])}}(this,arguments,(function(){var e,s,i;return p(this,(function(n){switch(n.label){case 0:e=t.getReader(),n.label=1;case 1:n.trys.push([1,,9,10]),n.label=2;case 2:return[4,y(e.read())];case 3:return s=n.sent(),i=s.value,s.done?[4,y(void 0)]:[3,5];case 4:return[2,n.sent()];case 5:return[4,y(i)];case 6:return[4,n.sent()];case 7:return n.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}}))}))}(t))}var e,s,i,n;throw function(t){return new TypeError("You provided "+(null!==t&&"object"==typeof t?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}(t)}function at(t){return new z((function(e){(function(t,e){var s,i,n,r,o,a,c,h;return o=this,a=void 0,h=function(){var o,a;return p(this,(function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),s=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,s=t[Symbol.asyncIterator];return s?s.call(t):(t=f(t),e={},i("next"),i("throw"),i("return"),e[Symbol.asyncIterator]=function(){return this},e);function i(s){e[s]=t[s]&&function(e){return new Promise((function(i,n){!function(t,e,s,i){Promise.resolve(i).then((function(e){t({value:e,done:s})}),e)}(i,n,(e=t[s](e)).done,e.value)}))}}}(t),c.label=1;case 1:return[4,s.next()];case 2:if((i=c.sent()).done)return[3,4];if(o=i.value,e.next(o),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),n={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),i&&!i.done&&(r=s.return)?[4,r.call(s)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(n)throw n.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}}))},new((c=void 0)||(c=Promise))((function(t,e){function s(t){try{n(h.next(t))}catch(t){e(t)}}function i(t){try{n(h.throw(t))}catch(t){e(t)}}function n(e){e.done?t(e.value):function(t){return t instanceof c?t:new c((function(e){e(t)}))}(e.value).then(s,i)}n((h=h.apply(o,a||[])).next())}))})(t,e).catch((function(t){return e.error(t)}))}))}function ct(t){void 0===t&&(t={});var e=t.connector,s=void 0===e?function(){return new Y}:e,i=t.resetOnError,n=void 0===i||i,r=t.resetOnComplete,o=void 0===r||r,a=t.resetOnRefCountZero,c=void 0===a||a;return function(t){var e,i,r,a=0,h=!1,u=!1,l=function(){null==i||i.unsubscribe(),i=void 0},d=function(){l(),e=r=void 0,h=u=!1},p=function(){var t=e;d(),null==t||t.unsubscribe()};return X((function(t,f){a++,u||h||l();var m=r=null!=r?r:s();f.add((function(){0!=--a||u||h||(i=ht(p,c))})),m.subscribe(f),!e&&a>0&&(e=new I({next:function(t){return m.next(t)},error:function(t){u=!0,l(),i=ht(d,n,t),m.error(t)},complete:function(){h=!0,l(),i=ht(d,o),m.complete()}}),ot(t).subscribe(e))}))(t)}}function ht(t,e){for(var s=[],i=2;i<arguments.length;i++)s[i-2]=arguments[i];if(!0!==e){if(!1!==e){var n=new I({next:function(){n.unsubscribe(),t()}});return ot(e.apply(void 0,g([],m(s)))).subscribe(n)}}else t()}function ut(t,e,s){return void 0===s&&(s=1/0),b(e)?ut((function(s,i){return it((function(t,n){return e(s,t,i,n)}))(ot(t(s,i)))}),s):("number"==typeof e&&(s=e),X((function(e,i){return function(t,e,s,i,n,r,o,a){var c=[],h=0,u=0,l=!1,d=function(){!l||c.length||h||e.complete()},p=function(t){return h<i?f(t):c.push(t)},f=function(t){h++;var n=!1;ot(s(t,u++)).subscribe(Z(e,(function(t){e.next(t)}),(function(){n=!0}),void 0,(function(){if(n)try{h--;for(var t=function(){var t=c.shift();f(t)};c.length&&h<i;)t();d()}catch(t){e.error(t)}})))};return t.subscribe(Z(e,p,(function(){l=!0,d()}))),function(){}}(e,i,t,s)})))}const lt=(t,e)=>{const[s,i,n,r]=t,[o,a,c,h]=e,u=Math.max(s,o),l=Math.max(i,a),d=Math.min(n,c),p=Math.min(r,h),f=Math.max(0,d-u)*Math.max(0,p-l);return f/((n-s)*(r-i)+(c-o)*(h-a)-f)},dt=(t,e)=>{const{origWidth:s,origHeight:i}=e,n=t.points.map((([t,e])=>[t*s/100,e*i/100]));return{...t,points:n}},pt=t=>{const{origWidth:e,origHeight:s,inputWidth:i,inputHeight:n}=t,[r,o,a,c]=t.boundingBox,h=r*e/i,u=o*s/n,l=a*e/i,d=c*s/n;return{...t,boundingBox:[h,u,l,d]}},ft=(t,e,s)=>{if(t.confidence<s.object.confidence)return!1;if(0===e.length)return!0;const[i,n,r,o]=t.boundingBox,a={xmin:i,ymin:n,xmax:r,ymax:o};let c=!1;for(const s of e){const e=dt(s,t);if(e.isPrivacyMask){if(gt(a,e.points)){c=!1;break}}else"include"===e.filter?"contain"===e.type?gt(a,e.points)&&(c=!0):"intersect"===e.type&&(mt(a,e.points)||gt(a,e.points))&&(c=!0):"exclude"===e.filter&&("contain"===e.type?gt(a,e.points)||(c=!0):"intersect"===e.type&&(mt(a,e.points)||gt(a,e.points)||(c=!0)))}return c},mt=(t,e)=>{const s=yt(t);for(const t of s)for(let s=0;s<e.length;s++){const i=[e[s],e[(s+1)%e.length]];if(bt(t,i))return!0}return!1},gt=(t,e)=>[[t.xmin,t.ymin],[t.xmax,t.ymin],[t.xmax,t.ymax],[t.xmin,t.ymax]].every((t=>vt(t,e))),yt=t=>{const{xmin:e,ymin:s,xmax:i,ymax:n}=t;return[[[e,s],[i,s]],[[i,s],[i,n]],[[i,n],[e,n]],[[e,n],[e,s]]]},bt=(t,e)=>{const s=(t,e,s)=>(s[1]-t[1])*(e[0]-t[0])>(e[1]-t[1])*(s[0]-t[0]);return i=t[0],n=t[1],s(i,r=e[0],o=e[1])!==s(n,r,o)&&s(i,n,r)!==s(i,n,o);var i,n,r,o},vt=(t,e)=>{const[s,i]=t;let n=!1,[r,o]=e[e.length-1];for(const[t,a]of e)a>i!=o>i&&s<(r-t)*(i-a)/(o-a)+t&&(n=!n),[r,o]=[t,a];return n};class wt extends o{logger;snapshotCache;cameraSubject;cameraState=new K(!1);lightState=new K(this.getLightState({state:!1},!0));motionState=new K(this.getMotionState({detections:[],state:!1},!0));audioState=new K(this.getAudioState({state:!1,db:0},!0));objectState=new K(this.getObjectState({detections:[]},!0));doorbellState=new K(this.getDoorbellState({state:!1},!0));sirenState=new K(this.getSirenState({state:!1,level:0},!0));batteryState=new K(this.getBatteryState({level:100,charging:!1,lowBattery:!1},!0));onConnected=this.createStateObservable(this.cameraState);onLightSwitched=this.createStateObservable(this.lightState);onMotionDetected=this.createStateObservable(this.motionState);onAudioDetected=this.createStateObservable(this.audioState);onObjectDetected=this.createStateObservable(this.objectState);onDoorbellPressed=this.createStateObservable(this.doorbellState);onSirenDetected=this.createStateObservable(this.sirenState);onBatteryChanged=this.createStateObservable(this.batteryState);get cameraObject(){return c(this.cameraSubject.getValue())}get id(){return this.cameraSubject.getValue()._id}get nativeId(){return this.cameraSubject.getValue().nativeId}get pluginId(){return this.cameraSubject.getValue().pluginId}get connected(){return this.cameraState.getValue()}get disabled(){return this.cameraSubject.getValue().disabled}get name(){return this.cameraSubject.getValue().name}get type(){return this.cameraSubject.getValue().type}get info(){return c(this.cameraSubject.getValue().info)}get isCloud(){return this.cameraSubject.getValue().isCloud}get hasLight(){return this.cameraSubject.getValue().hasLight}get hasSiren(){return this.cameraSubject.getValue().hasSiren}get hasBinarySensor(){return this.cameraSubject.getValue().hasBinarySensor}get hasBattery(){return this.cameraSubject.getValue().hasBattery}get hasMotionDetector(){return this.cameraSubject.getValue().hasMotionDetector}get hasAudioDetector(){return this.cameraSubject.getValue().hasAudioDetector}get hasObjectDetector(){return this.cameraSubject.getValue().hasObjectDetector}get hasPtz(){return this.cameraSubject.getValue().hasPtz}get hasPrebuffer(){return this.cameraSubject.getValue().hasPrebuffer}get snapshotTTL(){return this.cameraSubject.getValue().snapshotTTL}get activityZones(){return c(this.cameraSubject.getValue().activityZones)}get activitySettings(){return c(this.cameraSubject.getValue().activitySettings)}get frameWorkerSettings(){return c(this.cameraSubject.getValue().frameWorkerSettings)}get streamSource(){return this.highResolutionSource||this.midResolutionSource||this.lowResolutionSource}get snapshotSource(){return this.sources.find((t=>t.roles.includes("snapshot")&&!t.internal))}get highResolutionSource(){return this.sources.find((t=>t.roles.includes("high-resolution")&&!t.internal))}get midResolutionSource(){return this.sources.find((t=>t.roles.includes("mid-resolution")&&!t.internal))}get lowResolutionSource(){return this.sources.find((t=>t.roles.includes("low-resolution")&&!t.internal))}get ptz(){return this.ptzDelegate}constructor(t,e){super(),this.logger=e,this.cameraSubject=new K(t),this.updateCamera(t),this.snapshotCache=new(u())({max:100,ttl:1e3*this.snapshotTTL}),"native"===t.pluginId&&this.cameraState.next(!0)}getValue(t){switch(t){case"light":return c(this.lightState.getValue());case"motion":return c(this.motionState.getValue());case"audio":return c(this.audioState.getValue());case"object":return c(this.objectState.getValue());case"doorbell":return c(this.doorbellState.getValue());case"siren":return c(this.sirenState.getValue());case"battery":return c(this.batteryState.getValue());default:throw new Error(`Unknown state: ${t}`)}}async snapshot(t){this.snapshotCache.purgeStale();const e=this.snapshotSource||this.streamSource,s=e.urls.www.jpegSnapshot,i=this.snapshotCache.get(e._id);if(!t&&i)return this.logger.trace(this.name,"Snapshot requested (cached)"),i;this.logger.trace(this.name,"Snapshot requested (fetching)");try{if("native"!==this.cameraObject.pluginId){const t=await this.cameraDelegate.snapshot();if(t&&t.byteLength>0)return this.snapshotCache.set(e._id,t),t}const t=new AbortController,i=setTimeout((()=>t.abort()),5e3),n=await fetch(s,{signal:t.signal});if(clearTimeout(i),!n.ok)throw new Error("Status Code: "+n.status);const r=await n.arrayBuffer();return r.byteLength>0&&this.snapshotCache.set(e._id,r),r}catch{return}}onStateChange(t){return this[`${t}State`].pipe(et(),st((([e,s])=>"boolean"==typeof e||"boolean"==typeof s?e!==s:this.stateChanged(e,s,t))),it((([t,e])=>({oldState:t,newState:e}))),ct({connector:()=>new Q(1)}))}onPropertyChange(t){return this.cameraSubject.pipe(et(),ut((([e,s])=>(Array.isArray(t)?t:[t]).map((t=>({property:t,oldData:e[t],newData:s[t]}))))),st((({oldData:t,newData:e})=>!a(t,e,!0))),ct({connector:()=>new Q(1)}))}removeAllListeners(){this.lightState.complete(),this.motionState.complete(),this.audioState.complete(),this.objectState.complete(),this.doorbellState.complete(),this.sirenState.complete(),this.batteryState.complete(),this.cameraSubject.complete(),this.cameraState.complete()}updateCamera(t){t.snapshotTTL!==this.snapshotTTL&&this.snapshotCache.clear(),this.cameraSubject.next(t)}updateCameraState(t){this.cameraState.next(t)}updateStateInternal(t,e,s){let i,n=!1;if(s)n=!0,i=e;else{const s=this.checkStateInternal(t,e);n=s.changed,i=s.event}if(n)switch(t){case"light":this.lightState.next(this.getLightState(i));break;case"motion":this.motionState.next(this.getMotionState(i));break;case"audio":this.audioState.next(this.getAudioState(i));break;case"object":this.objectState.next(this.getObjectState(i));break;case"doorbell":this.doorbellState.next(this.getDoorbellState(i));break;case"siren":this.sirenState.next(this.getSirenState(i));break;case"battery":this.batteryState.next(this.getBatteryState(i));break;default:throw new Error(`Unknown state: ${t}`)}}checkStateInternal(t,e){let s,i=!1;switch(t){case"audio":const n=e;s=this.getAudioState(n),i=this.stateChanged(this.getValue("audio"),s,"audio");break;case"light":const r=e;s=this.getLightState(r),i=this.stateChanged(this.getValue("light"),s,"light");break;case"motion":const o=e;void 0!==o.state&&(o.detections=[]),o.detections=((t,e=.2)=>{if(0===t.length)return[];const s=[...t].sort(((t,e)=>{const s=(t.boundingBox[2]-t.boundingBox[0])*(t.boundingBox[3]-t.boundingBox[1]);return(e.boundingBox[2]-e.boundingBox[0])*(e.boundingBox[3]-e.boundingBox[1])-s})),i=[];for(;s.length>0;){let t={...s[0]};s.shift();const n=[];for(let i=0;i<s.length;i++)lt(t.boundingBox,s[i].boundingBox)>e&&n.push(i);if(n.length>0){const e=[t,...n.map((t=>s[t]))],i=[Math.min(...e.map((t=>t.boundingBox[0]))),Math.min(...e.map((t=>t.boundingBox[1]))),Math.max(...e.map((t=>t.boundingBox[2]))),Math.max(...e.map((t=>t.boundingBox[3])))],r=e.reduce(((t,e)=>t.confidence>e.confidence?t:e));t={...r,boundingBox:i,id:r.id||t.id};for(let t=n.length-1;t>=0;t--)s.splice(n[t],1)}i.push(t)}return i})(o.detections),o.detections=((t,e,s)=>{const i=[];for(const n of t)ft(pt(n),e,s)&&e.some((t=>!t.classes.length||t.classes.includes(n.label)))&&i.push(n);return i})(o.detections,this.activityZones,this.activitySettings),s=this.getMotionState(o),i=this.stateChanged(this.getValue("motion"),s,"motion");break;case"object":const a=e;a.detections=((t,e,s)=>{const i=[];for(const n of t)ft(pt(n),e,s)&&e.some((t=>!t.classes.length||t.classes.includes(n.label)))&&i.push(n);return i})(a.detections,this.activityZones,this.activitySettings),s=this.getObjectState(a),i=this.stateChanged(this.getValue("object"),s,"object");break;case"doorbell":const c=e;s=this.getDoorbellState(c),i=this.stateChanged(this.getValue("doorbell"),s,"doorbell");break;case"siren":const h=e;s=this.getSirenState(h),i=this.stateChanged(this.getValue("siren"),s,"siren");break;case"battery":const u=e;s=this.getBatteryState(u),i=this.stateChanged(this.getValue("battery"),s,"battery");break;default:throw new Error(`Unknown state: ${t}`)}return{changed:i,event:s}}stateChanged(t,e,s){if(!t||!e||!s)return!1;if("audio"==s){if(!this.hasAudioDetector)return!1;const s=t,i=e;return s.state!==i.state||s.db!==i.db}if("motion"==s){if(!this.hasMotionDetector)return!1;const s=t,i=e;return void 0!==i.state?s.state!==i.state:!a(s.detections,i.detections,!0)}if("object"==s){if(!this.hasObjectDetector)return!1;const s=e;return!a(t.detections,s.detections,!0)}if("siren"==s){if(!this.hasSiren)return!1;const s=t,i=e;return s.state!==i.state||s.level!==i.level}if("battery"==s){if(!this.hasBattery)return!1;const s=t,i=e;return s.level!==i.level||s.lowBattery!==i.lowBattery||s.charging!==i.charging}if("doorbell"==s){if(!this.hasBinarySensor)return!1;const s=e;return t.state!==s.state}if("light"==s){if(!this.hasLight)return!1;const s=e;return t.state!==s.state}return!1}getAudioState(t,e=!1){let s,i;if(!e){const t=this.getValue("audio");t.state?s=t:t.lastEvent?.state&&(s=t.lastEvent),s&&delete s.lastEvent}if(this.isStateEvent(t))i=t;else{const e={...t,timestamp:Date.now()};i={...e,db:e.db||s?.db||0,lastEvent:s||(e.state?e:void 0)}}return i}getMotionState(t,e=!1){let s,i;if(!e){const t=this.getValue("motion");t.detections.length?s=t:t.lastEvent?.detections.length&&(s=t.lastEvent),s&&delete s.lastEvent}if(this.isStateEvent(t))i=t;else{const e={...t,timestamp:Date.now()};i={...e,lastEvent:s||(e.detections.length?e:void 0)}}return i}getObjectState(t,e=!1){let s,i;if(!e){const t=this.getValue("object");t.detections.length?s=t:t.lastEvent?.detections.length&&(s=t.lastEvent),s&&delete s.lastEvent}if(this.isStateEvent(t))i=t;else{const e={...t,timestamp:Date.now()};i={...e,lastEvent:s||(e.detections.length?e:void 0)}}return i}getDoorbellState(t,e=!1){let s,i;if(!e){const t=this.getValue("doorbell");t.state?s=t:t.lastEvent?.state&&(s=t.lastEvent),s&&delete s.lastEvent}if(this.isStateEvent(t))i=t;else{const e={...t,timestamp:Date.now()};i={...e,lastEvent:s||(e.state?e:void 0)}}return i}getLightState(t,e=!1){let s,i;if(!e){const t=this.getValue("light");t.state?s=t:t.lastEvent?.state&&(s=t.lastEvent),s&&delete s.lastEvent}if(this.isStateEvent(t))i=t;else{const e={...t,timestamp:Date.now()};i={...e,lastEvent:s||(e.state?e:void 0)}}return i}getSirenState(t,e=!1){let s,i;if(!e){const t=this.getValue("siren");t.state?s=t:t.lastEvent?.state&&(s=t.lastEvent),s&&delete s.lastEvent}if(this.isStateEvent(t))i=t;else{const e={...t,timestamp:Date.now()};i={...e,level:e.level||s?.level||0,lastEvent:s||(e.state?e:void 0)}}return i}getBatteryState(t,e=!1){let s,i;if(!e){const e=this.getValue("battery");this.stateChanged(e,t,"battery")?s=e:e.lastEvent&&this.stateChanged(e.lastEvent,t,"battery")&&(s=e.lastEvent),s&&delete s.lastEvent}if(this.isStateEvent(t))i=t;else{const e={...t,timestamp:Date.now()};i={...e,charging:t.charging||s?.charging||!1,lowBattery:t.lowBattery||s?.lowBattery||!1,lastEvent:s||e}}return i}isStateEvent(t){return"timestamp"in t}createStateObservable(t){return t.pipe(ct({connector:()=>new Q(1)}))}}class St{delegate;onRequest;constructor(t){this.onRequest=t}async snapshot(){return this.delegate?this.delegate.snapshot():this._onRequest("snapshot",[],5e3)}_onRequest(t,e,s){return this.onRequest("cameraDelegate",t,e,s)}}class _t{delegate;onRequest;constructor(t){this.onRequest=t}async getPrebufferingState(t,e){return this.delegate?this.delegate.getPrebufferingState(t,e):this._onRequest("prebufferDelegate","getPrebufferingState",[t,e])}_onRequest(t,e,s,i){return this.onRequest(t,e,s,i)}}class kt{delegate;onRequest;constructor(t){this.onRequest=t}async moveAbsolute(t,e,s){return this.delegate?this.delegate.moveAbsolute(t,e,s):this._onRequest("moveAbsolute",[t,e,s])}async moveRelative(t,e,s){return this.delegate?this.delegate.moveRelative(t,e,s):this._onRequest("moveRelative",[t,e,s])}async moveContinuous(t,e,s){return this.delegate?this.delegate.moveContinuous(t,e,s):this._onRequest("moveContinuous",[t,e,s])}async stop(){return this.delegate?this.delegate.stop():this._onRequest("stop",[])}_onRequest(t,e,s){return this.onRequest("ptzDelegate",t,e,s)}}const xt=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)}));class Et extends EventTarget{cameraDevice;socketService;logger;options;videoPlayer;socket;streamId;hasBackchannel=!1;hasAudio=!0;closed=!1;micTransceiver=null;pc=null;buf=new Uint8Array(2097152);mediaSource=null;sourceBuffer=null;bufLen=0;mseCodecs="";videoPlayerMp4;media=["video","audio","microphone"];codecList=[];reconnectTimeout;_finishLoading=!1;_firstFrameReceived=!1;animationFrameId;get mode(){return this.options.mode}webrtcReconnectTimeout;constructor(t,e,s,i){super(),this.options=i,this.videoPlayer=i.videoElement,this.cameraDevice=t,this.socketService=e,this.logger=s;const{socket:n}=this.socketService.getSocket(`${t.id}-go2rtcSession`,!0);this.socket=n,this.socket.connect(),this.streamId=xt(),this.createCodecsList()}connect(t){t&&(this.options.mode=t),console.log(this.cameraDevice.name,`Connecting... (${this.options.mode})`),this.socket.on("ws-open",this.onWsOpen.bind(this)),this.socket.on("ws-close",this.onWsClose.bind(this)),this.socket.on("ws-message",this.onWsMessage.bind(this)),this.socket.emit("ws-open",{id:this.streamId,cameraSource:this.options.sourceName,mode:this.options.mode})}disconnect(){console.log(this.cameraDevice.name,"Disconnecting..."),this.socket.removeListener("ws-open",this.onWsOpen.bind(this)),this.socket.removeListener("ws-close",this.onWsClose.bind(this)),this.socket.removeListener("ws-message",this.onWsMessage.bind(this)),this.socket.emit("ws-close",{id:this.streamId})}async reconnect(t){console.log(this.cameraDevice.name,"Reconnecting..."),this.dispatchEvent(new Event("reconnect")),this.close(),await new Promise((t=>setTimeout(t,100))),this.connect(t)}reset(){this._finishLoading=!1,this._firstFrameReceived=!1,this.pc?.getTransceivers().forEach((t=>t.sender?.track?.stop())),this.pc?.close(),this.pc=null,this.videoPlayerMp4?.remove(),this.videoPlayerMp4=void 0,this.videoPlayer.srcObject=null,this.videoPlayer.src="",this.videoPlayer.poster="",void 0!==this.animationFrameId&&("cancelVideoFrameCallback"in this.videoPlayer?this.videoPlayer.cancelVideoFrameCallback(this.animationFrameId):cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}close(){console.log(this.cameraDevice.name,"Closing..."),this.closed=!0,this.reset(),this.disconnect(),this.socket.emit("end"),this.socket.removeAllListeners()}onWsOpen({id:t}){if(t===this.streamId)switch(console.log(this.cameraDevice.name,"Connected"),this.options.mode){case"webrtc":case"webrtc/tcp":console.log(this.cameraDevice.name,"Requesting WebRTC session..."),this.requestWebrtc();break;case"mse":console.log(this.cameraDevice.name,"Requesting MSE session..."),this.requestMse();break;case"hls":console.log(this.cameraDevice.name,"Requesting HLS session..."),this.requestHls();break;case"mp4":console.log(this.cameraDevice.name,"Requesting MP4 session..."),this.requestMp4();break;case"mjpeg":console.log(this.cameraDevice.name,"Requesting MJPEG session..."),this.requestMjpeg();break;default:console.log(this.cameraDevice.name,"Unknown mode:",this.options.mode),this.dispatchEvent(new ErrorEvent("error",{message:"Unknown mode: "+this.options.mode}))}}onWsClose({id:t}){t===this.streamId&&(this.closed||void 0===this.options.reconnectInterval||(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=setTimeout((()=>{this.reconnect()}),this.options.reconnectInterval)))}onWsMessage({id:t,data:e}){if(t===this.streamId&&e.type){switch(e.type){case"mse":this.onMseData(e);break;case"hls":this.onHlsData(e);break;case"webrtc/candidate":case"webrtc/answer":this.onWebrtcData(e);break;case"mse-binary":this.onMseBuffer(e);break;case"mjpeg-binary":this.onMjpegBuffer(e);break;case"mp4-binary":this.onMp4Buffer(e);break;case"stream-info":this.onStreamInfo(e);break;case"error":this.dispatchEvent(new ErrorEvent("error",{error:e,message:e.value}))}!this._firstFrameReceived&&["mse-binary","mjpeg-binary","mp4-binary"].includes(e.type)&&this.onFirstFrame()}}async requestWebrtc(){this.reset(),this.pc=new RTCPeerConnection({bundlePolicy:"max-bundle",iceServers:[{urls:"stun:stun.l.google.com:19302"}],sdpSemantics:"unified-plan"}),this.pc.addEventListener("icecandidate",(t=>{if("webrtc/tcp"===this.options.mode&&"udp"===t.candidate?.protocol)return;const e=t.candidate?.toJSON().candidate||"";this.socket.emit("stream-payload",{id:this.streamId,data:{type:"webrtc/candidate",value:e}})})),this.pc.addEventListener("connectionstatechange",(()=>{if(console.log(this.cameraDevice.name,"Connection state:",this.pc?.connectionState),"connected"===this.pc?.connectionState){const t=this.pc?.getTransceivers().filter((t=>"recvonly"===t.currentDirection)).map((t=>t.receiver.track));this.videoPlayer.srcObject=new MediaStream(t),this.onFinishLoading(),this.play(),this.disconnect()}else"failed"!==this.pc?.connectionState&&"disconnected"!==this.pc?.connectionState||(clearTimeout(this.webrtcReconnectTimeout),this.webrtcReconnectTimeout=setTimeout((()=>{"failed"!==this.pc?.connectionState&&"disconnected"!==this.pc?.connectionState||this.reconnect()}),1e3))})),this.pc.addTransceiver("video",{direction:"recvonly"}),this.pc.addTransceiver("audio",{direction:"recvonly"}),this.micTransceiver=this.pc.addTransceiver("audio",{direction:"sendonly"});const t=await this.pc.createOffer();await this.pc.setLocalDescription(t),console.log(this.cameraDevice.name,"Offer:",t.sdp),this.socket.emit("stream-payload",{id:this.streamId,data:{type:"webrtc/offer",value:t.sdp}})}async onWebrtcData(t){try{switch(t.type){case"webrtc/candidate":if("webrtc/tcp"===this.options.mode&&t.value.indexOf(" udp ")>0)return;await(this.pc?.addIceCandidate({candidate:t.value,sdpMid:"0"}));break;case"webrtc/answer":if(console.log(this.cameraDevice.name,"Answer:",t.value),await(this.pc?.setRemoteDescription({type:"answer",sdp:t.value})),!this._firstFrameReceived&&this.pc){const t=this.pc.getReceivers().find((t=>"video"===t.track.kind))?.track;if(t)if("requestVideoFrameCallback"in t)this.animationFrameId=t.requestVideoFrameCallback((()=>{this.onFirstFrame()}));else{const t=()=>{this.videoPlayer.readyState>=2&&this.videoPlayer.videoWidth>0?this.onFirstFrame():this.animationFrameId=requestAnimationFrame(t)};this.animationFrameId=requestAnimationFrame(t)}}break;case"error":if(console.log(this.cameraDevice.name,"WebRTC Error:",t.value),t.value.indexOf("webrtc/offer")<0)return;this.pc?.close()}}catch(t){this.dispatchEvent(new ErrorEvent("error",{error:t,message:t.message}))}}requestMse(){if(this.reset(),"ManagedMediaSource"in window){console.log(this.cameraDevice.name,"Using ManagedMediaSource");const t=window.ManagedMediaSource;this.mediaSource=new t,this.mediaSource.addEventListener("sourceopen",(()=>{this.socket.emit("stream-payload",{id:this.streamId,data:{type:"mse",value:this.parseCodecs(t.isTypeSupported)}})}),{once:!0}),this.videoPlayer.disableRemotePlayback=!0,this.videoPlayer.srcObject=this.mediaSource}else console.log(this.cameraDevice.name,"Using MediaSource"),this.mediaSource=new MediaSource,this.mediaSource.addEventListener("sourceopen",(()=>{URL.revokeObjectURL(this.videoPlayer.src),this.socket.emit("stream-payload",{id:this.streamId,data:{type:"mse",value:this.parseCodecs(MediaSource.isTypeSupported)}})}),{once:!0}),this.videoPlayer.src=URL.createObjectURL(this.mediaSource),this.videoPlayer.srcObject=null;this.play(),this.mseCodecs=""}onMseData(t){this.mediaSource&&(this.mseCodecs=t.value,this.bufLen=0,this.buf=new Uint8Array(2097152),this.sourceBuffer=this.mediaSource.addSourceBuffer(t.value),this.sourceBuffer.mode="segments",this.sourceBuffer.addEventListener("updateend",(()=>{if(!this.sourceBuffer?.updating)try{if(this.bufLen>0){const t=this.buf.slice(0,this.bufLen);this.bufLen=0,this.sourceBuffer?.appendBuffer(t)}else if(this.sourceBuffer?.buffered?.length){const t=this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)-15,e=this.sourceBuffer.buffered.start(0);t>e&&(this.sourceBuffer.remove(e,t),this.mediaSource?.setLiveSeekableRange(t,t+15))}}catch{}})))}async onMseBuffer(t){if("closed"!==this.mediaSource?.readyState)if(this.onFinishLoading(),this.sourceBuffer?.updating||this.bufLen>0){const e=new Uint8Array(t.value);this.buf.set(e,this.bufLen),this.bufLen+=e.byteLength}else try{this.sourceBuffer?.appendBuffer(t.value)}catch{}else this.closed||(this.closed=!0,this.dispatchEvent(new ErrorEvent("error",{message:"MediaSource closed"})),this.options.mode="webrtc",this.requestWebrtc())}requestMjpeg(){this.reset(),this.socket.emit("stream-payload",{id:this.streamId,data:{type:"mjpeg"}})}onMjpegBuffer(t){this.videoPlayer.controls=!1,this.videoPlayer.poster="data:image/jpeg;base64,"+this.btoaBinary(t.value),this.onFinishLoading()}requestMp4(){this.reset();const t=document.createElement("canvas");let e=null;this.videoPlayerMp4=document.createElement("video"),this.videoPlayerMp4.autoplay=!0,this.videoPlayerMp4.playsInline=!0,this.videoPlayerMp4.muted=!0,this.videoPlayerMp4.addEventListener("loadeddata",(()=>{this.videoPlayerMp4&&(e||(t.width=this.videoPlayerMp4.videoWidth,t.height=this.videoPlayerMp4.videoHeight,e=t.getContext("2d")),e?.drawImage(this.videoPlayerMp4,0,0,t.width,t.height),this.videoPlayer.controls=!1,this.videoPlayer.poster=t.toDataURL("image/jpeg"))}));const s=this.codecList.filter((t=>this.media.includes(t.indexOf("vc1")>0?"video":"audio"))).filter((t=>this.videoPlayer.canPlayType(`video/mp4; codecs="${t}"`))).join();console.log(this.cameraDevice.name,"Playable codecs (MP4):",s),this.socket.emit("stream-payload",{id:this.streamId,data:{type:"mp4",value:s}})}onMp4Buffer(t){this.onFinishLoading(),this.videoPlayerMp4&&(this.videoPlayerMp4.src="data:video/mp4;base64,"+this.btoaBinary(t.value))}requestHls(){this.reset();const t=this.parseCodecs((t=>this.videoPlayer.canPlayType(t)));console.log(this.cameraDevice.name,"Playable codecs (HLS):",t),this.socket.emit("stream-payload",{id:this.streamId,data:{type:"hls",value:t}})}onHlsData(t){const e="http"+t.wsURL.substring(2,t.wsURL.indexOf("/ws"))+"/hls/",s=t.value.replace("hls/",e),i="data:application/vnd.apple.mpegurl;base64,"+btoa(s.toString());this.videoPlayer.src=i,this.onFinishLoading(),this.play()}onStreamInfo(t){const e=t.value,s=e?.producers[0];s&&(this.hasBackchannel=s.senders?.some((t=>"audio"===t.codec.codec_type))||!1,this.hasAudio=s.receivers?.some((t=>"audio"===t.codec.codec_type))||!1)}async play(){try{await this.videoPlayer.play()}catch(t){if(!this.videoPlayer.muted)return this.videoPlayer.muted=!0,this.play();this.logger.warn(this.cameraDevice.name,t)}}onFirstFrame(){this._firstFrameReceived||(this._firstFrameReceived=!0,this.dispatchEvent(new Event("onFirstFrame")),console.log(this.cameraDevice.name,"First frame received"))}onFinishLoading(){this._finishLoading||(this._finishLoading=!0,this.dispatchEvent(new Event("onFinishLoading")))}createCodecsList(){const t=["avc1.640029","avc1.64002A","avc1.640033","hvc1.1.6.L153.B0","mp4a.40.2","mp4a.40.5","flac","opus"],e="undefined"==typeof window?null:navigator.userAgent.match(/Version\/(\d+).+Safari/);if(e?.[1]){const s=e[1]<"13"?"mp4a.40.2":e[1]<"14"?"flac":"opus";t.splice(t.indexOf(s))}this.codecList=t}parseCodecs(t){return this.codecList.filter((t=>this.media.includes(t.indexOf("vc1")>0?"video":"audio"))).filter((e=>t(`video/mp4; codecs="${e}"`))).join()}btoaBinary(t){const e=new Uint8Array(t),s=e.byteLength;let i="";for(let t=0;t<s;t++)i+=String.fromCharCode(e[t]);return window.btoa(i)}}class Tt extends wt{socketService;socket;pluginName="@camera.ui/client";subject;_started=!1;get started(){return this._started}cameraDelegate=new St(this.onRequest.bind(this));ptzDelegate=new kt(this.onRequest.bind(this));prebufferDelegate=new _t(this.onRequest.bind(this));get sources(){return this._sources.filter((t=>!t.internal))}get internalSources(){return this._sources.map((t=>({...t,type:t.name.endsWith(" AAC")?"aac":t.name.endsWith(" OPUS")?"opus":"pcma"}))).filter((t=>t.internal))}get _sources(){return JSON.parse(JSON.stringify(this.cameraSubject.getValue().sources)).map((t=>({...t,getPrebufferingState:e=>this.prebufferDelegate.getPrebufferingState(t.name,e),probeStream:()=>this.onRequest("cameraFn","probeStream",[t._id])})))}constructor(t,e,s){super(t,s),this.socketService=e;const{socket:i}=this.socketService.getSocket(this.id,!0);this.socket=i,this.socket.connect(),this.subject=`${this.pluginName}.camera.${this.id}`,this.listenToMessages()}async start(){this._started||(this._started=!0,await this.refreshStates(),this.socket.emit("joinRoomStates",this.id))}stop(){this._started=!1,this.socket.emit("leaveRoomStates",this.id)}close(){this.cleanup()}connect(){return this.onRequest("cameraFn","connect")}disconnect(){return this.onRequest("cameraFn","disconnect")}createSession(t){return new Et(this,this.socketService,this.logger,t)}async refreshStates(){const t=await this.onRequest("cameraFn","refreshStates");super.updateCamera(t.camera),super.updateCameraState(t.cameraState);for(const[e,s]of Object.entries(t.states))super.updateStateInternal(e,s,!0)}async cleanup(){this.stop(),this.removeAllListeners(),this.unsubscribe(),this.socket.removeAllListeners()}listenToMessages(){this.socket.emit("joinRoomDevice",this.id),this.socket.on("updateState",(t=>{t.cameraId===this.id&&super.updateStateInternal(t.stateName,t.data.newEvent,!0)})),this.socket.on("updateDevice",(t=>{if(t.cameraId===this.id)switch(t.type){case"removed":this.cleanup();break;case"updated":super.updateCamera(t.data);break;case"cameraState":super.updateCameraState(t.data)}}))}onRequest(t,e,s=[]){const i={requestId:xt(),targetId:this.subject,targetName:this.name,pluginId:this.pluginName,cameraId:this.id,type:"request",proxy:"camera",client:t,fn:e,args:s,timestamp:Date.now(),timeout:5e3};return new Promise(((t,e)=>{this.socket.emit("request",i,(s=>{s.error?e(s.error):t(s.response)}))}))}}class Ot{socketService;socket;logger;pluginName="@camera.ui/client";subject;constructor(t,e){this.socketService=t,this.socket=t.socket,this.logger=e,this.subject=`${this.pluginName}.coreManager`}async getFFmpegPath(){return this.onRequest("getFFmpegPath")}async getHwaccelInfo(){return this.onRequest("getHwaccelInfo")}async getServerAddresses(){return this.onRequest("getServerAddresses")}async getIceServers(){return this.onRequest("getIceServers")}onRequest(t,e){const s={requestId:xt(),targetId:this.subject,targetName:this.pluginName,pluginId:this.pluginName,type:"request",proxy:"core",client:"coreFn",fn:t,args:e||[],timestamp:Date.now(),timeout:5e3};return new Promise(((t,e)=>{this.socket.emit("request",s,(s=>{s.error?e(s.error):t(s.response)}))}))}}class Ct{socketService;socket;logger;pluginName="@camera.ui/client";subject;constructor(t,e){this.socketService=t,this.socket=t.socket,this.logger=e,this.subject=`${this.pluginName}.deviceManager`}async getCameraById(t){const e=await this.onRequest("getCameraById",[t]);if(e){const t=new Tt(e,this.socketService,this.logger);return await t.refreshStates(),t}}async getCameraByName(t){const e=await this.onRequest("getCameraByName",[t]);if(e){const t=new Tt(e,this.socketService,this.logger);return await t.refreshStates(),t}}onRequest(t,e){const s={requestId:xt(),targetId:this.subject,targetName:this.pluginName,pluginId:this.pluginName,type:"request",proxy:"device",client:"deviceFn",fn:t,args:e||[],timestamp:Date.now(),timeout:5e3};return new Promise(((t,e)=>{this.socket.emit("request",s,(s=>{s.error?e(s.error):t(s.response)}))}))}}const Rt=Object.create(null);Rt.open="0",Rt.close="1",Rt.ping="2",Rt.pong="3",Rt.message="4",Rt.upgrade="5",Rt.noop="6";const At=Object.create(null);Object.keys(Rt).forEach((t=>{At[Rt[t]]=t}));const Bt={type:"error",data:"parser error"},jt="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Lt="function"==typeof ArrayBuffer,Pt=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,Mt=({type:t,data:e},s,i)=>jt&&e instanceof Blob?s?i(e):Dt(e,i):Lt&&(e instanceof ArrayBuffer||Pt(e))?s?i(e):Dt(new Blob([e]),i):i(Rt[t]+(e||"")),Dt=(t,e)=>{const s=new FileReader;return s.onload=function(){const t=s.result.split(",")[1];e("b"+(t||""))},s.readAsDataURL(t)};function qt(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let It;const Nt="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)Nt["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const Ft="function"==typeof ArrayBuffer,Ut=(t,e)=>{if("string"!=typeof t)return{type:"message",data:Wt(t,e)};const s=t.charAt(0);return"b"===s?{type:"message",data:Vt(t.substring(1),e)}:At[s]?t.length>1?{type:At[s],data:t.substring(1)}:{type:At[s]}:Bt},Vt=(t,e)=>{if(Ft){const s=(t=>{let e,s,i,n,r,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);const h=new ArrayBuffer(o),u=new Uint8Array(h);for(e=0;e<a;e+=4)s=Nt[t.charCodeAt(e)],i=Nt[t.charCodeAt(e+1)],n=Nt[t.charCodeAt(e+2)],r=Nt[t.charCodeAt(e+3)],u[c++]=s<<2|i>>4,u[c++]=(15&i)<<4|n>>2,u[c++]=(3&n)<<6|63&r;return h})(t);return Wt(s,e)}return{base64:!0,data:t}},Wt=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,zt=String.fromCharCode(30);let Ht;function $t(t){return t.reduce(((t,e)=>t+e.length),0)}function Yt(t,e){if(t[0].length===e)return t.shift();const s=new Uint8Array(e);let i=0;for(let n=0;n<e;n++)s[n]=t[0][i++],i===t[0].length&&(t.shift(),i=0);return t.length&&i<t[0].length&&(t[0]=t[0].slice(i)),s}function Jt(t){if(t)return function(t){for(var e in Jt.prototype)t[e]=Jt.prototype[e];return t}(t)}Jt.prototype.on=Jt.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},Jt.prototype.once=function(t,e){function s(){this.off(t,s),e.apply(this,arguments)}return s.fn=e,this.on(t,s),this},Jt.prototype.off=Jt.prototype.removeListener=Jt.prototype.removeAllListeners=Jt.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var s,i=this._callbacks["$"+t];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var n=0;n<i.length;n++)if((s=i[n])===e||s.fn===e){i.splice(n,1);break}return 0===i.length&&delete this._callbacks["$"+t],this},Jt.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),s=this._callbacks["$"+t],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(s){i=0;for(var n=(s=s.slice(0)).length;i<n;++i)s[i].apply(this,e)}return this},Jt.prototype.emitReserved=Jt.prototype.emit,Jt.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},Jt.prototype.hasListeners=function(t){return!!this.listeners(t).length};const Kt="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),Gt="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Qt(t,...e){return e.reduce(((e,s)=>(t.hasOwnProperty(s)&&(e[s]=t[s]),e)),{})}const Xt=Gt.setTimeout,Zt=Gt.clearTimeout;function te(t,e){e.useNativeTimers?(t.setTimeoutFn=Xt.bind(Gt),t.clearTimeoutFn=Zt.bind(Gt)):(t.setTimeoutFn=Gt.setTimeout.bind(Gt),t.clearTimeoutFn=Gt.clearTimeout.bind(Gt))}function ee(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class se extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}class ie extends Jt{constructor(t){super(),this.writable=!1,te(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,s){return super.emitReserved("error",new se(t,e,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=Ut(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(t){const e=function(t){let e="";for(let s in t)t.hasOwnProperty(s)&&(e.length&&(e+="&"),e+=encodeURIComponent(s)+"="+encodeURIComponent(t[s]));return e}(t);return e.length?"?"+e:""}}class ne extends ie{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let t=0;this._polling&&(t++,this.once("pollComplete",(function(){--t||e()}))),this.writable||(t++,this.once("drain",(function(){--t||e()})))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const s=t.split(zt),i=[];for(let t=0;t<s.length;t++){const n=Ut(s[t],e);if(i.push(n),"error"===n.type)break}return i})(t,this.socket.binaryType).forEach((t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)})),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const s=t.length,i=new Array(s);let n=0;t.forEach(((t,r)=>{Mt(t,!1,(t=>{i[r]=t,++n===s&&e(i.join(zt))}))}))})(t,(t=>{this.doWrite(t,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=ee()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let re=!1;try{re="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const oe=re;function ae(){}class ce extends ne{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let s=location.port;s||(s=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",((t,e)=>{this.onError("xhr post error",t,e)}))}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",((t,e)=>{this.onError("xhr poll error",t,e)})),this.pollXhr=t}}class he extends Jt{constructor(t,e,s){super(),this.createRequest=t,te(this,s),this._opts=s,this._method=s.method||"GET",this._uri=e,this._data=void 0!==s.data?s.data:null,this._create()}_create(){var t;const e=Qt(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(e);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let t in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(t)&&s.setRequestHeader(t,this._opts.extraHeaders[t])}}catch(t){}if("POST"===this._method)try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{s.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var t;3===s.readyState&&(null===(t=this._opts.cookieJar)||void 0===t||t.parseCookies(s.getResponseHeader("set-cookie"))),4===s.readyState&&(200===s.status||1223===s.status?this._onLoad():this.setTimeoutFn((()=>{this._onError("number"==typeof s.status?s.status:0)}),0))},s.send(this._data)}catch(t){return void this.setTimeoutFn((()=>{this._onError(t)}),0)}"undefined"!=typeof document&&(this._index=he.requestsCount++,he.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=ae,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete he.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}function ue(){for(let t in he.requests)he.requests.hasOwnProperty(t)&&he.requests[t].abort()}he.requestsCount=0,he.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",ue):"function"==typeof addEventListener&&addEventListener("onpagehide"in Gt?"pagehide":"unload",ue,!1));const le=function(){const t=de({xdomain:!1});return t&&null!==t.responseType}();function de(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||oe))return new XMLHttpRequest}catch(t){}if(!e)try{return new(Gt[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const pe="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class fe extends ie{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,s=pe?{}:Qt(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,s)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],i=e===t.length-1;Mt(s,this.supportsBinary,(t=>{try{this.doWrite(s,t)}catch(t){}i&&Kt((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=ee()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const me=Gt.WebSocket||Gt.MozWebSocket,ge={websocket:class extends fe{createSocket(t,e,s){return pe?new me(t,e,s):e?new me(t,e):new me(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends ie{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then((()=>{this.onClose()})).catch((t=>{this.onError("webtransport error",t)})),this._transport.ready.then((()=>{this._transport.createBidirectionalStream().then((t=>{const e=function(t,e){Ht||(Ht=new TextDecoder);const s=[];let i=0,n=-1,r=!1;return new TransformStream({transform(o,a){for(s.push(o);;){if(0===i){if($t(s)<1)break;const t=Yt(s,1);r=!(128&~t[0]),n=127&t[0],i=n<126?3:126===n?1:2}else if(1===i){if($t(s)<2)break;const t=Yt(s,2);n=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),i=3}else if(2===i){if($t(s)<8)break;const t=Yt(s,8),e=new DataView(t.buffer,t.byteOffset,t.length),r=e.getUint32(0);if(r>Math.pow(2,21)-1){a.enqueue(Bt);break}n=r*Math.pow(2,32)+e.getUint32(4),i=3}else{if($t(s)<n)break;const t=Yt(s,n);a.enqueue(Ut(r?t:Ht.decode(t),e)),i=0}if(0===n||n>t){a.enqueue(Bt);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(e).getReader(),i=new TransformStream({transform(t,e){!function(t,e){jt&&t.data instanceof Blob?t.data.arrayBuffer().then(qt).then(e):Lt&&(t.data instanceof ArrayBuffer||Pt(t.data))?e(qt(t.data)):Mt(t,!1,(t=>{It||(It=new TextEncoder),e(It.encode(t))}))}(t,(s=>{const i=s.length;let n;if(i<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,i);else if(i<65536){n=new Uint8Array(3);const t=new DataView(n.buffer);t.setUint8(0,126),t.setUint16(1,i)}else{n=new Uint8Array(9);const t=new DataView(n.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(i))}t.data&&"string"!=typeof t.data&&(n[0]|=128),e.enqueue(n),e.enqueue(s)}))}});i.readable.pipeTo(t.writable),this._writer=i.writable.getWriter();const n=()=>{s.read().then((({done:t,value:e})=>{t||(this.onPacket(e),n())})).catch((t=>{}))};n();const r={type:"open"};this.query.sid&&(r.data=`{"sid":"${this.query.sid}"}`),this._writer.write(r).then((()=>this.onOpen()))}))}))}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],i=e===t.length-1;this._writer.write(s).then((()=>{i&&Kt((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}},polling:class extends ce{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=le&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new he(de,this.uri(),t)}}},ye=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,be=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ve(t){if(t.length>8e3)throw"URI too long";const e=t,s=t.indexOf("["),i=t.indexOf("]");-1!=s&&-1!=i&&(t=t.substring(0,s)+t.substring(s,i).replace(/:/g,";")+t.substring(i,t.length));let n=ye.exec(t||""),r={},o=14;for(;o--;)r[be[o]]=n[o]||"";return-1!=s&&-1!=i&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(t,e){const s=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||s.splice(0,1),"/"==e.slice(-1)&&s.splice(s.length-1,1),s}(0,r.path),r.queryKey=function(t,e){const s={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,i){e&&(s[e]=i)})),s}(0,r.query),r}const we="function"==typeof addEventListener&&"function"==typeof removeEventListener,Se=[];we&&addEventListener("offline",(()=>{Se.forEach((t=>t()))}),!1);class _e extends Jt{constructor(t,e){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&"object"==typeof t&&(e=t,t=null),t){const s=ve(t);e.hostname=s.host,e.secure="https"===s.protocol||"wss"===s.protocol,e.port=s.port,s.query&&(e.query=s.query)}else e.host&&(e.hostname=ve(e.host).host);te(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach((t=>{const e=t.prototype.name;this.transports.push(e),this._transportsByName[e]=t})),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},s=t.split("&");for(let t=0,i=s.length;t<i;t++){let i=s[t].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}(this.opts.query)),we&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Se.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](s)}_open(){if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);const t=this.opts.rememberUpgrade&&_e.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",(t=>this._onClose("transport close",t)))}onOpen(){this.readyState="open",_e.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn((()=>{this._onClose("ping timeout")}),t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s<this.writeBuffer.length;s++){const i=this.writeBuffer[s].data;if(i&&(t+="string"==typeof(e=i)?function(t){let e=0,s=0;for(let i=0,n=t.length;i<n;i++)e=t.charCodeAt(i),e<128?s+=1:e<2048?s+=2:e<55296||e>=57344?s+=3:(i++,s+=4);return s}(e):Math.ceil(1.33*(e.byteLength||e.size))),s>0&&t>this._maxPayload)return this.writeBuffer.slice(0,s);t+=2}var e;return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Kt((()=>{this._onClose("ping timeout")}),this.setTimeoutFn)),t}write(t,e,s){return this._sendPacket("message",t,e,s),this}send(t,e,s){return this._sendPacket("message",t,e,s),this}_sendPacket(t,e,s,i){if("function"==typeof e&&(i=e,e=void 0),"function"==typeof s&&(i=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const n={type:t,data:e,options:s};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?s():t()})):this.upgrading?s():t()),this}_onError(t){if(_e.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),we&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=Se.indexOf(this._offlineEventListener);-1!==t&&Se.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}_e.protocol=4;class ke extends _e{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),s=!1;_e.priorWebsocketSuccess=!1;const i=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",(t=>{if(!s)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;_e.priorWebsocketSuccess="websocket"===e.name,this.transport.pause((()=>{s||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())}))}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}})))};function n(){s||(s=!0,h(),e.close(),e=null)}const r=t=>{const s=new Error("probe error: "+t);s.transport=e.name,n(),this.emitReserved("upgradeError",s)};function o(){r("transport closed")}function a(){r("socket closed")}function c(t){e&&t.name!==e.name&&n()}const h=()=>{e.removeListener("open",i),e.removeListener("error",r),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",i),e.once("error",r),e.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn((()=>{s||e.open()}),200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}class xe extends ke{constructor(t,e={}){const s="object"==typeof t?t:e;(!s.transports||s.transports&&"string"==typeof s.transports[0])&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map((t=>ge[t])).filter((t=>!!t))),super(t,s)}}const Ee="function"==typeof ArrayBuffer,Te=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer,Oe=Object.prototype.toString,Ce="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Oe.call(Blob),Re="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Oe.call(File);function Ae(t){return Ee&&(t instanceof ArrayBuffer||Te(t))||Ce&&t instanceof Blob||Re&&t instanceof File}function Be(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,s=t.length;e<s;e++)if(Be(t[e]))return!0;return!1}if(Ae(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return Be(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&Be(t[e]))return!0;return!1}function je(t){const e=[],s=t.data,i=t;return i.data=Le(s,e),i.attachments=e.length,{packet:i,buffers:e}}function Le(t,e){if(!t)return t;if(Ae(t)){const s={_placeholder:!0,num:e.length};return e.push(t),s}if(Array.isArray(t)){const s=new Array(t.length);for(let i=0;i<t.length;i++)s[i]=Le(t[i],e);return s}if("object"==typeof t&&!(t instanceof Date)){const s={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(s[i]=Le(t[i],e));return s}return t}function Pe(t,e){return t.data=Me(t.data,e),delete t.attachments,t}function Me(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let s=0;s<t.length;s++)t[s]=Me(t[s],e);else if("object"==typeof t)for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=Me(t[s],e));return t}const De=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],qe=5;var Ie;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(Ie||(Ie={}));class Ne{constructor(t){this.replacer=t}encode(t){return t.type!==Ie.EVENT&&t.type!==Ie.ACK||!Be(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===Ie.EVENT?Ie.BINARY_EVENT:Ie.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==Ie.BINARY_EVENT&&t.type!==Ie.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=je(t),s=this.encodeAsString(e.packet),i=e.buffers;return i.unshift(s),i}}function Fe(t){return"[object Object]"===Object.prototype.toString.call(t)}class Ue extends Jt{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const s=e.type===Ie.BINARY_EVENT;s||e.type===Ie.BINARY_ACK?(e.type=s?Ie.EVENT:Ie.ACK,this.reconstructor=new Ve(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!Ae(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const s={type:Number(t.charAt(0))};if(void 0===Ie[s.type])throw new Error("unknown packet type "+s.type);if(s.type===Ie.BINARY_EVENT||s.type===Ie.BINARY_ACK){const i=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const n=t.substring(i,e);if(n!=Number(n)||"-"!==t.charAt(e))throw new Error("Illegal attachments");s.attachments=Number(n)}if("/"===t.charAt(e+1)){const i=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);s.nsp=t.substring(i,e)}else s.nsp="/";const i=t.charAt(e+1);if(""!==i&&Number(i)==i){const i=e+1;for(;++e;){const s=t.charAt(e);if(null==s||Number(s)!=s){--e;break}if(e===t.length)break}s.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(!Ue.isPayloadValid(s.type,i))throw new Error("invalid payload");s.data=i}return s}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case Ie.CONNECT:return Fe(e);case Ie.DISCONNECT:return void 0===e;case Ie.CONNECT_ERROR:return"string"==typeof e||Fe(e);case Ie.EVENT:case Ie.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===De.indexOf(e[0]));case Ie.ACK:case Ie.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Ve{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=Pe(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function We(t,e,s){return t.on(e,s),function(){t.off(e,s)}}const ze=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class He extends Jt{constructor(t,e,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[We(t,"open",this.onopen.bind(this)),We(t,"packet",this.onpacket.bind(this)),We(t,"error",this.onerror.bind(this)),We(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var s,i,n;if(ze.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const r={type:Ie.EVENT,data:e,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,s=e.pop();this._registerAckCallback(t,s),r.id=t}const o=null===(i=null===(s=this.io.engine)||void 0===s?void 0:s.transport)||void 0===i?void 0:i.writable,a=this.connected&&!(null===(n=this.io.engine)||void 0===n?void 0:n._hasPingExpired());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(t,e){var s;const i=null!==(s=this.flags.timeout)&&void 0!==s?s:this._opts.ackTimeout;if(void 0===i)return void(this.acks[t]=e);const n=this.io.setTimeoutFn((()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))}),i),r=(...t)=>{this.io.clearTimeoutFn(n),e.apply(this,t)};r.withError=!0,this.acks[t]=r}emitWithAck(t,...e){return new Promise(((s,i)=>{const n=(t,e)=>t?i(t):s(e);n.withError=!0,e.push(n),this.emit(t,...e)}))}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push(((t,...i)=>{if(s===this._queue[0])return null!==t?s.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...i)),s.pending=!1,this._drainQueue()})),this._queue.push(s),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth((t=>{this._sendConnectPacket(t)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:Ie.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach((t=>{if(!this.sendBuffer.some((e=>String(e.id)===t))){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}}))}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case Ie.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ie.EVENT:case Ie.BINARY_EVENT:this.onevent(t);break;case Ie.ACK:case Ie.BINARY_ACK:this.onack(t);break;case Ie.DISCONNECT:this.ondisconnect();break;case Ie.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const s of e)s.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let s=!1;return function(...i){s||(s=!0,e.packet({type:Ie.ACK,id:t,data:i}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((t=>this.emitEvent(t))),this.receiveBuffer=[],this.sendBuffer.forEach((t=>{this.notifyOutgoingListeners(t),this.packet(t)})),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((t=>t())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Ie.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const s of e)s.apply(this,t.data)}}}function $e(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}$e.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),s=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+s:t-s}return 0|Math.min(t,this.max)},$e.prototype.reset=function(){this.attempts=0},$e.prototype.setMin=function(t){this.ms=t},$e.prototype.setMax=function(t){this.max=t},$e.prototype.setJitter=function(t){this.jitter=t};class Ye extends Jt{constructor(t,e){var s;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,te(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(s=e.randomizationFactor)&&void 0!==s?s:.5),this.backoff=new $e({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const i=e.parser||n;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new xe(this.uri,this.opts);const e=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=We(e,"open",(function(){s.onopen(),t&&t()})),n=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},r=We(e,"error",n);if(!1!==this._timeout){const t=this._timeout,s=this.setTimeoutFn((()=>{i(),n(new Error("timeout")),e.close()}),t);this.opts.autoUnref&&s.unref(),this.subs.push((()=>{this.clearTimeoutFn(s)}))}return this.subs.push(i),this.subs.push(r),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(We(t,"ping",this.onping.bind(this)),We(t,"data",this.ondata.bind(this)),We(t,"error",this.onerror.bind(this)),We(t,"close",this.onclose.bind(this)),We(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){Kt((()=>{this.emitReserved("packet",t)}),this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s?this._autoConnect&&!s.active&&s.connect():(s=new He(this,t,e),this.nsps[t]=s),s}_destroy(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let s=0;s<e.length;s++)this.engine.write(e[s],t.options)}cleanup(){this.subs.forEach((t=>t())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var s;this.cleanup(),null===(s=this.engine)||void 0===s||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn((()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open((e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()})))}),e);this.opts.autoUnref&&s.unref(),this.subs.push((()=>{this.clearTimeoutFn(s)}))}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Je={};function Ke(t,e){"object"==typeof t&&(e=t,t=void 0);const s=function(t,e="",s){let i=t;s=s||"undefined"!=typeof location&&location,null==t&&(t=s.protocol+"//"+s.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?s.protocol+t:s.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==s?s.protocol+"//"+t:"https://"+t),i=ve(t)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const n=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+e,i.href=i.protocol+"://"+n+(s&&s.port===i.port?"":":"+i.port),i}(t,(e=e||{}).path||"/socket.io"),i=s.source,n=s.id,r=s.path,o=Je[n]&&r in Je[n].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new Ye(i,e):(Je[n]||(Je[n]=new Ye(i,e)),a=Je[n]),s.query&&!e.query&&(e.query=s.queryKey),a.socket(s.path,e)}Object.assign(Ke,{Manager:Ye,Socket:He,io:Ke,connect:Ke});class Ge{socket;token;endpoint;socketList=new Map;constructor(t,e){this.endpoint=t.replace("https://","wss://").replace("http://","ws://"),this.token=e,this.socket=this.getSocket("default").socket,this.socket.connect()}close(){this.socket.emit("end"),this.socket.removeAllListeners(),this.socket.disconnect()}getSocket(t,e){return this.createManager(e)}createManager(t){const e=new Ye(this.endpoint,{reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:5e3,randomizationFactor:.5,timeout:2e4,autoConnect:!0,transports:["websocket","polling"],rejectUnauthorized:!1,secure:!0,forceNew:t}),s=e.socket("/proxy",{auth:{token:`Bearer ${this.token}`}});return{manager:e,socket:s}}}class Qe{api;socketService;config;logger;token;deviceManager;coreManager;constructor(t){this.config=t,this.logger=t.logger||{...console,attention:console.warn},this.api=new r(t.endpoint)}async connect(){return this.deviceManager&&this.coreManager||(this.cleanUpClient(),await this.login(),this.token=this.token||this.config.token,this.socketService=new Ge(this.config.endpoint,this.token),this.coreManager=new Ot(this.socketService,this.logger),this.deviceManager=new Ct(this.socketService,this.logger),this.checkSession()),{coreManager:this.coreManager,deviceManager:this.deviceManager}}async disconnect(){this.socketService?.close(),this.cleanUpClient(),this.config.username&&this.config.password&&await this.api.post("/auth/logout",void 0,{headers:{Authorization:`Bearer ${this.token}`}})}async updateCredentials(t){this.config={...this.config,...t},this.socketService&&await this.disconnect(),await this.connect()}async login(){if(this.config.username&&this.config.password)try{const t=await this.api.post("/auth/login",{username:this.config.username,password:this.config.password}),e=await t.json();this.token=e.access_token}catch(t){throw 401===t.response?.status?new Error("Invalid credentials"):new Error(`Failed to get token: ${t.message}`)}else if(this.config.token&&!this.config.skipCheck)try{await this.api.get("/auth/check",{headers:{Authorization:`Bearer ${this.config.token}`}})}catch(t){throw new Error(`Invalid token: ${t.message}`)}this.token=this.token||this.config.token}getDeviceManager(){return this.deviceManager}checkSession(){this.socketService?.socket.removeListener("invalidToken"),this.socketService?.socket.on("invalidToken",(async t=>{t===this.token&&await this.disconnect()}))}cleanUpClient(){this.deviceManager=void 0}}var Xe=i.j;export{Xe as CameraUiClient};
|
|
@@ -10,6 +10,7 @@ export declare class Go2RTCSession extends EventTarget {
|
|
|
10
10
|
private socket;
|
|
11
11
|
private streamId;
|
|
12
12
|
hasBackchannel: boolean;
|
|
13
|
+
hasAudio: boolean;
|
|
13
14
|
closed: boolean;
|
|
14
15
|
micTransceiver: RTCRtpTransceiver | null;
|
|
15
16
|
private pc;
|
|
@@ -23,6 +24,8 @@ export declare class Go2RTCSession extends EventTarget {
|
|
|
23
24
|
private codecList;
|
|
24
25
|
private reconnectTimeout?;
|
|
25
26
|
private _finishLoading;
|
|
27
|
+
private _firstFrameReceived;
|
|
28
|
+
private animationFrameId?;
|
|
26
29
|
get mode(): VideoStreamingMode;
|
|
27
30
|
private webrtcReconnectTimeout?;
|
|
28
31
|
constructor(cameraDevice: CameraDevice, socketService: SocketService, logger: BaseLogger, options: Go2RTCSessionOptions);
|
|
@@ -47,7 +50,8 @@ export declare class Go2RTCSession extends EventTarget {
|
|
|
47
50
|
private onHlsData;
|
|
48
51
|
private onStreamInfo;
|
|
49
52
|
private play;
|
|
50
|
-
private
|
|
53
|
+
private onFirstFrame;
|
|
54
|
+
private onFinishLoading;
|
|
51
55
|
private createCodecsList;
|
|
52
56
|
private parseCodecs;
|
|
53
57
|
private btoaBinary;
|
|
@@ -2,7 +2,7 @@ import type { Observable, Subject } from 'rxjs';
|
|
|
2
2
|
import type { BaseCameraDevice } from '../../../../packages/plugineer/src/polyglot/node/camera/index.js';
|
|
3
3
|
import type { VideoStreamingMode } from '../../../../shared/types/index.js';
|
|
4
4
|
import type { Go2RTCSession } from './streaming/go2rts-session.js';
|
|
5
|
-
export type { AudioSetEvent, AudioState, BatterySetEvent, BatteryState, CameraActivitySettings, CameraSource, CameraZone, Container, Detection, DetectionZone, DoorbellState, LightSetEvent, LightState, MotionSetEvent, MotionState, ObjectSetEvent, ObjectState, Point, PrebufferState, SirenSetEvent, SirenState, ZoneFilter, ZoneType, } from '../../../../shared/types/index.js';
|
|
5
|
+
export type { AudioSetEvent, AudioState, BatterySetEvent, BatteryState, CameraActivitySettings, CameraRoles, CameraSource, CameraZone, Container, Detection, DetectionZone, DoorbellState, LightSetEvent, LightState, MotionSetEvent, MotionState, ObjectSetEvent, ObjectState, Point, PrebufferState, SirenSetEvent, SirenState, VideoStreamingMode, ZoneFilter, ZoneType, } from '../../../../shared/types/index.js';
|
|
6
6
|
export type { Go2RTCSession } from './streaming/go2rts-session.js';
|
|
7
7
|
export type CameraUiClientConfig = WithCredentials | WithToken;
|
|
8
8
|
export interface BasicBrowserPeerConnection {
|
|
@@ -85,10 +85,18 @@ export declare const removeFunctionsFromSchema: (jsonSchema: JsonSchema) => Json
|
|
|
85
85
|
* Checks if a given JSON schema is readonly.
|
|
86
86
|
*
|
|
87
87
|
* @param jsonSchema - The JSON schema to check.
|
|
88
|
+
* @param group - The group to check.
|
|
88
89
|
* @returns - True if the JSON schema is readonly, false otherwise.
|
|
89
90
|
*/
|
|
90
|
-
export declare const schemaIsReadonly: (jsonSchema: JsonSchema) => boolean;
|
|
91
|
-
|
|
91
|
+
export declare const schemaIsReadonly: (jsonSchema: JsonSchema, group?: string) => boolean;
|
|
92
|
+
/**
|
|
93
|
+
* Checks if a given JSON schema is storable.
|
|
94
|
+
*
|
|
95
|
+
* @param jsonSchema - The JSON schema to check.
|
|
96
|
+
* @param group - The group to check.
|
|
97
|
+
* @returns - True if the JSON schema is storable, false otherwise.
|
|
98
|
+
*/
|
|
99
|
+
export declare const schemaIsStorable: (jsonSchema: JsonSchema, group?: string) => boolean;
|
|
92
100
|
/**
|
|
93
101
|
* Converts a config path to a schema path.
|
|
94
102
|
*
|
|
@@ -2,7 +2,7 @@ import type { FastifyInstance } from 'fastify';
|
|
|
2
2
|
import type { Database as DB, RootDatabase as RootDB } from 'lmdb';
|
|
3
3
|
import type { DBAuth, DBCamera, DBPlugin, DBSettings, DBSystem, DBUser } from './types.js';
|
|
4
4
|
export declare class Database {
|
|
5
|
-
static readonly VERSION = "1.0.
|
|
5
|
+
static readonly VERSION = "1.0.2";
|
|
6
6
|
authDB: RootDB<DBAuth, 'auth'>;
|
|
7
7
|
camerasDB: DB<DBCamera[], 'cameras'>;
|
|
8
8
|
pluginsDB: DB<DBPlugin[], 'plugins'>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { UsableNetworkAddress } from '@camera.ui/common/network';
|
|
2
|
-
import type { BaseCamera, CameraInputSettings, ZoneCoord } from '@camera.ui/types';
|
|
2
|
+
import type { BaseCamera, CameraInputSettings, CameraRoles, ZoneCoord } from '@camera.ui/types';
|
|
3
3
|
import type { Database as DB } from 'lmdb';
|
|
4
4
|
import type { CamviewSettingsLayoutMode, ClientData, JwtTokenEncoded } from '../types/index.js';
|
|
5
5
|
import type { CAMERAS_ID, PLUGINS_ID, SETTINGS_ID, USERS_ID } from './constants.js';
|
|
@@ -93,6 +93,7 @@ export interface CameraRecordingSettings {
|
|
|
93
93
|
}
|
|
94
94
|
export interface CameraUiSettings {
|
|
95
95
|
streamingMode: VideoStreamingMode;
|
|
96
|
+
streamingSource: Exclude<CameraRoles, 'snapshot'>;
|
|
96
97
|
}
|
|
97
98
|
export type VideoStreamingMode = 'webrtc' | 'mse' | 'webrtc/tcp' | 'mjpeg' | 'hls' | 'mp4';
|
|
98
99
|
export interface SystemInfo extends DBSystem {
|
|
@@ -5,7 +5,7 @@ export declare class StreamsApi {
|
|
|
5
5
|
constructor(requestQueue: RequestQueue);
|
|
6
6
|
createStream(data: CreateStreamData): Promise<void>;
|
|
7
7
|
deleteStream(data: SourceData): Promise<void>;
|
|
8
|
-
getStreamInfo(data: SourceData): Promise<
|
|
8
|
+
getStreamInfo(data: SourceData): Promise<Go2RTCProbe>;
|
|
9
9
|
updateStreamSource(data: UpdateStreamData): Promise<void>;
|
|
10
10
|
probeStreamSource(data: SourceData): Promise<Go2RTCProbe>;
|
|
11
11
|
}
|
|
@@ -1,30 +1,14 @@
|
|
|
1
1
|
export interface ApplicationResponse {
|
|
2
2
|
config_path: string;
|
|
3
3
|
host: string;
|
|
4
|
-
rtsp:
|
|
4
|
+
rtsp: RTSPInfo;
|
|
5
5
|
version: string;
|
|
6
6
|
}
|
|
7
|
-
export interface
|
|
7
|
+
export interface RTSPInfo {
|
|
8
8
|
listen: string;
|
|
9
9
|
default_query: string;
|
|
10
10
|
PacketSize: number;
|
|
11
11
|
}
|
|
12
|
-
export interface StreamInfoResponse {
|
|
13
|
-
producers: Consumer[];
|
|
14
|
-
consumers: Consumer[];
|
|
15
|
-
}
|
|
16
|
-
export interface Consumer {
|
|
17
|
-
type: string;
|
|
18
|
-
url: string;
|
|
19
|
-
remote_addr: string;
|
|
20
|
-
user_agent: string;
|
|
21
|
-
sdp: string;
|
|
22
|
-
medias: string[];
|
|
23
|
-
senders?: string[];
|
|
24
|
-
send?: number;
|
|
25
|
-
receivers?: string[];
|
|
26
|
-
recv?: number;
|
|
27
|
-
}
|
|
28
12
|
export interface HomeKitResponse {
|
|
29
13
|
sources: HomeKitSource[];
|
|
30
14
|
}
|
|
@@ -151,6 +151,7 @@ export declare const activitySettingsSchema: zod.ZodObject<{
|
|
|
151
151
|
};
|
|
152
152
|
}>;
|
|
153
153
|
export declare const inputRoleSchema: zod.ZodUnion<[zod.ZodLiteral<"high-resolution">, zod.ZodLiteral<"mid-resolution">, zod.ZodLiteral<"low-resolution">, zod.ZodLiteral<"snapshot">]>;
|
|
154
|
+
export declare const streamingSourceRole: zod.ZodUnion<[zod.ZodLiteral<"high-resolution">, zod.ZodLiteral<"mid-resolution">, zod.ZodLiteral<"low-resolution">]>;
|
|
154
155
|
export declare const inputProtocolSchema: zod.ZodUnion<[zod.ZodLiteral<"bubble://">, zod.ZodLiteral<"dvrip://">, zod.ZodLiteral<"echo:">, zod.ZodLiteral<"exec:">, zod.ZodLiteral<"expr:">, zod.ZodLiteral<"ffmpeg:">, zod.ZodLiteral<"gopro://">, zod.ZodLiteral<"hass:">, zod.ZodLiteral<"homekit://">, zod.ZodLiteral<"http://">, zod.ZodLiteral<"https://">, zod.ZodLiteral<"httpx://">, zod.ZodLiteral<"isapi://">, zod.ZodLiteral<"ivideon:">, zod.ZodLiteral<"kasa://">, zod.ZodLiteral<"nest:">, zod.ZodLiteral<"onvif://">, zod.ZodLiteral<"roborock://">, zod.ZodLiteral<"rtmp://">, zod.ZodLiteral<"rtsp://">, zod.ZodLiteral<"rtspx://">, zod.ZodLiteral<"tapo://">, zod.ZodLiteral<"tcp://">, zod.ZodLiteral<"webrtc:">, zod.ZodLiteral<"webtorrent:">]>;
|
|
155
156
|
export declare const inputSchema: zod.ZodObject<{
|
|
156
157
|
_id: zod.ZodEffects<zod.ZodDefault<zod.ZodString>, string, string | undefined>;
|
|
@@ -232,10 +233,13 @@ export declare const frameWorkerSettingsSchema: zod.ZodObject<{
|
|
|
232
233
|
export declare const cameraTypeSchema: zod.ZodUnion<[zod.ZodLiteral<"camera">, zod.ZodLiteral<"doorbell">]>;
|
|
233
234
|
export declare const interfaceSettingsSchema: zod.ZodObject<{
|
|
234
235
|
streamingMode: zod.ZodUnion<[zod.ZodLiteral<"mse">, zod.ZodLiteral<"webrtc">, zod.ZodLiteral<"webrtc/tcp">, zod.ZodLiteral<"mjpeg">, zod.ZodLiteral<"hls">, zod.ZodLiteral<"mp4">]>;
|
|
236
|
+
streamingSource: zod.ZodUnion<[zod.ZodLiteral<"high-resolution">, zod.ZodLiteral<"mid-resolution">, zod.ZodLiteral<"low-resolution">]>;
|
|
235
237
|
}, "strip", zod.ZodTypeAny, {
|
|
236
238
|
streamingMode: "mp4" | "mjpeg" | "mse" | "webrtc" | "webrtc/tcp" | "hls";
|
|
239
|
+
streamingSource: "high-resolution" | "mid-resolution" | "low-resolution";
|
|
237
240
|
}, {
|
|
238
241
|
streamingMode: "mp4" | "mjpeg" | "mse" | "webrtc" | "webrtc/tcp" | "hls";
|
|
242
|
+
streamingSource: "high-resolution" | "mid-resolution" | "low-resolution";
|
|
239
243
|
}>;
|
|
240
244
|
export declare const cameraInfoSchema: zod.ZodObject<{
|
|
241
245
|
model: zod.ZodOptional<zod.ZodString>;
|
|
@@ -359,10 +363,13 @@ export declare const createCameraSchema: zod.ZodObject<{
|
|
|
359
363
|
}>>;
|
|
360
364
|
interface: zod.ZodDefault<zod.ZodObject<{
|
|
361
365
|
streamingMode: zod.ZodUnion<[zod.ZodLiteral<"mse">, zod.ZodLiteral<"webrtc">, zod.ZodLiteral<"webrtc/tcp">, zod.ZodLiteral<"mjpeg">, zod.ZodLiteral<"hls">, zod.ZodLiteral<"mp4">]>;
|
|
366
|
+
streamingSource: zod.ZodUnion<[zod.ZodLiteral<"high-resolution">, zod.ZodLiteral<"mid-resolution">, zod.ZodLiteral<"low-resolution">]>;
|
|
362
367
|
}, "strip", zod.ZodTypeAny, {
|
|
363
368
|
streamingMode: "mp4" | "mjpeg" | "mse" | "webrtc" | "webrtc/tcp" | "hls";
|
|
369
|
+
streamingSource: "high-resolution" | "mid-resolution" | "low-resolution";
|
|
364
370
|
}, {
|
|
365
371
|
streamingMode: "mp4" | "mjpeg" | "mse" | "webrtc" | "webrtc/tcp" | "hls";
|
|
372
|
+
streamingSource: "high-resolution" | "mid-resolution" | "low-resolution";
|
|
366
373
|
}>>;
|
|
367
374
|
activityZones: zod.ZodDefault<zod.ZodArray<zod.ZodObject<{
|
|
368
375
|
name: zod.ZodString;
|
|
@@ -541,6 +548,7 @@ export declare const createCameraSchema: zod.ZodObject<{
|
|
|
541
548
|
};
|
|
542
549
|
interface: {
|
|
543
550
|
streamingMode: "mp4" | "mjpeg" | "mse" | "webrtc" | "webrtc/tcp" | "hls";
|
|
551
|
+
streamingSource: "high-resolution" | "mid-resolution" | "low-resolution";
|
|
544
552
|
};
|
|
545
553
|
nativeId?: string | undefined;
|
|
546
554
|
}, {
|
|
@@ -612,6 +620,7 @@ export declare const createCameraSchema: zod.ZodObject<{
|
|
|
612
620
|
} | undefined;
|
|
613
621
|
interface?: {
|
|
614
622
|
streamingMode: "mp4" | "mjpeg" | "mse" | "webrtc" | "webrtc/tcp" | "hls";
|
|
623
|
+
streamingSource: "high-resolution" | "mid-resolution" | "low-resolution";
|
|
615
624
|
} | undefined;
|
|
616
625
|
}>;
|
|
617
626
|
export declare const patchCameraSchema: zod.ZodObject<{
|
|
@@ -699,10 +708,13 @@ export declare const patchCameraSchema: zod.ZodObject<{
|
|
|
699
708
|
}>>;
|
|
700
709
|
interface: zod.ZodOptional<zod.ZodObject<{
|
|
701
710
|
streamingMode: zod.ZodOptional<zod.ZodUnion<[zod.ZodLiteral<"mse">, zod.ZodLiteral<"webrtc">, zod.ZodLiteral<"webrtc/tcp">, zod.ZodLiteral<"mjpeg">, zod.ZodLiteral<"hls">, zod.ZodLiteral<"mp4">]>>;
|
|
711
|
+
streamingSource: zod.ZodOptional<zod.ZodUnion<[zod.ZodLiteral<"high-resolution">, zod.ZodLiteral<"mid-resolution">, zod.ZodLiteral<"low-resolution">]>>;
|
|
702
712
|
}, "strip", zod.ZodTypeAny, {
|
|
703
713
|
streamingMode?: "mp4" | "mjpeg" | "mse" | "webrtc" | "webrtc/tcp" | "hls" | undefined;
|
|
714
|
+
streamingSource?: "high-resolution" | "mid-resolution" | "low-resolution" | undefined;
|
|
704
715
|
}, {
|
|
705
716
|
streamingMode?: "mp4" | "mjpeg" | "mse" | "webrtc" | "webrtc/tcp" | "hls" | undefined;
|
|
717
|
+
streamingSource?: "high-resolution" | "mid-resolution" | "low-resolution" | undefined;
|
|
706
718
|
}>>;
|
|
707
719
|
recording: zod.ZodOptional<zod.ZodObject<{
|
|
708
720
|
enabled: zod.ZodOptional<zod.ZodDefault<zod.ZodBoolean>>;
|
|
@@ -881,6 +893,7 @@ export declare const patchCameraSchema: zod.ZodObject<{
|
|
|
881
893
|
} | undefined;
|
|
882
894
|
interface?: {
|
|
883
895
|
streamingMode?: "mp4" | "mjpeg" | "mse" | "webrtc" | "webrtc/tcp" | "hls" | undefined;
|
|
896
|
+
streamingSource?: "high-resolution" | "mid-resolution" | "low-resolution" | undefined;
|
|
884
897
|
} | undefined;
|
|
885
898
|
}, {
|
|
886
899
|
type?: "camera" | "doorbell" | undefined;
|
|
@@ -943,6 +956,7 @@ export declare const patchCameraSchema: zod.ZodObject<{
|
|
|
943
956
|
} | undefined;
|
|
944
957
|
interface?: {
|
|
945
958
|
streamingMode?: "mp4" | "mjpeg" | "mse" | "webrtc" | "webrtc/tcp" | "hls" | undefined;
|
|
959
|
+
streamingSource?: "high-resolution" | "mid-resolution" | "low-resolution" | undefined;
|
|
946
960
|
} | undefined;
|
|
947
961
|
}>;
|
|
948
962
|
export declare const patchExtensionsSchema: zod.ZodRecord<zod.ZodString, zod.ZodAny>;
|
|
@@ -219,6 +219,11 @@ export type CamerasParamsRequest = {
|
|
|
219
219
|
cameraname: string;
|
|
220
220
|
};
|
|
221
221
|
};
|
|
222
|
+
export type CameraSnapshotQueryRequest = {
|
|
223
|
+
Querystring: {
|
|
224
|
+
forceNew?: boolean;
|
|
225
|
+
};
|
|
226
|
+
};
|
|
222
227
|
export type CameraSourceParamsRequest = {
|
|
223
228
|
Params: {
|
|
224
229
|
sourcename: string;
|
|
@@ -401,6 +406,7 @@ export interface ConsoleSettings {
|
|
|
401
406
|
zoom: number;
|
|
402
407
|
}
|
|
403
408
|
export type CamviewSettingsLayoutMode = 'dnd' | 'view';
|
|
409
|
+
export type SettingsViews = 'account' | 'appearance' | 'user' | 'recordings' | 'backup' | 'system';
|
|
404
410
|
export interface CamviewSettings {
|
|
405
411
|
dragDisabled?: boolean;
|
|
406
412
|
viewid?: string;
|
|
@@ -410,6 +416,7 @@ export interface CamerasSettings {
|
|
|
410
416
|
}
|
|
411
417
|
export interface InterfaceSettinges {
|
|
412
418
|
showBottomBarOnMobile: boolean;
|
|
419
|
+
selectedSettingsView: SettingsViews;
|
|
413
420
|
}
|
|
414
421
|
export interface UiSettingsLocalStorage {
|
|
415
422
|
cameras: CamerasSettings;
|
|
@@ -2,8 +2,6 @@ export declare const HOST_CERT_FILENAME = "camera.ui.cert.pem";
|
|
|
2
2
|
export declare const HOST_KEY_FILENAME = "camera.ui.key.pem";
|
|
3
3
|
export declare const ROOT_CERT_FILENAME = "camera.ui.root.cert.pem";
|
|
4
4
|
export declare const ROOT_KEY_FILENAME = "camera.ui.root.key.pem";
|
|
5
|
-
export declare const P12_FILENAME = "camera.ui.p12";
|
|
6
|
-
export declare const P12_PASSWORD = "camera.ui";
|
|
7
5
|
export declare const DEFAULTS: {
|
|
8
6
|
C: string;
|
|
9
7
|
ST: string;
|
|
@@ -8,14 +8,19 @@ export declare class ServerNamespace {
|
|
|
8
8
|
private pluginsService;
|
|
9
9
|
private serverUpdate;
|
|
10
10
|
private pluginUpdates;
|
|
11
|
+
private checkPluginUpdateInterval;
|
|
12
|
+
private checkServerUpdateInterval;
|
|
11
13
|
constructor(io: Server);
|
|
12
|
-
getUpdates(payload
|
|
14
|
+
getUpdates(payload?: any, callback?: Function): {
|
|
13
15
|
server?: INpmPluginState;
|
|
14
16
|
plugins: INpmPluginState[];
|
|
15
17
|
};
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
18
|
+
checkPlugins(interval?: boolean): Promise<void>;
|
|
19
|
+
checkServer(interval?: boolean): Promise<void>;
|
|
20
|
+
private checkServerUpdate;
|
|
21
|
+
private checkPluginUpdates;
|
|
19
22
|
private getPluginFromNpm;
|
|
20
23
|
private getAvailablePluginVersions;
|
|
24
|
+
restartPluginInterval(timer?: number): void;
|
|
25
|
+
restartServerInterval(timer?: number): void;
|
|
21
26
|
}
|
|
@@ -14,12 +14,12 @@ export interface ProcessInfo {
|
|
|
14
14
|
timestamp: number;
|
|
15
15
|
}
|
|
16
16
|
export interface ServerProcessInfo {
|
|
17
|
-
|
|
17
|
+
'camera.ui': ProcessInfo;
|
|
18
18
|
go2rtc: ProcessInfo;
|
|
19
19
|
nats: ProcessInfo;
|
|
20
20
|
}
|
|
21
21
|
export interface ServerProcesses {
|
|
22
|
-
|
|
22
|
+
'camera.ui': ProcessInfo[];
|
|
23
23
|
go2rtc: ProcessInfo[];
|
|
24
24
|
nats: ProcessInfo[];
|
|
25
25
|
}
|
|
@@ -38,7 +38,7 @@ export interface PluginRuntimeInfo {
|
|
|
38
38
|
status: PLUGIN_STATUS;
|
|
39
39
|
}
|
|
40
40
|
export interface ServerRuntime {
|
|
41
|
-
|
|
41
|
+
'camera.ui'?: RuntimeInfo;
|
|
42
42
|
go2rtc?: RuntimeInfo;
|
|
43
43
|
nats?: RuntimeInfo;
|
|
44
44
|
}
|
|
@@ -6,6 +6,11 @@ import type { LoggingLevel } from '../config/types.js';
|
|
|
6
6
|
export declare class LoggerService extends Logger {
|
|
7
7
|
notifications: UiNotification[];
|
|
8
8
|
constructor(options?: LoggerOptions);
|
|
9
|
-
notify(title: string, text: string, type: LoggingLevel, link: string):
|
|
9
|
+
notify(title: string, text: string, type: LoggingLevel, link: string): UiNotification | undefined;
|
|
10
|
+
notify(notification: UiNotification): UiNotification | undefined;
|
|
11
|
+
removeNotification(id: string, notify: boolean): void;
|
|
12
|
+
removeNotification(notification: UiNotification, notify: boolean): void;
|
|
13
|
+
clearNotifications(notifiy: boolean): void;
|
|
14
|
+
createNotification(id: string | undefined, title: string, text: string, type: LoggingLevel, link: string): UiNotification;
|
|
10
15
|
private checkIfNotificationExists;
|
|
11
16
|
}
|
|
@@ -5,6 +5,7 @@ export * from '../../packages/plugineer/src/polyglot/node/plugins/types.js';
|
|
|
5
5
|
export type * from '../../packages/plugineer/src/utils/messageQueue.js';
|
|
6
6
|
export * from '../../packages/types/src/index.js';
|
|
7
7
|
export type * from '../../server/src/api/database/types.js';
|
|
8
|
+
export type * from '../../server/src/api/go2rtc/types.js';
|
|
8
9
|
export * from '../../server/src/api/schemas/cameras.schema.js';
|
|
9
10
|
export * from '../../server/src/api/schemas/plugins.schema.js';
|
|
10
11
|
export * from '../../server/src/api/schemas/system.schema.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@camera.ui/browser",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.99",
|
|
4
4
|
"description": "camera.ui browser client",
|
|
5
5
|
"author": "seydx (https://github.com/seydx/camera.ui)",
|
|
6
6
|
"module": "./dist/bundle.js",
|
|
@@ -27,14 +27,14 @@
|
|
|
27
27
|
"dependencies": {
|
|
28
28
|
"@isaacs/ttlcache": "^1.4.1",
|
|
29
29
|
"rxjs": "^7.8.1",
|
|
30
|
-
"socket.io-client": "^4.
|
|
30
|
+
"socket.io-client": "^4.8.0"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@rushstack/eslint-patch": "^1.10.4",
|
|
34
34
|
"@swc/register": "^0.1.10",
|
|
35
35
|
"@types/webrtc": "^0.0.43",
|
|
36
|
-
"@typescript-eslint/eslint-plugin": "^8.
|
|
37
|
-
"@typescript-eslint/parser": "^8.
|
|
36
|
+
"@typescript-eslint/eslint-plugin": "^8.7.0",
|
|
37
|
+
"@typescript-eslint/parser": "^8.7.0",
|
|
38
38
|
"bufferutil": "^4.0.8",
|
|
39
39
|
"eslint": "^8.57.0",
|
|
40
40
|
"eslint-config-prettier": "^9.1.0",
|