@camera.ui/browser 0.0.111 → 0.0.112
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/LICENSE.md +1 -1
- package/README.md +10 -1
- package/dist/index.d.ts +1269 -0
- package/dist/index.js +4179 -0
- package/package.json +55 -39
- package/CHANGELOG.md +0 -8
- package/dist/bundle.js +0 -2
- package/dist/bundle.js.LICENSE.txt +0 -14
- package/dist/types/packages/client/browser/src/api.d.ts +0 -8
- package/dist/types/packages/client/browser/src/client.d.ts +0 -21
- package/dist/types/packages/client/browser/src/index.d.ts +0 -2
- package/dist/types/packages/client/browser/src/proxy/cameraDevice.d.ts +0 -26
- package/dist/types/packages/client/browser/src/proxy/coreManager.d.ts +0 -14
- package/dist/types/packages/client/browser/src/proxy/deviceManager.d.ts +0 -16
- package/dist/types/packages/client/browser/src/proxy/index.d.ts +0 -3
- package/dist/types/packages/client/browser/src/proxy.d.ts +0 -7
- package/dist/types/packages/client/browser/src/streaming/config.d.ts +0 -21
- package/dist/types/packages/client/browser/src/streaming/go2rts-session.d.ts +0 -286
- package/dist/types/packages/client/browser/src/streaming/types.d.ts +0 -38
- package/dist/types/packages/client/browser/src/types.d.ts +0 -56
- package/dist/types/packages/client/browser/src/utils.d.ts +0 -12
- package/dist/types/packages/common/src/utils/subscribed.d.ts +0 -18
- package/dist/types/packages/types/src/index.d.ts +0 -812
- package/dist/types/server/src/api/database/types.d.ts +0 -80
- package/dist/types/server/src/api/go2rtc/types.d.ts +0 -147
- package/dist/types/server/src/api/schemas/backup.schema.d.ts +0 -211
- package/dist/types/server/src/api/schemas/cameras.schema.d.ts +0 -1864
- package/dist/types/server/src/api/schemas/config.schema.d.ts +0 -102
- package/dist/types/server/src/api/schemas/go2rtc.schema.d.ts +0 -735
- package/dist/types/server/src/api/schemas/plugins.schema.d.ts +0 -72
- package/dist/types/server/src/api/schemas/storage.schema.d.ts +0 -22
- package/dist/types/server/src/api/schemas/system.schema.d.ts +0 -185
- package/dist/types/server/src/api/schemas/users.schema.d.ts +0 -857
- package/dist/types/server/src/api/types/index.d.ts +0 -612
- package/dist/types/server/src/api/websocket/types.d.ts +0 -43
- package/dist/types/server/src/camera/classes.d.ts +0 -2
- package/dist/types/server/src/camera/index.d.ts +0 -92
- package/dist/types/server/src/camera/interfaces.d.ts +0 -17
- package/dist/types/server/src/camera/iou.d.ts +0 -2
- package/dist/types/server/src/camera/polygon.d.ts +0 -4
- package/dist/types/server/src/camera/types.d.ts +0 -17
- package/dist/types/server/src/go2rtc/types.d.ts +0 -15
- package/dist/types/server/src/manager/types.d.ts +0 -15
- package/dist/types/server/src/plugins/schema.d.ts +0 -27
- package/dist/types/server/src/plugins/types.d.ts +0 -49
- package/dist/types/server/src/rpc/namespaces.d.ts +0 -35
- package/dist/types/server/src/rpc/types.d.ts +0 -111
- package/dist/types/server/src/services/config/defaults.d.ts +0 -12
- package/dist/types/server/src/services/config/types.d.ts +0 -162
- package/dist/types/server/src/types.d.ts +0 -34
- package/dist/types/shared/types/index.d.ts +0 -22
package/dist/bundle.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
/*! For license information please see bundle.js.LICENSE.txt */
|
|
2
|
-
var e={69:e=>{var t=1e3,r=60*t,h=60*r,s=24*h,i=7*s,n=365.25*s;function o(e,t,r,s){var i=t>=1.5*r;return Math.round(e/r)+" "+s+(i?"s":"")}e.exports=function(e,a){a=a||{};var c=typeof e;if("string"===c&&e.length>0)return function(e){if((e=String(e)).length>100)return;var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!o)return;var a=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return a*n;case"weeks":case"week":case"w":return a*i;case"days":case"day":case"d":return a*s;case"hours":case"hour":case"hrs":case"hr":case"h":return a*h;case"minutes":case"minute":case"mins":case"min":case"m":return a*r;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}(e);if("number"===c&&isFinite(e))return a.long?function(e){var i=Math.abs(e);if(i>=s)return o(e,i,s,"day");if(i>=h)return o(e,i,h,"hour");if(i>=r)return o(e,i,r,"minute");if(i>=t)return o(e,i,t,"second");return e+" ms"}(e):function(e){var i=Math.abs(e);if(i>=s)return Math.round(e/s)+"d";if(i>=h)return Math.round(e/h)+"h";if(i>=r)return Math.round(e/r)+"m";if(i>=t)return Math.round(e/t)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},142:e=>{var t=1e3,r=60*t,h=60*r,s=24*h,i=7*s,n=365.25*s;function o(e,t,r,s){var i=t>=1.5*r;return Math.round(e/r)+" "+s+(i?"s":"")}e.exports=function(e,a){a=a||{};var c=typeof e;if("string"===c&&e.length>0)return function(e){if((e=String(e)).length>100)return;var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!o)return;var a=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return a*n;case"weeks":case"week":case"w":return a*i;case"days":case"day":case"d":return a*s;case"hours":case"hour":case"hrs":case"hr":case"h":return a*h;case"minutes":case"minute":case"mins":case"min":case"m":return a*r;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}(e);if("number"===c&&isFinite(e))return a.long?function(e){var i=Math.abs(e);if(i>=s)return o(e,i,s,"day");if(i>=h)return o(e,i,h,"hour");if(i>=r)return o(e,i,r,"minute");if(i>=t)return o(e,i,t,"second");return e+" ms"}(e):function(e){var i=Math.abs(e);if(i>=s)return Math.round(e/s)+"d";if(i>=h)return Math.round(e/h)+"h";if(i>=r)return Math.round(e/r)+"m";if(i>=t)return Math.round(e/t)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},287:(e,t,r)=>{e.exports=function(e){function t(e){let r,i,n,o=null;function a(...e){if(!a.enabled)return;const s=a,i=Number(new Date),n=i-(r||i);s.diff=n,s.prev=r,s.curr=i,r=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,i)=>{if("%%"===r)return"%";o++;const n=t.formatters[i];if("function"==typeof n){const t=e[o];r=n.call(s,t),e.splice(o,1),o--}return r})),t.formatArgs.call(s,e);(s.log||t.log).apply(s,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=s,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,n=t.enabled(e)),n),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function s(e,r){const s=t(this.namespace+(void 0===r?":":r)+e);return s.log=this.log,s}function i(e,t){let r=0,s=0,i=-1,n=0;for(;r<e.length;)if(s<t.length&&(t[s]===e[r]||"*"===t[s]))"*"===t[s]?(i=s,n=r,s++):(r++,s++);else{if(-1===i)return!1;s=i+1,n++,r=n}for(;s<t.length&&"*"===t[s];)s++;return s===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(" ",",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(i(e,r))return!1;for(const r of t.names)if(i(e,r))return!0;return!1},t.humanize=r(142),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}},288:(e,t,r)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let s=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(s++,"%c"===e&&(i=s))})),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(287)(t);const{formatters:s}=e.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},413:(e,t,r)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let s=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(s++,"%c"===e&&(i=s))})),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(692)(t);const{formatters:s}=e.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},672:e=>{const t="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,r=()=>t.now(),s=e=>e===1/0||(e=>e&&e===Math.floor(e)&&e>0&&isFinite(e))(e);class i{constructor({max:e=1/0,ttl:t,updateAgeOnGet:r=!1,checkAgeOnGet:i=!1,noUpdateTTL:n=!1,dispose:o,noDisposeOnSet:a=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,void 0!==t&&!s(t))throw new TypeError("ttl must be positive integer or Infinity if set");if(!s(e))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=t,this.max=e,this.updateAgeOnGet=!!r,this.checkAgeOnGet=!!i,this.noUpdateTTL=!!n,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(e,t){if(this.timerExpiration<e)return;this.timer&&clearTimeout(this.timer);const s=setTimeout((()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(const e in this.expirations){this.setTimer(e,e-r());break}}),t);s.unref&&s.unref(),this.timerExpiration=e,this.timer=s}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 e=this.dispose!==i.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(const[t,r]of e)this.dispose(r,t,"delete")}setTTL(e,t=this.ttl){const s=this.expirationMap.get(e);if(void 0!==s){const t=this.expirations[s];!t||t.length<=1?delete this.expirations[s]:this.expirations[s]=t.filter((t=>t!==e))}if(t!==1/0){const s=Math.floor(r()+t);this.expirationMap.set(e,s),this.expirations[s]||(this.expirations[s]=[],this.setTimer(s,t)),this.expirations[s].push(e)}else this.expirationMap.set(e,1/0)}set(e,t,{ttl:r=this.ttl,noUpdateTTL:i=this.noUpdateTTL,noDisposeOnSet:n=this.noDisposeOnSet}={}){if(!s(r))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(e)){i||this.setTTL(e,r);const s=this.data.get(e);s!==t&&(this.data.set(e,t),n||this.dispose(s,e,"set"))}else this.setTTL(e,r),this.data.set(e,t);for(;this.size>this.max;)this.purgeToCapacity();return this}has(e){return this.data.has(e)}getRemainingTTL(e){const t=this.expirationMap.get(e);return t===1/0?t:void 0!==t?Math.max(0,Math.ceil(t-r())):0}get(e,{updateAgeOnGet:t=this.updateAgeOnGet,ttl:r=this.ttl,checkAgeOnGet:s=this.checkAgeOnGet}={}){const i=this.data.get(e);if(!s||0!==this.getRemainingTTL(e))return t&&this.setTTL(e,r),i;this.delete(e)}dispose(e,t){}delete(e){const t=this.expirationMap.get(e);if(void 0!==t){const r=this.data.get(e);this.data.delete(e),this.expirationMap.delete(e);const s=this.expirations[t];return s&&(s.length<=1?delete this.expirations[t]:this.expirations[t]=s.filter((t=>t!==e))),this.dispose(r,e,"delete"),0===this.size&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(const e in this.expirations){const t=this.expirations[e];if(!(this.size-t.length>=this.max)){const e=this.size-this.max,r=[];for(const s of t.splice(0,e))r.push([s,this.data.get(s)]),this.data.delete(s),this.expirationMap.delete(s);for(const[e,t]of r)this.dispose(t,e,"evict");return}{delete this.expirations[e];const r=[];for(const e of t)r.push([e,this.data.get(e)]),this.data.delete(e),this.expirationMap.delete(e);for(const[e,t]of r)this.dispose(t,e,"evict")}}}get size(){return this.data.size}purgeStale(){const e=Math.ceil(r());for(const t in this.expirations){if("Infinity"===t||t>e)return;const r=[...this.expirations[t]||[]],s=[];delete this.expirations[t];for(const e of r)s.push([e,this.data.get(e)]),this.data.delete(e),this.expirationMap.delete(e);for(const[e,t]of s)this.dispose(t,e,"stale")}0===this.size&&this.cancelTimer()}*entries(){for(const e in this.expirations)for(const t of this.expirations[e])yield[t,this.data.get(t)]}*keys(){for(const e in this.expirations)for(const t of this.expirations[e])yield t}*values(){for(const e in this.expirations)for(const t of this.expirations[e])yield this.data.get(t)}[Symbol.iterator](){return this.entries()}}e.exports=i},692:(e,t,r)=>{e.exports=function(e){function t(e){let r,i,n,o=null;function a(...e){if(!a.enabled)return;const s=a,i=Number(new Date),n=i-(r||i);s.diff=n,s.prev=r,s.curr=i,r=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,i)=>{if("%%"===r)return"%";o++;const n=t.formatters[i];if("function"==typeof n){const t=e[o];r=n.call(s,t),e.splice(o,1),o--}return r})),t.formatArgs.call(s,e);(s.log||t.log).apply(s,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=s,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,n=t.enabled(e)),n),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function s(e,r){const s=t(this.namespace+(void 0===r?":":r)+e);return s.log=this.log,s}function i(e,t){let r=0,s=0,i=-1,n=0;for(;r<e.length;)if(s<t.length&&(t[s]===e[r]||"*"===t[s]))"*"===t[s]?(i=s,n=r,s++):(r++,s++);else{if(-1===i)return!1;s=i+1,n++,r=n}for(;s<t.length&&"*"===t[s];)s++;return s===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(" ",",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(i(e,r))return!1;for(const r of t.names)if(i(e,r))return!0;return!1},t.humanize=r(69),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}},779:(e,t,r)=>{var s;!function(e){!function(){var t="object"==typeof globalThis?globalThis:"object"==typeof r.g?r.g:"object"==typeof self?self:"object"==typeof this?this:function(){try{return Function("return this;")()}catch(e){}}()||function(){try{return(0,eval)("(function() { return this; })()")}catch(e){}}(),s=i(e);function i(e,t){return function(r,s){Object.defineProperty(e,r,{configurable:!0,writable:!0,value:s}),t&&t(r,s)}}void 0!==t.Reflect&&(s=i(t.Reflect,s)),function(e,t){var r=Object.prototype.hasOwnProperty,s="function"==typeof Symbol,i=s&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",n=s&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",o="function"==typeof Object.create,a={__proto__:[]}instanceof Array,c=!o&&!a,u={create:o?function(){return de(Object.create(null))}:a?function(){return de({__proto__:null})}:function(){return de({})},has:c?function(e,t){return r.call(e,t)}:function(e,t){return t in e},get:c?function(e,t){return r.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},l=Object.getPrototypeOf(Function),d="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:ue(),p="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:he(),f="function"==typeof WeakMap?WeakMap:le(),m=s?Symbol.for("@reflect-metadata:registry"):void 0,g=ne(),y=oe(g);function b(e,t,r,s){if(L(r)){if(!W(e))throw new TypeError;if(!J(t))throw new TypeError;return R(e,t)}if(!W(e))throw new TypeError;if(!q(t))throw new TypeError;if(!q(s)&&!L(s)&&!U(s))throw new TypeError;return U(s)&&(s=void 0),O(e,t,r=H(r),s)}function v(e,t){function r(r,s){if(!q(r))throw new TypeError;if(!L(s)&&!K(s))throw new TypeError;N(e,t,r,s)}return r}function _(e,t,r,s){if(!q(r))throw new TypeError;return L(s)||(s=H(s)),N(e,t,r,s)}function w(e,t,r){if(!q(t))throw new TypeError;return L(r)||(r=H(r)),A(e,t,r)}function S(e,t,r){if(!q(t))throw new TypeError;return L(r)||(r=H(r)),P(e,t,r)}function C(e,t,r){if(!q(t))throw new TypeError;return L(r)||(r=H(r)),I(e,t,r)}function E(e,t,r){if(!q(t))throw new TypeError;return L(r)||(r=H(r)),M(e,t,r)}function x(e,t){if(!q(e))throw new TypeError;return L(t)||(t=H(t)),j(e,t)}function k(e,t){if(!q(e))throw new TypeError;return L(t)||(t=H(t)),F(e,t)}function T(e,t,r){if(!q(t))throw new TypeError;if(L(r)||(r=H(r)),!q(t))throw new TypeError;L(r)||(r=H(r));var s=ce(t,r,!1);return!L(s)&&s.OrdinaryDeleteMetadata(e,t,r)}function R(e,t){for(var r=e.length-1;r>=0;--r){var s=(0,e[r])(t);if(!L(s)&&!U(s)){if(!J(s))throw new TypeError;t=s}}return t}function O(e,t,r,s){for(var i=e.length-1;i>=0;--i){var n=(0,e[i])(t,r,s);if(!L(n)&&!U(n)){if(!q(n))throw new TypeError;s=n}}return s}function A(e,t,r){if(P(e,t,r))return!0;var s=se(t);return!U(s)&&A(e,s,r)}function P(e,t,r){var s=ce(t,r,!1);return!L(s)&&G(s.OrdinaryHasOwnMetadata(e,t,r))}function I(e,t,r){if(P(e,t,r))return M(e,t,r);var s=se(t);return U(s)?void 0:I(e,s,r)}function M(e,t,r){var s=ce(t,r,!1);if(!L(s))return s.OrdinaryGetOwnMetadata(e,t,r)}function N(e,t,r,s){ce(r,s,!0).OrdinaryDefineOwnMetadata(e,t,r,s)}function j(e,t){var r=F(e,t),s=se(e);if(null===s)return r;var i=j(s,t);if(i.length<=0)return r;if(r.length<=0)return i;for(var n=new p,o=[],a=0,c=r;a<c.length;a++){var u=c[a];n.has(u)||(n.add(u),o.push(u))}for(var l=0,d=i;l<d.length;l++){u=d[l];n.has(u)||(n.add(u),o.push(u))}return o}function F(e,t){var r=ce(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function $(e){if(null===e)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===e?1:6;default:return 6}}function L(e){return void 0===e}function U(e){return null===e}function D(e){return"symbol"==typeof e}function q(e){return"object"==typeof e?null!==e:"function"==typeof e}function B(e,t){switch($(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var r=3===t?"string":5===t?"number":"default",s=Q(e,i);if(void 0!==s){var n=s.call(e,r);if(q(n))throw new TypeError;return n}return z(e,"default"===r?"number":r)}function z(e,t){if("string"===t){var r=e.toString;if(Z(r))if(!q(i=r.call(e)))return i;if(Z(s=e.valueOf))if(!q(i=s.call(e)))return i}else{var s;if(Z(s=e.valueOf))if(!q(i=s.call(e)))return i;var i,n=e.toString;if(Z(n))if(!q(i=n.call(e)))return i}throw new TypeError}function G(e){return!!e}function V(e){return""+e}function H(e){var t=B(e,3);return D(t)?t:V(t)}function W(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function Z(e){return"function"==typeof e}function J(e){return"function"==typeof e}function K(e){switch($(e)){case 3:case 4:return!0;default:return!1}}function Y(e,t){return e===t||e!=e&&t!=t}function Q(e,t){var r=e[t];if(null!=r){if(!Z(r))throw new TypeError;return r}}function X(e){var t=Q(e,n);if(!Z(t))throw new TypeError;var r=t.call(e);if(!q(r))throw new TypeError;return r}function ee(e){return e.value}function te(e){var t=e.next();return!t.done&&t}function re(e){var t=e.return;t&&t.call(e)}function se(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===l)return t;if(t!==l)return t;var r=e.prototype,s=r&&Object.getPrototypeOf(r);if(null==s||s===Object.prototype)return t;var i=s.constructor;return"function"!=typeof i||i===e?t:i}function ie(){var e,r,s,i;L(m)||void 0===t.Reflect||m in t.Reflect||"function"!=typeof t.Reflect.defineMetadata||(e=ae(t.Reflect));var n=new f,o={registerProvider:a,getProvider:u,setProvider:g};return o;function a(t){if(!Object.isExtensible(o))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===t:break;case L(r):r=t;break;case r===t:break;case L(s):s=t;break;case s===t:break;default:void 0===i&&(i=new p),i.add(t)}}function c(t,n){if(!L(r)){if(r.isProviderFor(t,n))return r;if(!L(s)){if(s.isProviderFor(t,n))return r;if(!L(i))for(var o=X(i);;){var a=te(o);if(!a)return;var c=ee(a);if(c.isProviderFor(t,n))return re(o),c}}}if(!L(e)&&e.isProviderFor(t,n))return e}function u(e,t){var r,s=n.get(e);return L(s)||(r=s.get(t)),L(r)?(L(r=c(e,t))||(L(s)&&(s=new d,n.set(e,s)),s.set(t,r)),r):r}function l(e){if(L(e))throw new TypeError;return r===e||s===e||!L(i)&&i.has(e)}function g(e,t,r){if(!l(r))throw new Error("Metadata provider not registered.");var s=u(e,t);if(s!==r){if(!L(s))return!1;var i=n.get(e);L(i)&&(i=new d,n.set(e,i)),i.set(t,r)}return!0}}function ne(){var e;return!L(m)&&q(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[m]),L(e)&&(e=ie()),!L(m)&&q(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,m,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function oe(e){var t=new f,r={isProviderFor:function(e,r){var s=t.get(e);return!L(s)&&s.has(r)},OrdinaryDefineOwnMetadata:o,OrdinaryHasOwnMetadata:i,OrdinaryGetOwnMetadata:n,OrdinaryOwnMetadataKeys:a,OrdinaryDeleteMetadata:c};return g.registerProvider(r),r;function s(s,i,n){var o=t.get(s),a=!1;if(L(o)){if(!n)return;o=new d,t.set(s,o),a=!0}var c=o.get(i);if(L(c)){if(!n)return;if(c=new d,o.set(i,c),!e.setProvider(s,i,r))throw o.delete(i),a&&t.delete(s),new Error("Wrong provider for target.")}return c}function i(e,t,r){var i=s(t,r,!1);return!L(i)&&G(i.has(e))}function n(e,t,r){var i=s(t,r,!1);if(!L(i))return i.get(e)}function o(e,t,r,i){s(r,i,!0).set(e,t)}function a(e,t){var r=[],i=s(e,t,!1);if(L(i))return r;for(var n=X(i.keys()),o=0;;){var a=te(n);if(!a)return r.length=o,r;var c=ee(a);try{r[o]=c}catch(e){try{re(n)}finally{throw e}}o++}}function c(e,r,i){var n=s(r,i,!1);if(L(n))return!1;if(!n.delete(e))return!1;if(0===n.size){var o=t.get(r);L(o)||(o.delete(i),0===o.size&&t.delete(o))}return!0}}function ae(e){var t=e.defineMetadata,r=e.hasOwnMetadata,s=e.getOwnMetadata,i=e.getOwnMetadataKeys,n=e.deleteMetadata,o=new f,a={isProviderFor:function(e,t){var r=o.get(e);return!(L(r)||!r.has(t))||!!i(e,t).length&&(L(r)&&(r=new p,o.set(e,r)),r.add(t),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:s,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:n};return a}function ce(e,t,r){var s=g.getProvider(e,t);if(!L(s))return s;if(r){if(g.setProvider(e,t,y))return y;throw new Error("Illegal state.")}}function ue(){var e={},t=[],r=function(){function e(e,t,r){this._index=0,this._keys=e,this._values=t,this._selector=r}return e.prototype["@@iterator"]=function(){return this},e.prototype[n]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var r=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:r,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}(),s=function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var r=this._find(e,!0);return this._values[r]=t,this},t.prototype.delete=function(t){var r=this._find(t,!1);if(r>=0){for(var s=this._keys.length,i=r+1;i<s;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,Y(t,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new r(this._keys,this._values,i)},t.prototype.values=function(){return new r(this._keys,this._values,o)},t.prototype.entries=function(){return new r(this._keys,this._values,a)},t.prototype["@@iterator"]=function(){return this.entries()},t.prototype[n]=function(){return this.entries()},t.prototype._find=function(e,t){if(!Y(this._cacheKey,e)){this._cacheIndex=-1;for(var r=0;r<this._keys.length;r++)if(Y(this._keys[r],e)){this._cacheIndex=r;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();return s;function i(e,t){return e}function o(e,t){return t}function a(e,t){return[e,t]}}function he(){return function(){function e(){this._map=new d}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[n]=function(){return this.keys()},e}()}function le(){var e=16,t=u.create(),s=i();return function(){function e(){this._key=i()}return e.prototype.has=function(e){var t=n(e,!1);return void 0!==t&&u.has(t,this._key)},e.prototype.get=function(e){var t=n(e,!1);return void 0!==t?u.get(t,this._key):void 0},e.prototype.set=function(e,t){return n(e,!0)[this._key]=t,this},e.prototype.delete=function(e){var t=n(e,!1);return void 0!==t&&delete t[this._key]},e.prototype.clear=function(){this._key=i()},e}();function i(){var e;do{e="@@WeakMap@@"+c()}while(u.has(t,e));return t[e]=!0,e}function n(e,t){if(!r.call(e,s)){if(!t)return;Object.defineProperty(e,s,{value:u.create()})}return e[s]}function o(e,t){for(var r=0;r<t;++r)e[r]=255*Math.random()|0;return e}function a(e){if("function"==typeof Uint8Array){var t=new Uint8Array(e);return"undefined"!=typeof crypto?crypto.getRandomValues(t):"undefined"!=typeof msCrypto?msCrypto.getRandomValues(t):o(t,e),t}return o(new Array(e),e)}function c(){var t=a(e);t[6]=79&t[6]|64,t[8]=191&t[8]|128;for(var r="",s=0;s<e;++s){var i=t[s];4!==s&&6!==s&&8!==s||(r+="-"),i<16&&(r+="0"),r+=i.toString(16).toLowerCase()}return r}}function de(e){return e.__=void 0,delete e.__,e}e("decorate",b),e("metadata",v),e("defineMetadata",_),e("hasMetadata",w),e("hasOwnMetadata",S),e("getMetadata",C),e("getOwnMetadata",E),e("getMetadataKeys",x),e("getOwnMetadataKeys",k),e("deleteMetadata",T)}(s,t),void 0===t.Reflect&&(t.Reflect=e)}()}(s||(s={}))}},t={};function r(s){var i=t[s];if(void 0!==i)return i.exports;var n=t[s]={exports:{}};return e[s](n,n.exports,r),n.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var s in t)r.o(t,s)&&!r.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);class s{baseURL;abortControllers=new Set;constructor(e){this.baseURL=`${e}/api`}async request(e,t,r,s={}){const i=new AbortController;this.abortControllers.add(i);const n=setTimeout((()=>{i.abort(),this.abortControllers.delete(i)}),15e3);try{const n=await fetch(`${this.baseURL}${t}`,{method:e,headers:{"Content-Type":"application/json",...s.headers},body:r?JSON.stringify(r):void 0,signal:i.signal,...s});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return n}finally{clearTimeout(n),this.abortControllers.delete(i)}}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,r){return this.request("POST",e,t,r)}}const i={FAILED:"CONNECTION_FAILED",TIMEOUT:"CONNECTION_TIMEOUT",NOT_CONNECTED:"CONNECTION_NOT_CONNECTED",INVALID_STATE:"CONNECTION_INVALID_STATE",INTERNAL_ERROR:"CONNECTION_INTERNAL_ERROR"},n={MISSING:"CONFIG_MISSING",INVALID:"CONFIG_INVALID",INTERNAL_ERROR:"CONFIG_INTERNAL_ERROR"},o={INVALID_CREDENTIALS:"AUTH_INVALID_CREDENTIALS",UNAUTHORIZED:"AUTH_UNAUTHORIZED",FORBIDDEN:"AUTH_FORBIDDEN",INTERNAL_ERROR:"AUTH_INTERNAL_ERROR"},a={REGISTRATION_FAILED:"CLIENT_REGISTRATION_FAILED",UNREGISTRATION_FAILED:"CLIENT_UNREGISTRATION_FAILED",NOT_FOUND:"CLIENT_NOT_FOUND",INVALID_STATE:"CLIENT_INVALID_STATE",INTERNAL_ERROR:"CLIENT_INTERNAL_ERROR"},c={INVALID_FORMAT:"MESSAGE_INVALID_FORMAT",DELIVERY_FAILED:"MESSAGE_DELIVERY_FAILED",TIMEOUT:"MESSAGE_TIMEOUT",EXECUTION_FAILED:"MESSAGE_EXECUTION_FAILED",INTERNAL_ERROR:"MESSAGE_INTERNAL_ERROR"},u={METHOD_NOT_FOUND:"RPC_METHOD_NOT_FOUND",INVALID_REQUEST:"RPC_INVALID_REQUEST",INTERNAL_ERROR:"RPC_INTERNAL_ERROR",CONNECTION_FAILED:"RPC_CONNECTION_FAILED"},l={INTERNAL_ERROR:"REGISTRY_INTERNAL_ERROR"},d={JOIN_FAILED:"CLUSTER_JOIN_FAILED",SYNC_FAILED:"CLUSTER_SYNC_FAILED",COMMUNICATION_FAILED:"CLUSTER_COMMUNICATION_FAILED",INVALID_STATE:"CLUSTER_INVALID_STATE",NODE_NOT_FOUND:"CLUSTER_NODE_NOT_FOUND",INSTANCE_NOT_FOUND:"CLUSTER_INSTANCE_NOT_FOUND",INTERNAL_ERROR:"CLUSTER_INTERNAL_ERROR"};class p extends Error{code;details;cause;constructor(e,t,r,s){super(e),this.code=t,this.details=r,this.cause=s,this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),this.cause&&(this.cause={name:this.cause.name,message:this.cause.message,...this.cause instanceof p?{code:this.cause.code,details:this.cause.details}:{code:"INTERNAL_ERROR",details:{description:this.cause.message}}})}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack,cause:this.cause}}static fromJSON(e){return new p(e.message,e.code,e.details,e.cause?p.fromJSON(e.cause):void 0)}}class f extends p{constructor(e,t,r){super(e,i.INTERNAL_ERROR,t,r)}}class m extends p{constructor(e,t,r){super(e,n.INTERNAL_ERROR,t,r)}}class g extends p{constructor(e,t,r){super(e,o.INTERNAL_ERROR,t,r)}}class y extends p{constructor(e,t,r){super(e,a.INTERNAL_ERROR,t,r)}}class b extends p{constructor(e,t,r){super(e,c.INTERNAL_ERROR,t,r)}}class v extends p{constructor(e,t,r){super(e,u.INTERNAL_ERROR,t,r)}}class _ extends p{constructor(e,t,r){super(e,l.INTERNAL_ERROR,t,r)}}class w extends p{constructor(e,t,r){super(e,d.INTERNAL_ERROR,t,r)}}class S{static create(e,t,r,s){if(t instanceof p)return t;const i=t instanceof Error?t:new Error(String(t)),n=function(e){function t(e){let r=!1;try{"undefined"!=typeof Buffer&&(r=e instanceof Buffer)}catch{r=!1}return e instanceof ArrayBuffer||e instanceof Uint8Array||r||ArrayBuffer.isView(e)?"<binary>":Array.isArray(e)?e.map(t):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,r])=>[e,t(r)]))):e}return t(e??{})}(s);switch(e){case"connection":return new f(r,n,i);case"config":return new m(r,n,i);case"auth":return new g(r,n,i);case"client":return new y(r,n,i);case"message":return new b(r,n,i);case"rpc":return new v(r,n,i);case"registry":return new _(r,n,i);case"cluster":return new w(r,n,i)}}static connection={connectionFailed:(e,t)=>S.create("connection",e,"Connection failed",{description:"Failed to establish connection",code:i.FAILED,...t}),subscribeFailed:(e,t)=>S.create("connection",e,"Subscription failed",{description:"Failed to subscribe to subject",code:i.INTERNAL_ERROR,...t}),requestFailed:(e,t)=>S.create("connection",e,"Request failed",{description:"Failed to send request",code:i.INTERNAL_ERROR,...t}),timeout:(e,t)=>S.create("connection",e,"Connection timeout",{description:"Connection attempt timed out",code:i.TIMEOUT,...t}),notConnected:(e,t)=>S.create("connection",e,"Not connected",{description:"Connection is not established",code:i.INTERNAL_ERROR,...t}),invalidState:(e,t)=>S.create("connection",e,"Invalid connection state",{description:"Connection is in invalid state",code:i.INVALID_STATE,...t}),internalError:(e,t)=>S.create("connection",e,"Internal connection error",{description:"Internal connection error",code:i.INTERNAL_ERROR,...t})};static config={missing:(e,t)=>S.create("config",e,"Missing configuration",{description:"Required configuration is missing",code:n.MISSING,...t}),invalid:(e,t)=>S.create("config",e,"Invalid configuration",{description:"Invalid configuration provided",code:n.INVALID,...t}),internalError:(e,t)=>S.create("config",e,"Internal configuration error",{description:"Internal configuration error",code:n.INTERNAL_ERROR,...t})};static auth={unauthorized:(e,t)=>S.create("auth",e,"Unauthorized",{description:"Authentication failed",code:o.UNAUTHORIZED,...t}),forbidden:(e,t)=>S.create("auth",e,"Forbidden",{description:"Insufficient permissions",code:o.FORBIDDEN,...t}),internalError:(e,t)=>S.create("auth",e,"Internal auth error",{description:"Internal auth error",code:o.INTERNAL_ERROR,...t})};static client={registrationFailed:(e,t)=>S.create("client",e,"Registration failed",{description:"Failed to register client",code:a.REGISTRATION_FAILED,...t}),notFound:(e,t)=>S.create("client",e,"Client not found",{description:"Requested client could not be found",code:a.NOT_FOUND,...t}),invalidState:(e,t)=>S.create("client",e,"Invalid client state",{description:"Client is in invalid state",code:a.INVALID_STATE,...t}),internalError:(e,t)=>S.create("client",e,"Internal client error",{description:"Internal client error",code:a.INTERNAL_ERROR,...t})};static message={invalidFormat:(e,t)=>S.create("message",e,"Invalid message format",{description:"Failed to parse message",code:c.INVALID_FORMAT,...t}),deliveryFailed:(e,t)=>S.create("message",e,"Message delivery failed",{description:"Failed to deliver message",code:c.DELIVERY_FAILED,...t}),timeout:(e,t)=>S.create("message",e,"Message timeout",{description:"Message processing timed out",code:c.TIMEOUT,...t}),executionFailed:(e,t)=>S.create("message",e,"Message execution failed",{description:"Failed to execute message",code:c.EXECUTION_FAILED,...t}),internalError:(e,t)=>S.create("message",e,"Internal message error",{description:"Internal message error",code:c.INTERNAL_ERROR,...t})};static cluster={joinFailed:(e,t)=>S.create("cluster",e,"Failed to join cluster",{description:"Failed to join cluster",code:d.JOIN_FAILED,...t}),syncFailed:(e,t)=>S.create("cluster",e,"Failed to sync cluster",{description:"Failed to sync cluster",code:d.SYNC_FAILED,...t}),nodeNotFound:(e,t)=>S.create("cluster",e,"Node not found",{description:"Requested node could not be found",code:d.NODE_NOT_FOUND,...t}),instanceNotFound:(e,t)=>S.create("cluster",e,"Instance not found",{description:"Requested instance could not be found",code:d.INSTANCE_NOT_FOUND,...t}),communicationFailed:(e,t)=>S.create("cluster",e,"Communication failed",{description:"Cluster communication failed",code:d.COMMUNICATION_FAILED,...t}),invalidState:(e,t)=>S.create("cluster",e,"Invalid cluster state",{description:"Cluster is in invalid state",code:d.INVALID_STATE,...t}),internalError:(e,t)=>S.create("cluster",e,"Internal cluster error",{description:"Internal cluster error",code:d.INTERNAL_ERROR,...t})};static registry={internalError:(e,t)=>S.create("registry",e,"Internal registry error",{description:"Internal registry error",code:l.INTERNAL_ERROR,...t})};static rpc={methodNotFound:(e,t,r)=>S.create("rpc",t,`Method not found: ${e}`,{description:"Requested method could not be found",code:u.METHOD_NOT_FOUND,...r}),invalidRequest:(e,t)=>S.create("rpc",e,"Invalid request",{description:"Invalid RPC request",code:u.INVALID_REQUEST,...t}),requestFailed:(e,t)=>S.create("rpc",e,"RPC request failed",{description:"Failed to send RPC request",code:u.INTERNAL_ERROR,...t}),executionFailed:(e,t)=>S.create("rpc",e,"RPC execution failed",{description:"Failed to execute RPC request",code:u.INTERNAL_ERROR,...t}),connectionFailed:(e,t)=>S.create("rpc",e,"Failed to get RPC connection",{description:"Failed to get RPC connection",code:u.CONNECTION_FAILED,...t}),internalError:(e,t)=>S.create("rpc",e,"Internal RPC error",{description:"Internal RPC error",code:u.INTERNAL_ERROR,...t})};static async handle(e,t,r,s){try{return await e()}catch(e){throw S.create(t,e,r,s)}}}class C{static getPluginToPluginSubject(e,t){return this.createRoutingPattern("plugin","plugin",e,t)}static getPluginToServiceSubject(e,t){return this.createRoutingPattern("plugin","service",e,t)}static getServiceToServiceSubject(e,t){return this.createRoutingPattern("service","service",e,t)}static getServiceToPluginSubject(e,t){return this.createRoutingPattern("service","plugin",e,t)}static getPluginToServerSubject(e,t){return this.createRoutingPattern("plugin","server",e,t)}static getServiceToServerSubject(e,t){return this.createRoutingPattern("service","server",e,t)}static getServerToPluginSubject(e,t){return this.createRoutingPattern("server","plugin",e,t)}static getServerToServiceSubject(e,t){return this.createRoutingPattern("server","service",e,t)}static createRoutingMetadata(e,t,r,s){const i={source:{type:e,id:t}};return r&&s&&(i.target={type:r,id:s}),i}static createRoutingPattern(e,t,r,s){return s?`${e}.${t}.${r}.${s}`:`${e}.${t}.${r}.*`}}class E{static validateMetadata(e){if(!e.id)throw S.config.invalid(void 0,{description:"Invalid ID in metadata",code:n.INVALID,metadata:{metadata:e}});if(!e.name)throw S.config.invalid(void 0,{description:"Invalid name in metadata",code:n.INVALID,metadata:{metadata:e}})}static validateConnectionOptions(e){if(E.validateMetadata(e.metadata),!e.endpoints||0===e.endpoints.length)throw S.config.invalid(void 0,{description:"No NATS endpoints provided",code:n.INVALID,metadata:{endpoints:e.endpoints}});if(!e.auth)throw S.config.invalid(void 0,{description:"No authentication configuration provided",code:o.INVALID_CREDENTIALS});if("server"in e.auth){const{server:t,cluster:r}=e.auth;if(!t||"object"!=typeof t)throw S.config.invalid(void 0,{description:"Missing server authentication configuration",code:o.INVALID_CREDENTIALS});if(!r||"object"!=typeof r)throw S.config.invalid(void 0,{description:"Missing cluster authentication configuration",code:o.INVALID_CREDENTIALS});if("string"!=typeof t.user||0===t.user.length)throw S.config.invalid(void 0,{description:"Invalid server username provided",code:o.INVALID_CREDENTIALS,metadata:{provided:{user:t.user}}});if("string"!=typeof t.password||0===t.password.length)throw S.config.invalid(void 0,{description:"Invalid server password provided",code:o.INVALID_CREDENTIALS,metadata:{provided:{password:"***"}}});if("string"!=typeof r.user||0===r.user.length)throw S.config.invalid(void 0,{description:"Invalid cluster username provided",code:o.INVALID_CREDENTIALS,metadata:{provided:{user:r.user}}});if("string"!=typeof r.password||0===r.password.length)throw S.config.invalid(void 0,{description:"Invalid cluster password provided",code:o.INVALID_CREDENTIALS,metadata:{provided:{password:"***"}}})}else{const{user:t,password:r}=e.auth;if("string"!=typeof t||0===t.length)throw S.config.invalid(void 0,{description:"Invalid username provided",code:o.INVALID_CREDENTIALS,metadata:{provided:{user:t}}});if("string"!=typeof r||0===r.length)throw S.config.invalid(void 0,{description:"Invalid password provided",code:o.INVALID_CREDENTIALS,metadata:{provided:{password:"***"}}})}}}var x=r(288);const k=new Uint8Array(0),T=new TextEncoder,R=new TextDecoder;function O(...e){const t=[];for(let r=0;r<e.length;r++)t.push(T.encode(e[r]));return 0===t.length?k:1===t.length?t[0]:function(...e){let t=0;for(let r=0;r<e.length;r++)t+=e[r].length;const r=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++)r.set(e[t],s),s+=e[t].length;return r}(...t)}function A(e){return e&&0!==e.length?R.decode(e):""}const P="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";function I(e){globalThis?.crypto?.getRandomValues?globalThis.crypto.getRandomValues(e):function(e){for(let t=0;t<e.length;t++)e[t]=Math.floor(255*Math.random())}(e)}const M=new class{buf;seq;inc;inited;constructor(){this.buf=new Uint8Array(22),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){this.seq=Math.floor(0xcfd41b9100000*Math.random()),this.inc=Math.floor(300*Math.random()+33)}setPre(){const e=new Uint8Array(12);I(e);for(let t=0;t<12;t++){const r=e[t]%36;this.buf[t]=P.charCodeAt(r)}}fillSeq(){let e=this.seq;for(let t=21;t>=12;t--)this.buf[t]=P.charCodeAt(e%36),e=Math.floor(e/36)}next(){return this.inited||this.init(),this.seq+=this.inc,this.seq>0xcfd41b9100000&&(this.setPre(),this.initSeqAndInc()),this.fillSeq(),String.fromCharCode.apply(String,this.buf)}reset(){this.init()}};var N,j,F;!function(e){e.Disconnect="disconnect",e.Reconnect="reconnect",e.Update="update",e.LDM="ldm",e.Error="error"}(N||(N={})),function(e){e.Reconnecting="reconnecting",e.PingTimer="pingTimer",e.StaleConnection="staleConnection",e.ClientInitiatedReconnect="client initiated reconnect"}(j||(j={})),function(e){e.ApiError="BAD API",e.BadAuthentication="BAD_AUTHENTICATION",e.BadCreds="BAD_CREDS",e.BadHeader="BAD_HEADER",e.BadJson="BAD_JSON",e.BadPayload="BAD_PAYLOAD",e.BadSubject="BAD_SUBJECT",e.Cancelled="CANCELLED",e.ConnectionClosed="CONNECTION_CLOSED",e.ConnectionDraining="CONNECTION_DRAINING",e.ConnectionRefused="CONNECTION_REFUSED",e.ConnectionTimeout="CONNECTION_TIMEOUT",e.Disconnect="DISCONNECT",e.InvalidOption="INVALID_OPTION",e.InvalidPayload="INVALID_PAYLOAD",e.MaxPayloadExceeded="MAX_PAYLOAD_EXCEEDED",e.NoResponders="503",e.NotFunction="NOT_FUNC",e.RequestError="REQUEST_ERROR",e.ServerOptionNotAvailable="SERVER_OPT_NA",e.SubClosed="SUB_CLOSED",e.SubDraining="SUB_DRAINING",e.Timeout="TIMEOUT",e.Tls="TLS",e.Unknown="UNKNOWN_ERROR",e.WssRequired="WSS_REQUIRED",e.JetStreamInvalidAck="JESTREAM_INVALID_ACK",e.JetStream404NoMessages="404",e.JetStream408RequestTimeout="408",e.JetStream409MaxAckPendingExceeded="409",e.JetStream409="409",e.JetStreamNotEnabled="503",e.JetStreamIdleHeartBeat="IDLE_HEARTBEAT",e.AuthorizationViolation="AUTHORIZATION_VIOLATION",e.AuthenticationExpired="AUTHENTICATION_EXPIRED",e.ProtocolError="NATS_PROTOCOL_ERR",e.PermissionsViolation="PERMISSIONS_VIOLATION",e.AuthenticationTimeout="AUTHENTICATION_TIMEOUT",e.AccountExpired="ACCOUNT_EXPIRED"}(F||(F={}));class ${messages;constructor(){this.messages=new Map,this.messages.set(F.InvalidPayload,"Invalid payload type - payloads can be 'binary', 'string', or 'json'"),this.messages.set(F.BadJson,"Bad JSON"),this.messages.set(F.WssRequired,"TLS is required, therefore a secure websocket connection is also required")}static getMessage(e){return L.getMessage(e)}getMessage(e){return this.messages.get(e)||e}}const L=new $;class U extends Error{name;message;code;permissionContext;chainedError;api_error;constructor(e,t,r){super(e),this.name="NatsError",this.message=e,this.code=t,this.chainedError=r}static errorForCode(e,t){const r=$.getMessage(e);return new U(r,e,t)}isAuthError(){return this.code===F.AuthenticationExpired||this.code===F.AuthorizationViolation||this.code===F.AccountExpired}isAuthTimeout(){return this.code===F.AuthenticationTimeout}isPermissionError(){return this.code===F.PermissionsViolation}isProtocolError(){return this.code===F.ProtocolError}isJetStreamError(){return void 0!==this.api_error}jsError(){return this.api_error?this.api_error:null}}var D,q,B;!function(e){e[e.Exact=0]="Exact",e[e.CanonicalMIME=1]="CanonicalMIME",e[e.IgnoreCase=2]="IgnoreCase"}(D||(D={})),function(e){e.Timer="timer",e.Count="count",e.JitterTimer="jitterTimer",e.SentinelMsg="sentinelMsg"}(q||(q={})),function(e){e.STATS="io.nats.micro.v1.stats_response",e.INFO="io.nats.micro.v1.info_response",e.PING="io.nats.micro.v1.ping_response"}(B||(B={}));const z="Nats-Service-Error",G="Nats-Service-Error-Code";class V extends Error{code;constructor(e,t){super(t),this.code=e}static isServiceError(e){return null!==V.toServiceError(e)}static toServiceError(e){const t=e?.headers?.get(G)||"";if(""!==t){const r=parseInt(t)||400,s=e?.headers?.get(z)||"";return new V(r,s.length?s:t)}return null}}function H(e=""){if("string"!=typeof(e=e||"_INBOX"))throw new Error("prefix must be a string");return e.split(".").forEach((t=>{if("*"===t||">"===t)throw new Error(`inbox prefixes cannot have wildcards '${e}'`)})),`${e}.${M.next()}`}const W="127.0.0.1";var Z;function J(e,...t){for(let r=0;r<t.length;r++){const s=t[r];Object.keys(s).forEach((function(t){e[t]=s[t]}))}return e}function K(e){return R.decode(e).replace(/\n/g,"␊").replace(/\r/g,"␍")}function Y(e,t=!0){const r=t?U.errorForCode(F.Timeout):null;let s,i;const n=new Promise(((t,n)=>{s={cancel:()=>{i&&clearTimeout(i)}},i=setTimeout((()=>{n(null===r?U.errorForCode(F.Timeout):r)}),e)}));return Object.assign(n,s)}function Q(e=0){let t;const r=new Promise((r=>{const s=setTimeout((()=>{r()}),e);t={cancel:()=>{s&&clearTimeout(s)}}}));return Object.assign(r,t)}function X(){let e={};const t=new Promise(((t,r)=>{e={resolve:t,reject:r}}));return Object.assign(t,e)}function ee(e){for(let t=e.length-1;t>0;t--){const r=Math.floor(Math.random()*(t+1));[e[t],e[r]]=[e[r],e[t]]}return e}!function(e){e.PING="PING",e.STATS="STATS",e.INFO="INFO"}(Z||(Z={}));function te(e=[0,250,250,500,500,3e3,5e3]){Array.isArray(e)||(e=[0,250,250,500,500,3e3,5e3]);const t=e.length-1;return{backoff:r=>function(e){return 0===e?0:Math.floor(e/2+Math.random()*e)}(r>t?e[t]:e[r])}}function re(e){return 1e6*e}function se(e){return Math.floor(e/1e6)}function ie(e){let t=!0;const r=new Array(e.length);for(let s=0;s<e.length;s++){let i=e.charCodeAt(s);if(58===i||i<33||i>126)throw new U(`'${e[s]}' is not a valid character for a header key`,F.BadHeader);t&&97<=i&&i<=122?i-=32:!t&&65<=i&&i<=90&&(i+=32),r[s]=i,t=45==i}return String.fromCharCode(...r)}function ne(e=0,t=""){if(0===e&&""!==t||e>0&&""===t)throw new Error("setting status requires both code and description");return new ae(e,t)}const oe="NATS/1.0";class ae{_code;headers;_description;constructor(e=0,t=""){this._code=e,this._description=t,this.headers=new Map}[Symbol.iterator](){return this.headers.entries()}size(){return this.headers.size}equals(e){if(e&&this.headers.size===e.headers.size&&this._code===e._code){for(const[t,r]of this.headers){const s=e.values(t);if(r.length!==s.length)return!1;const i=[...r].sort(),n=[...s].sort();for(let e=0;e<i.length;e++)if(i[e]!==n[e])return!1}return!0}return!1}static decode(e){const t=new ae,r=R.decode(e).split("\r\n"),h=r[0];if(h!==oe){let e=h.replace(oe,"").trim();if(e.length>0){t._code=parseInt(e,10),isNaN(t._code)&&(t._code=0);const r=t._code.toString();e=e.replace(r,""),t._description=e.trim()}}return r.length>=1&&r.slice(1).map((e=>{if(e){const r=e.indexOf(":");if(r>-1){const s=e.slice(0,r),i=e.slice(r+1).trim();t.append(s,i)}}})),t}toString(){if(0===this.headers.size&&0===this._code)return"";let e=oe;this._code>0&&""!==this._description&&(e+=` ${this._code} ${this._description}`);for(const[t,r]of this.headers)for(let s=0;s<r.length;s++)e=`${e}\r\n${t}: ${r[s]}`;return`${e}\r\n\r\n`}encode(){return T.encode(this.toString())}static validHeaderValue(e){if(/[\r\n]/.test(e))throw new U("invalid header value - \\r and \\n are not allowed.",F.BadHeader);return e.trim()}keys(){const e=[];for(const t of this.headers.keys())e.push(t);return e}findKeys(e,t=D.Exact){const r=this.keys();switch(t){case D.Exact:return r.filter((t=>t===e));case D.CanonicalMIME:return e=ie(e),r.filter((t=>t===e));default:{const t=e.toLowerCase();return r.filter((e=>t===e.toLowerCase()))}}}get(e,t=D.Exact){const r=this.findKeys(e,t);if(r.length){const e=this.headers.get(r[0]);if(e)return Array.isArray(e)?e[0]:e}return""}last(e,t=D.Exact){const r=this.findKeys(e,t);if(r.length){const e=this.headers.get(r[0]);if(e)return Array.isArray(e)?e[e.length-1]:e}return""}has(e,t=D.Exact){return this.findKeys(e,t).length>0}set(e,t,r=D.Exact){this.delete(e,r),this.append(e,t,r)}append(e,t,r=D.Exact){const s=ie(e);r===D.CanonicalMIME&&(e=s);const i=this.findKeys(e,r);e=i.length>0?i[0]:e;const n=ae.validHeaderValue(t);let o=this.headers.get(e);o||(o=[],this.headers.set(e,o)),o.push(n)}values(e,t=D.Exact){const r=[];return this.findKeys(e,t).forEach((e=>{const t=this.headers.get(e);t&&r.push(...t)})),r}delete(e,t=D.Exact){this.findKeys(e,t).forEach((e=>{this.headers.delete(e)}))}get hasError(){return this._code>=300}get status(){return`${this._code} ${this._description}`.trim()}toRecord(){const e={};return this.keys().forEach((t=>{e[t]=this.values(t)})),e}get code(){return this._code}get description(){return this._description}static fromRecord(e){const h=new ae;for(const t in e)h.headers.set(t,e[t]);return h}}function ce(){return{encode:e=>T.encode(e),decode:e=>R.decode(e)}}function ue(e){return{encode(e){try{return void 0===e&&(e=null),T.encode(JSON.stringify(e))}catch(e){throw U.errorForCode(F.BadJson,e)}},decode(t){try{return JSON.parse(R.decode(t),e)}catch(e){throw U.errorForCode(F.BadJson,e)}}}}function he(e){return e&&0===e.data.length&&503===e.headers?.code?U.errorForCode(F.NoResponders):null}class le{_headers;_msg;_rdata;_reply;_subject;publisher;static jc;constructor(e,t,r){this._msg=e,this._rdata=t,this.publisher=r}get subject(){return this._subject||(this._subject=R.decode(this._msg.subject)),this._subject}get reply(){return this._reply||(this._reply=R.decode(this._msg.reply)),this._reply}get sid(){return this._msg.sid}get headers(){if(this._msg.hdr>-1&&!this._headers){const e=this._rdata.subarray(0,this._msg.hdr);this._headers=ae.decode(e)}return this._headers}get data(){return this._rdata?this._msg.hdr>-1?this._rdata.subarray(this._msg.hdr):this._rdata:new Uint8Array(0)}respond(e=k,t){return!!this.reply&&(this.publisher.publish(this.reply,e,t),!0)}size(){return this._msg.subject.length+(this._msg.reply?.length||0)+(-1===this._msg.size?0:this._msg.size)}json(e){return ue(e).decode(this.data)}string(){return R.decode(this.data)}requestInfo(){const e=this.headers?.get("Nats-Request-Info");return e?JSON.parse(e,(function(e,t){return"start"!==e&&"stop"!==e||""===t?t:new Date(Date.parse(t))})):null}}function de(e){return fe("durable",e)}function pe(e){return fe("stream",e)}function fe(e,t=""){if(""===t)throw Error(`${e} name required`);return[".","*",">","/","\\"," ","\t","\n","\r"].forEach((r=>{if(-1!==t.indexOf(r)){switch(r){case"\n":r="\\n";break;case"\r":r="\\r";break;case"\t":r="\\t"}throw Error(`invalid ${e} name - ${e} name cannot contain '${r}'`)}})),""}function me(e,t=""){if(""===t)throw Error(`${e} name required`);const r=function(e=""){if(""===e)throw Error("name required");const t=/^[-\w]+$/g,r=e.match(t);if(null===r)for(const r of e.split("")){if(null===r.match(t))return`cannot contain '${r}'`}return""}(t);if(r.length)throw new Error(`invalid ${e} name - ${e} name ${r}`)}function ge(e){if(e.data.length>0)return!1;const h=e.headers;return!!h&&(h.code>=100&&h.code<200)}function ye(e){return ge(e)&&"Idle Heartbeat"===e.headers?.description}function be(e){if(0!==e.data.length)return null;const h=e.headers;return h?_e(h.code,h.description):null}var ve;!function(e){e.MaxBatchExceeded="exceeded maxrequestbatch of",e.MaxExpiresExceeded="exceeded maxrequestexpires of",e.MaxBytesExceeded="exceeded maxrequestmaxbytes of",e.MaxMessageSizeExceeded="message size exceeds maxbytes",e.PushConsumer="consumer is push based",e.MaxWaitingExceeded="exceeded maxwaiting",e.IdleHeartbeatMissed="idle heartbeats missed",e.ConsumerDeleted="consumer deleted"}(ve||(ve={}));function _e(e,t=""){if(e<300)return null;switch(t=t.toLowerCase(),e){case 404:return new U(t,F.JetStream404NoMessages);case 408:return new U(t,F.JetStream408RequestTimeout);case 409:{const e=t.startsWith(ve.IdleHeartbeatMissed)?F.JetStreamIdleHeartBeat:F.JetStream409;return new U(t,e)}case 503:return U.errorForCode(F.JetStreamNotEnabled,new Error(t));default:return""===t&&(t=F.Unknown),new U(t,`${e}`)}}class we{inflight;processed;received;noIterator;iterClosed;done;signal;yields;filtered;pendingFiltered;ingestionFilterFn;protocolFilterFn;dispatchedFn;ctx;_data;err;time;yielding;constructor(){this.inflight=0,this.filtered=0,this.pendingFiltered=0,this.processed=0,this.received=0,this.noIterator=!1,this.done=!1,this.signal=X(),this.yields=[],this.iterClosed=X(),this.time=0,this.yielding=!1}[Symbol.asyncIterator](){return this.iterate()}push(e){if(this.done)return;if("function"==typeof e)return this.yields.push(e),void this.signal.resolve();const{ingest:t,protocol:r}=this.ingestionFilterFn?this.ingestionFilterFn(e,this.ctx||this):{ingest:!0,protocol:!1};t&&(r&&(this.filtered++,this.pendingFiltered++),this.yields.push(e),this.signal.resolve())}async*iterate(){if(this.noIterator)throw new U("unsupported iterator",F.ApiError);if(this.yielding)throw new U("already yielding",F.ApiError);this.yielding=!0;try{for(;;){if(0===this.yields.length&&await this.signal,this.err)throw this.err;const e=this.yields;this.inflight=e.length,this.yields=[];for(let t=0;t<e.length;t++){if("function"==typeof e[t]){const r=e[t];try{r()}catch(e){throw e}if(this.err)throw this.err;continue}if(!this.protocolFilterFn||this.protocolFilterFn(e[t])){this.processed++;const r=Date.now();yield e[t],this.time=Date.now()-r,this.dispatchedFn&&e[t]&&this.dispatchedFn(e[t])}else this.pendingFiltered--;this.inflight--}if(this.done)break;0===this.yields.length&&(e.length=0,this.yields=e,this.signal=X())}}finally{this.stop()}}stop(e){this.done||(this.err=e,this.done=!0,this.signal.resolve(),this.iterClosed.resolve(e))}getProcessed(){return this.noIterator?this.received:this.processed}getPending(){return this.yields.length+this.inflight-this.pendingFiltered}getReceived(){return this.received-this.filtered}}class Se{interval;maxOut;cancelAfter;timer;autoCancelTimer;last;missed;count;callback;constructor(e,t,r={maxOut:2}){this.interval=e,this.maxOut=r?.maxOut||2,this.cancelAfter=r?.cancelAfter||0,this.last=Date.now(),this.missed=0,this.count=0,this.callback=t,this._schedule()}cancel(){this.autoCancelTimer&&clearTimeout(this.autoCancelTimer),this.timer&&clearInterval(this.timer),this.timer=0,this.autoCancelTimer=0,this.missed=0}work(){this.last=Date.now(),this.missed=0}_change(e,t=0,r=2){this.interval=e,this.maxOut=r,this.cancelAfter=t,this.restart()}restart(){this.cancel(),this._schedule()}_schedule(){this.cancelAfter>0&&(this.autoCancelTimer=setTimeout((()=>{this.cancel()}),this.cancelAfter)),this.timer=setInterval((()=>{if(this.count++,Date.now()-this.last>this.interval&&this.missed++,this.missed>=this.maxOut)try{!0===this.callback(this.missed)&&this.cancel()}catch(e){console.log(e)}}),this.interval)}}var Ce,Ee,xe,ke,Te,Re,Oe,Ae,Pe,Ie,Me,Ne,je;!function(e){e.Limits="limits",e.Interest="interest",e.Workqueue="workqueue"}(Ce||(Ce={})),function(e){e.Old="old",e.New="new"}(Ee||(Ee={})),function(e){e.File="file",e.Memory="memory"}(xe||(xe={})),function(e){e.All="all",e.Last="last",e.New="new",e.StartSequence="by_start_sequence",e.StartTime="by_start_time",e.LastPerSubject="last_per_subject"}(ke||(ke={})),function(e){e.None="none",e.All="all",e.Explicit="explicit",e.NotSet=""}(Te||(Te={})),function(e){e.Instant="instant",e.Original="original"}(Re||(Re={})),function(e){e.None="none",e.S2="s2"}(Oe||(Oe={})),function(e){e.CreateOrUpdate="",e.Update="update",e.Create="create"}(Ae||(Ae={})),function(e){e.API="api_audit",e.StreamAction="stream_action",e.ConsumerAction="consumer_action",e.SnapshotCreate="snapshot_create",e.SnapshotComplete="snapshot_complete",e.RestoreCreate="restore_create",e.RestoreComplete="restore_complete",e.MaxDeliver="max_deliver",e.Terminated="terminated",e.Ack="consumer_ack",e.StreamLeaderElected="stream_leader_elected",e.StreamQuorumLost="stream_quorum_lost",e.ConsumerLeaderElected="consumer_leader_elected",e.ConsumerQuorumLost="consumer_quorum_lost"}(Pe||(Pe={})),function(e){e.StreamSourceHdr="Nats-Stream-Source",e.LastConsumerSeqHdr="Nats-Last-Consumer",e.LastStreamSeqHdr="Nats-Last-Stream",e.ConsumerStalledHdr="Nats-Consumer-Stalled",e.MessageSizeHdr="Nats-Msg-Size",e.RollupHdr="Nats-Rollup",e.RollupValueSubject="sub",e.RollupValueAll="all",e.PendingMessagesHdr="Nats-Pending-Messages",e.PendingBytesHdr="Nats-Pending-Bytes"}(Ie||(Ie={})),function(e){e.LastValue="",e.AllHistory="history",e.UpdatesOnly="updates"}(Me||(Me={})),function(e){e.Stream="Nats-Stream",e.Sequence="Nats-Sequence",e.TimeStamp="Nats-Time-Stamp",e.Subject="Nats-Subject"}(Ne||(Ne={})),function(e){e.Stream="Nats-Stream",e.Subject="Nats-Subject",e.Sequence="Nats-Sequence",e.LastSequence="Nats-Last-Sequence",e.Size="Nats-Msg-Size"}(je||(je={}));const Fe="KV_";class $e{config;ordered;mack;stream;callbackFn;max;qname;isBind;filters;constructor(e){this.stream="",this.mack=!1,this.ordered=!1,this.config=function(e,t={}){return Object.assign({name:e,deliver_policy:ke.All,ack_policy:Te.Explicit,ack_wait:re(3e4),replay_policy:Re.Instant},t)}("",e||{})}getOpts(){const e={};if(e.config=Object.assign({},this.config),e.config.filter_subject&&(this.filterSubject(e.config.filter_subject),e.config.filter_subject=void 0),e.config.filter_subjects&&(e.config.filter_subjects?.forEach((e=>{this.filterSubject(e)})),e.config.filter_subjects=void 0),e.mack=this.mack,e.stream=this.stream,e.callbackFn=this.callbackFn,e.max=this.max,e.queue=this.qname,e.ordered=this.ordered,e.config.ack_policy=e.ordered?Te.None:e.config.ack_policy,e.isBind=e.isBind||!1,this.filters)switch(this.filters.length){case 0:break;case 1:e.config.filter_subject=this.filters[0];break;default:e.config.filter_subjects=this.filters}return e}description(e){return this.config.description=e,this}deliverTo(e){return this.config.deliver_subject=e,this}durable(e){return de(e),this.config.durable_name=e,this}startSequence(e){if(e<=0)throw new Error("sequence must be greater than 0");return this.config.deliver_policy=ke.StartSequence,this.config.opt_start_seq=e,this}startTime(e){return this.config.deliver_policy=ke.StartTime,this.config.opt_start_time=e.toISOString(),this}deliverAll(){return this.config.deliver_policy=ke.All,this}deliverLastPerSubject(){return this.config.deliver_policy=ke.LastPerSubject,this}deliverLast(){return this.config.deliver_policy=ke.Last,this}deliverNew(){return this.config.deliver_policy=ke.New,this}startAtTimeDelta(e){return this.startTime(new Date(Date.now()-e)),this}headersOnly(){return this.config.headers_only=!0,this}ackNone(){return this.config.ack_policy=Te.None,this}ackAll(){return this.config.ack_policy=Te.All,this}ackExplicit(){return this.config.ack_policy=Te.Explicit,this}ackWait(e){return this.config.ack_wait=re(e),this}maxDeliver(e){return this.config.max_deliver=e,this}filterSubject(e){return this.filters=this.filters||[],this.filters.push(e),this}replayInstantly(){return this.config.replay_policy=Re.Instant,this}replayOriginal(){return this.config.replay_policy=Re.Original,this}sample(e){if((e=Math.trunc(e))<0||e>100)throw new Error("value must be between 0-100");return this.config.sample_freq=`${e}%`,this}limit(e){return this.config.rate_limit_bps=e,this}maxWaiting(e){return this.config.max_waiting=e,this}maxAckPending(e){return this.config.max_ack_pending=e,this}idleHeartbeat(e){return this.config.idle_heartbeat=re(e),this}flowControl(){return this.config.flow_control=!0,this}deliverGroup(e){return this.queue(e),this}manualAck(){return this.mack=!0,this}maxMessages(e){return this.max=e,this}callback(e){return this.callbackFn=e,this}queue(e){return this.qname=e,this.config.deliver_group=e,this}orderedConsumer(){return this.ordered=!0,this}bind(e,t){return this.stream=e,this.config.durable_name=t,this.isBind=!0,this}bindStream(e){return this.stream=e,this}inactiveEphemeralThreshold(e){return this.config.inactive_threshold=re(e),this}maxPullBatch(e){return this.config.max_batch=e,this}maxPullRequestExpires(e){return this.config.max_expires=re(e),this}memory(){return this.config.mem_storage=!0,this}numReplicas(e){return this.config.num_replicas=e,this}consumerName(e){return this.config.name=e,this}}function Le(e){return new $e(e)}function Ue(e){return"function"==typeof e.getOpts}class De{static encode(e){if("string"==typeof e)return btoa(e);const t=Array.from(e);return btoa(String.fromCharCode(...t))}static decode(e,t=!1){const r=atob(e);return t?Uint8Array.from(r,(e=>e.charCodeAt(0))):r}}class qe{static encode(e){return qe.toB64URLEncoding(De.encode(e))}static decode(e,t=!1){return qe.decode(qe.fromB64URLEncoding(e),t)}static toB64URLEncoding(e){return e.replace(/\+/g,"-").replace(/\//g,"_")}static fromB64URLEncoding(e){return e.replace(/_/g,"/").replace(/-/g,"+")}}class Be{buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...e){let t=0;for(let r=0;r<e.length;r++)t+=e[r].length;const r=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++)r.set(e[t],s),s+=e[t].length;return r}static fromAscii(e){return e||(e=""),T.encode(e)}static toAscii(e){return R.decode(e)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){const e=new Uint8Array(this.byteLength);let t=0;for(let r=0;r<this.buffers.length;r++)e.set(this.buffers[r],t),t+=this.buffers[r].length;this.buffers.length=0,this.buffers.push(e)}}shift(){if(this.buffers.length){const e=this.buffers.shift();if(e)return this.byteLength-=e.length,e}return new Uint8Array(0)}drain(e){if(this.buffers.length){this.pack();const t=this.buffers.pop();if(t){const r=this.byteLength;(void 0===e||e>r)&&(e=r);const s=t.subarray(0,e);return r>e&&this.buffers.push(t.subarray(e)),this.byteLength=r-e,s}}return new Uint8Array(0)}fill(e,...t){e&&(this.buffers.push(e),this.byteLength+=e.length);for(let e=0;e<t.length;e++)t[e]&&t[e].length&&(this.buffers.push(t[e]),this.byteLength+=t[e].length)}peek(){return this.buffers.length?(this.pack(),this.buffers[0]):new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}var ze="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function Ge(){throw new Error("setTimeout has not been defined")}function Ve(){throw new Error("clearTimeout has not been defined")}var h=Ge,He=Ve;function We(e){if(h===setTimeout)return setTimeout(e,0);if((h===Ge||!h)&&setTimeout)return h=setTimeout,setTimeout(e,0);try{return h(e,0)}catch(t){try{return h.call(null,e,0)}catch(t){return h.call(this,e,0)}}}"function"==typeof ze.setTimeout&&(h=setTimeout),"function"==typeof ze.clearTimeout&&(He=clearTimeout);var Ze,Je=[],Ke=!1,Ye=-1;function Qe(){Ke&&Ze&&(Ke=!1,Ze.length?Je=Ze.concat(Je):Ye=-1,Je.length&&Xe())}function Xe(){if(!Ke){var e=We(Qe);Ke=!0;for(var t=Je.length;t;){for(Ze=Je,Je=[];++Ye<t;)Ze&&Ze[Ye].run();Ye=-1,t=Je.length}Ze=null,Ke=!1,function(e){if(He===clearTimeout)return clearTimeout(e);if((He===Ve||!He)&&clearTimeout)return He=clearTimeout,clearTimeout(e);try{return He(e)}catch(t){try{return He.call(null,e)}catch(t){return He.call(this,e)}}}(e)}}function et(e,t){this.fun=e,this.array=t}function tt(){}et.prototype.run=function(){this.fun.apply(null,this.array)};var rt=tt,st=tt,it=tt,nt=tt,ot=tt,at=tt,ct=tt,ut=ze.performance||{},ht=ut.now||ut.mozNow||ut.msNow||ut.oNow||ut.webkitNow||function(){return(new Date).getTime()},lt=new Date,dt={nextTick:function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];Je.push(new et(e,t)),1!==Je.length||Ke||We(Xe)},title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:rt,addListener:st,once:it,off:nt,removeListener:ot,removeAllListeners:at,emit:ct,binding:function(e){throw new Error("process.binding is not supported")},cwd:function(){return"/"},chdir:function(e){throw new Error("process.chdir is not supported")},umask:function(){return 0},hrtime:function(e){var t=.001*ht.call(ut),r=Math.floor(t),s=Math.floor(t%1*1e9);return e&&(r-=e[0],(s-=e[1])<0&&(r--,s+=1e9)),[r,s]},platform:"browser",release:{},config:{},uptime:function(){return(new Date-lt)/1e3}},pt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var ft,mt={exports:{}},gt={},yt=function(e){if(e.__esModule)return e;var t=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(e).forEach((function(r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})})),t}(function(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(r){if("default"!==r&&!(r in e)){var s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,s.get?s:{enumerable:!0,get:function(){return t[r]}})}}))})),Object.freeze(e)}({__proto__:null,default:gt},[gt]));ft=mt,function(){var e="input is invalid type",t="object"==typeof window,r=t?window:{};r.JS_SHA256_NO_WINDOW&&(t=!1);var s=!t&&"object"==typeof self,h=!r.JS_SHA256_NO_NODE_JS&&dt.versions&&dt.versions.node;h?r=pt:s&&(r=self);var i=!r.JS_SHA256_NO_COMMON_JS&&ft.exports,n=!r.JS_SHA256_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,o="0123456789abcdef".split(""),a=[-2147483648,8388608,32768,128],c=[24,16,8,0],u=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],l=["hex","array","digest","arrayBuffer"],d=[];!r.JS_SHA256_NO_NODE_JS&&Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),!n||!r.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});var p=function(e,t){return function(r){return new b(t,!0).update(r)[e]()}},f=function(e){var t=p("hex",e);h&&(t=m(t,e)),t.create=function(){return new b(e)},t.update=function(e){return t.create().update(e)};for(var r=0;r<l.length;++r){var s=l[r];t[s]=p(s,e)}return t},m=function(t,s){var h,i=yt,n=yt.Buffer,o=s?"sha224":"sha256";return h=n.from&&!r.JS_SHA256_NO_BUFFER_FROM?n.from:function(e){return new n(e)},function(r){if("string"==typeof r)return i.createHash(o).update(r,"utf8").digest("hex");if(null==r)throw new Error(e);return r.constructor===ArrayBuffer&&(r=new Uint8Array(r)),Array.isArray(r)||ArrayBuffer.isView(r)||r.constructor===n?i.createHash(o).update(h(r)).digest("hex"):t(r)}},g=function(e,t){return function(r,s){return new v(r,t,!0).update(s)[e]()}},y=function(e){var t=g("hex",e);t.create=function(t){return new v(t,e)},t.update=function(e,r){return t.create(e).update(r)};for(var r=0;r<l.length;++r){var s=l[r];t[s]=g(s,e)}return t};function b(e,t){t?(d[0]=d[16]=d[1]=d[2]=d[3]=d[4]=d[5]=d[6]=d[7]=d[8]=d[9]=d[10]=d[11]=d[12]=d[13]=d[14]=d[15]=0,this.blocks=d):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}function v(t,r,s){var h,i=typeof t;if("string"===i){var o,a=[],c=t.length,u=0;for(h=0;h<c;++h)(o=t.charCodeAt(h))<128?a[u++]=o:o<2048?(a[u++]=192|o>>>6,a[u++]=128|63&o):o<55296||o>=57344?(a[u++]=224|o>>>12,a[u++]=128|o>>>6&63,a[u++]=128|63&o):(o=65536+((1023&o)<<10|1023&t.charCodeAt(++h)),a[u++]=240|o>>>18,a[u++]=128|o>>>12&63,a[u++]=128|o>>>6&63,a[u++]=128|63&o);t=a}else{if("object"!==i)throw new Error(e);if(null===t)throw new Error(e);if(n&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!(Array.isArray(t)||n&&ArrayBuffer.isView(t)))throw new Error(e)}t.length>64&&(t=new b(r,!0).update(t).array());var l=[],d=[];for(h=0;h<64;++h){var p=t[h]||0;l[h]=92^p,d[h]=54^p}b.call(this,r,s),this.update(d),this.oKeyPad=l,this.inner=!0,this.sharedMemory=s}b.prototype.update=function(t){if(!this.finalized){var r,s=typeof t;if("string"!==s){if("object"!==s)throw new Error(e);if(null===t)throw new Error(e);if(n&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!(Array.isArray(t)||n&&ArrayBuffer.isView(t)))throw new Error(e);r=!0}for(var h,i,o=0,a=t.length,u=this.blocks;o<a;){if(this.hashed&&(this.hashed=!1,u[0]=this.block,this.block=u[16]=u[1]=u[2]=u[3]=u[4]=u[5]=u[6]=u[7]=u[8]=u[9]=u[10]=u[11]=u[12]=u[13]=u[14]=u[15]=0),r)for(i=this.start;o<a&&i<64;++o)u[i>>>2]|=t[o]<<c[3&i++];else for(i=this.start;o<a&&i<64;++o)(h=t.charCodeAt(o))<128?u[i>>>2]|=h<<c[3&i++]:h<2048?(u[i>>>2]|=(192|h>>>6)<<c[3&i++],u[i>>>2]|=(128|63&h)<<c[3&i++]):h<55296||h>=57344?(u[i>>>2]|=(224|h>>>12)<<c[3&i++],u[i>>>2]|=(128|h>>>6&63)<<c[3&i++],u[i>>>2]|=(128|63&h)<<c[3&i++]):(h=65536+((1023&h)<<10|1023&t.charCodeAt(++o)),u[i>>>2]|=(240|h>>>18)<<c[3&i++],u[i>>>2]|=(128|h>>>12&63)<<c[3&i++],u[i>>>2]|=(128|h>>>6&63)<<c[3&i++],u[i>>>2]|=(128|63&h)<<c[3&i++]);this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.block=u[16],this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this}},b.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=a[3&t],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},b.prototype.hash=function(){var e,t,r,s,h,i,n,o,a,c=this.h0,l=this.h1,d=this.h2,p=this.h3,f=this.h4,m=this.h5,g=this.h6,y=this.h7,b=this.blocks;for(e=16;e<64;++e)t=((h=b[e-15])>>>7|h<<25)^(h>>>18|h<<14)^h>>>3,r=((h=b[e-2])>>>17|h<<15)^(h>>>19|h<<13)^h>>>10,b[e]=b[e-16]+t+b[e-7]+r|0;for(a=l&d,e=0;e<64;e+=4)this.first?(this.is224?(i=300032,y=(h=b[0]-1413257819)-150054599|0,p=h+24177077|0):(i=704751109,y=(h=b[0]-210244248)-1521486534|0,p=h+143694565|0),this.first=!1):(t=(c>>>2|c<<30)^(c>>>13|c<<19)^(c>>>22|c<<10),s=(i=c&l)^c&d^a,y=p+(h=y+(r=(f>>>6|f<<26)^(f>>>11|f<<21)^(f>>>25|f<<7))+(f&m^~f&g)+u[e]+b[e])|0,p=h+(t+s)|0),t=(p>>>2|p<<30)^(p>>>13|p<<19)^(p>>>22|p<<10),s=(n=p&c)^p&l^i,g=d+(h=g+(r=(y>>>6|y<<26)^(y>>>11|y<<21)^(y>>>25|y<<7))+(y&f^~y&m)+u[e+1]+b[e+1])|0,t=((d=h+(t+s)|0)>>>2|d<<30)^(d>>>13|d<<19)^(d>>>22|d<<10),s=(o=d&p)^d&c^n,m=l+(h=m+(r=(g>>>6|g<<26)^(g>>>11|g<<21)^(g>>>25|g<<7))+(g&y^~g&f)+u[e+2]+b[e+2])|0,t=((l=h+(t+s)|0)>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),s=(a=l&d)^l&p^o,f=c+(h=f+(r=(m>>>6|m<<26)^(m>>>11|m<<21)^(m>>>25|m<<7))+(m&g^~m&y)+u[e+3]+b[e+3])|0,c=h+(t+s)|0,this.chromeBugWorkAround=!0;this.h0=this.h0+c|0,this.h1=this.h1+l|0,this.h2=this.h2+d|0,this.h3=this.h3+p|0,this.h4=this.h4+f|0,this.h5=this.h5+m|0,this.h6=this.h6+g|0,this.h7=this.h7+y|0},b.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,s=this.h3,h=this.h4,i=this.h5,n=this.h6,a=this.h7,c=o[e>>>28&15]+o[e>>>24&15]+o[e>>>20&15]+o[e>>>16&15]+o[e>>>12&15]+o[e>>>8&15]+o[e>>>4&15]+o[15&e]+o[t>>>28&15]+o[t>>>24&15]+o[t>>>20&15]+o[t>>>16&15]+o[t>>>12&15]+o[t>>>8&15]+o[t>>>4&15]+o[15&t]+o[r>>>28&15]+o[r>>>24&15]+o[r>>>20&15]+o[r>>>16&15]+o[r>>>12&15]+o[r>>>8&15]+o[r>>>4&15]+o[15&r]+o[s>>>28&15]+o[s>>>24&15]+o[s>>>20&15]+o[s>>>16&15]+o[s>>>12&15]+o[s>>>8&15]+o[s>>>4&15]+o[15&s]+o[h>>>28&15]+o[h>>>24&15]+o[h>>>20&15]+o[h>>>16&15]+o[h>>>12&15]+o[h>>>8&15]+o[h>>>4&15]+o[15&h]+o[i>>>28&15]+o[i>>>24&15]+o[i>>>20&15]+o[i>>>16&15]+o[i>>>12&15]+o[i>>>8&15]+o[i>>>4&15]+o[15&i]+o[n>>>28&15]+o[n>>>24&15]+o[n>>>20&15]+o[n>>>16&15]+o[n>>>12&15]+o[n>>>8&15]+o[n>>>4&15]+o[15&n];return this.is224||(c+=o[a>>>28&15]+o[a>>>24&15]+o[a>>>20&15]+o[a>>>16&15]+o[a>>>12&15]+o[a>>>8&15]+o[a>>>4&15]+o[15&a]),c},b.prototype.toString=b.prototype.hex,b.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,s=this.h3,h=this.h4,i=this.h5,n=this.h6,o=this.h7,a=[e>>>24&255,e>>>16&255,e>>>8&255,255&e,t>>>24&255,t>>>16&255,t>>>8&255,255&t,r>>>24&255,r>>>16&255,r>>>8&255,255&r,s>>>24&255,s>>>16&255,s>>>8&255,255&s,h>>>24&255,h>>>16&255,h>>>8&255,255&h,i>>>24&255,i>>>16&255,i>>>8&255,255&i,n>>>24&255,n>>>16&255,n>>>8&255,255&n];return this.is224||a.push(o>>>24&255,o>>>16&255,o>>>8&255,255&o),a},b.prototype.array=b.prototype.digest,b.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e},v.prototype=new b,v.prototype.finalize=function(){if(b.prototype.finalize.call(this),this.inner){this.inner=!1;var e=this.array();b.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(e),b.prototype.finalize.call(this)}};var _=f();_.sha256=_,_.sha224=f(!0),_.sha256.hmac=y(),_.sha224.hmac=y(!0),i?ft.exports=_:(r.sha256=_.sha256,r.sha224=_.sha224)}();mt.exports.sha224;var bt=mt.exports.sha256;function vt(e){return function(e){switch(function(e){if(function(e){if(!/^[0-9A-Fa-f]+$/.test(e))return!1;const t=/^[0-9A-F]+$/.test(e),r=/^[0-9a-f]+$/.test(e);if(!t&&!r)return!1;return e.length%2==0}(e))return"hex";if(function(e){return/^[A-Za-z0-9\-_]*(={0,2})?$/.test(e)||/^[A-Za-z0-9+/]*(={0,2})?$/.test(e)}(e))return"b64";return""}(e)){case"hex":return function(e){if(e.length%2!=0)throw new Error("hex string must have an even length");const t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.substring(r,r+2),16);return t}(e);case"b64":return function(e){e=e.replace(/-/g,"+"),e=e.replace(/_/g,"/");const t=atob(e);return Uint8Array.from(t,(e=>e.charCodeAt(0)))}(e)}return null}(e)}function _t(e,t){const r="string"==typeof e?vt(e):e,s="string"==typeof t?vt(t):t;if(null===r||null===s)return!1;if(r.length!==s.length)return!1;for(let e=0;e<r.length;e++)if(r[e]!==s[e])return!1;return!0}class wt{token;received;ctx;requestSubject;mux;constructor(e,t,r=!0){this.mux=e,this.requestSubject=t,this.received=0,this.token=M.next(),r&&(this.ctx=new Error)}}class St extends wt{callback;done;timer;max;opts;constructor(e,t,r={maxWait:1e3}){if(super(e,t),this.opts=r,"function"!=typeof this.opts.callback)throw new Error("callback is required");this.callback=this.opts.callback,this.max="number"==typeof r.maxMessages&&r.maxMessages>0?r.maxMessages:-1,this.done=X(),this.done.then((()=>{this.callback(null,null)})),this.timer=setTimeout((()=>{this.cancel()}),r.maxWait)}cancel(e){e&&this.callback(e,null),clearTimeout(this.timer),this.mux.cancel(this),this.done.resolve()}resolver(e,t){e?(this.ctx&&(e.stack+=`\n\n${this.ctx.stack}`),this.cancel(e)):(this.callback(null,t),this.opts.strategy===q.Count&&(this.max--,0===this.max&&this.cancel()),this.opts.strategy===q.JitterTimer&&(clearTimeout(this.timer),this.timer=setTimeout((()=>{this.cancel()}),this.opts.jitter||300)),this.opts.strategy===q.SentinelMsg&&t&&0===t.data.length&&this.cancel())}}class Ct extends wt{deferred;timer;constructor(e,t,r={timeout:1e3},s=!0){super(e,t,s),this.deferred=X(),this.timer=Y(r.timeout,s)}resolver(e,t){this.timer&&this.timer.cancel(),e?(this.ctx&&(e.stack+=`\n\n${this.ctx.stack}`),this.deferred.reject(e)):this.deferred.resolve(t),this.cancel()}cancel(e){this.timer&&this.timer.cancel(),this.mux.cancel(this),this.deferred.reject(e||U.errorForCode(F.Cancelled))}}class Et{nc;opts;prefix;timeout;jc;constructor(e,t){this.nc=e,this.opts=function(e){return(e=e||{}).domain&&(e.apiPrefix=`$JS.${e.domain}.API`,delete e.domain),J({apiPrefix:"$JS.API",timeout:5e3},e)}(t),this._parseOpts(),this.prefix=this.opts.apiPrefix,this.timeout=this.opts.timeout,this.jc=ue()}getOptions(){return Object.assign({},this.opts)}_parseOpts(){let e=this.opts.apiPrefix;if(!e||0===e.length)throw new Error("invalid empty prefix");"."===e[e.length-1]&&(e=e.substr(0,e.length-1)),this.opts.apiPrefix=e}async _request(e,t=null,r){(r=r||{}).timeout=this.timeout;let s=k;t&&(s=this.jc.encode(t));let{retries:i}=r;i=i||1,i=-1===i?Number.MAX_SAFE_INTEGER:i;const n=te();for(let t=0;t<i;t++)try{const t=await this.nc.request(e,s,r);return this.parseJsResponse(t)}catch(e){const r=e;if("503"!==r.code&&r.code!==F.Timeout||!(t+1<i))throw e;await Q(n.backoff(t))}}async findStream(e){const t={subject:e},r=await this._request(`${this.prefix}.STREAM.NAMES`,t);if(!r.streams||1!==r.streams.length)throw new Error("no stream matches subject");return r.streams[0]}getConnection(){return this.nc}parseJsResponse(e){const t=this.jc.decode(e.data),r=t;if(r.error){const e=_e(r.error.code,r.error.description);if(null!==e)throw e.api_error=r.error,e}return t}}class xt{err;offset;pageInfo;subject;jsm;filter;payload;constructor(e,t,r,s){if(!e)throw new Error("subject is required");this.subject=e,this.jsm=r,this.offset=0,this.pageInfo={},this.filter=t,this.payload=s||{}}async next(){if(this.err)return[];if(this.pageInfo&&this.offset>=this.pageInfo.total)return[];const e={offset:this.offset};this.payload&&Object.assign(e,this.payload);try{const t=await this.jsm._request(this.subject,e,{timeout:this.jsm.timeout});this.pageInfo=t;const r=this.countResponse(t);if(0===r)return[];this.offset+=r;return this.filter(t)}catch(e){throw this.err=e,e}}countResponse(e){switch(e?.type){case"io.nats.jetstream.api.v1.stream_names_response":case"io.nats.jetstream.api.v1.stream_list_response":return e.streams?.length||0;case"io.nats.jetstream.api.v1.consumer_list_response":return e.consumers?.length||0;default:return console.error(`jslister.ts: unknown API response for paged output: ${e?.type}`),e.streams?.length||0}return 0}async*[Symbol.asyncIterator](){let e=await this.next();for(;e.length>0;){for(const t of e)yield t;e=await this.next()}}}function kt(e=""){const t=e.match(/(\d+).(\d+).(\d+)/);if(t)return{major:parseInt(t[1]),minor:parseInt(t[2]),micro:parseInt(t[3])};throw new Error(`'${e}' is not a semver value`)}function Tt(e,t){return e.major<t.major?-1:e.major>t.major?1:e.minor<t.minor?-1:e.minor>t.minor?1:e.micro<t.micro?-1:e.micro>t.micro?1:0}var Rt;!function(e){e.JS_KV="js_kv",e.JS_OBJECTSTORE="js_objectstore",e.JS_PULL_MAX_BYTES="js_pull_max_bytes",e.JS_NEW_CONSUMER_CREATE_API="js_new_consumer_create",e.JS_ALLOW_DIRECT="js_allow_direct",e.JS_MULTIPLE_CONSUMER_FILTER="js_multiple_consumer_filter",e.JS_SIMPLIFICATION="js_simplification",e.JS_STREAM_CONSUMER_METADATA="js_stream_consumer_metadata",e.JS_CONSUMER_FILTER_SUBJECTS="js_consumer_filter_subjects",e.JS_STREAM_FIRST_SEQ="js_stream_first_seq",e.JS_STREAM_SUBJECT_TRANSFORM="js_stream_subject_transform",e.JS_STREAM_SOURCE_SUBJECT_TRANSFORM="js_stream_source_subject_transform",e.JS_STREAM_COMPRESSION="js_stream_compression",e.JS_DEFAULT_CONSUMER_LIMITS="js_default_consumer_limits",e.JS_BATCH_DIRECT_GET="js_batch_direct_get"}(Rt||(Rt={}));class Ot{server;features;disabled;constructor(e){this.features=new Map,this.disabled=[],this.update(e)}resetDisabled(){this.disabled.length=0,this.update(this.server)}disable(e){this.disabled.push(e),this.update(this.server)}isDisabled(e){return-1!==this.disabled.indexOf(e)}update(e){"string"==typeof e&&(e=kt(e)),this.server=e,this.set(Rt.JS_KV,"2.6.2"),this.set(Rt.JS_OBJECTSTORE,"2.6.3"),this.set(Rt.JS_PULL_MAX_BYTES,"2.8.3"),this.set(Rt.JS_NEW_CONSUMER_CREATE_API,"2.9.0"),this.set(Rt.JS_ALLOW_DIRECT,"2.9.0"),this.set(Rt.JS_MULTIPLE_CONSUMER_FILTER,"2.10.0"),this.set(Rt.JS_SIMPLIFICATION,"2.9.4"),this.set(Rt.JS_STREAM_CONSUMER_METADATA,"2.10.0"),this.set(Rt.JS_CONSUMER_FILTER_SUBJECTS,"2.10.0"),this.set(Rt.JS_STREAM_FIRST_SEQ,"2.10.0"),this.set(Rt.JS_STREAM_SUBJECT_TRANSFORM,"2.10.0"),this.set(Rt.JS_STREAM_SOURCE_SUBJECT_TRANSFORM,"2.10.0"),this.set(Rt.JS_STREAM_COMPRESSION,"2.10.0"),this.set(Rt.JS_DEFAULT_CONSUMER_LIMITS,"2.10.0"),this.set(Rt.JS_BATCH_DIRECT_GET,"2.11.0"),this.disabled.forEach((e=>{this.features.delete(e)}))}set(e,t){this.features.set(e,{min:t,ok:Tt(this.server,kt(t))>=0})}get(e){return this.features.get(e)||{min:"unknown",ok:!1}}supports(e){return this.get(e)?.ok||!1}require(e){return"string"==typeof e&&(e=kt(e)),Tt(this.server,e)>=0}}class At extends Et{constructor(e,t){super(e,t)}async add(e,t,r=Ae.Create){if(pe(e),t.deliver_group&&t.flow_control)throw new Error("jetstream flow control is not supported with queue groups");if(t.deliver_group&&t.idle_heartbeat)throw new Error("jetstream idle heartbeat is not supported with queue groups");const s={};s.config=t,s.stream_name=e,s.action=r,s.config.durable_name&&de(s.config.durable_name);const i=this.nc;let{min:n,ok:o}=i.features.get(Rt.JS_NEW_CONSUMER_CREATE_API);const a=""===t.name?void 0:t.name;if(a&&!o)throw new Error(`consumer 'name' requires server ${n}`);if(a)try{fe("name",a)}catch(e){const t=e.message,r=t.indexOf("cannot contain");if(-1!==r)throw new Error(`consumer 'name' ${t.substring(r)}`);throw e}let c,u="";if(Array.isArray(t.filter_subjects)){const{min:e,ok:t}=i.features.get(Rt.JS_MULTIPLE_CONSUMER_FILTER);if(!t)throw new Error(`consumer 'filter_subjects' requires server ${e}`);o=!1}if(t.metadata){const{min:e,ok:t}=i.features.get(Rt.JS_STREAM_CONSUMER_METADATA);if(!t)throw new Error(`consumer 'metadata' requires server ${e}`)}if(o&&(u=t.name??t.durable_name??""),""!==u){let r=t.filter_subject??void 0;">"===r&&(r=void 0),c=void 0!==r?`${this.prefix}.CONSUMER.CREATE.${e}.${u}.${r}`:`${this.prefix}.CONSUMER.CREATE.${e}.${u}`}else c=t.durable_name?`${this.prefix}.CONSUMER.DURABLE.CREATE.${e}.${t.durable_name}`:`${this.prefix}.CONSUMER.CREATE.${e}`;return await this._request(c,s)}async update(e,t,r){const s=await this.info(e,t),i=r;return this.add(e,Object.assign(s.config,i),Ae.Update)}async info(e,t){pe(e),de(t);return await this._request(`${this.prefix}.CONSUMER.INFO.${e}.${t}`)}async delete(e,t){pe(e),de(t);return(await this._request(`${this.prefix}.CONSUMER.DELETE.${e}.${t}`)).success}list(e){pe(e);const t=`${this.prefix}.CONSUMER.LIST.${e}`;return new xt(t,(e=>e.consumers),this)}pause(e,t,r){const s=`${this.prefix}.CONSUMER.PAUSE.${e}.${t}`,i={pause_until:r.toISOString()};return this._request(s,i)}resume(e,t){return this.pause(e,t,new Date(0))}}function Pt(e,t,r=!1){if(!0===r&&!e)throw U.errorForCode(F.ApiError,new Error(`${t} is not a function`));if(e&&"function"!=typeof e)throw U.errorForCode(F.ApiError,new Error(`${t} is not a function`))}class It extends we{sub;adapter;subIterDone;constructor(e,t,r){super(),Pt(r.adapter,"adapter",!0),this.adapter=r.adapter,r.callback&&Pt(r.callback,"callback"),this.noIterator="function"==typeof r.callback,r.ingestionFilterFn&&(Pt(r.ingestionFilterFn,"ingestionFilterFn"),this.ingestionFilterFn=r.ingestionFilterFn),r.protocolFilterFn&&(Pt(r.protocolFilterFn,"protocolFilterFn"),this.protocolFilterFn=r.protocolFilterFn),r.dispatchedFn&&(Pt(r.dispatchedFn,"dispatchedFn"),this.dispatchedFn=r.dispatchedFn),r.cleanupFn&&Pt(r.cleanupFn,"cleanupFn");let s=(e,t)=>{this.callback(e,t)};if(r.callback){const e=r.callback;s=(t,r)=>{const[s,i]=this.adapter(t,r);if(s)return void e(s,null);const{ingest:n}=this.ingestionFilterFn?this.ingestionFilterFn(i,this):{ingest:!0};if(n){(!this.protocolFilterFn||this.protocolFilterFn(i))&&(e(s,i),this.dispatchedFn&&i&&this.dispatchedFn(i))}}}const{max:i,queue:n,timeout:o}=r,a={queue:n,timeout:o,callback:s};i&&i>0&&(a.max=i),this.sub=e.subscribe(t,a),r.cleanupFn&&(this.sub.cleanupFn=r.cleanupFn),this.noIterator||this.iterClosed.then((()=>{this.unsubscribe()})),this.subIterDone=X(),Promise.all([this.sub.closed,this.iterClosed]).then((()=>{this.subIterDone.resolve()})).catch((()=>{this.subIterDone.resolve()})),(async e=>{await e.closed,this.stop()})(this.sub).then().catch()}unsubscribe(e){this.sub.unsubscribe(e)}drain(){return this.sub.drain()}isDraining(){return this.sub.isDraining()}isClosed(){return this.sub.isClosed()}callback(e,t){this.sub.cancelTimeout();const[r,s]=this.adapter(e,t);r&&this.stop(r),s&&this.push(s)}getSubject(){return this.sub.getSubject()}getReceived(){return this.sub.getReceived()}getProcessed(){return this.sub.getProcessed()}getPending(){return this.sub.getPending()}getID(){return this.sub.getID()}getMax(){return this.sub.getMax()}get closed(){return this.sub.closed}}let Mt;function Nt(){return void 0!==Mt&&void 0!==Mt.defaultPort?Mt.defaultPort:4222}function jt(){return void 0!==Mt&&Mt.urlParseFn?Mt.urlParseFn:void 0}function Ft(){return void 0!==Mt&&Mt.dnsResolveFn?Mt.dnsResolveFn:void 0}const $t="\r\n",Lt=Be.fromAscii($t),Ut=new Uint8Array(Lt)[0],Dt=new Uint8Array(Lt)[1];function qt(e){const t=function(e){for(let t=0;t<e.length;t++){const r=t+1;if(e.byteLength>r&&e[t]===Ut&&e[r]===Dt)return r+1}return 0}(e);if(t>0){const r=new Uint8Array(e).slice(0,t);return R.decode(r)}return""}function Bt(h){return void 0!==function(h){for(let e=0;e<h.length;e++)switch(h[e]){case".":return zt(h);case":":return Gt(h)}return}(h)}function zt(e){const t=new Uint8Array(4);for(let r=0;r<4;r++){if(0===e.length)return;if(r>0){if("."!==e[0])return;e=e.substring(1)}const{n:s,c:i,ok:n}=Vt(e);if(!n||s>255)return;e=e.substring(i),t[r]=s}return function(e,t,r,s){const i=new Uint8Array(16);return[0,0,0,0,0,0,0,0,0,0,255,255].forEach(((e,t)=>{i[t]=e})),i[12]=e,i[13]=t,i[14]=r,i[15]=s,i}(t[0],t[1],t[2],t[3])}function Gt(e){const t=new Uint8Array(16);let r=-1;if(e.length>=2&&":"===e[0]&&":"===e[1]&&(r=0,0===(e=e.substring(2)).length))return t;let s=0;for(;s<16;){const{n:i,c:n,ok:o}=Ht(e);if(!o||i>65535)return;if(n<e.length&&"."===e[n]){if(r<0&&12!=s)return;if(s+4>16)return;const i=zt(e);if(void 0===i)return;t[s]=i[12],t[s+1]=i[13],t[s+2]=i[14],t[s+3]=i[15],e="",s+=4;break}if(t[s]=i>>8,t[s+1]=i,s+=2,0===(e=e.substring(n)).length)break;if(":"!==e[0]||1==e.length)return;if(":"===(e=e.substring(1))[0]){if(r>=0)return;if(r=s,0===(e=e.substring(1)).length)break}}if(0===e.length){if(s<16){if(r<0)return;const e=16-s;for(let i=s-1;i>=r;i--)t[i+e]=t[i];for(let s=r+e-1;s>=r;s--)t[s]=0}else if(r>=0)return;return t}}function Vt(e){let t=0,r=0;for(t=0;t<e.length&&48<=e.charCodeAt(t)&&e.charCodeAt(t)<=57;t++)if(r=10*r+(e.charCodeAt(t)-48),r>=16777215)return{n:16777215,c:t,ok:!1};return 0===t?{n:0,c:0,ok:!1}:{n:r,c:t,ok:!0}}function Ht(e){let t=0,r=0;for(r=0;r<e.length;r++){if(48<=e.charCodeAt(r)&&e.charCodeAt(r)<=57)t*=16,t+=e.charCodeAt(r)-48;else if(97<=e.charCodeAt(r)&&e.charCodeAt(r)<=102)t*=16,t+=e.charCodeAt(r)-97+10;else{if(!(65<=e.charCodeAt(r)&&e.charCodeAt(r)<=70))break;t*=16,t+=e.charCodeAt(r)-65+10}if(t>=16777215)return{n:0,c:r,ok:!1}}return 0===r?{n:0,c:r,ok:!1}:{n:t,c:r,ok:!0}}function Wt(e){return!function(e){return-1===e.indexOf("[")&&-1===e.indexOf("::")&&(-1!==e.indexOf(".")||e.split(":").length<=2)}(e)}class Zt{src;listen;hostname;port;didConnect;reconnects;lastConnect;gossiped;tlsName;resolves;constructor(e,t=!1){this.src=e,this.tlsName="";const r=function(e){(e=e.trim()).match(/^(.*:\/\/)(.*)/m)&&(e=e.replace(/^(.*:\/\/)(.*)/gm,"$2")),Wt(e=function(e){const t="::FFFF:",r=e.toUpperCase().indexOf(t);if(-1!==r&&-1!==e.indexOf(".")){let t=e.substring(r+7);return t=t.replace("[",""),t.replace("]","")}return e}(e))&&-1===e.indexOf("[")&&(e=`[${e}]`);const t=Wt(e)?e.match(/(]:)(\d+)/):e.match(/(:)(\d+)/),r=t&&3===t.length&&t[1]&&t[2]?parseInt(t[2]):4222,s=new URL(`${80===r?"https":"http"}://${e}`);s.port=`${r}`;let i=s.hostname;return"["===i.charAt(0)&&(i=i.substring(1,i.length-1)),{listen:s.host,hostname:i,port:r}}(e);this.listen=r.listen,this.hostname=r.hostname,this.port=r.port,this.didConnect=!1,this.reconnects=0,this.lastConnect=0,this.gossiped=t}toString(){return this.listen}async resolve(e){if(!e.fn||!1===e.resolve)return[this];const t=[];if(Bt(this.hostname))return[this];{const r=await e.fn(this.hostname);e.debug&&console.log(`resolve ${this.hostname} = ${r.join(",")}`);for(const e of r){const r=80===this.port?"https":"http",s=new URL(`${r}://${Wt(e)?"["+e+"]":e}`);s.port=`${this.port}`;const i=new Zt(s.host,!1);i.tlsName=this.hostname,t.push(i)}}return e.randomize&&ee(t),this.resolves=t,t}}class Jt{firstSelect;servers;currentServer;tlsName;randomize;constructor(e=[],t={}){this.firstSelect=!0,this.servers=[],this.tlsName="",this.randomize=t.randomize||!1;const r=jt();e&&(e.forEach((e=>{e=r?r(e):e,this.servers.push(new Zt(e))})),this.randomize&&(this.servers=ee(this.servers))),0===this.servers.length&&this.addServer(`${W}:${Nt()}`,!1),this.currentServer=this.servers[0]}clear(){this.servers.length=0}updateTLSName(){const e=this.getCurrentServer();Bt(e.hostname)||(this.tlsName=e.hostname,this.servers.forEach((e=>{e.gossiped&&(e.tlsName=this.tlsName)})))}getCurrentServer(){return this.currentServer}addServer(e,t=!1){const r=jt();e=r?r(e):e;const s=new Zt(e,t);Bt(s.hostname)&&(s.tlsName=this.tlsName),this.servers.push(s)}selectServer(){if(this.firstSelect)return this.firstSelect=!1,this.currentServer;const e=this.servers.shift();return e&&(this.servers.push(e),this.currentServer=e),e}removeCurrentServer(){this.removeServer(this.currentServer)}removeServer(e){if(e){const t=this.servers.indexOf(e);this.servers.splice(t,1)}}length(){return this.servers.length}next(){return this.servers.length?this.servers[0]:void 0}getServers(){return this.servers}update(e,t){const r=[];let s=[];const i=jt(),n=new Map;e.connect_urls&&e.connect_urls.length>0&&e.connect_urls.forEach((e=>{e=i?i(e,t):e;const r=new Zt(e,!0);n.set(e,r)}));const o=[];return this.servers.forEach(((e,t)=>{const r=e.listen;e.gossiped&&this.currentServer.listen!==r&&void 0===n.get(r)&&o.push(t),n.delete(r)})),o.reverse(),o.forEach((e=>{const t=this.servers.splice(e,1);s=s.concat(t[0].listen)})),n.forEach(((e,t)=>{this.servers.push(e),r.push(t)})),{added:r,deleted:s}}}class Kt{baseInbox;reqs;constructor(){this.reqs=new Map}size(){return this.reqs.size}init(e){return this.baseInbox=`${H(e)}.`,this.baseInbox}add(e){isNaN(e.received)||(e.received=0),this.reqs.set(e.token,e)}get(e){return this.reqs.get(e)}cancel(e){this.reqs.delete(e.token)}getToken(e){const t=e.subject||"";return 0===t.indexOf(this.baseInbox)?t.substring(this.baseInbox.length):null}all(){return Array.from(this.reqs.values())}handleError(e,t){if(t&&t.permissionContext){if(e)return this.all().forEach((e=>{e.resolver(t,{})})),!0;const r=t.permissionContext;if("publish"===r.operation){const e=this.all().find((e=>e.requestSubject===r.subject));if(e)return e.resolver(t,{}),!0}}return!1}dispatcher(){return(e,t)=>{const r=this.getToken(t);if(r){const s=this.get(r);s&&(null===e&&t.headers&&(e=he(t)),s.resolver(e,t))}}}close(){const e=U.errorForCode(F.Timeout);this.reqs.forEach((t=>{t.resolver(e,{})}))}}class Yt{ph;interval;maxOut;timer;pendings;constructor(e,t,r){this.ph=e,this.interval=t,this.maxOut=r,this.pendings=[]}start(){this.cancel(),this._schedule()}cancel(e){this.timer&&(clearTimeout(this.timer),this.timer=void 0),this._reset(),e&&this.ph.disconnect()}_schedule(){this.timer=setTimeout((()=>{if(this.ph.dispatchStatus({type:j.PingTimer,data:`${this.pendings.length+1}`}),this.pendings.length===this.maxOut)return void this.cancel(!0);const e=X();this.ph.flush(e).then((()=>{this._reset()})).catch((()=>{this.cancel()})),this.pendings.push(e),this._schedule()}),this.interval)}_reset(){this.pendings=this.pendings.filter((e=>(e.resolve(),!1)))}}class Qt extends Error{constructor(e){super(e),this.name="AssertionError"}}const Xt=2**32-2;function er(e,t,r=0){const s=t.byteLength-r;return e.byteLength>s&&(e=e.subarray(0,s)),t.set(e,r),e.byteLength}class tr{_buf;_off;constructor(e){this._off=0,this._buf=null!=e?new Uint8Array(e):new Uint8Array(0)}bytes(e={copy:!0}){return!1===e.copy?this._buf.subarray(this._off):this._buf.slice(this._off)}empty(){return this._buf.byteLength<=this._off}get length(){return this._buf.byteLength-this._off}get capacity(){return this._buf.buffer.byteLength}truncate(e){if(0!==e){if(e<0||e>this.length)throw Error("bytes.Buffer: truncation out of range");this._reslice(this._off+e)}else this.reset()}reset(){this._reslice(0),this._off=0}_tryGrowByReslice(e){const t=this._buf.byteLength;return e<=this.capacity-t?(this._reslice(t+e),t):-1}_reslice(e){!function(e,t="Assertion failed."){if(!e)throw new Qt(t)}(e<=this._buf.buffer.byteLength),this._buf=new Uint8Array(this._buf.buffer,0,e)}readByte(){const e=new Uint8Array(1);return this.read(e)?e[0]:null}read(e){if(this.empty())return this.reset(),0===e.byteLength?0:null;const t=er(this._buf.subarray(this._off),e);return this._off+=t,t}writeByte(e){return this.write(Uint8Array.of(e))}writeString(e){return this.write(T.encode(e))}write(e){const t=this._grow(e.byteLength);return er(e,this._buf,t)}_grow(e){const t=this.length;0===t&&0!==this._off&&this.reset();const r=this._tryGrowByReslice(e);if(r>=0)return r;const s=this.capacity;if(e<=Math.floor(s/2)-t)er(this._buf.subarray(this._off),this._buf);else{if(s+e>Xt)throw new Error("The buffer cannot be grown beyond the maximum size.");{const t=new Uint8Array(Math.min(2*s+e,Xt));er(this._buf.subarray(this._off),t),this._buf=t}}return this._off=0,this._reslice(Math.min(t+e,Xt)),t}grow(e){if(e<0)throw Error("Buffer._grow: negative count");const t=this._grow(e);this._reslice(t)}readFrom(e){let t=0;const r=new Uint8Array(32768);for(;;){const s=this.capacity-this.length<32768,i=s?r:new Uint8Array(this._buf.buffer,this.length),n=e.read(i);if(null===n)return t;s?this.write(i.subarray(0,n)):this._reslice(this.length+n),t+=n}}}var rr;function sr(){const e={sid:-1,hdr:-1,size:-1};return e}!function(e){e[e.OK=0]="OK",e[e.ERR=1]="ERR",e[e.MSG=2]="MSG",e[e.INFO=3]="INFO",e[e.PING=4]="PING",e[e.PONG=5]="PONG"}(rr||(rr={}));class ir{dispatcher;state;as;drop;hdr;ma;argBuf;msgBuf;constructor(e){this.dispatcher=e,this.state=nr.OP_START,this.as=0,this.drop=0,this.hdr=0}parse(e){let t;for(t=0;t<e.length;t++){const r=e[t];switch(this.state){case nr.OP_START:switch(r){case or.M:case or.m:this.state=nr.OP_M,this.hdr=-1,this.ma=sr();break;case or.H:case or.h:this.state=nr.OP_H,this.hdr=0,this.ma=sr();break;case or.P:case or.p:this.state=nr.OP_P;break;case or.PLUS:this.state=nr.OP_PLUS;break;case or.MINUS:this.state=nr.OP_MINUS;break;case or.I:case or.i:this.state=nr.OP_I;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_H:switch(r){case or.M:case or.m:this.state=nr.OP_M;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_M:switch(r){case or.S:case or.s:this.state=nr.OP_MS;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_MS:switch(r){case or.G:case or.g:this.state=nr.OP_MSG;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_MSG:switch(r){case or.SPACE:case or.TAB:this.state=nr.OP_MSG_SPC;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_MSG_SPC:switch(r){case or.SPACE:case or.TAB:continue;default:this.state=nr.MSG_ARG,this.as=t}break;case nr.MSG_ARG:switch(r){case or.CR:this.drop=1;break;case or.NL:{const r=this.argBuf?this.argBuf.bytes():e.subarray(this.as,t-this.drop);this.processMsgArgs(r),this.drop=0,this.as=t+1,this.state=nr.MSG_PAYLOAD,t=this.as+this.ma.size-1;break}default:this.argBuf&&this.argBuf.writeByte(r)}break;case nr.MSG_PAYLOAD:if(this.msgBuf)if(this.msgBuf.length>=this.ma.size){const e=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:rr.MSG,msg:this.ma,data:e}),this.argBuf=void 0,this.msgBuf=void 0,this.state=nr.MSG_END}else{let s=this.ma.size-this.msgBuf.length;const i=e.length-t;i<s&&(s=i),s>0?(this.msgBuf.write(e.subarray(t,t+s)),t=t+s-1):this.msgBuf.writeByte(r)}else t-this.as>=this.ma.size&&(this.dispatcher.push({kind:rr.MSG,msg:this.ma,data:e.subarray(this.as,t)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=nr.MSG_END);break;case nr.MSG_END:if(r!==or.NL)continue;this.drop=0,this.as=t+1,this.state=nr.OP_START;break;case nr.OP_PLUS:switch(r){case or.O:case or.o:this.state=nr.OP_PLUS_O;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_PLUS_O:switch(r){case or.K:case or.k:this.state=nr.OP_PLUS_OK;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_PLUS_OK:if(r===or.NL)this.dispatcher.push({kind:rr.OK}),this.drop=0,this.state=nr.OP_START;break;case nr.OP_MINUS:switch(r){case or.E:case or.e:this.state=nr.OP_MINUS_E;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_MINUS_E:switch(r){case or.R:case or.r:this.state=nr.OP_MINUS_ER;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_MINUS_ER:switch(r){case or.R:case or.r:this.state=nr.OP_MINUS_ERR;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_MINUS_ERR:switch(r){case or.SPACE:case or.TAB:this.state=nr.OP_MINUS_ERR_SPC;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_MINUS_ERR_SPC:switch(r){case or.SPACE:case or.TAB:continue;default:this.state=nr.MINUS_ERR_ARG,this.as=t}break;case nr.MINUS_ERR_ARG:switch(r){case or.CR:this.drop=1;break;case or.NL:{let r;this.argBuf?(r=this.argBuf.bytes(),this.argBuf=void 0):r=e.subarray(this.as,t-this.drop),this.dispatcher.push({kind:rr.ERR,data:r}),this.drop=0,this.as=t+1,this.state=nr.OP_START;break}default:this.argBuf&&this.argBuf.write(Uint8Array.of(r))}break;case nr.OP_P:switch(r){case or.I:case or.i:this.state=nr.OP_PI;break;case or.O:case or.o:this.state=nr.OP_PO;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_PO:switch(r){case or.N:case or.n:this.state=nr.OP_PON;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_PON:switch(r){case or.G:case or.g:this.state=nr.OP_PONG;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_PONG:if(r===or.NL)this.dispatcher.push({kind:rr.PONG}),this.drop=0,this.state=nr.OP_START;break;case nr.OP_PI:switch(r){case or.N:case or.n:this.state=nr.OP_PIN;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_PIN:switch(r){case or.G:case or.g:this.state=nr.OP_PING;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_PING:if(r===or.NL)this.dispatcher.push({kind:rr.PING}),this.drop=0,this.state=nr.OP_START;break;case nr.OP_I:switch(r){case or.N:case or.n:this.state=nr.OP_IN;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_IN:switch(r){case or.F:case or.f:this.state=nr.OP_INF;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_INF:switch(r){case or.O:case or.o:this.state=nr.OP_INFO;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_INFO:switch(r){case or.SPACE:case or.TAB:this.state=nr.OP_INFO_SPC;break;default:throw this.fail(e.subarray(t))}break;case nr.OP_INFO_SPC:switch(r){case or.SPACE:case or.TAB:continue;default:this.state=nr.INFO_ARG,this.as=t}break;case nr.INFO_ARG:switch(r){case or.CR:this.drop=1;break;case or.NL:{let r;this.argBuf?(r=this.argBuf.bytes(),this.argBuf=void 0):r=e.subarray(this.as,t-this.drop),this.dispatcher.push({kind:rr.INFO,data:r}),this.drop=0,this.as=t+1,this.state=nr.OP_START;break}default:this.argBuf&&this.argBuf.writeByte(r)}break;default:throw this.fail(e.subarray(t))}}this.state!==nr.MSG_ARG&&this.state!==nr.MINUS_ERR_ARG&&this.state!==nr.INFO_ARG||this.argBuf||(this.argBuf=new tr(e.subarray(this.as,t-this.drop))),this.state!==nr.MSG_PAYLOAD||this.msgBuf||(this.argBuf||this.cloneMsgArg(),this.msgBuf=new tr(e.subarray(this.as)))}cloneMsgArg(){const e=this.ma.subject.length,t=this.ma.reply?this.ma.reply.length:0,r=new Uint8Array(e+t);r.set(this.ma.subject),this.ma.reply&&r.set(this.ma.reply,e),this.argBuf=new tr(r),this.ma.subject=r.subarray(0,e),this.ma.reply&&(this.ma.reply=r.subarray(e))}processMsgArgs(e){if(this.hdr>=0)return this.processHeaderMsgArgs(e);const t=[];let r=-1;for(let s=0;s<e.length;s++){switch(e[s]){case or.SPACE:case or.TAB:case or.CR:case or.NL:r>=0&&(t.push(e.subarray(r,s)),r=-1);break;default:r<0&&(r=s)}}switch(r>=0&&t.push(e.subarray(r)),t.length){case 3:this.ma.subject=t[0],this.ma.sid=this.protoParseInt(t[1]),this.ma.reply=void 0,this.ma.size=this.protoParseInt(t[2]);break;case 4:this.ma.subject=t[0],this.ma.sid=this.protoParseInt(t[1]),this.ma.reply=t[2],this.ma.size=this.protoParseInt(t[3]);break;default:throw this.fail(e,"processMsgArgs Parse Error")}if(this.ma.sid<0)throw this.fail(e,"processMsgArgs Bad or Missing Sid Error");if(this.ma.size<0)throw this.fail(e,"processMsgArgs Bad or Missing Size Error")}fail(e,t=""){return t=t?`${t} [${this.state}]`:`parse error [${this.state}]`,new Error(`${t}: ${R.decode(e)}`)}processHeaderMsgArgs(e){const t=[];let r=-1;for(let s=0;s<e.length;s++){switch(e[s]){case or.SPACE:case or.TAB:case or.CR:case or.NL:r>=0&&(t.push(e.subarray(r,s)),r=-1);break;default:r<0&&(r=s)}}switch(r>=0&&t.push(e.subarray(r)),t.length){case 4:this.ma.subject=t[0],this.ma.sid=this.protoParseInt(t[1]),this.ma.reply=void 0,this.ma.hdr=this.protoParseInt(t[2]),this.ma.size=this.protoParseInt(t[3]);break;case 5:this.ma.subject=t[0],this.ma.sid=this.protoParseInt(t[1]),this.ma.reply=t[2],this.ma.hdr=this.protoParseInt(t[3]),this.ma.size=this.protoParseInt(t[4]);break;default:throw this.fail(e,"processHeaderMsgArgs Parse Error")}if(this.ma.sid<0)throw this.fail(e,"processHeaderMsgArgs Bad or Missing Sid Error");if(this.ma.hdr<0||this.ma.hdr>this.ma.size)throw this.fail(e,"processHeaderMsgArgs Bad or Missing Header Size Error");if(this.ma.size<0)throw this.fail(e,"processHeaderMsgArgs Bad or Missing Size Error")}protoParseInt(e){if(0===e.length)return-1;let t=0;for(let r=0;r<e.length;r++){if(e[r]<48||e[r]>57)return-1;t=10*t+(e[r]-48)}return t}}var nr,or;!function(e){e[e.OP_START=0]="OP_START",e[e.OP_PLUS=1]="OP_PLUS",e[e.OP_PLUS_O=2]="OP_PLUS_O",e[e.OP_PLUS_OK=3]="OP_PLUS_OK",e[e.OP_MINUS=4]="OP_MINUS",e[e.OP_MINUS_E=5]="OP_MINUS_E",e[e.OP_MINUS_ER=6]="OP_MINUS_ER",e[e.OP_MINUS_ERR=7]="OP_MINUS_ERR",e[e.OP_MINUS_ERR_SPC=8]="OP_MINUS_ERR_SPC",e[e.MINUS_ERR_ARG=9]="MINUS_ERR_ARG",e[e.OP_M=10]="OP_M",e[e.OP_MS=11]="OP_MS",e[e.OP_MSG=12]="OP_MSG",e[e.OP_MSG_SPC=13]="OP_MSG_SPC",e[e.MSG_ARG=14]="MSG_ARG",e[e.MSG_PAYLOAD=15]="MSG_PAYLOAD",e[e.MSG_END=16]="MSG_END",e[e.OP_H=17]="OP_H",e[e.OP_P=18]="OP_P",e[e.OP_PI=19]="OP_PI",e[e.OP_PIN=20]="OP_PIN",e[e.OP_PING=21]="OP_PING",e[e.OP_PO=22]="OP_PO",e[e.OP_PON=23]="OP_PON",e[e.OP_PONG=24]="OP_PONG",e[e.OP_I=25]="OP_I",e[e.OP_IN=26]="OP_IN",e[e.OP_INF=27]="OP_INF",e[e.OP_INFO=28]="OP_INFO",e[e.OP_INFO_SPC=29]="OP_INFO_SPC",e[e.INFO_ARG=30]="INFO_ARG"}(nr||(nr={})),function(e){e[e.CR="\r".charCodeAt(0)]="CR",e[e.E="E".charCodeAt(0)]="E",e[e.e="e".charCodeAt(0)]="e",e[e.F="F".charCodeAt(0)]="F",e[e.f="f".charCodeAt(0)]="f",e[e.G="G".charCodeAt(0)]="G",e[e.g="g".charCodeAt(0)]="g",e[e.H="H".charCodeAt(0)]="H",e[e.h="h".charCodeAt(0)]="h",e[e.I="I".charCodeAt(0)]="I",e[e.i="i".charCodeAt(0)]="i",e[e.K="K".charCodeAt(0)]="K",e[e.k="k".charCodeAt(0)]="k",e[e.M="M".charCodeAt(0)]="M",e[e.m="m".charCodeAt(0)]="m",e[e.MINUS="-".charCodeAt(0)]="MINUS",e[e.N="N".charCodeAt(0)]="N",e[e.n="n".charCodeAt(0)]="n",e[e.NL="\n".charCodeAt(0)]="NL",e[e.O="O".charCodeAt(0)]="O",e[e.o="o".charCodeAt(0)]="o",e[e.P="P".charCodeAt(0)]="P",e[e.p="p".charCodeAt(0)]="p",e[e.PLUS="+".charCodeAt(0)]="PLUS",e[e.R="R".charCodeAt(0)]="R",e[e.r="r".charCodeAt(0)]="r",e[e.S="S".charCodeAt(0)]="S",e[e.s="s".charCodeAt(0)]="s",e[e.SPACE=" ".charCodeAt(0)]="SPACE",e[e.TAB="\t".charCodeAt(0)]="TAB"}(or||(or={})),function(e){var t=function(h,e){this.hi=0|h,this.lo=0|e},r=function(e){var t,r=new Float64Array(16);if(e)for(t=0;t<e.length;t++)r[t]=e[t];return r},s=function(){throw new Error("no PRNG")},i=new Uint8Array(16),n=new Uint8Array(32);n[0]=9;var o=r(),a=r([1]),c=r([56129,1]),u=r([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),l=r([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),d=r([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),p=r([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),f=r([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function m(e,t){return e<<t|e>>>32-t}function g(e,t){var r=255&e[t+3];return(r=(r=r<<8|255&e[t+2])<<8|255&e[t+1])<<8|255&e[t+0]}function y(e,r){var h=e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3],s=e[r+4]<<24|e[r+5]<<16|e[r+6]<<8|e[r+7];return new t(h,s)}function b(e,t,r){var s;for(s=0;s<4;s++)e[t+s]=255&r,r>>>=8}function v(e,t,r){e[t]=r.hi>>24&255,e[t+1]=r.hi>>16&255,e[t+2]=r.hi>>8&255,e[t+3]=255&r.hi,e[t+4]=r.lo>>24&255,e[t+5]=r.lo>>16&255,e[t+6]=r.lo>>8&255,e[t+7]=255&r.lo}function _(e,t,r,s,i){var n,o=0;for(n=0;n<i;n++)o|=e[t+n]^r[s+n];return(1&o-1>>>8)-1}function w(e,t,r,s){return _(e,t,r,s,16)}function S(e,t,r,s){return _(e,t,r,s,32)}function C(e,t,r,s,h){var i,n,o,a=new Uint32Array(16),c=new Uint32Array(16),u=new Uint32Array(16),l=new Uint32Array(4);for(i=0;i<4;i++)c[5*i]=g(s,4*i),c[1+i]=g(r,4*i),c[6+i]=g(t,4*i),c[11+i]=g(r,16+4*i);for(i=0;i<16;i++)u[i]=c[i];for(i=0;i<20;i++){for(n=0;n<4;n++){for(o=0;o<4;o++)l[o]=c[(5*n+4*o)%16];for(l[1]^=m(l[0]+l[3]|0,7),l[2]^=m(l[1]+l[0]|0,9),l[3]^=m(l[2]+l[1]|0,13),l[0]^=m(l[3]+l[2]|0,18),o=0;o<4;o++)a[4*n+(n+o)%4]=l[o]}for(o=0;o<16;o++)c[o]=a[o]}if(h){for(i=0;i<16;i++)c[i]=c[i]+u[i]|0;for(i=0;i<4;i++)c[5*i]=c[5*i]-g(s,4*i)|0,c[6+i]=c[6+i]-g(t,4*i)|0;for(i=0;i<4;i++)b(e,4*i,c[5*i]),b(e,16+4*i,c[6+i])}else for(i=0;i<16;i++)b(e,4*i,c[i]+u[i]|0)}function E(e,t,r,s){return C(e,t,r,s,!1),0}function x(e,t,r,s){return C(e,t,r,s,!0),0}var k=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function T(e,t,r,s,i,n,o){var a,c,u=new Uint8Array(16),l=new Uint8Array(64);if(!i)return 0;for(c=0;c<16;c++)u[c]=0;for(c=0;c<8;c++)u[c]=n[c];for(;i>=64;){for(E(l,u,o,k),c=0;c<64;c++)e[t+c]=(r?r[s+c]:0)^l[c];for(a=1,c=8;c<16;c++)a=a+(255&u[c])|0,u[c]=255&a,a>>>=8;i-=64,t+=64,r&&(s+=64)}if(i>0)for(E(l,u,o,k),c=0;c<i;c++)e[t+c]=(r?r[s+c]:0)^l[c];return 0}function R(e,t,r,s,i){return T(e,t,null,0,r,s,i)}function O(e,t,r,s,i){var n=new Uint8Array(32);return x(n,s,i,k),R(e,t,r,s.subarray(16),n)}function A(e,t,r,s,i,n,o){var a=new Uint8Array(32);return x(a,n,o,k),T(e,t,r,s,i,n.subarray(16),a)}function P(h,e){var t,r=0;for(t=0;t<17;t++)r=r+(h[t]+e[t]|0)|0,h[t]=255&r,r>>>=8}var I=new Uint32Array([5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252]);function M(e,t,r,s,i,n){var o,a,c,u,l=new Uint32Array(17),d=new Uint32Array(17),h=new Uint32Array(17),p=new Uint32Array(17),f=new Uint32Array(17);for(c=0;c<17;c++)d[c]=h[c]=0;for(c=0;c<16;c++)d[c]=n[c];for(d[3]&=15,d[4]&=252,d[7]&=15,d[8]&=252,d[11]&=15,d[12]&=252,d[15]&=15;i>0;){for(c=0;c<17;c++)p[c]=0;for(c=0;c<16&&c<i;++c)p[c]=r[s+c];for(p[c]=1,s+=c,i-=c,P(h,p),a=0;a<17;a++)for(l[a]=0,c=0;c<17;c++)l[a]=l[a]+h[c]*(c<=a?d[a-c]:320*d[a+17-c]|0)|0;for(a=0;a<17;a++)h[a]=l[a];for(u=0,c=0;c<16;c++)u=u+h[c]|0,h[c]=255&u,u>>>=8;for(u=u+h[16]|0,h[16]=3&u,u=5*(u>>>2)|0,c=0;c<16;c++)u=u+h[c]|0,h[c]=255&u,u>>>=8;u=u+h[16]|0,h[16]=u}for(c=0;c<17;c++)f[c]=h[c];for(P(h,I),o=0|-(h[16]>>>7),c=0;c<17;c++)h[c]^=o&(f[c]^h[c]);for(c=0;c<16;c++)p[c]=n[c+16];for(p[16]=0,P(h,p),c=0;c<16;c++)e[t+c]=h[c];return 0}function N(h,e,t,r,s,i){var n=new Uint8Array(16);return M(n,0,t,r,s,i),w(h,e,n,0)}function j(e,t,r,s,i){var n;if(r<32)return-1;for(A(e,0,t,0,r,s,i),M(e,16,e,32,r-32,e),n=0;n<16;n++)e[n]=0;return 0}function F(e,t,r,s,i){var n,o=new Uint8Array(32);if(r<32)return-1;if(O(o,0,32,s,i),0!==N(t,16,t,32,r-32,o))return-1;for(A(e,0,t,0,r,s,i),n=0;n<32;n++)e[n]=0;return 0}function $(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function L(e){var t,r;for(r=0;r<16;r++)e[r]+=65536,t=Math.floor(e[r]/65536),e[(r+1)*(r<15?1:0)]+=t-1+37*(t-1)*(15===r?1:0),e[r]-=65536*t}function U(e,t,r){for(var s,i=~(r-1),n=0;n<16;n++)s=i&(e[n]^t[n]),e[n]^=s,t[n]^=s}function D(e,t){var s,i,n,o=r(),a=r();for(s=0;s<16;s++)a[s]=t[s];for(L(a),L(a),L(a),i=0;i<2;i++){for(o[0]=a[0]-65517,s=1;s<15;s++)o[s]=a[s]-65535-(o[s-1]>>16&1),o[s-1]&=65535;o[15]=a[15]-32767-(o[14]>>16&1),n=o[15]>>16&1,o[14]&=65535,U(a,o,1-n)}for(s=0;s<16;s++)e[2*s]=255&a[s],e[2*s+1]=a[s]>>8}function q(e,t){var r=new Uint8Array(32),s=new Uint8Array(32);return D(r,e),D(s,t),S(r,0,s,0)}function B(e){var t=new Uint8Array(32);return D(t,e),1&t[0]}function z(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function G(e,t,r){var s;for(s=0;s<16;s++)e[s]=t[s]+r[s]|0}function V(e,t,r){var s;for(s=0;s<16;s++)e[s]=t[s]-r[s]|0}function H(e,t,r){var s,i,n=new Float64Array(31);for(s=0;s<31;s++)n[s]=0;for(s=0;s<16;s++)for(i=0;i<16;i++)n[s+i]+=t[s]*r[i];for(s=0;s<15;s++)n[s]+=38*n[s+16];for(s=0;s<16;s++)e[s]=n[s];L(e),L(e)}function W(e,t){H(e,t,t)}function Z(e,t){var s,i=r();for(s=0;s<16;s++)i[s]=t[s];for(s=253;s>=0;s--)W(i,i),2!==s&&4!==s&&H(i,i,t);for(s=0;s<16;s++)e[s]=i[s]}function J(e,t){var s,i=r();for(s=0;s<16;s++)i[s]=t[s];for(s=250;s>=0;s--)W(i,i),1!==s&&H(i,i,t);for(s=0;s<16;s++)e[s]=i[s]}function K(e,t,s){var i,n,o=new Uint8Array(32),a=new Float64Array(80),u=r(),l=r(),d=r(),p=r(),f=r(),m=r();for(n=0;n<31;n++)o[n]=t[n];for(o[31]=127&t[31]|64,o[0]&=248,z(a,s),n=0;n<16;n++)l[n]=a[n],p[n]=u[n]=d[n]=0;for(u[0]=p[0]=1,n=254;n>=0;--n)U(u,l,i=o[n>>>3]>>>(7&n)&1),U(d,p,i),G(f,u,d),V(u,u,d),G(d,l,p),V(l,l,p),W(p,f),W(m,u),H(u,d,u),H(d,l,f),G(f,u,d),V(u,u,d),W(l,u),V(d,p,m),H(u,d,c),G(u,u,p),H(d,d,u),H(u,p,m),H(p,l,a),W(l,f),U(u,l,i),U(d,p,i);for(n=0;n<16;n++)a[n+16]=u[n],a[n+32]=d[n],a[n+48]=l[n],a[n+64]=p[n];var g=a.subarray(32),y=a.subarray(16);return Z(g,g),H(y,y,g),D(e,y),0}function Y(e,t){return K(e,t,n)}function Q(e,t){return s(t,32),Y(e,t)}function X(e,t,r){var s=new Uint8Array(32);return K(s,r,t),x(e,i,s,k)}var ee=j,te=F;function re(){var e,h,r,s=0,i=0,n=0,o=0,a=65535;for(r=0;r<arguments.length;r++)s+=(e=arguments[r].lo)&a,i+=e>>>16,n+=(h=arguments[r].hi)&a,o+=h>>>16;return new t((n+=(i+=s>>>16)>>>16)&a|(o+=n>>>16)<<16,s&a|i<<16)}function se(e,r){return new t(e.hi>>>r,e.lo>>>r|e.hi<<32-r)}function ie(){var e,r=0,h=0;for(e=0;e<arguments.length;e++)r^=arguments[e].lo,h^=arguments[e].hi;return new t(h,r)}function ne(e,r){var h,s,i=32-r;return r<32?(h=e.hi>>>r|e.lo<<i,s=e.lo>>>r|e.hi<<i):r<64&&(h=e.lo>>>r|e.hi<<i,s=e.hi>>>r|e.lo<<i),new t(h,s)}function oe(e,r,s){var h=e.hi&r.hi^~e.hi&s.hi,i=e.lo&r.lo^~e.lo&s.lo;return new t(h,i)}function ae(e,r,s){var h=e.hi&r.hi^e.hi&s.hi^r.hi&s.hi,i=e.lo&r.lo^e.lo&s.lo^r.lo&s.lo;return new t(h,i)}function ce(e){return ie(ne(e,28),ne(e,34),ne(e,39))}function ue(e){return ie(ne(e,14),ne(e,18),ne(e,41))}function he(e){return ie(ne(e,1),ne(e,8),se(e,7))}function le(e){return ie(ne(e,19),ne(e,61),se(e,6))}var de=[new t(1116352408,3609767458),new t(1899447441,602891725),new t(3049323471,3964484399),new t(3921009573,2173295548),new t(961987163,4081628472),new t(1508970993,3053834265),new t(2453635748,2937671579),new t(2870763221,3664609560),new t(3624381080,2734883394),new t(310598401,1164996542),new t(607225278,1323610764),new t(1426881987,3590304994),new t(1925078388,4068182383),new t(2162078206,991336113),new t(2614888103,633803317),new t(3248222580,3479774868),new t(3835390401,2666613458),new t(4022224774,944711139),new t(264347078,2341262773),new t(604807628,2007800933),new t(770255983,1495990901),new t(1249150122,1856431235),new t(1555081692,3175218132),new t(1996064986,2198950837),new t(2554220882,3999719339),new t(2821834349,766784016),new t(2952996808,2566594879),new t(3210313671,3203337956),new t(3336571891,1034457026),new t(3584528711,2466948901),new t(113926993,3758326383),new t(338241895,168717936),new t(666307205,1188179964),new t(773529912,1546045734),new t(1294757372,1522805485),new t(1396182291,2643833823),new t(1695183700,2343527390),new t(1986661051,1014477480),new t(2177026350,1206759142),new t(2456956037,344077627),new t(2730485921,1290863460),new t(2820302411,3158454273),new t(3259730800,3505952657),new t(3345764771,106217008),new t(3516065817,3606008344),new t(3600352804,1432725776),new t(4094571909,1467031594),new t(275423344,851169720),new t(430227734,3100823752),new t(506948616,1363258195),new t(659060556,3750685593),new t(883997877,3785050280),new t(958139571,3318307427),new t(1322822218,3812723403),new t(1537002063,2003034995),new t(1747873779,3602036899),new t(1955562222,1575990012),new t(2024104815,1125592928),new t(2227730452,2716904306),new t(2361852424,442776044),new t(2428436474,593698344),new t(2756734187,3733110249),new t(3204031479,2999351573),new t(3329325298,3815920427),new t(3391569614,3928383900),new t(3515267271,566280711),new t(3940187606,3454069534),new t(4118630271,4000239992),new t(116418474,1914138554),new t(174292421,2731055270),new t(289380356,3203993006),new t(460393269,320620315),new t(685471733,587496836),new t(852142971,1086792851),new t(1017036298,365543100),new t(1126000580,2618297676),new t(1288033470,3409855158),new t(1501505948,4234509866),new t(1607167915,987167468),new t(1816402316,1246189591)];function pe(e,t,r){var s,i,n,o=[],a=[],c=[],u=[];for(i=0;i<8;i++)o[i]=c[i]=y(e,8*i);for(var l=0;r>=128;){for(i=0;i<16;i++)u[i]=y(t,8*i+l);for(i=0;i<80;i++){for(n=0;n<8;n++)a[n]=c[n];for(s=re(c[7],ue(c[4]),oe(c[4],c[5],c[6]),de[i],u[i%16]),a[7]=re(s,ce(c[0]),ae(c[0],c[1],c[2])),a[3]=re(a[3],s),n=0;n<8;n++)c[(n+1)%8]=a[n];if(i%16==15)for(n=0;n<16;n++)u[n]=re(u[n],u[(n+9)%16],he(u[(n+1)%16]),le(u[(n+14)%16]))}for(i=0;i<8;i++)c[i]=re(c[i],o[i]),o[i]=c[i];l+=128,r-=128}for(i=0;i<8;i++)v(e,8*i,o[i]);return r}var fe=new Uint8Array([106,9,230,103,243,188,201,8,187,103,174,133,132,202,167,59,60,110,243,114,254,148,248,43,165,79,245,58,95,29,54,241,81,14,82,127,173,230,130,209,155,5,104,140,43,62,108,31,31,131,217,171,251,65,189,107,91,224,205,25,19,126,33,121]);function me(e,r,s){var i,h=new Uint8Array(64),n=new Uint8Array(256),o=s;for(i=0;i<64;i++)h[i]=fe[i];for(pe(h,r,s),s%=128,i=0;i<256;i++)n[i]=0;for(i=0;i<s;i++)n[i]=r[o-s+i];for(n[s]=128,n[(s=256-128*(s<112?1:0))-9]=0,v(n,s-8,new t(o/536870912|0,o<<3)),pe(h,n,s),i=0;i<64;i++)e[i]=h[i];return 0}function ge(e,t){var s=r(),i=r(),n=r(),o=r(),a=r(),c=r(),u=r(),h=r(),d=r();V(s,e[1],e[0]),V(d,t[1],t[0]),H(s,s,d),G(i,e[0],e[1]),G(d,t[0],t[1]),H(i,i,d),H(n,e[3],t[3]),H(n,n,l),H(o,e[2],t[2]),G(o,o,o),V(a,i,s),V(c,o,n),G(u,o,n),G(h,i,s),H(e[0],a,c),H(e[1],h,u),H(e[2],u,c),H(e[3],a,h)}function ye(e,t,r){var s;for(s=0;s<4;s++)U(e[s],t[s],r)}function be(e,t){var s=r(),i=r(),n=r();Z(n,t[2]),H(s,t[0],n),H(i,t[1],n),D(e,i),e[31]^=B(s)<<7}function ve(e,t,r){var s,i;for($(e[0],o),$(e[1],a),$(e[2],a),$(e[3],o),i=255;i>=0;--i)ye(e,t,s=r[i/8|0]>>(7&i)&1),ge(t,e),ge(e,e),ye(e,t,s)}function _e(e,t){var s=[r(),r(),r(),r()];$(s[0],d),$(s[1],p),$(s[2],a),H(s[3],d,p),ve(e,s,t)}function we(e,t,i){var n,o=new Uint8Array(64),a=[r(),r(),r(),r()];for(i||s(t,32),me(o,t,32),o[0]&=248,o[31]&=127,o[31]|=64,_e(a,o),be(e,a),n=0;n<32;n++)t[n+32]=e[n];return 0}var Se=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function Ce(e,t){var r,s,i,n;for(s=63;s>=32;--s){for(r=0,i=s-32,n=s-12;i<n;++i)t[i]+=r-16*t[s]*Se[i-(s-32)],r=Math.floor((t[i]+128)/256),t[i]-=256*r;t[i]+=r,t[s]=0}for(r=0,i=0;i<32;i++)t[i]+=r-(t[31]>>4)*Se[i],r=t[i]>>8,t[i]&=255;for(i=0;i<32;i++)t[i]-=r*Se[i];for(s=0;s<32;s++)t[s+1]+=t[s]>>8,e[s]=255&t[s]}function Ee(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;Ce(e,r)}function xe(e,t,s,i){var n,o,a=new Uint8Array(64),h=new Uint8Array(64),c=new Uint8Array(64),u=new Float64Array(64),l=[r(),r(),r(),r()];me(a,i,32),a[0]&=248,a[31]&=127,a[31]|=64;var d=s+64;for(n=0;n<s;n++)e[64+n]=t[n];for(n=0;n<32;n++)e[32+n]=a[32+n];for(me(c,e.subarray(32),s+32),Ee(c),_e(l,c),be(e,l),n=32;n<64;n++)e[n]=i[n];for(me(h,e,s+64),Ee(h),n=0;n<64;n++)u[n]=0;for(n=0;n<32;n++)u[n]=c[n];for(n=0;n<32;n++)for(o=0;o<32;o++)u[n+o]+=h[n]*a[o];return Ce(e.subarray(32),u),d}function ke(e,t,s,i){var n,c=new Uint8Array(32),h=new Uint8Array(64),l=[r(),r(),r(),r()],d=[r(),r(),r(),r()];if(s<64)return-1;if(function(e,t){var s=r(),i=r(),n=r(),c=r(),l=r(),d=r(),p=r();return $(e[2],a),z(e[1],t),W(n,e[1]),H(c,n,u),V(n,n,e[2]),G(c,e[2],c),W(l,c),W(d,l),H(p,d,l),H(s,p,n),H(s,s,c),J(s,s),H(s,s,n),H(s,s,c),H(s,s,c),H(e[0],s,c),W(i,e[0]),H(i,i,c),q(i,n)&&H(e[0],e[0],f),W(i,e[0]),H(i,i,c),q(i,n)?-1:(B(e[0])===t[31]>>7&&V(e[0],o,e[0]),H(e[3],e[0],e[1]),0)}(d,i))return-1;for(n=0;n<s;n++)e[n]=t[n];for(n=0;n<32;n++)e[n+32]=i[n];if(me(h,e,s),Ee(h),ve(l,d,h),_e(d,t.subarray(32)),ge(l,d),be(c,l),s-=64,S(t,0,c,0)){for(n=0;n<s;n++)e[n]=0;return-1}for(n=0;n<s;n++)e[n]=t[n+64];return s}var Te=16,Re=64,Oe=32,Ae=64;function Pe(e,t){if(32!==e.length)throw new Error("bad key size");if(24!==t.length)throw new Error("bad nonce size")}function Ie(){for(var e=0;e<arguments.length;e++)if(!(arguments[e]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function Me(e){for(var t=0;t<e.length;t++)e[t]=0}e.lowlevel={crypto_core_hsalsa20:x,crypto_stream_xor:A,crypto_stream:O,crypto_stream_salsa20_xor:T,crypto_stream_salsa20:R,crypto_onetimeauth:M,crypto_onetimeauth_verify:N,crypto_verify_16:w,crypto_verify_32:S,crypto_secretbox:j,crypto_secretbox_open:F,crypto_scalarmult:K,crypto_scalarmult_base:Y,crypto_box_beforenm:X,crypto_box_afternm:ee,crypto_box:function(e,t,r,s,i,n){var o=new Uint8Array(32);return X(o,i,n),ee(e,t,r,s,o)},crypto_box_open:function(e,t,r,s,i,n){var o=new Uint8Array(32);return X(o,i,n),te(e,t,r,s,o)},crypto_box_keypair:Q,crypto_hash:me,crypto_sign:xe,crypto_sign_keypair:we,crypto_sign_open:ke,crypto_secretbox_KEYBYTES:32,crypto_secretbox_NONCEBYTES:24,crypto_secretbox_ZEROBYTES:32,crypto_secretbox_BOXZEROBYTES:Te,crypto_scalarmult_BYTES:32,crypto_scalarmult_SCALARBYTES:32,crypto_box_PUBLICKEYBYTES:32,crypto_box_SECRETKEYBYTES:32,crypto_box_BEFORENMBYTES:32,crypto_box_NONCEBYTES:24,crypto_box_ZEROBYTES:32,crypto_box_BOXZEROBYTES:16,crypto_sign_BYTES:Re,crypto_sign_PUBLICKEYBYTES:Oe,crypto_sign_SECRETKEYBYTES:Ae,crypto_sign_SEEDBYTES:32,crypto_hash_BYTES:64,gf:r,D:u,L:Se,pack25519:D,unpack25519:z,M:H,A:G,S:W,Z:V,pow2523:J,add:ge,set25519:$,modL:Ce,scalarmult:ve,scalarbase:_e},e.randomBytes=function(e){var t=new Uint8Array(e);return s(t,e),t},e.secretbox=function(e,t,r){Ie(e,t,r),Pe(r,t);for(var s=new Uint8Array(32+e.length),i=new Uint8Array(s.length),n=0;n<e.length;n++)s[n+32]=e[n];return j(i,s,s.length,t,r),i.subarray(Te)},e.secretbox.open=function(e,t,r){Ie(e,t,r),Pe(r,t);for(var s=new Uint8Array(Te+e.length),i=new Uint8Array(s.length),n=0;n<e.length;n++)s[n+Te]=e[n];return s.length<32||0!==F(i,s,s.length,t,r)?null:i.subarray(32)},e.secretbox.keyLength=32,e.secretbox.nonceLength=24,e.secretbox.overheadLength=Te,e.scalarMult=function(e,t){if(Ie(e,t),32!==e.length)throw new Error("bad n size");if(32!==t.length)throw new Error("bad p size");var r=new Uint8Array(32);return K(r,e,t),r},e.scalarMult.base=function(e){if(Ie(e),32!==e.length)throw new Error("bad n size");var t=new Uint8Array(32);return Y(t,e),t},e.scalarMult.scalarLength=32,e.scalarMult.groupElementLength=32,e.box=function(t,r,s,i){var n=e.box.before(s,i);return e.secretbox(t,r,n)},e.box.before=function(e,t){Ie(e,t),function(e,t){if(32!==e.length)throw new Error("bad public key size");if(32!==t.length)throw new Error("bad secret key size")}(e,t);var r=new Uint8Array(32);return X(r,e,t),r},e.box.after=e.secretbox,e.box.open=function(t,r,s,i){var n=e.box.before(s,i);return e.secretbox.open(t,r,n)},e.box.open.after=e.secretbox.open,e.box.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(32);return Q(e,t),{publicKey:e,secretKey:t}},e.box.keyPair.fromSecretKey=function(e){if(Ie(e),32!==e.length)throw new Error("bad secret key size");var t=new Uint8Array(32);return Y(t,e),{publicKey:t,secretKey:new Uint8Array(e)}},e.box.publicKeyLength=32,e.box.secretKeyLength=32,e.box.sharedKeyLength=32,e.box.nonceLength=24,e.box.overheadLength=e.secretbox.overheadLength,e.sign=function(e,t){if(Ie(e,t),t.length!==Ae)throw new Error("bad secret key size");var r=new Uint8Array(Re+e.length);return xe(r,e,e.length,t),r},e.sign.open=function(e,t){if(Ie(e,t),t.length!==Oe)throw new Error("bad public key size");var r=new Uint8Array(e.length),s=ke(r,e,e.length,t);if(s<0)return null;for(var i=new Uint8Array(s),n=0;n<i.length;n++)i[n]=r[n];return i},e.sign.detached=function(t,r){for(var s=e.sign(t,r),i=new Uint8Array(Re),n=0;n<i.length;n++)i[n]=s[n];return i},e.sign.detached.verify=function(e,t,r){if(Ie(e,t,r),t.length!==Re)throw new Error("bad signature size");if(r.length!==Oe)throw new Error("bad public key size");var s,i=new Uint8Array(Re+e.length),n=new Uint8Array(Re+e.length);for(s=0;s<Re;s++)i[s]=t[s];for(s=0;s<e.length;s++)i[s+Re]=e[s];return ke(n,i,i.length,r)>=0},e.sign.keyPair=function(){var e=new Uint8Array(Oe),t=new Uint8Array(Ae);return we(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(Ie(e),e.length!==Ae)throw new Error("bad secret key size");for(var t=new Uint8Array(Oe),r=0;r<t.length;r++)t[r]=e[32+r];return{publicKey:t,secretKey:new Uint8Array(e)}},e.sign.keyPair.fromSeed=function(e){if(Ie(e),32!==e.length)throw new Error("bad seed size");for(var t=new Uint8Array(Oe),r=new Uint8Array(Ae),s=0;s<32;s++)r[s]=e[s];return we(t,r,!0),{publicKey:t,secretKey:r}},e.sign.publicKeyLength=Oe,e.sign.secretKeyLength=Ae,e.sign.seedLength=32,e.sign.signatureLength=Re,e.hash=function(e){Ie(e);var h=new Uint8Array(64);return me(h,e,e.length),h},e.hash.hashLength=64,e.verify=function(e,t){return Ie(e,t),0!==e.length&&0!==t.length&&(e.length===t.length&&0===_(e,0,t,0,e.length))},e.setPRNG=function(e){s=e},function(){var t="undefined"!=typeof globalThis?globalThis.crypto||globalThis.msCrypto:null;if(t&&t.getRandomValues){e.setPRNG((function(e,r){var s,i=new Uint8Array(r);for(s=0;s<r;s+=65536)t.getRandomValues(i.subarray(s,s+Math.min(r-s,65536)));for(s=0;s<r;s++)e[s]=i[s];Me(i)}))}else"undefined"!=typeof require&&(t=require("crypto"))&&t.randomBytes&&e.setPRNG((function(e,r){var s,i=t.randomBytes(r);for(s=0;s<r;s++)e[s]=i[s];Me(i)}))}()}("undefined"!=typeof module&&module.exports?module.exports:globalThis.nacl=globalThis.nacl||{});const ar="undefined"!=typeof module&&module.exports?module.exports:globalThis.nacl,cr={fromSeed:ar.sign.keyPair.fromSeed,sign:ar.sign.detached,verify:ar.sign.detached.verify,randomBytes:ar.randomBytes};let ur;new Uint16Array([0,4129,8258,12387,16516,20645,24774,28903,33032,37161,41290,45419,49548,53677,57806,61935,4657,528,12915,8786,21173,17044,29431,25302,37689,33560,45947,41818,54205,50076,62463,58334,9314,13379,1056,5121,25830,29895,17572,21637,42346,46411,34088,38153,58862,62927,50604,54669,13907,9842,5649,1584,30423,26358,22165,18100,46939,42874,38681,34616,63455,59390,55197,51132,18628,22757,26758,30887,2112,6241,10242,14371,51660,55789,59790,63919,35144,39273,43274,47403,23285,19156,31415,27286,6769,2640,14899,10770,56317,52188,64447,60318,39801,35672,47931,43802,27814,31879,19684,23749,11298,15363,3168,7233,60846,64911,52716,56781,44330,48395,36200,40265,32407,28342,24277,20212,15891,11826,7761,3696,65439,61374,57309,53244,48923,44858,40793,36728,37256,33193,45514,41451,53516,49453,61774,57711,4224,161,12482,8419,20484,16421,28742,24679,33721,37784,41979,46042,49981,54044,58239,62302,689,4752,8947,13010,16949,21012,25207,29270,46570,42443,38312,34185,62830,58703,54572,50445,13538,9411,5280,1153,29798,25671,21540,17413,42971,47098,34713,38840,59231,63358,50973,55100,9939,14066,1681,5808,26199,30326,17941,22068,55628,51565,63758,59695,39368,35305,47498,43435,22596,18533,30726,26663,6336,2273,14466,10403,52093,56156,60223,64286,35833,39896,43963,48026,19061,23124,27191,31254,2801,6864,10931,14994,64814,60687,56684,52557,48554,44427,40424,36297,31782,27655,23652,19525,15522,11395,7392,3265,61215,65342,53085,57212,44955,49082,36825,40952,28183,32310,20053,24180,11923,16050,3793,7920]);Error;var hr,lr;!function(e){e.InvalidPrefixByte="nkeys: invalid prefix byte",e.InvalidKey="nkeys: invalid key",e.InvalidPublicKey="nkeys: invalid public key",e.InvalidSeedLen="nkeys: invalid seed length",e.InvalidSeed="nkeys: invalid seed",e.InvalidEncoding="nkeys: invalid encoded key",e.InvalidSignature="nkeys: signature verification failed",e.CannotSign="nkeys: cannot sign, no private key available",e.PublicKeyOnly="nkeys: no seed or private key available",e.InvalidChecksum="nkeys: invalid checksum",e.SerializationError="nkeys: serialization error",e.ApiError="nkeys: api error",e.ClearedPair="nkeys: pair is cleared"}(hr||(hr={})),function(e){e[e.Seed=144]="Seed",e[e.Private=120]="Private",e[e.Operator=112]="Operator",e[e.Server=104]="Server",e[e.Cluster=16]="Cluster",e[e.Account=0]="Account",e[e.User=160]="User"}(lr||(lr={}));ur=cr;const dr=12e4;function pr(e){const t=[];var r,s,i,n;return"function"==typeof e.authenticator&&t.push(e.authenticator),Array.isArray(e.authenticator)&&t.push(...e.authenticator),e.token&&t.push((r=e.token,()=>({auth_token:"function"==typeof r?r():r}))),e.user&&t.push((s=e.user,i=e.pass,()=>({user:"function"==typeof s?s():s,pass:"function"==typeof i?i():i}))),0===t.length?()=>{}:(n=t,e=>{let t={};return n.forEach((r=>{const s=r(e)||{};t=Object.assign(t,s)})),t})}function fr(e){const t=`${W}:${Nt()}`;if((e=e||{servers:[t]}).servers=e.servers||[],"string"==typeof e.servers&&(e.servers=[e.servers]),e.servers.length>0&&e.port)throw new U("port and servers options are mutually exclusive",F.InvalidOption);0===e.servers.length&&e.port&&(e.servers=[`${W}:${e.port}`]),e.servers&&0===e.servers.length&&(e.servers=[t]);const r=J({maxPingOut:2,maxReconnectAttempts:10,noRandomize:!1,pedantic:!1,pingInterval:dr,reconnect:!0,reconnectJitter:100,reconnectJitterTLS:1e3,reconnectTimeWait:2e3,tls:void 0,verbose:!1,waitOnFirstConnect:!1,ignoreAuthErrorAbort:!1},e);if(r.authenticator=pr(r),["reconnectDelayHandler","authenticator"].forEach((e=>{if(r[e]&&"function"!=typeof r[e])throw new U(`${e} option should be a function`,F.NotFunction)})),r.reconnectDelayHandler||(r.reconnectDelayHandler=()=>{let e=r.tls?r.reconnectJitterTLS:r.reconnectJitter;return e&&(e++,e=Math.floor(Math.random()*e)),r.reconnectTimeWait+e}),r.inboxPrefix)try{H(r.inboxPrefix)}catch(e){throw new U(e.message,F.ApiError)}if(void 0===r.resolve&&(r.resolve="function"==typeof Ft()),r.resolve&&"function"!=typeof Ft())throw new U("'resolve' is not supported on this client",F.InvalidOption);return r}const mr=/^INFO\s+([^\r\n]+)\r\n/i,gr=O("PONG\r\n"),yr=O("PING\r\n");class br{echo;no_responders;protocol;verbose;pedantic;jwt;nkey;sig;user;pass;auth_token;tls_required;name;lang;version;headers;constructor(e,t,r){this.protocol=1,this.version=e.version,this.lang=e.lang,this.echo=!t.noEcho&&void 0,this.verbose=t.verbose,this.pedantic=t.pedantic,this.tls_required=!!t.tls||void 0,this.name=t.name;J(this,(t&&"function"==typeof t.authenticator?t.authenticator(r):{})||{})}}class vr extends we{sid;queue;draining;max;subject;drained;protocol;timer;info;cleanupFn;closed;requestSubject;constructor(e,t,r={}){super(),J(this,r),this.protocol=e,this.subject=t,this.draining=!1,this.noIterator="function"==typeof r.callback,this.closed=X();const s=!e.options?.noAsyncTraces;r.timeout&&(this.timer=Y(r.timeout,s),this.timer.then((()=>{this.timer=void 0})).catch((e=>{this.stop(e),this.noIterator&&this.callback(e,{})}))),this.noIterator||this.iterClosed.then((()=>{this.closed.resolve(),this.unsubscribe()}))}setPrePostHandlers(e){if(this.noIterator){const t=this.callback,r=e.ingestionFilterFn?e.ingestionFilterFn:()=>({ingest:!0,protocol:!1}),s=e.protocolFilterFn?e.protocolFilterFn:()=>!0,i=e.dispatchedFn?e.dispatchedFn:()=>{};this.callback=(e,n)=>{const{ingest:o}=r(n);o&&s(n)&&(t(e,n),i(n))}}else this.protocolFilterFn=e.protocolFilterFn,this.dispatchedFn=e.dispatchedFn}callback(e,t){this.cancelTimeout(),e?this.stop(e):this.push(t)}close(){if(!this.isClosed()){this.cancelTimeout();const e=()=>{if(this.stop(),this.cleanupFn)try{this.cleanupFn(this,this.info)}catch(e){}this.closed.resolve()};this.noIterator?e():this.push(e)}}unsubscribe(e){this.protocol.unsubscribe(this,e)}cancelTimeout(){this.timer&&(this.timer.cancel(),this.timer=void 0)}drain(){return this.protocol.isClosed()?Promise.reject(U.errorForCode(F.ConnectionClosed)):this.isClosed()?Promise.reject(U.errorForCode(F.SubClosed)):(this.drained||(this.draining=!0,this.protocol.unsub(this),this.drained=this.protocol.flush(X()).then((()=>{this.protocol.subscriptions.cancel(this)})).catch((()=>{this.protocol.subscriptions.cancel(this)}))),this.drained)}isDraining(){return this.draining}isClosed(){return this.done}getSubject(){return this.subject}getMax(){return this.max}getID(){return this.sid}}class _r{mux;subs;sidCounter;constructor(){this.sidCounter=0,this.mux=null,this.subs=new Map}size(){return this.subs.size}add(e){return this.sidCounter++,e.sid=this.sidCounter,this.subs.set(e.sid,e),e}setMux(e){return this.mux=e,e}getMux(){return this.mux}get(e){return this.subs.get(e)}resub(e){return this.sidCounter++,this.subs.delete(e.sid),e.sid=this.sidCounter,this.subs.set(e.sid,e),e}all(){return Array.from(this.subs.values())}cancel(e){e&&(e.close(),this.subs.delete(e.sid))}handleError(e){if(e&&e.permissionContext){const t=e.permissionContext,r=this.all();let s;if("subscription"===t.operation&&(s=r.find((e=>e.subject===t.subject&&e.queue===t.queue))),"publish"===t.operation&&(s=r.find((e=>e.requestSubject===t.subject))),s)return s.callback(e,{}),s.close(),this.subs.delete(s.sid),s!==this.mux}return!1}close(){this.subs.forEach((e=>{e.close()}))}}class wr{connected;connectedOnce;infoReceived;info;muxSubscriptions;options;outbound;pongs;subscriptions;transport;noMorePublishing;connectError;publisher;_closed;closed;listeners;heartbeats;parser;outMsgs;inMsgs;outBytes;inBytes;pendingLimit;lastError;abortReconnect;whyClosed;servers;server;features;connectPromise;constructor(e,t){this._closed=!1,this.connected=!1,this.connectedOnce=!1,this.infoReceived=!1,this.noMorePublishing=!1,this.abortReconnect=!1,this.listeners=[],this.pendingLimit=32768,this.outMsgs=0,this.inMsgs=0,this.outBytes=0,this.inBytes=0,this.options=e,this.publisher=t,this.subscriptions=new _r,this.muxSubscriptions=new Kt,this.outbound=new Be,this.pongs=[],this.whyClosed="",this.pendingLimit=e.pendingLimit||this.pendingLimit,this.features=new Ot({major:0,minor:0,micro:0}),this.connectPromise=null;const r="string"==typeof e.servers?[e.servers]:e.servers;this.servers=new Jt(r,{randomize:!e.noRandomize}),this.closed=X(),this.parser=new ir(this),this.heartbeats=new Yt(this,this.options.pingInterval||dr,this.options.maxPingOut||2)}resetOutbound(){this.outbound.reset();const e=this.pongs;this.pongs=[];const t=U.errorForCode(F.Disconnect);t.stack="",e.forEach((e=>{e.reject(t)})),this.parser=new ir(this),this.infoReceived=!1}dispatchStatus(e){this.listeners.forEach((t=>{t.push(e)}))}status(){const e=new we;return this.listeners.push(e),e}prepare(){this.transport&&this.transport.discard(),this.info=void 0,this.resetOutbound();const e=X();return e.catch((()=>{})),this.pongs.unshift(e),this.connectError=t=>{e.reject(t)},this.transport=function(){if(!Mt||"function"!=typeof Mt.factory)throw new Error("transport fn is not set");return Mt.factory()}(),this.transport.closed().then((async e=>{this.connected=!1,this.isClosed()||await this.disconnected(this.transport.closeError||this.lastError)})),e}disconnect(){this.dispatchStatus({type:j.StaleConnection,data:""}),this.transport.disconnect()}reconnect(){return this.connected&&(this.dispatchStatus({type:j.ClientInitiatedReconnect,data:""}),this.transport.disconnect()),Promise.resolve()}async disconnected(e){this.dispatchStatus({type:N.Disconnect,data:this.servers.getCurrentServer().toString()}),this.options.reconnect?await this.dialLoop().then((()=>{this.dispatchStatus({type:N.Reconnect,data:this.servers.getCurrentServer().toString()}),this.lastError?.code===F.AuthenticationExpired&&(this.lastError=void 0)})).catch((e=>{this._close(e)})):await this._close(e)}async dial(e){const t=this.prepare();let r;try{r=Y(this.options.timeout||2e4);const t=this.transport.connect(e,this.options);await Promise.race([t,r]),(async()=>{try{for await(const e of this.transport)this.parser.parse(e)}catch(e){console.log("reader closed",e)}})().then()}catch(e){t.reject(e)}try{await Promise.race([r,t]),r&&r.cancel(),this.connected=!0,this.connectError=void 0,this.sendSubscriptions(),this.connectedOnce=!0,this.server.didConnect=!0,this.server.reconnects=0,this.flushPending(),this.heartbeats.start()}catch(e){throw r&&r.cancel(),await this.transport.close(e),e}}async _doDial(e){const{resolve:t}=this.options,r=await e.resolve({fn:Ft(),debug:this.options.debug,randomize:!this.options.noRandomize,resolve:t});let s=null;for(const e of r)try{return s=null,this.dispatchStatus({type:j.Reconnecting,data:e.toString()}),void await this.dial(e)}catch(e){s=e}throw s}dialLoop(){return null===this.connectPromise&&(this.connectPromise=this.dodialLoop(),this.connectPromise.then((()=>{})).catch((()=>{})).finally((()=>{this.connectPromise=null}))),this.connectPromise}async dodialLoop(){let e;for(;;){this._closed&&this.servers.clear();const t=this.options.reconnectDelayHandler?this.options.reconnectDelayHandler():2e3;let r=t;const s=this.selectServer();if(!s||this.abortReconnect)throw e||(this.lastError?this.lastError:U.errorForCode(F.ConnectionRefused));const i=Date.now();if(0===s.lastConnect||s.lastConnect+t<=i){s.lastConnect=Date.now();try{await this._doDial(s);break}catch(t){if(e=t,!this.connectedOnce){if(this.options.waitOnFirstConnect)continue;this.servers.removeCurrentServer()}s.reconnects++;const r=this.options.maxReconnectAttempts||0;-1!==r&&s.reconnects>=r&&this.servers.removeCurrentServer()}}else r=Math.min(r,s.lastConnect+t-i),await Q(r)}}static async connect(e,t){const h=new wr(e,t);return await h.dialLoop(),h}static toError(e){const t=e?e.toLowerCase():"";if(-1!==t.indexOf("permissions violation")){const t=new U(e,F.PermissionsViolation),r=e.match(/(Publish|Subscription) to "(\S+)"/);if(r){t.permissionContext={operation:r[1].toLowerCase(),subject:r[2],queue:void 0};const s=e.match(/using queue "(\S+)"/);s&&(t.permissionContext.queue=s[1])}return t}return-1!==t.indexOf("authorization violation")?new U(e,F.AuthorizationViolation):-1!==t.indexOf("user authentication expired")?new U(e,F.AuthenticationExpired):-1!=t.indexOf("account authentication expired")?new U(e,F.AccountExpired):-1!==t.indexOf("authentication timeout")?new U(e,F.AuthenticationTimeout):new U(e,F.ProtocolError)}processMsg(e,t){if(this.inMsgs++,this.inBytes+=t.length,!this.subscriptions.sidCounter)return;const r=this.subscriptions.get(e.sid);r&&(r.received+=1,r.callback&&r.callback(null,new le(e,t,this)),void 0!==r.max&&r.received>=r.max&&r.unsubscribe())}processError(e){const t=A(e),r=wr.toError(t),s={type:N.Error,data:r.code};if(r.isPermissionError()){let e=!1;if(r.permissionContext){s.permissionContext=r.permissionContext;const t=this.subscriptions.getMux();e=t?.subject===r.permissionContext.subject}this.subscriptions.handleError(r),this.muxSubscriptions.handleError(e,r),e&&this.subscriptions.setMux(null)}this.dispatchStatus(s),this.handleError(r)}handleError(e){e.isAuthError()?this.handleAuthError(e):(e.isProtocolError()||e.isAuthTimeout())&&(this.lastError=e),e.isPermissionError()||(this.lastError=e)}handleAuthError(e){this.lastError&&e.code===this.lastError.code&&!1===this.options.ignoreAuthErrorAbort&&(this.abortReconnect=!0),this.connectError?this.connectError(e):this.disconnect()}processPing(){this.transport.send(gr)}processPong(){const e=this.pongs.shift();e&&e.resolve()}processInfo(e){const t=JSON.parse(A(e));this.info=t;const r=this.options&&this.options.ignoreClusterUpdates?void 0:this.servers.update(t,this.transport.isEncrypted());if(!this.infoReceived){this.features.update(kt(t.version)),this.infoReceived=!0,this.transport.isEncrypted()&&this.servers.updateTLSName();const{version:e,lang:r}=this.transport;try{const s=new br({version:e,lang:r},this.options,t.nonce);t.headers&&(s.headers=!0,s.no_responders=!0);const i=JSON.stringify(s);this.transport.send(O(`CONNECT ${i}${$t}`)),this.transport.send(yr)}catch(e){this._close(e)}}r&&this.dispatchStatus({type:N.Update,data:r});void 0!==t.ldm&&t.ldm&&this.dispatchStatus({type:N.LDM,data:this.servers.getCurrentServer().toString()})}push(e){switch(e.kind){case rr.MSG:{const{msg:t,data:r}=e;this.processMsg(t,r);break}case rr.OK:break;case rr.ERR:this.processError(e.data);break;case rr.PING:this.processPing();break;case rr.PONG:this.processPong();break;case rr.INFO:this.processInfo(e.data)}}sendCommand(e,...t){const r=this.outbound.length();let s;s="string"==typeof e?O(e):e,this.outbound.fill(s,...t),0===r?queueMicrotask((()=>{this.flushPending()})):this.outbound.size()>=this.pendingLimit&&this.flushPending()}publish(e,t=k,r){let s;if(t instanceof Uint8Array)s=t;else{if("string"!=typeof t)throw U.errorForCode(F.BadPayload);s=T.encode(t)}let i=s.length;(r=r||{}).reply=r.reply||"";let n,o=k,a=0;if(r.headers){if(this.info&&!this.info.headers)throw new U("headers",F.ServerOptionNotAvailable);o=r.headers.encode(),a=o.length,i=s.length+a}if(this.info&&i>this.info.max_payload)throw U.errorForCode(F.MaxPayloadExceeded);this.outBytes+=i,this.outMsgs++,r.headers?(n=r.reply?`HPUB ${e} ${r.reply} ${a} ${i}\r\n`:`HPUB ${e} ${a} ${i}\r\n`,this.sendCommand(n,o,s,Lt)):(n=r.reply?`PUB ${e} ${r.reply} ${i}\r\n`:`PUB ${e} ${i}\r\n`,this.sendCommand(n,s,Lt))}request(e){return this.initMux(),this.muxSubscriptions.add(e),e}subscribe(e){return this.subscriptions.add(e),this._subunsub(e),e}_sub(e){e.queue?this.sendCommand(`SUB ${e.subject} ${e.queue} ${e.sid}\r\n`):this.sendCommand(`SUB ${e.subject} ${e.sid}\r\n`)}_subunsub(e){return this._sub(e),e.max&&this.unsubscribe(e,e.max),e}unsubscribe(e,t){this.unsub(e,t),(void 0===e.max||e.received>=e.max)&&this.subscriptions.cancel(e)}unsub(e,t){e&&!this.isClosed()&&(t?this.sendCommand(`UNSUB ${e.sid} ${t}\r\n`):this.sendCommand(`UNSUB ${e.sid}\r\n`),e.max=t)}resub(e,t){e&&!this.isClosed()&&(this.unsub(e),e.subject=t,this.subscriptions.resub(e),this._sub(e))}flush(e){return e||(e=X()),this.pongs.push(e),this.outbound.fill(yr),this.flushPending(),e}sendSubscriptions(){const e=[];this.subscriptions.all().forEach((t=>{const r=t;r.queue?e.push(`SUB ${r.subject} ${r.queue} ${r.sid}${$t}`):e.push(`SUB ${r.subject} ${r.sid}${$t}`)})),e.length&&this.transport.send(O(e.join("")))}async _close(e){this._closed||(this.whyClosed=new Error("close trace").stack||"",this.heartbeats.cancel(),this.connectError&&(this.connectError(e),this.connectError=void 0),this.muxSubscriptions.close(),this.subscriptions.close(),this.listeners.forEach((e=>{e.stop()})),this._closed=!0,await this.transport.close(e),await this.closed.resolve(e))}close(){return this._close()}isClosed(){return this._closed}drain(){const e=this.subscriptions.all(),t=[];return e.forEach((e=>{t.push(e.drain())})),Promise.all(t).then((async()=>(this.noMorePublishing=!0,await this.flush(),this.close()))).catch((()=>{}))}flushPending(){if(this.infoReceived&&this.connected&&this.outbound.size()){const e=this.outbound.drain();this.transport.send(e)}}initMux(){if(!this.subscriptions.getMux()){const e=this.muxSubscriptions.init(this.options.inboxPrefix),t=new vr(this,`${e}*`);t.callback=this.muxSubscriptions.dispatcher(),this.subscriptions.setMux(t),this.subscribe(t)}}selectServer(){const e=this.servers.selectServer();if(void 0!==e)return this.server=e,this.server}getServer(){return this.server}}class Sr{msg;constructor(e){this.msg=e}get data(){return this.msg.data}get sid(){return this.msg.sid}get subject(){return this.msg.subject}get reply(){return this.msg.reply||""}get headers(){return this.msg.headers}respond(e,t){return this.msg.respond(e,t)}respondError(e,t,r,s){return(s=s||{}).headers=s.headers||ne(),s.headers?.set(G,`${e}`),s.headers?.set(z,t),this.msg.respond(r,s)}json(e){return this.msg.json(e)}string(){return this.msg.string()}}class Cr{subject;queue;srv;constructor(e,t="",r=""){""!==t&&function(e,t){if(-1!==t.indexOf(" "))throw new Error(`${e} cannot contain spaces: '${t}'`);t.split(".").forEach((r=>{if(">"===r)throw new Error(`${e} name cannot contain internal '>': '${t}'`)}))}("service group",t);let s="";if(e instanceof Er)this.srv=e,s="";else{if(!(e instanceof Cr))throw new Error("unknown ServiceGroup type");{const t=e;this.srv=t.srv,""===r&&""!==t.queue&&(r=t.queue),s=t.subject}}this.subject=this.calcSubject(s,t),this.queue=r}calcSubject(e,t=""){return""===t?e:""!==e?`${e}.${t}`:t}addEndpoint(e="",t){const r="function"==typeof(t=t||{subject:e})?{handler:t,subject:e}:t;me("endpoint",e);let{subject:s,handler:i,metadata:n,queue:o}=r;s=s||e,o=o||this.queue,function(e,t){if(""===t)throw new Error(`${e} cannot be empty`);if(-1!==t.indexOf(" "))throw new Error(`${e} cannot contain spaces: '${t}'`);const r=t.split(".");r.forEach(((s,i)=>{if(">"===s&&i!==r.length-1)throw new Error(`${e} cannot have internal '>': '${t}'`)}))}("endpoint subject",s),s=this.calcSubject(this.subject,s);const a={name:e,subject:s,queue:o,handler:i,metadata:n};return this.srv._addEndpoint(a)}addGroup(e="",t=""){return new Cr(this,e,t)}}class Er{nc;_id;config;handlers;internal;_stopped;_done;started;static controlSubject(e,t="",r="",s){const i=s??"$SRV";return""===t&&""===r?`${i}.${e}`:(me("control subject name",t),""!==r?(me("control subject id",r),`${i}.${e}.${t}.${r}`):`${i}.${e}.${t}`)}constructor(e,t={name:"",version:""}){this.nc=e,this.config=Object.assign({},t),this.config.queue||(this.config.queue="q"),me("name",this.config.name),me("queue",this.config.queue),kt(this.config.version),this._id=M.next(),this.internal=[],this._done=X(),this._stopped=!1,this.handlers=[],this.started=(new Date).toISOString(),this.reset(),this.nc.closed().then((()=>{this.close().catch()})).catch((e=>{this.close(e).catch()}))}get subjects(){return this.handlers.filter((e=>!1===e.internal)).map((e=>e.subject))}get id(){return this._id}get name(){return this.config.name}get description(){return this.config.description??""}get version(){return this.config.version}get metadata(){return this.config.metadata}errorToHeader(e){const h=ne();if(e instanceof V){const t=e;h.set(z,t.message),h.set(G,`${t.code}`)}else h.set(z,e.message),h.set(G,"500");return h}setupHandler(h,e=!1){const t=e?"":h.queue?h.queue:this.config.queue,{name:r,subject:s,handler:i}=h,n=h;n.internal=e,e&&this.internal.push(n),n.stats=new xr(r,s,t),n.queue=t;const o=i?(e,t)=>{if(e)return void this.close(e);const r=Date.now();try{i(e,new Sr(t))}catch(e){n.stats.countError(e),t?.respond(k,{headers:this.errorToHeader(e)})}finally{n.stats.countLatency(r)}}:void 0;return n.sub=this.nc.subscribe(s,{callback:o,queue:t}),n.sub.closed.then((()=>{this._stopped||this.close(new Error(`required subscription ${h.subject} stopped`)).catch()})).catch((e=>{if(!this._stopped){const t=new Error(`required subscription ${h.subject} errored: ${e.message}`);t.stack=e.stack,this.close(t).catch()}})),n}info(){return{type:B.INFO,name:this.name,id:this.id,version:this.version,description:this.description,metadata:this.metadata,endpoints:this.endpoints()}}endpoints(){return this.handlers.map((e=>{const{subject:t,metadata:r,name:s,queue:i}=e;return{subject:t,metadata:r,name:s,queue_group:i}}))}async stats(){const e=[];for(const h of this.handlers){if("function"==typeof this.config.statsHandler)try{h.stats.data=await this.config.statsHandler(h)}catch(e){h.stats.countError(e)}e.push(h.stats.stats(h.qi))}return{type:B.STATS,name:this.name,id:this.id,version:this.version,started:this.started,metadata:this.metadata,endpoints:e}}addInternalHandler(e,t){const r=`${e}`.toUpperCase();this._doAddInternalHandler(`${r}-all`,e,t),this._doAddInternalHandler(`${r}-kind`,e,t,this.name),this._doAddInternalHandler(`${r}`,e,t,this.name,this.id)}_doAddInternalHandler(e,t,r,s="",i=""){const n={};n.name=e,n.subject=Er.controlSubject(t,s,i),n.handler=r,this.setupHandler(n,!0)}start(){const e=ue(),t=e.encode(this.ping());return this.addInternalHandler(Z.PING,((e,r)=>e?(this.close(e).then().catch(),Promise.reject(e)):(r.respond(t),Promise.resolve()))),this.addInternalHandler(Z.STATS,((t,r)=>t?(this.close(t),Promise.reject(t)):this.stats().then((t=>(r?.respond(e.encode(t)),Promise.resolve()))))),this.addInternalHandler(Z.INFO,((t,r)=>t?(this.close(t),Promise.reject(t)):(r?.respond(e.encode(this.info())),Promise.resolve()))),this.handlers.forEach((h=>{const{subject:e}=h;"string"==typeof e&&null!==h.handler&&this.setupHandler(h)})),Promise.resolve(this)}close(e){if(this._stopped)return this._done;this._stopped=!0;let t=[];return this.nc.isClosed()||(t=this.handlers.concat(this.internal).map((h=>h.sub.drain()))),Promise.allSettled(t).then((()=>{this._done.resolve(e||null)})),this._done}get stopped(){return this._done}get isStopped(){return this._stopped}stop(e){return this.close(e)}ping(){return{type:B.PING,name:this.name,id:this.id,version:this.version,metadata:this.metadata}}reset(){if(this.started=(new Date).toISOString(),this.handlers)for(const h of this.handlers)h.stats.reset(h.qi)}addGroup(e,t){return new Cr(this,e,t)}addEndpoint(e,t){return new Cr(this).addEndpoint(e,t)}_addEndpoint(e){const t=new we;t.noIterator="function"==typeof e.handler,t.noIterator||(e.handler=(e,r)=>{e?this.stop(e).catch():t.push(new Sr(r))},t.iterClosed.then((()=>{this.close().catch()})));const r=this.setupHandler(e,!1);return r.qi=t,this.handlers.push(r),t}}class xr{name;subject;average_processing_time;num_requests;processing_time;num_errors;last_error;data;metadata;queue;constructor(e,t,r=""){this.name=e,this.subject=t,this.average_processing_time=0,this.num_errors=0,this.num_requests=0,this.processing_time=0,this.queue=r}reset(e){this.num_requests=0,this.processing_time=0,this.average_processing_time=0,this.num_errors=0,this.last_error=void 0,this.data=void 0;const t=e;t&&(t.time=0,t.processed=0)}countLatency(e){this.num_requests++,this.processing_time+=re(Date.now()-e),this.average_processing_time=Math.round(this.processing_time/this.num_requests)}countError(e){this.num_errors++,this.last_error=e.message}_stats(){const{name:e,subject:t,average_processing_time:r,num_errors:s,num_requests:i,processing_time:n,last_error:o,data:a,queue:c}=this;return{name:e,subject:t,average_processing_time:r,num_errors:s,num_requests:i,processing_time:n,last_error:o,data:a,queue_group:c}}stats(e){const t=e;return!1===t?.noIterator&&(this.processing_time=re(t.time),this.num_requests=t.processed,this.average_processing_time=this.processing_time>0&&this.num_requests>0?this.processing_time/this.num_requests:0),this._stats()}}class kr{nc;prefix;opts;constructor(e,t={strategy:q.JitterTimer,maxWait:2e3},r){this.nc=e,this.prefix=r,this.opts=t}ping(e="",t=""){return this.q(Z.PING,e,t)}stats(e="",t=""){return this.q(Z.STATS,e,t)}info(e="",t=""){return this.q(Z.INFO,e,t)}async q(e,t="",r=""){const s=new we,i=ue(),n=Er.controlSubject(e,t,r,this.prefix),o=await this.nc.requestMany(n,k,this.opts);return(async()=>{for await(const e of o)try{const t=i.decode(e.data);s.push(t)}catch(e){s.push((()=>{s.stop(e)}))}s.push((()=>{s.stop()}))})().catch((e=>{s.stop(e)})),s}}const Tr="KV-Operation",Rr=/^[-/=.\w]+$/,Or=/^[-/=.>*\w]+$/,Ar=/^[-\w]+$/;function Pr(e){if(e.startsWith(".")||e.endsWith(".")||!Rr.test(e))throw new Error(`invalid key: ${e}`)}function Ir(e){if(e.startsWith(".")||e.endsWith(".")||!Or.test(e))throw new Error(`invalid key: ${e}`)}function Mr(e){if(e.startsWith(".")||e.endsWith("."))throw new Error(`invalid key: ${e}`);const t=e.split(".");let r=!1;for(let s=0;s<t.length;s++)switch(t[s]){case"*":r=!0;break;case">":if(s!==t.length-1)throw new Error(`invalid key: ${e}`);r=!0}return r}function Nr(e){if(!Ar.test(e))throw new Error(`invalid bucket name: ${e}`)}var jr;!function(e){e.MsgIdHdr="Nats-Msg-Id",e.ExpectedStreamHdr="Nats-Expected-Stream",e.ExpectedLastSeqHdr="Nats-Expected-Last-Sequence",e.ExpectedLastMsgIdHdr="Nats-Expected-Last-Msg-Id",e.ExpectedLastSubjectSequenceHdr="Nats-Expected-Last-Subject-Sequence"}(jr||(jr={}));class Fr{js;jsm;stream;bucket;direct;codec;prefix;editPrefix;useJsPrefix;_prefixLen;constructor(e,t,r){Nr(e),this.js=t,this.jsm=r,this.bucket=e,this.prefix="$KV",this.editPrefix="",this.useJsPrefix=!1,this._prefixLen=0}static async create(e,t,r={}){Nr(t);const s=await e.jetstreamManager(),i=new Fr(t,e,s);return await i.init(r),i}static async bind(e,t,r={}){const s=await e.jetstreamManager(),i={config:{allow_direct:r.allow_direct}};Nr(t);const n=new Fr(t,e,s);return i.config.name=r.streamName??n.bucketName(),Object.assign(n,i),n.stream=i.config.name,n.codec=r.codec||{key:{encode:e=>e,decode:e=>e},value:{encode:e=>e,decode:e=>e}},n.direct=i.config.allow_direct??!1,n.initializePrefixes(i),n}async init(e={}){const t=Object.assign({replicas:1,history:1,timeout:2e3,max_bytes:-1,maxValueSize:-1,codec:{key:{encode:e=>e,decode:e=>e},value:{encode:e=>e,decode:e=>e}},storage:xe.File},e);this.codec=t.codec;const r={};this.stream=r.name=e.streamName??this.bucketName(),r.retention=Ce.Limits,r.max_msgs_per_subject=t.history,t.maxBucketSize&&(t.max_bytes=t.maxBucketSize),t.max_bytes&&(r.max_bytes=t.max_bytes),r.max_msg_size=t.maxValueSize,r.storage=t.storage;const s=e.placementCluster??"";if(s&&(e.placement={},e.placement.cluster=s,e.placement.tags=[]),e.placement&&(r.placement=e.placement),e.republish&&(r.republish=e.republish),e.description&&(r.description=e.description),e.mirror){const t=Object.assign({},e.mirror);t.name.startsWith(Fe)||(t.name=`${Fe}${t.name}`),r.mirror=t,r.mirror_direct=!0}else if(e.sources){const t=e.sources.map((e=>{const t=Object.assign({},e),r=t.name.startsWith(Fe)?t.name.substring(3):t.name;return t.name.startsWith(Fe)||(t.name=`${Fe}${t.name}`),e.external||r===this.bucket||(t.subject_transforms=[{src:`$KV.${r}.>`,dest:`$KV.${this.bucket}.>`}]),t}));r.sources=t,r.subjects=[this.subjectForBucket()]}else r.subjects=[this.subjectForBucket()];e.metadata&&(r.metadata=e.metadata),"boolean"==typeof e.compression&&(r.compression=e.compression?Oe.S2:Oe.None);const i=this.js.nc,n=i.getServerVersion(),o=!!n&&Tt(n,kt("2.7.2"))>=0;r.discard=o?Ee.New:Ee.Old;const{ok:a,min:c}=i.features.get(Rt.JS_ALLOW_DIRECT);if(!a&&!0===e.allow_direct){const e=n?`${n.major}.${n.minor}.${n.micro}`:"unknown";return Promise.reject(new Error(`allow_direct is not available on server version ${e} - requires ${c}`))}let u;e.allow_direct="boolean"==typeof e.allow_direct?e.allow_direct:a,r.allow_direct=e.allow_direct,this.direct=r.allow_direct,r.num_replicas=t.replicas,t.ttl&&(r.max_age=re(t.ttl)),r.allow_rollup_hdrs=!0;try{u=await this.jsm.streams.info(r.name),u.config.allow_direct||!0!==this.direct||(this.direct=!1)}catch(e){if("stream not found"!==e.message)throw e;u=await this.jsm.streams.add(r)}this.initializePrefixes(u)}initializePrefixes(e){this._prefixLen=0,this.prefix=`$KV.${this.bucket}`,this.useJsPrefix="$JS.API"!==this.js.apiPrefix;const{mirror:t}=e.config;if(t){let e=t.name;if(e.startsWith(Fe)&&(e=e.substring(3)),t.external&&""!==t.external.api){const r=t.name.substring(3);this.useJsPrefix=!1,this.prefix=`$KV.${r}`,this.editPrefix=`${t.external.api}.$KV.${e}`}else this.editPrefix=this.prefix}}bucketName(){return this.stream??`${Fe}${this.bucket}`}subjectForBucket(){return`${this.prefix}.${this.bucket}.>`}subjectForKey(e,t=!1){const r=[];return t?(this.useJsPrefix&&r.push(this.js.apiPrefix),""!==this.editPrefix?r.push(this.editPrefix):r.push(this.prefix)):this.prefix&&r.push(this.prefix),r.push(e),r.join(".")}fullKeyName(e){return""!==this.prefix?`${this.prefix}.${e}`:`$KV.${this.bucket}.${e}`}get prefixLen(){return 0===this._prefixLen&&(this._prefixLen=this.prefix.length+1),this._prefixLen}encodeKey(e){const t=[];for(const r of e.split("."))switch(r){case">":case"*":t.push(r);break;default:t.push(this.codec.key.encode(r))}return t.join(".")}decodeKey(e){const t=[];for(const r of e.split("."))switch(r){case">":case"*":t.push(r);break;default:t.push(this.codec.key.decode(r))}return t.join(".")}validateKey=Pr;validateSearchKey=Ir;hasWildcards=Mr;close(){return Promise.resolve()}dataLen(e,h){const t=h&&h.get(Ie.MessageSizeHdr)||"";return""!==t?parseInt(t,10):e.length}smToEntry(e){return new ys(this.bucket,this.prefixLen,e)}jmToEntry(e){const t=this.decodeKey(e.subject.substring(this.prefixLen));return new bs(this.bucket,t,e)}async create(e,t){let r;try{const r=await this.put(e,t,{previousSeq:0});return Promise.resolve(r)}catch(e){if(r=e,10071!==e?.api_error?.err_code)return Promise.reject(e)}let s=0;try{const i=await this.get(e);return"DEL"===i?.operation||"PURGE"===i?.operation?(s=null!==i?i.revision:0,this.update(e,t,s)):Promise.reject(r)}catch(e){return Promise.reject(e)}}update(e,t,r){if(r<=0)throw new Error("version must be greater than 0");return this.put(e,t,{previousSeq:r})}async put(e,t,r={}){const s=this.encodeKey(e);this.validateKey(s);const i={};if(void 0!==r.previousSeq){const h=ne();i.headers=h,h.set(jr.ExpectedLastSubjectSequenceHdr,`${r.previousSeq}`)}try{return(await this.js.publish(this.subjectForKey(s,!0),t,i)).seq}catch(e){const t=e;return t.isJetStreamError()?(t.message=t.api_error?.description,t.code=`${t.api_error?.code}`,Promise.reject(t)):Promise.reject(e)}}async get(e,t){const r=this.encodeKey(e);this.validateKey(r);let s,i={last_by_subj:this.subjectForKey(r)};t&&t.revision>0&&(i={seq:t.revision});try{if(this.direct){const e=this.jsm.direct;s=await e.getMessage(this.bucketName(),i)}else s=await this.jsm.streams.getMessage(this.bucketName(),i);const e=this.smToEntry(s);return e.key!==r?null:e}catch(e){if(e.code===F.JetStream404NoMessages)return null;throw e}}purge(e,t){return this._deleteOrPurge(e,"PURGE",t)}delete(e,t){return this._deleteOrPurge(e,"DEL",t)}async purgeDeletes(e=18e5){const t=X(),r=[],s=await this.watch({key:">",initializedFn:()=>{t.resolve()}});(async()=>{for await(const e of s)"DEL"!==e.operation&&"PURGE"!==e.operation||r.push(e)})().then(),await t,s.stop();const i=Date.now()-e,n=r.map((e=>{const t=this.subjectForKey(e.key);return e.created.getTime()>=i?this.jsm.streams.purge(this.stream,{filter:t,keep:1}):this.jsm.streams.purge(this.stream,{filter:t,keep:0})})),o=await Promise.all(n);return o.unshift({success:!0,purged:0}),o.reduce(((e,t)=>(e.purged+=t.purged,e)))}async _deleteOrPurge(e,t,r){if(!this.hasWildcards(e))return this._doDeleteOrPurge(e,t,r);const s=await this.keys(e),i=[];for await(const e of s)i.push(this._doDeleteOrPurge(e,t)),100===i.length&&(await Promise.all(i),i.length=0);i.length>0&&await Promise.all(i)}async _doDeleteOrPurge(e,t,r){const s=this.encodeKey(e);this.validateKey(s);const h=ne();h.set(Tr,t),"PURGE"===t&&h.set(Ie.RollupHdr,Ie.RollupValueSubject),r?.previousSeq&&h.set(jr.ExpectedLastSubjectSequenceHdr,`${r.previousSeq}`),await this.js.publish(this.subjectForKey(s,!0),k,{headers:h})}_buildCC(e,t,r={}){let s,i=(Array.isArray(e)?e:[e]).map((e=>{const t=this.encodeKey(e);return this.validateSearchKey(e),this.fullKeyName(t)})),n=ke.LastPerSubject;return t===Me.AllHistory&&(n=ke.All),t===Me.UpdatesOnly&&(n=ke.New),1===i.length&&(s=i[0],i=void 0),Object.assign({deliver_policy:n,ack_policy:Te.None,filter_subjects:i,filter_subject:s,flow_control:!0,idle_heartbeat:re(5e3)},r)}remove(e){return this.purge(e)}async history(e={}){const t=e.key??">",r=new we,s={};let i;s.headers_only=e.headers_only||!1,i=()=>{r.stop()};let n=0;const o=this._buildCC(t,Me.AllHistory,s),a=o.filter_subject,c=Le(o);c.bindStream(this.stream),c.orderedConsumer(),c.callback(((e,t)=>{if(e)r.stop(e);else if(t){const e=this.jmToEntry(t);r.push(e),r.received++,(i&&n>0&&r.received>=n||0===t.info.pending)&&(r.push(i),i=void 0)}}));const u=await this.js.subscribe(a,c);if(i){const{info:{last:e}}=u,t=e.num_pending+e.delivered.consumer_seq;if(0===t||r.received>=t)try{i()}catch(e){r.stop(e)}finally{i=void 0}else n=t}return r._data=u,r.iterClosed.then((()=>{u.unsubscribe()})),u.closed.then((()=>{r.stop()})).catch((e=>{r.stop(e)})),r}canSetWatcherName(){const e=this.js.nc,{ok:t}=e.features.get(Rt.JS_NEW_CONSUMER_CREATE_API);return t}async watch(e={}){const t=e.key??">",r=new we,s={};s.headers_only=e.headers_only||!1;let i=Me.LastValue;e.include===Me.AllHistory?i=Me.AllHistory:e.include===Me.UpdatesOnly&&(i=Me.UpdatesOnly);const n=!0===e.ignoreDeletes;let o=e.initializedFn,a=0;const c=this._buildCC(t,i,s),u=c.filter_subject,l=Le(c);this.canSetWatcherName()&&l.consumerName(M.next()),l.bindStream(this.stream),e.resumeFromRevision&&e.resumeFromRevision>0&&l.startSequence(e.resumeFromRevision),l.orderedConsumer(),l.callback(((e,t)=>{if(e)r.stop(e);else if(t){const e=this.jmToEntry(t);if(n&&"DEL"===e.operation)return;r.push(e),r.received++,o&&(a>0&&r.received>=a||0===t.info.pending)&&(r.push(o),o=void 0)}}));const d=await this.js.subscribe(u,l);if(o){const{info:{last:e}}=d,t=e.num_pending+e.delivered.consumer_seq;if(0===t||r.received>=t)try{o()}catch(e){r.stop(e)}finally{o=void 0}else a=t}return r._data=d,r.iterClosed.then((()=>{d.unsubscribe()})),d.closed.then((()=>{r.stop()})).catch((e=>{r.stop(e)})),r}async keys(e=">"){const t=new we,r=this._buildCC(e,Me.LastValue,{headers_only:!0}),s=Array.isArray(e)?">":r.filter_subject,i=Le(r);i.bindStream(this.stream),i.orderedConsumer();const n=await this.js.subscribe(s,i);(async()=>{for await(const e of n){const r=e.headers?.get(Tr);if("DEL"!==r&&"PURGE"!==r){const r=this.decodeKey(e.subject.substring(this.prefixLen));t.push(r)}0===e.info.pending&&n.unsubscribe()}})().then((()=>{t.stop()})).catch((e=>{t.stop(e)}));return 0===n.info.last.num_pending&&n.unsubscribe(),t}purgeBucket(e){return this.jsm.streams.purge(this.bucketName(),e)}destroy(){return this.jsm.streams.delete(this.bucketName())}async status(){const e=this.js.nc,t=e.info?.cluster??"",r=this.bucketName(),s=await this.jsm.streams.info(r);return new $r(s,t)}}class $r{si;cluster;constructor(e,t=""){this.si=e,this.cluster=t}get bucket(){return this.si.config.name.startsWith(Fe)?this.si.config.name.substring(3):this.si.config.name}get values(){return this.si.state.messages}get history(){return this.si.config.max_msgs_per_subject}get ttl(){return se(this.si.config.max_age)}get bucket_location(){return this.cluster}get backingStore(){return this.si.config.storage}get storage(){return this.si.config.storage}get replicas(){return this.si.config.num_replicas}get description(){return this.si.config.description??""}get maxBucketSize(){return this.si.config.max_bytes}get maxValueSize(){return this.si.config.max_msg_size}get max_bytes(){return this.si.config.max_bytes}get placement(){return this.si.config.placement||{cluster:"",tags:[]}}get placementCluster(){return this.si.config.placement?.cluster??""}get republish(){return this.si.config.republish??{src:"",dest:""}}get streamInfo(){return this.si}get size(){return this.si.state.bytes}get metadata(){return this.si.config.metadata??{}}get compression(){return!!this.si.config.compression&&this.si.config.compression!==Oe.None}}const Lr="OBJ_",Ur="SHA-256=";class Dr{si;backingStore;constructor(e){this.si=e,this.backingStore="JetStream"}get bucket(){return(e=this.si.config.name).startsWith(Lr)?e.substring(4):e;var e}get description(){return this.si.config.description??""}get ttl(){return this.si.config.max_age}get storage(){return this.si.config.storage}get replicas(){return this.si.config.num_replicas}get sealed(){return this.si.config.sealed}get size(){return this.si.state.bytes}get streamInfo(){return this.si}get metadata(){return this.si.config.metadata}get compression(){return!!this.si.config.compression&&this.si.config.compression!==Oe.None}}function qr(e){if(void 0===e)return;const{domain:t}=e;if(void 0===t)return e;const r=Object.assign({},e);if(delete r.domain,""===t)return r;if(r.external)throw new Error("domain and external are both set");return r.external={api:`$JS.${t}.API`},r}var Br,zr,Gr;!function(e){e[e.Unset=-1]="Unset",e[e.Consume=0]="Consume",e[e.Fetch=1]="Fetch"}(Br||(Br={})),function(e){e.HeartbeatsMissed="heartbeats_missed",e.ConsumerNotFound="consumer_not_found",e.StreamNotFound="stream_not_found",e.ConsumerDeleted="consumer_deleted",e.OrderedConsumerRecreated="ordered_consumer_recreated",e.NoResponders="no_responders"}(zr||(zr={})),function(e){e.DebugEvent="debug",e.Discard="discard",e.Reset="reset",e.Next="next"}(Gr||(Gr={}));const Vr=Uint8Array.of(43,65,67,75),Hr=Uint8Array.of(45,78,65,75),Wr=Uint8Array.of(43,87,80,73),Zr=Uint8Array.of(43,78,88,84),Jr=Uint8Array.of(43,84,69,82,77),Kr=Uint8Array.of(32);function Yr(e,t=5e3){return new Cs(e,t)}class Qr extends we{consumer;opts;sub;monitor;pending;inbox;refilling;pong;callback;timeout;cleanupHandler;listeners;statusIterator;forOrderedConsumer;resetHandler;abortOnMissingResource;bind;inBackOff;constructor(e,t,r=!1){super(),this.consumer=e;const s=t;this.opts=this.parseOptions(t,r),this.callback=s.callback||null,this.noIterator="function"==typeof this.callback,this.monitor=null,this.pong=null,this.pending={msgs:0,bytes:0,requests:0},this.refilling=r,this.timeout=null,this.inbox=H(e.api.nc.options.inboxPrefix),this.listeners=[],this.forOrderedConsumer=!1,this.abortOnMissingResource=!0===s.abort_on_missing_resource,this.bind=!0===s.bind,this.inBackOff=!1,this.start()}start(){const{max_messages:e,max_bytes:t,idle_heartbeat:r,threshold_bytes:s,threshold_messages:i}=this.opts;this.closed().then((e=>{if(this.cleanupHandler)try{this.cleanupHandler(e)}catch(e){}}));const{sub:n}=this;n&&n.unsubscribe(),this.sub=this.consumer.api.nc.subscribe(this.inbox,{callback:(r,n)=>{if(r)return void this.stop(r);this.monitor?.work();if(n.subject===this.inbox){if(ye(n))return;const e=n.headers?.code,t=n.headers?.description?.toLowerCase()||"unknown",{msgsLeft:r,bytesLeft:s}=this.parseDiscard(n.headers);if(r>0||s>0)this.pending.msgs-=r,this.pending.bytes-=s,this.pending.requests--,this.notify(Gr.Discard,{msgsLeft:r,bytesLeft:s});else{if(400===e)return void this.stop(new U(t,`${e}`));if(409===e&&"consumer deleted"===t){if(this.notify(zr.ConsumerDeleted,`${e} ${t}`),!this.refilling||this.abortOnMissingResource){const r=new U(t,`${e}`);return void this.stop(r)}}else if(503===e){if(this.notify(zr.NoResponders,`${e} No Responders`),!this.refilling||this.abortOnMissingResource){const t=new U("no responders",`${e}`);return void this.stop(t)}}else this.notify(Gr.DebugEvent,`${e} ${t}`)}}else this._push(Yr(n,this.consumer.api.timeout)),this.received++,this.pending.msgs&&this.pending.msgs--,this.pending.bytes&&(this.pending.bytes-=n.size());if(0===this.pending.msgs&&0===this.pending.bytes&&(this.pending.requests=0),this.refilling){if(e&&this.pending.msgs<=i||t&&this.pending.bytes<=s){const e=this.pullOptions();this.pull(e)}}else 0===this.pending.requests&&this._push((()=>{this.stop()}))}}),this.sub.closed.then((()=>{this.sub.draining&&this._push((()=>{this.stop()}))})),r&&(this.monitor=new Se(r,(e=>(this.notify(zr.HeartbeatsMissed,e),this.resetPending().then((()=>{})).catch((()=>{})),!1)),{maxOut:2})),(async()=>{const e=this.consumer.api.nc.status();this.statusIterator=e;for await(const t of e)switch(t.type){case N.Disconnect:this.monitor?.cancel();break;case N.Reconnect:this.resetPending().then((e=>{e&&this.monitor?.restart()})).catch((()=>{}))}})(),this.pull(this.pullOptions())}_push(e){if(this.callback){const t="function"==typeof e?e:null;try{t?t():this.callback(e)}catch(e){this.stop(e)}}else super.push(e)}notify(e,t){this.listeners.length>0&&(()=>{this.listeners.forEach((r=>{r.done||r.push({type:e,data:t})}))})()}resetPending(){return this.bind?this.resetPendingNoInfo():this.resetPendingWithInfo()}resetPendingNoInfo(){return this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),Promise.resolve(!0)}async resetPendingWithInfo(){if(this.inBackOff)return!1;let e=0,t=0;const r=te([this.opts.expires]);let s=0;for(;;){if(this.done)return!1;if(this.consumer.api.nc.isClosed())return console.error("aborting resetPending - connection is closed"),!1;try{return await this.consumer.info(),this.inBackOff=!1,e=0,this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),!0}catch(i){if("stream not found"===i.message){if(t++,this.notify(zr.StreamNotFound,t),!this.refilling||this.abortOnMissingResource)return this.stop(i),!1}else if("consumer not found"===i.message){if(e++,this.notify(zr.ConsumerNotFound,e),this.resetHandler)try{this.resetHandler()}catch(e){}if(!this.refilling||this.abortOnMissingResource)return this.stop(i),!1;if(this.forOrderedConsumer)return!1}else e=0,t=0;this.inBackOff=!0;const n=Q(r.backoff(s));await Promise.race([n,this.consumer.api.nc.closed()]),n.cancel(),s++}}}pull(e){this.pending.bytes+=e.max_bytes??0,this.pending.msgs+=e.batch??0,this.pending.requests++;const t=this.consumer.api.nc;this._push((()=>{t.publish(`${this.consumer.api.prefix}.CONSUMER.MSG.NEXT.${this.consumer.stream}.${this.consumer.name}`,this.consumer.api.jc.encode(e),{reply:this.inbox}),this.notify(Gr.Next,e)}))}pullOptions(){return{batch:this.opts.max_messages-this.pending.msgs,max_bytes:this.opts.max_bytes-this.pending.bytes,idle_heartbeat:re(this.opts.idle_heartbeat),expires:re(this.opts.expires)}}parseDiscard(e){const t={msgsLeft:0,bytesLeft:0},r=e?.get(Ie.PendingMessagesHdr);r&&(t.msgsLeft=parseInt(r));const s=e?.get(Ie.PendingBytesHdr);return s&&(t.bytesLeft=parseInt(s)),t}trackTimeout(e){this.timeout=e}close(){return this.stop(),this.iterClosed}closed(){return this.iterClosed}clearTimers(){this.monitor?.cancel(),this.monitor=null,this.timeout?.cancel(),this.timeout=null}setCleanupHandler(e){this.cleanupHandler=e}stop(e){this.done||(this.sub?.unsubscribe(),this.clearTimers(),this.statusIterator?.stop(),this._push((()=>{super.stop(e),this.listeners.forEach((e=>{e.stop()}))})))}parseOptions(e,t=!1){const r=e||{};if(r.max_messages=r.max_messages||0,r.max_bytes=r.max_bytes||0,0!==r.max_messages&&0!==r.max_bytes)throw new Error("only specify one of max_messages or max_bytes");if(0===r.max_messages&&(r.max_messages=100),r.expires=r.expires||3e4,r.expires<1e3)throw new Error("expires should be at least 1000ms");if(r.idle_heartbeat=r.idle_heartbeat||r.expires/2,r.idle_heartbeat=r.idle_heartbeat>3e4?3e4:r.idle_heartbeat,t){const e=Math.round(.75*r.max_messages)||1;r.threshold_messages=r.threshold_messages||e;const t=Math.round(.75*r.max_bytes)||1;r.threshold_bytes=r.threshold_bytes||t}return r}status(){const e=new we;return this.listeners.push(e),Promise.resolve(e)}}class Xr extends we{src;listeners;constructor(){super(),this.listeners=[]}setSource(e){this.src&&(this.src.resetHandler=void 0,this.src.setCleanupHandler(),this.src.stop()),this.src=e,this.src.setCleanupHandler((e=>{this.stop(e||void 0)})),(async()=>{const e=await this.src.status();for await(const t of e)this.notify(t.type,t.data)})().catch((()=>{}))}notify(e,t){this.listeners.length>0&&(()=>{this.listeners.forEach((r=>{r.done||r.push({type:e,data:t})}))})()}stop(e){this.done||(this.src?.stop(e),super.stop(e),this.listeners.forEach((e=>{e.stop()})))}close(){return this.stop(),this.iterClosed}closed(){return this.iterClosed}status(){const e=new we;return this.listeners.push(e),Promise.resolve(e)}}class es{api;_info;stream;name;constructor(e,t){this.api=e,this._info=t,this.stream=t.stream_name,this.name=t.name}consume(e={max_messages:100,expires:3e4}){return Promise.resolve(new Qr(this,e,!0))}fetch(e={max_messages:100,expires:3e4}){const t=new Qr(this,e,!1),r=Y(Math.round(1.05*t.opts.expires));return t.closed().catch((()=>{})).finally((()=>{r.cancel()})),r.catch((()=>{t.close().catch()})),t.trackTimeout(r),Promise.resolve(t)}next(e={expires:3e4}){const t=X(),r=e;r.max_messages=1;const s=new Qr(this,r,!1),i=Math.round(1.05*s.opts.expires);i>=6e4&&(async()=>{for await(const e of await s.status())if(e.type===zr.HeartbeatsMissed&&e.data>=2){t.reject(new Error("consumer missed heartbeats"));break}})().catch(),(async()=>{for await(const e of s){t.resolve(e);break}})().catch((()=>{}));const n=Y(i);return s.closed().then((e=>{e?t.reject(e):t.resolve(null)})).catch((e=>{t.reject(e)})).finally((()=>{n.cancel()})),n.catch((e=>{t.resolve(null),s.close().catch()})),s.trackTimeout(n),t}delete(){const{stream_name:e,name:t}=this._info;return this.api.delete(e,t)}info(e=!1){if(e)return Promise.resolve(this._info);const{stream_name:t,name:r}=this._info;return this.api.info(t,r).then((e=>(this._info=e,this._info)))}}class ts{api;consumerOpts;consumer;opts;cursor;stream;namePrefix;serial;currentConsumer;userCallback;iter;type;startSeq;maxInitialReset;constructor(e,t,r={}){this.api=e,this.stream=t,this.cursor={stream_seq:1,deliver_seq:0},this.namePrefix=M.next(),"string"==typeof r.name_prefix&&(fe("name_prefix",r.name_prefix),this.namePrefix=r.name_prefix+this.namePrefix),this.serial=0,this.currentConsumer=null,this.userCallback=null,this.iter=null,this.type=Br.Unset,this.consumerOpts=r,this.maxInitialReset=30,this.startSeq=this.consumerOpts.opt_start_seq||0,this.cursor.stream_seq=this.startSeq>0?this.startSeq-1:0}getConsumerOpts(e){this.serial++;e=0===e?1:e;const t={name:`${this.namePrefix}_${this.serial}`,deliver_policy:ke.StartSequence,opt_start_seq:e,ack_policy:Te.None,inactive_threshold:re(3e5),num_replicas:1};return!0===this.consumerOpts.headers_only&&(t.headers_only=!0),Array.isArray(this.consumerOpts.filterSubjects)&&(t.filter_subjects=this.consumerOpts.filterSubjects),"string"==typeof this.consumerOpts.filterSubjects&&(t.filter_subject=this.consumerOpts.filterSubjects),this.consumerOpts.replay_policy&&(t.replay_policy=this.consumerOpts.replay_policy),e===this.startSeq+1&&(t.deliver_policy=this.consumerOpts.deliver_policy||ke.StartSequence,this.consumerOpts.deliver_policy!==ke.LastPerSubject&&this.consumerOpts.deliver_policy!==ke.New&&this.consumerOpts.deliver_policy!==ke.Last||(delete t.opt_start_seq,t.deliver_policy=this.consumerOpts.deliver_policy),t.deliver_policy===ke.LastPerSubject&&void 0===t.filter_subjects&&void 0===t.filter_subject&&(t.filter_subject=">"),this.consumerOpts.opt_start_time&&(delete t.opt_start_seq,t.deliver_policy=ke.StartTime,t.opt_start_time=this.consumerOpts.opt_start_time),this.consumerOpts.inactive_threshold&&(t.inactive_threshold=re(this.consumerOpts.inactive_threshold))),t}async resetConsumer(e=0){M.next();const t=0===this.serial;this.consumer?.delete().catch((()=>{})),e=0===e?1:e,this.cursor.deliver_seq=0;const r=this.getConsumerOpts(e);r.max_deliver=1,r.mem_storage=!0;const s=te([this.opts?.expires||3e4]);let i;for(let e=0;;e++)try{i=await this.api.add(this.stream,r),this.iter?.notify(zr.OrderedConsumerRecreated,i.name);break}catch(r){if("stream not found"===r.message&&(this.iter?.notify(zr.StreamNotFound,e),this.type===Br.Fetch||!0===this.opts.abort_on_missing_resource))return this.iter?.stop(r),Promise.reject(r);if(t&&e>=this.maxInitialReset)throw r;await Q(s.backoff(e+1))}return i}internalHandler(e){return t=>{if(this.serial!==e)return;const r=t.info.deliverySequence;r===this.cursor.deliver_seq+1?(this.cursor.deliver_seq=r,this.cursor.stream_seq=t.info.streamSequence,this.userCallback?this.userCallback(t):this.iter?.push(t)):this.notifyOrderedResetAndReset()}}async reset(e={max_messages:100,expires:3e4},t){const r=(t=t||{}).fromFetch||!1,s=t.orderedReset||!1;if(this.type===Br.Fetch&&s)return this.iter?.src.stop(),await(this.iter?.closed()),void(this.currentConsumer=null);(null===this.currentConsumer||s)&&(this.currentConsumer=await this.resetConsumer(this.cursor.stream_seq+1)),(null===this.iter||r)&&(this.iter=new Xr),this.consumer=new es(this.api,this.currentConsumer);e.callback=this.internalHandler(this.serial);let i=null;this.type===Br.Fetch&&r?i=await this.consumer.fetch(e):this.type===Br.Consume&&(i=await this.consumer.consume(e));const n=i;n.forOrderedConsumer=!0,n.resetHandler=()=>{this.notifyOrderedResetAndReset()},this.iter.setSource(n)}notifyOrderedResetAndReset(){this.iter?.notify(Gr.Reset,""),this.reset(this.opts,{orderedReset:!0})}async consume(e={max_messages:100,expires:3e4}){if(e.bind)return Promise.reject(new Error("bind is not supported"));if(this.type===Br.Fetch)return Promise.reject(new Error("ordered consumer initialized as fetch"));if(this.type===Br.Consume)return Promise.reject(new Error("ordered consumer doesn't support concurrent consume"));const{callback:t}=e;return t&&(this.userCallback=t),this.type=Br.Consume,this.opts=e,await this.reset(e),this.iter}async fetch(e={max_messages:100,expires:3e4}){if(e.bind)return Promise.reject(new Error("bind is not supported"));if(this.type===Br.Consume)return Promise.reject(new Error("ordered consumer already initialized as consume"));if(!1===this.iter?.done)return Promise.reject(new Error("ordered consumer doesn't support concurrent fetch"));const{callback:t}=e;return t&&(this.userCallback=t),this.type=Br.Fetch,this.opts=e,await this.reset(e,{fromFetch:!0}),this.iter}async next(e={expires:3e4}){const t=e;if(t.bind)return Promise.reject(new Error("bind is not supported"));t.max_messages=1;const r=X();t.callback=e=>{this.userCallback=null,r.resolve(e)};return(await this.fetch(t)).iterClosed.then((e=>{e&&r.reject(e),r.resolve(null)})).catch((e=>{r.reject(e)})),r}delete(){return this.currentConsumer?this.api.delete(this.stream,this.currentConsumer.name).then((e=>Promise.resolve(e))).catch((e=>Promise.reject(e))).finally((()=>{this.currentConsumer=null})):Promise.resolve(!1)}async info(e){return null==this.currentConsumer?(this.currentConsumer=await this.resetConsumer(this.startSeq),Promise.resolve(this.currentConsumer)):e&&this.currentConsumer?Promise.resolve(this.currentConsumer):this.api.info(this.stream,this.currentConsumer.name)}}class rs{api;notified;constructor(e){this.api=e,this.notified=!1}checkVersion(){const e=this.api.nc.features.get(Rt.JS_SIMPLIFICATION);return e.ok?Promise.resolve():Promise.reject(new Error(`consumers framework is only supported on servers ${e.min} or better`))}getPullConsumerFor(e){if(void 0!==e.config.deliver_subject)throw new Error("push consumer not supported");return new es(this.api,e)}async get(e,t={}){return"object"==typeof t?this.ordered(e,t):(await this.checkVersion(),this.api.info(e,t).then((e=>void 0!==e.config.deliver_subject?Promise.reject(new Error("push consumer not supported")):new es(this.api,e))).catch((e=>Promise.reject(e))))}async ordered(e,t){await this.checkVersion();const r=this.api;return new is(r.nc,r.opts).info(e).then((r=>Promise.resolve(new ts(this.api,e,t)))).catch((e=>Promise.reject(e)))}}class ss{api;_info;constructor(e,t){this.api=e,this._info=t}get name(){return this._info.config.name}alternates(){return this.info().then((e=>e.alternates?e.alternates:[]))}async best(){if(await this.info(),this._info.alternates){const e=await this.api.info(this._info.alternates[0].name);return new ss(this.api,e)}return this}info(e=!1,t){return e?Promise.resolve(this._info):this.api.info(this.name,t).then((e=>(this._info=e,this._info)))}getConsumerFromInfo(e){return new rs(new At(this.api.nc,this.api.opts)).getPullConsumerFor(e)}getConsumer(e){return new rs(new At(this.api.nc,this.api.opts)).get(this.name,e)}getMessage(e){return this.api.getMessage(this.name,e)}deleteMessage(e,t){return this.api.deleteMessage(this.name,e,t)}}class is extends Et{constructor(e,t){super(e,t)}checkStreamConfigVersions(e){const t=this.nc;if(e.metadata){const{min:e,ok:r}=t.features.get(Rt.JS_STREAM_CONSUMER_METADATA);if(!r)throw new Error(`stream 'metadata' requires server ${e}`)}if(e.first_seq){const{min:e,ok:r}=t.features.get(Rt.JS_STREAM_FIRST_SEQ);if(!r)throw new Error(`stream 'first_seq' requires server ${e}`)}if(e.subject_transform){const{min:e,ok:r}=t.features.get(Rt.JS_STREAM_SUBJECT_TRANSFORM);if(!r)throw new Error(`stream 'subject_transform' requires server ${e}`)}if(e.compression){const{min:e,ok:r}=t.features.get(Rt.JS_STREAM_COMPRESSION);if(!r)throw new Error(`stream 'compression' requires server ${e}`)}if(e.consumer_limits){const{min:e,ok:r}=t.features.get(Rt.JS_DEFAULT_CONSUMER_LIMITS);if(!r)throw new Error(`stream 'consumer_limits' requires server ${e}`)}function r(e,r){if((r?.subject_transforms?.length||0)>0){const{min:r,ok:s}=t.features.get(Rt.JS_STREAM_SOURCE_SUBJECT_TRANSFORM);if(!s)throw new Error(`${e} 'subject_transforms' requires server ${r}`)}}e.sources&&e.sources.forEach((e=>{r("stream sources",e)})),e.mirror&&r("stream mirror",e.mirror)}async add(e={}){this.checkStreamConfigVersions(e),pe(e.name),e.mirror=qr(e.mirror),e.sources=e.sources?.map(qr);const t=await this._request(`${this.prefix}.STREAM.CREATE.${e.name}`,e);return this._fixInfo(t),t}async delete(e){pe(e);return(await this._request(`${this.prefix}.STREAM.DELETE.${e}`)).success}async update(e,t={}){if("object"==typeof e){const r=e;e=r.name,t=r,console.trace("[33m >> streams.update(config: StreamConfig) api changed to streams.update(name: string, config: StreamUpdateConfig) - this shim will be removed - update your code. [0m")}this.checkStreamConfigVersions(t),pe(e);const r=await this.info(e),s=Object.assign(r.config,t);s.mirror=qr(s.mirror),s.sources=s.sources?.map(qr);const i=await this._request(`${this.prefix}.STREAM.UPDATE.${e}`,s);return this._fixInfo(i),i}async info(e,t){pe(e);const r=`${this.prefix}.STREAM.INFO.${e}`;let s=await this._request(r,t),{total:i,limit:n}=s,o=s.state.subjects?Object.getOwnPropertyNames(s.state.subjects).length:1;if(i&&i>o){const e=[s],a=t||{};let c=0;for(;i>o;){c++,a.offset=n*c;const t=await this._request(r,a);i=t.total,e.push(t);const s=Object.getOwnPropertyNames(t.state.subjects).length;if(o+=s,s<n)break}let u={};for(let t=0;t<e.length;t++)s=e[t],s.state.subjects&&(u=Object.assign(u,s.state.subjects));s.offset=0,s.total=0,s.limit=0,s.state.subjects=u}return this._fixInfo(s),s}list(e=""){const t=e?.length?{subject:e}:{},r=`${this.prefix}.STREAM.LIST`;return new xt(r,(e=>{const t=e;return t.streams.forEach((e=>{this._fixInfo(e)})),t.streams}),this,t)}_fixInfo(e){e.config.sealed=e.config.sealed||!1,e.config.deny_delete=e.config.deny_delete||!1,e.config.deny_purge=e.config.deny_purge||!1,e.config.allow_rollup_hdrs=e.config.allow_rollup_hdrs||!1}async purge(e,t){if(t){const{keep:e,seq:r}=t;if("number"==typeof e&&"number"==typeof r)throw new Error("can specify one of keep or seq")}pe(e);return await this._request(`${this.prefix}.STREAM.PURGE.${e}`,t)}async deleteMessage(e,t,r=!0){pe(e);const s={seq:t};r||(s.no_erase=!0);return(await this._request(`${this.prefix}.STREAM.MSG.DELETE.${e}`,s)).success}async getMessage(e,t){pe(e);const r=await this._request(`${this.prefix}.STREAM.MSG.GET.${e}`,t);return new cs(r)}find(e){return this.findStream(e)}listKvs(){const e=`${this.prefix}.STREAM.LIST`;return new xt(e,(e=>{const t=e.streams.filter((e=>e.config.name.startsWith(Fe)));t.forEach((e=>{this._fixInfo(e)}));let r="";t.length&&(r=this.nc.info?.cluster??"");return t.map((e=>new $r(e,r)))}),this)}listObjectStores(){const e=`${this.prefix}.STREAM.LIST`;return new xt(e,(e=>{const t=e.streams.filter((e=>e.config.name.startsWith(Lr)));t.forEach((e=>{this._fixInfo(e)}));return t.map((e=>new Dr(e)))}),this)}names(e=""){const t=e?.length?{subject:e}:{},r=`${this.prefix}.STREAM.NAMES`;return new xt(r,(e=>e.streams),this,t)}async get(e){const t=await this.info(e);return Promise.resolve(new ss(this,t))}}class ns extends Et{constructor(e,t){super(e,t)}async getMessage(e,t){pe(e);let r=t;const{last_by_subj:s}=r;s&&(r=null);const i=r?this.jc.encode(r):k,n=this.opts.apiPrefix||"$JS.API",o=s?`${n}.DIRECT.GET.${e}.${s}`:`${n}.DIRECT.GET.${e}`,a=await this.nc.request(o,i,{timeout:this.timeout}),c=be(a);if(c)return Promise.reject(c);const u=new os(a);return Promise.resolve(u)}async getBatch(e,t){pe(e);const r=`${this.opts.apiPrefix||"$JS.API"}.DIRECT.GET.${e}`;if(!Array.isArray(t.multi_last)||0===t.multi_last.length)return Promise.reject("multi_last is required");const s=JSON.stringify(t,((e,t)=>"up_to_time"===e&&t instanceof Date?t.toISOString():t)),i=new we,n=await this.nc.requestMany(r,s,{strategy:q.SentinelMsg});return(async()=>{let e,t=!1,r=!1;for await(const s of n){if(!t){t=!0;const i=s.headers?.code||0;if(0!==i&&i<200||i>299){e=s.headers?.description.toLowerCase();break}const n=s.headers?.get("Nats-Num-Pending");if(""===n){r=!0;break}}if(0===s.data.length)break;i.push(new os(s))}i.push((()=>{if(r)throw new Error("batch direct get not supported by the server");if(e)throw new Error(`bad request: ${e}`);i.stop()}))})(),Promise.resolve(i)}}class os{data;header;static jc;constructor(e){if(!e.headers)throw new Error("headers expected");this.data=e.data,this.header=e.headers}get subject(){return this.header.last(Ne.Subject)}get seq(){const e=this.header.last(Ne.Sequence);return"string"==typeof e?parseInt(e):0}get time(){return new Date(Date.parse(this.timestamp))}get timestamp(){return this.header.last(Ne.TimeStamp)}get stream(){return this.header.last(Ne.Stream)}json(e){return ue(e).decode(this.data)}string(){return R.decode(this.data)}}class as extends Et{streams;consumers;direct;constructor(e,t){super(e,t),this.streams=new is(e,t),this.consumers=new At(e,t),this.direct=new ns(e,t)}async getAccountInfo(){return await this._request(`${this.prefix}.INFO`)}jetstream(){return this.nc.jetstream(this.getOptions())}advisories(){const e=new we;return this.nc.subscribe("$JS.EVENT.ADVISORY.>",{callback:(t,r)=>{if(t)throw t;try{const t=this.parseJsResponse(r),s=t.type.split("."),i=s[s.length-1];e.push({kind:i,data:t})}catch(t){e.stop(t)}}}),e}}class cs{_header;smr;static jc;constructor(e){this.smr=e}get subject(){return this.smr.message.subject}get seq(){return this.smr.message.seq}get timestamp(){return this.smr.message.time}get time(){return new Date(Date.parse(this.timestamp))}get data(){return this.smr.message.data?this._parse(this.smr.message.data):k}get header(){if(!this._header)if(this.smr.message.hdrs){const e=this._parse(this.smr.message.hdrs);this._header=ae.decode(e)}else this._header=ne();return this._header}_parse(e){const t=atob(e),r=t.length,s=new Uint8Array(r);for(let e=0;e<r;e++)s[e]=t.charCodeAt(e);return s}json(e){return ue(e).decode(this.data)}string(){return R.decode(this.data)}}class us{api;constructor(e){this.api=e}get(e){return this.api.info(e).then((e=>new ss(this.api,e)))}}class hs{info;hdrs;constructor(e){this.info=e}get name(){return this.info.name}get description(){return this.info.description??""}get headers(){return this.hdrs||(this.hdrs=ae.fromRecord(this.info.headers||{})),this.hdrs}get options(){return this.info.options}get bucket(){return this.info.bucket}get chunks(){return this.info.chunks}get deleted(){return this.info.deleted??!1}get digest(){return this.info.digest}get mtime(){return this.info.mtime}get nuid(){return this.info.nuid}get size(){return this.info.size}get revision(){return this.info.revision}get metadata(){return this.info.metadata||{}}isLink(){return void 0!==this.info.options?.link&&null!==this.info.options?.link}}function ls(e){const t={name:e.name,description:e.description??"",options:e.options,metadata:e.metadata};if(e.headers){const r=e.headers;t.headers=r.toRecord()}return t}class ds{jsm;js;stream;name;constructor(e,t,r){this.name=e,this.jsm=t,this.js=r}_checkNotEmpty(e){return e&&0!==e.length?{name:e}:{name:e,error:new Error("name cannot be empty")}}async info(e){const t=await this.rawInfo(e);return t?new hs(t):null}async list(){const e=[],t=await this.watch({ignoreDeletes:!0,includeHistory:!0});for await(const r of t){if(null===r)break;e.push(r)}return Promise.resolve(e)}async rawInfo(e){const{name:t,error:r}=this._checkNotEmpty(e);if(r)return Promise.reject(r);const s=this._metaSubject(t);try{const e=await this.jsm.streams.getMessage(this.stream,{last_by_subj:s}),t=ue().decode(e.data);return t.revision=e.seq,t}catch(e){return"404"===e.code?null:Promise.reject(e)}}async _si(e){try{return await this.jsm.streams.info(this.stream,e)}catch(e){return"404"===e.code?null:Promise.reject(e)}}async seal(){let e=await this._si();return null===e?Promise.reject(new Error("object store not found")):(e.config.sealed=!0,e=await this.jsm.streams.update(this.stream,e.config),Promise.resolve(new Dr(e)))}async status(e){const t=await this._si(e);return null===t?Promise.reject(new Error("object store not found")):Promise.resolve(new Dr(t))}destroy(){return this.jsm.streams.delete(this.stream)}async _put(e,t,r){const s=this.js.getOptions();(r=r||{timeout:s.timeout}).timeout=r.timeout||s.timeout,r.previousRevision=r.previousRevision??void 0;const{timeout:i,previousRevision:n}=r,o=this.js.nc.info,a=o?.max_payload||1024;(e=e||{}).options=e.options||{};let c=e.options?.max_chunk_size||131072;c=c>a?a:c,e.options.max_chunk_size=c;const u=await this.info(e.name),{name:l,error:d}=this._checkNotEmpty(e.name);if(d)return Promise.reject(d);const p=M.next(),f=this._chunkSubject(p),m=this._metaSubject(l),g=Object.assign({bucket:this.name,nuid:p,size:0,chunks:0},ls(e)),y=X(),b=[],v=new Be;try{const r=t?t.getReader():null,s=bt.create();for(;;){const{done:t,value:o}=r?await r.read():{done:!0,value:void 0};if(t){if(v.size()>0){const e=v.drain();s.update(e),g.chunks++,g.size+=e.length,b.push(this.js.publish(f,e,{timeout:i}))}await Promise.all(b),b.length=0,g.mtime=(new Date).toISOString();const e=qe.encode(s.digest());g.digest=`${Ur}${e}`,g.deleted=!1;const h=ne();"number"==typeof n&&h.set(jr.ExpectedLastSubjectSequenceHdr,`${n}`),h.set(Ie.RollupHdr,Ie.RollupValueSubject);const t=await this.js.publish(m,ue().encode(g),{headers:h,timeout:i});if(g.revision=t.seq,u)try{await this.jsm.streams.purge(this.stream,{filter:`$O.${this.name}.C.${u.nuid}`})}catch(e){}y.resolve(new hs(g));break}if(o)for(v.fill(o);v.size()>c;){g.chunks++,g.size+=c;const t=v.drain(e.options.max_chunk_size);s.update(t),b.push(this.js.publish(f,t,{timeout:i}))}}}catch(e){await this.jsm.streams.purge(this.stream,{filter:f}),y.reject(e)}return y}putBlob(e,t,r){return null===t&&(t=new Uint8Array(0)),this.put(e,function(e){return new ReadableStream({pull(t){t.enqueue(e),t.close()}})}(t),r)}put(e,t,r){return e?.options?.link?Promise.reject(new Error("link cannot be set when putting the object in bucket")):this._put(e,t,r)}async getBlob(e){const t=await this.get(e);if(null===t)return Promise.resolve(null);const r=await Promise.all([t.error,async function(e){const t=new Be,r=e.getReader();for(;;){const{done:e,value:s}=await r.read();if(e)return t.drain();s&&s.length&&t.fill(s)}}(t.data)]);return r[0]?Promise.reject(r[0]):Promise.resolve(r[1])}async get(e){const t=await this.rawInfo(e);if(null===t)return Promise.resolve(null);if(t.deleted)return Promise.resolve(null);if(t.options&&t.options.link){const e=t.options.link.name||"";if(""===e)throw new Error("link is a bucket");return(t.options.link.bucket!==this.name?await ds.create(this.js,t.options.link.bucket):this).get(e)}if(!t.digest.startsWith(Ur))return Promise.reject(new Error(`unknown digest type: ${t.digest}`));const r=vt(t.digest.substring(8));if(null===r)return Promise.reject(new Error(`unable to parse digest: ${t.digest}`));const s=X(),i={info:new hs(t),error:s};if(0===t.size)return i.data=new ReadableStream({pull(e){e.enqueue(new Uint8Array(0)),e.close()}}),s.resolve(null),Promise.resolve(i);let n;const o=Le();o.orderedConsumer();const a=bt.create(),c=`$O.${this.name}.C.${t.nuid}`,u=await this.js.subscribe(c,o);return(async()=>{for await(const e of u)e.data.length>0&&(a.update(e.data),n.enqueue(e.data)),0===e.info.pending&&(_t(r,a.digest())?n.close():n.error(new Error(`received a corrupt object, digests do not match received: ${t.digest} calculated ${r}`)),u.unsubscribe())})().then((()=>{s.resolve()})).catch((e=>{n.error(e),s.reject(e)})),i.data=new ReadableStream({start(e){n=e},cancel(){u.unsubscribe()}}),i}linkStore(e,t){if(!(t instanceof ds))return Promise.reject("bucket required");const r=t,{name:s,error:i}=this._checkNotEmpty(e);if(i)return Promise.reject(i);const n={name:s,options:{link:{bucket:r.name}}};return this._put(n,null)}async link(e,t){const{name:r,error:s}=this._checkNotEmpty(e);if(s)return Promise.reject(s);if(t.deleted)return Promise.reject(new Error("src object is deleted"));if(t.isLink())return Promise.reject(new Error("src object is a link"));const i=await this.rawInfo(e);if(null!==i&&!i.deleted)return Promise.reject(new Error("an object already exists with that name"));const n={bucket:t.bucket,name:t.name},o={name:r,bucket:t.bucket,options:{link:n}};await this.js.publish(this._metaSubject(e),JSON.stringify(o));const a=await this.info(e);return Promise.resolve(a)}async delete(e){const t=await this.rawInfo(e);if(null===t)return Promise.resolve({purged:0,success:!1});t.deleted=!0,t.size=0,t.chunks=0,t.digest="";const r=ue(),h=ne();return h.set(Ie.RollupHdr,Ie.RollupValueSubject),await this.js.publish(this._metaSubject(t.name),r.encode(t),{headers:h}),this.jsm.streams.purge(this.stream,{filter:this._chunkSubject(t.nuid)})}async update(e,t={}){const r=await this.rawInfo(e);if(null===r)return Promise.reject(new Error("object not found"));if(r.deleted)return Promise.reject(new Error("cannot update meta for a deleted object"));t.name=t.name??r.name;const{name:s,error:i}=this._checkNotEmpty(t.name);if(i)return Promise.reject(i);if(e!==t.name){const e=await this.info(t.name);if(e&&!e.deleted)return Promise.reject(new Error("an object already exists with that name"))}t.name=s;const n=Object.assign({},r,ls(t)),o=await this.js.publish(this._metaSubject(n.name),JSON.stringify(n));return e!==t.name&&await this.jsm.streams.purge(this.stream,{filter:this._metaSubject(e)}),Promise.resolve(o)}async watch(e={}){e.includeHistory=e.includeHistory??!1,e.ignoreDeletes=e.ignoreDeletes??!1;let t=!1;const r=new we,s=this._metaSubjectAll();try{await this.jsm.streams.getMessage(this.stream,{last_by_subj:s})}catch(e){"404"===e.code?(r.push(null),t=!0):r.stop(e)}const i=ue(),n=Le();n.orderedConsumer(),e.includeHistory?n.deliverLastPerSubject():(t=!0,n.deliverNew()),n.callback(((s,n)=>{if(s)r.stop(s);else if(null!==n){const s=i.decode(n.data);s.deleted&&!0===e.ignoreDeletes||r.push(s),0!==n.info?.pending||t||(t=!0,r.push(null))}}));const o=await this.js.subscribe(s,n);return r._data=o,r.iterClosed.then((()=>{o.unsubscribe()})),o.closed.then((()=>{r.stop()})).catch((e=>{r.stop(e)})),r}_chunkSubject(e){return`$O.${this.name}.C.${e}`}_metaSubject(e){return`$O.${this.name}.M.${qe.encode(e)}`}_metaSubjectAll(){return`$O.${this.name}.M.>`}async init(e={}){try{this.stream=(Nr(t=this.name),`${Lr}${t}`)}catch(e){return Promise.reject(e)}var t;const r=e?.ttl||0;delete e.ttl;const s=Object.assign({max_age:r},e);s.name=this.stream,s.num_replicas=e.replicas??1,s.allow_direct=!0,s.allow_rollup_hdrs=!0,s.discard=Ee.New,s.subjects=[`$O.${this.name}.C.>`,`$O.${this.name}.M.>`],e.placement&&(s.placement=e.placement),e.metadata&&(s.metadata=e.metadata),"boolean"==typeof e.compression&&(s.compression=e.compression?Oe.S2:Oe.None);try{await this.jsm.streams.info(s.name)}catch(e){"stream not found"===e.message&&await this.jsm.streams.add(s)}}static async create(e,t,r={}){const s=await e.jetstreamManager(),i=new ds(t,s,e);return await i.init(r),Promise.resolve(i)}}class ps{js;constructor(e){this.js=e}kv(e,t={}){const r=this.js,{ok:s,min:i}=r.nc.features.get(Rt.JS_KV);return s?t.bindOnly?Fr.bind(this.js,e,t):Fr.create(this.js,e,t):Promise.reject(new Error(`kv is only supported on servers ${i} or better`))}os(e,t={}){if("function"!=typeof crypto?.subtle?.digest)return Promise.reject(new Error("objectstore: unable to calculate hashes - crypto.subtle.digest with sha256 support is required"));const r=this.js,{ok:s,min:i}=r.nc.features.get(Rt.JS_OBJECTSTORE);return s?ds.create(this.js,e,t):Promise.reject(new Error(`objectstore is only supported on servers ${i} or better`))}}class fs extends Et{consumers;streams;consumerAPI;streamAPI;constructor(e,t){super(e,t),this.consumerAPI=new At(e,t),this.streamAPI=new is(e,t),this.consumers=new rs(this.consumerAPI),this.streams=new us(this.streamAPI)}jetstreamManager(e){void 0===e&&(e=this.opts.checkAPI);const t=Object.assign({},this.opts,{checkAPI:e});return this.nc.jetstreamManager(t)}get apiPrefix(){return this.prefix}get views(){return new ps(this)}async publish(e,t=k,r){(r=r||{}).expect=r.expect||{};const s=r?.headers||ne();r&&(r.msgID&&s.set(jr.MsgIdHdr,r.msgID),r.expect.lastMsgID&&s.set(jr.ExpectedLastMsgIdHdr,r.expect.lastMsgID),r.expect.streamName&&s.set(jr.ExpectedStreamHdr,r.expect.streamName),"number"==typeof r.expect.lastSequence&&s.set(jr.ExpectedLastSeqHdr,`${r.expect.lastSequence}`),"number"==typeof r.expect.lastSubjectSequence&&s.set(jr.ExpectedLastSubjectSequenceHdr,`${r.expect.lastSubjectSequence}`));const i=r.timeout||this.timeout,n={};i&&(n.timeout=i),r&&(n.headers=s);let o,{retries:a,retry_delay:c}=r;a=a||1,c=c||250;for(let r=0;r<a;r++)try{o=await this.nc.request(e,t,n);break}catch(e){if(!("503"===e.code&&r+1<a))throw e;await Q(c)}const u=this.parseJsResponse(o);if(""===u.stream)throw U.errorForCode(F.JetStreamInvalidAck);return u.duplicate=!!u.duplicate&&u.duplicate,u}async pull(e,t,r=0){pe(e),de(t);let s=this.timeout;r>s&&(s=r);const i={batch:1,no_wait:0===(r=r<0?0:re(r)),expires:r},n=await this.nc.request(`${this.prefix}.CONSUMER.MSG.NEXT.${e}.${t}`,this.jc.encode(i),{noMux:!0,timeout:s}),o=be(n);if(o)throw o;return Yr(n,this.timeout)}fetch(e,t,r={}){pe(e),de(t);let s=null;const i=(r.max_bytes??0)>0;let n=0;const o=i?r.max_bytes:0;let a=null;const c={};if(c.batch=r.batch||1,o){const e=this.nc.features.get(Rt.JS_PULL_MAX_BYTES);if(!e.ok)throw new Error(`max_bytes is only supported on servers ${e.min} or better`);c.max_bytes=o}c.no_wait=r.no_wait||!1,c.no_wait&&c.expires&&(c.expires=0);const u=r.expires||0;if(u&&(c.expires=re(u)),0===u&&!1===c.no_wait)throw new Error("expires or no_wait is required");const l=r.idle_heartbeat||0;l&&(c.idle_heartbeat=re(l),!0===r.delay_heartbeat&&(c.idle_heartbeat=re(4*l)));const d=new we,p=c.batch;let f=0;d.protocolFilterFn=(e,t=!1)=>!ye(e.msg)||(a?.work(),!1),d.dispatchedFn=e=>{if(e){if(i&&(n+=e.data.length),f++,s&&0===e.info.pending)return;(1===d.getPending()&&0===e.info.pending||p===f||o>0&&n>=o)&&d.stop()}};const m=H(this.nc.options.inboxPrefix),g=this.nc.subscribe(m,{max:r.batch,callback:(e,t)=>{null===e&&(e=be(t)),null!==e?(s&&(s.cancel(),s=null),!function(e){return"string"==typeof e.code}(e)?d.stop(e):d.stop(null===ws(e)?void 0:e)):(a?.work(),d.received++,d.push(Yr(t,this.timeout)))}});return u&&(s=Y(u),s.catch((()=>{g.isClosed()||(g.drain().catch((()=>{})),s=null),a&&a.cancel()}))),(async()=>{try{l&&(a=new Se(l,(e=>(d.push((()=>{d.err=new U(`${ve.IdleHeartbeatMissed}: ${e}`,F.JetStreamIdleHeartBeat)})),!0))))}catch(e){}await g.closed,null!==s&&(s.cancel(),s=null),a&&a.cancel(),d.stop()})().catch(),this.nc.publish(`${this.prefix}.CONSUMER.MSG.NEXT.${e}.${t}`,this.jc.encode(c),{reply:m}),d}async pullSubscribe(e,t=Le()){const r=await this._processOptions(e,t);if(r.ordered)throw new Error("pull subscribers cannot be be ordered");if(r.config.deliver_subject)throw new Error("consumer info specifies deliver_subject - pull consumers cannot have deliver_subject set");const s=r.config.ack_policy;if(s===Te.None||s===Te.All)throw new Error("ack policy for pull consumers must be explicit");const i=this._buildTypedSubscriptionOpts(r),n=new _s(this,r.deliver,i);n.info=r;try{await this._maybeCreateConsumer(r)}catch(e){throw n.unsubscribe(),e}return n}async subscribe(e,t=Le()){const r=await this._processOptions(e,t);if(!r.isBind&&!r.config.deliver_subject)throw new Error("push consumer requires deliver_subject");const s=this._buildTypedSubscriptionOpts(r),i=new vs(this,r.deliver,s);i.info=r;try{await this._maybeCreateConsumer(r)}catch(e){throw i.unsubscribe(),e}return i._maybeSetupHbMonitoring(),i}async _processOptions(e,t=Le()){const r=Ue(t)?t.getOpts():t;if(r.isBind=!!Ue(t)&&t.isBind,r.flow_control={heartbeat_count:0,fc_count:0,consumer_restarts:0},r.ordered){if(r.ordered_consumer_sequence={stream_seq:0,delivery_seq:0},r.config.ack_policy!==Te.NotSet&&r.config.ack_policy!==Te.None)throw new U("ordered consumer: ack_policy can only be set to 'none'",F.ApiError);if(r.config.durable_name&&r.config.durable_name.length>0)throw new U("ordered consumer: durable_name cannot be set",F.ApiError);if(r.config.deliver_subject&&r.config.deliver_subject.length>0)throw new U("ordered consumer: deliver_subject cannot be set",F.ApiError);if(void 0!==r.config.max_deliver&&r.config.max_deliver>1)throw new U("ordered consumer: max_deliver cannot be set",F.ApiError);if(r.config.deliver_group&&r.config.deliver_group.length>0)throw new U("ordered consumer: deliver_group cannot be set",F.ApiError);r.config.deliver_subject=H(this.nc.options.inboxPrefix),r.config.ack_policy=Te.None,r.config.max_deliver=1,r.config.flow_control=!0,r.config.idle_heartbeat=r.config.idle_heartbeat||re(5e3),r.config.ack_wait=re(792e5),r.config.mem_storage=!0,r.config.num_replicas=1}if(r.config.ack_policy===Te.NotSet&&(r.config.ack_policy=Te.All),r.api=this,r.config=r.config||{},r.stream=r.stream?r.stream:await this.findStream(e),r.attached=!1,r.config.durable_name)try{const t=await this.consumerAPI.info(r.stream,r.config.durable_name);if(t){if(t.config.filter_subject&&t.config.filter_subject!==e)throw new Error("subject does not match consumer");const s=r.config.deliver_group??"";if(""===s&&!0===t.push_bound)throw new Error("duplicate subscription");const i=t.config.deliver_group??"";if(s!==i)throw""===i?new Error("durable requires no queue group"):new Error(`durable requires queue group '${i}'`);r.last=t,r.config=t.config,r.attached=!0,r.config.durable_name||(r.name=t.name)}}catch(e){if("404"!==e.code)throw e}return r.attached||void 0!==r.config.filter_subject||void 0!==r.config.filter_subjects||(r.config.filter_subject=e),r.deliver=r.config.deliver_subject||H(this.nc.options.inboxPrefix),r}_buildTypedSubscriptionOpts(e){const t={};return t.adapter=function(e,t){return e?function(e){return(t,r)=>{if(t)return[t,null];const s=be(r);return null!==s?[ws(s),null]:[null,Yr(r,e)]}}(t):function(e){return(t,r)=>t||(t=be(r))?[t,null]:[null,Yr(r,e)]}(t)}(void 0===e.callbackFn,this.timeout),t.ingestionFilterFn=fs.ingestionFn(e.ordered),t.protocolFilterFn=(e,t=!1)=>{const r=e;return!ge(r.msg)||(t||r.msg.respond(),!1)},e.mack||e.config.ack_policy===Te.None||(t.dispatchedFn=Ss),e.callbackFn&&(t.callback=e.callbackFn),t.max=e.max||0,t.queue=e.queue,t}async _maybeCreateConsumer(e){if(e.attached)return;if(e.isBind)throw new Error(`unable to bind - durable consumer ${e.config.durable_name} doesn't exist in ${e.stream}`);e.config=Object.assign({deliver_policy:ke.All,ack_policy:Te.Explicit,ack_wait:re(3e4),replay_policy:Re.Instant},e.config);const t=await this.consumerAPI.add(e.stream,e.config);if(Array.isArray(e.config.filter_subjects&&!Array.isArray(t.config.filter_subjects)))throw new Error("jetstream server doesn't support consumers with multiple filter subjects");e.name=t.name,e.config=t.config,e.last=t}static ingestionFn(e){return(t,r)=>{const s=r;if(!t)return{ingest:!1,protocol:!1};const i=t;if(be(i.msg)||s.monitor?.work(),ye(i.msg)){const t=!e||s._checkHbOrderConsumer(i.msg);return e||s.info.flow_control.heartbeat_count++,{ingest:t,protocol:!0}}if(ge(i.msg))return s.info.flow_control.fc_count++,{ingest:!0,protocol:!0};return{ingest:!e||s._checkOrderedConsumer(t),protocol:!1}}}}class ms{options;protocol;draining;listeners;_services;constructor(e){this.draining=!1,this.options=fr(e),this.listeners=[]}static connect(e={}){return new Promise(((t,r)=>{const s=new ms(e);wr.connect(s.options,s).then((e=>{s.protocol=e,async function(){for await(const t of e.status())s.listeners.forEach((e=>{e.push(t)}))}(),t(s)})).catch((e=>{r(e)}))}))}closed(){return this.protocol.closed}async close(){await this.protocol.close()}_check(e,t,r){if(this.isClosed())throw U.errorForCode(F.ConnectionClosed);if(t&&this.isDraining())throw U.errorForCode(F.ConnectionDraining);if(r&&this.protocol.noMorePublishing)throw U.errorForCode(F.ConnectionDraining);if(0===(e=e||"").length)throw U.errorForCode(F.BadSubject)}publish(e,t,r){this._check(e,!1,!0),this.protocol.publish(e,t,r)}publishMessage(e){return this.publish(e.subject,e.data,{reply:e.reply,headers:e.headers})}respondMessage(e){return!!e.reply&&(this.publish(e.reply,e.data,{reply:e.reply,headers:e.headers}),!0)}subscribe(e,t={}){this._check(e,!0,!1);const r=new vr(this.protocol,e,t);return this.protocol.subscribe(r),r}_resub(e,t,r){this._check(t,!0,!1);const s=e;s.max=r,r&&(s.max=r+s.received),this.protocol.resub(s,t)}requestMany(e,t=k,r={maxWait:1e3,maxMessages:-1}){const s=!this.protocol.options.noAsyncTraces;try{this._check(e,!0,!0)}catch(e){return Promise.reject(e)}if(r.strategy=r.strategy||q.Timer,r.maxWait=r.maxWait||1e3,r.maxWait<1)return Promise.reject(new U("timeout",F.InvalidOption));const i=new we;function n(e){i.push((()=>{i.stop(e)}))}function o(e,t){e||null===t?n(null===e?void 0:e):i.push(t)}if(r.noMux){const a=s?(new Error).stack:null;let c="number"==typeof r.maxMessages&&r.maxMessages>0?r.maxMessages:-1;const u=this.subscribe(H(this.options.inboxPrefix),{callback:(e,t)=>{if(0===t?.data?.length&&t?.headers?.status===F.NoResponders&&(e=U.errorForCode(F.NoResponders)),e)return a&&(e.stack+=`\n\n${a}`),void l(e);o(null,t),r.strategy===q.Count&&(c--,0===c&&l()),r.strategy===q.JitterTimer&&(p(),d=setTimeout((()=>{l()}),300)),r.strategy===q.SentinelMsg&&t&&0===t.data.length&&l()}});u.requestSubject=e,u.closed.then((()=>{n()})).catch((e=>{i.stop(e)}));const l=e=>{e&&i.push((()=>{throw e})),p(),u.drain().then((()=>{n()})).catch((e=>{n()}))};i.iterClosed.then((()=>{p(),u?.unsubscribe()})).catch((e=>{p(),u?.unsubscribe()}));try{this.publish(e,t,{reply:u.getSubject()})}catch(e){l(e)}let d=setTimeout((()=>{l()}),r.maxWait);const p=()=>{d&&clearTimeout(d)}}else{const s=r;s.callback=o,i.iterClosed.then((()=>{n.cancel()})).catch((e=>{n.cancel(e)}));const n=new St(this.protocol.muxSubscriptions,e,s);this.protocol.request(n);try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${n.token}`,headers:r.headers})}catch(e){n.cancel(e)}}return Promise.resolve(i)}request(e,t,r={timeout:1e3,noMux:!1}){try{this._check(e,!0,!0)}catch(e){return Promise.reject(e)}const s=!this.protocol.options.noAsyncTraces;if(r.timeout=r.timeout||1e3,r.timeout<1)return Promise.reject(new U("timeout",F.InvalidOption));if(!r.noMux&&r.reply)return Promise.reject(new U("reply can only be used with noMux",F.InvalidOption));if(r.noMux){const i=r.reply?r.reply:H(this.options.inboxPrefix),n=X(),o=s?new Error:null,a=this.subscribe(i,{max:1,timeout:r.timeout,callback:(e,t)=>{e?(o&&e.code!==F.Timeout&&(e.stack+=`\n\n${o.stack}`),a.unsubscribe(),n.reject(e)):(e=he(t))?(o&&(e.stack+=`\n\n${o.stack}`),n.reject(e)):n.resolve(t)}});return a.requestSubject=e,this.protocol.publish(e,t,{reply:i,headers:r.headers}),n}{const i=new Ct(this.protocol.muxSubscriptions,e,r,s);this.protocol.request(i);try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${i.token}`,headers:r.headers})}catch(e){i.cancel(e)}const n=Promise.race([i.timer,i.deferred]);return n.catch((()=>{i.cancel()})),n}}flush(){return this.isClosed()?Promise.reject(U.errorForCode(F.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(U.errorForCode(F.ConnectionClosed)):this.isDraining()?Promise.reject(U.errorForCode(F.ConnectionDraining)):(this.draining=!0,this.protocol.drain())}isClosed(){return this.protocol.isClosed()}isDraining(){return this.draining}getServer(){const e=this.protocol.getServer();return e?e.listen:""}status(){const e=new we;return e.iterClosed.then((()=>{const t=this.listeners.indexOf(e);this.listeners.splice(t,1)})),this.listeners.push(e),e}get info(){return this.protocol.isClosed()?void 0:this.protocol.info}async context(){return(await this.request("$SYS.REQ.USER.INFO")).json(((e,t)=>"time"===e?new Date(Date.parse(t)):t))}stats(){return{inBytes:this.protocol.inBytes,outBytes:this.protocol.outBytes,inMsgs:this.protocol.inMsgs,outMsgs:this.protocol.outMsgs}}async jetstreamManager(e={}){const t=new as(this,e);if(!1!==e.checkAPI)try{await t.getAccountInfo()}catch(e){const t=e;throw t.code===F.NoResponders&&(t.code=F.JetStreamNotEnabled),t}return t}jetstream(e={}){return new fs(this,e)}getServerVersion(){const e=this.info;return e?kt(e.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw U.errorForCode(F.Disconnect);const e=Date.now();return await this.flush(),Date.now()-e}get features(){return this.protocol.features}get services(){return this._services||(this._services=new gs(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(U.errorForCode(F.ConnectionClosed)):this.isDraining()?Promise.reject(U.errorForCode(F.ConnectionDraining)):this.protocol.reconnect()}}class gs{nc;constructor(e){this.nc=e}add(e){try{return new Er(this.nc,e).start()}catch(e){return Promise.reject(e)}}client(e,t){return new kr(this.nc,e,t)}}class ys{bucket;sm;prefixLen;constructor(e,t,r){this.bucket=e,this.prefixLen=t,this.sm=r}get key(){return this.sm.subject.substring(this.prefixLen)}get value(){return this.sm.data}get delta(){return 0}get created(){return this.sm.time}get revision(){return this.sm.seq}get operation(){return this.sm.header.get(Tr)||"PUT"}get length(){const e=this.sm.header.get(Ie.MessageSizeHdr)||"";return""!==e?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class bs{bucket;key;sm;constructor(e,t,r){this.bucket=e,this.key=t,this.sm=r}get value(){return this.sm.data}get created(){return new Date(se(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){return this.sm.headers?.get(Tr)||"PUT"}get delta(){return this.sm.info.pending}get length(){const e=this.sm.headers?.get(Ie.MessageSizeHdr)||"";return""!==e?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class vs extends It{js;monitor;constructor(e,t,r){super(e.nc,t,r),this.js=e,this.monitor=null,this.sub.closed.then((()=>{this.monitor&&this.monitor.cancel()}))}set info(e){this.sub.info=e}get info(){return this.sub.info}_resetOrderedConsumer(e){if(null===this.info||this.sub.isClosed())return;const t=H(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,t);const r=this.info;r.config.name=M.next(),r.ordered_consumer_sequence.delivery_seq=0,r.flow_control.heartbeat_count=0,r.flow_control.fc_count=0,r.flow_control.consumer_restarts++,r.deliver=t,r.config.deliver_subject=t,r.config.deliver_policy=ke.StartSequence,r.config.opt_start_seq=e;const s={};s.stream_name=this.info.stream,s.config=r.config;const i=`${r.api.prefix}.CONSUMER.CREATE.${r.stream}`;this.js._request(i,s,{retries:-1}).then((e=>{const t=e;this.sub.info.last=t,this.info.config=t.config,this.info.name=t.name})).catch((t=>{const s=new U(`unable to recreate ordered consumer ${r.stream} at seq ${e}`,F.RequestError,t);this.sub.callback(s,{})}))}_maybeSetupHbMonitoring(){const e=this.info?.config?.idle_heartbeat||0;e&&this._setupHbMonitoring(se(e))}_setupHbMonitoring(e,t=0){const r={cancelAfter:0,maxOut:2};t&&(r.cancelAfter=t);const s=this.sub;this.monitor=new Se(e,(e=>{const t=function(e,t,r){const h=ne(e,t),s=new le({hdr:1,sid:0,size:0},k,{});return s._headers=h,s._subject=r,s}(409,`${ve.IdleHeartbeatMissed}: ${e}`,this.sub.subject),r=this.info?.ordered;if(r){if(!this.js.nc.protocol.connected)return!1;const e=this.info?.ordered_consumer_sequence?.stream_seq||0;return this._resetOrderedConsumer(e+1),this.monitor?.restart(),!1}return this.sub.callback(null,t),!s.noIterator}),r)}_checkHbOrderConsumer(e){const t=e.headers.get(Ie.ConsumerStalledHdr);if(""!==t){this.js.nc.publish(t)}const r=parseInt(e.headers.get(Ie.LastConsumerSeqHdr),10),s=this.info.ordered_consumer_sequence;return this.info.flow_control.heartbeat_count++,r!==s.delivery_seq&&this._resetOrderedConsumer(s.stream_seq+1),!1}_checkOrderedConsumer(e){const t=this.info.ordered_consumer_sequence,r=e.info.streamSequence,s=e.info.deliverySequence;return s!=t.delivery_seq+1?(this._resetOrderedConsumer(t.stream_seq+1),!1):(t.delivery_seq=s,t.stream_seq=r,!0)}async destroy(){this.isClosed()||await this.drain();const e=this.sub.info,t=e.config.durable_name||e.name,r=`${e.api.prefix}.CONSUMER.DELETE.${e.stream}.${t}`;await e.api._request(r)}async consumerInfo(){const e=this.sub.info,t=e.config.durable_name||e.name,r=`${e.api.prefix}.CONSUMER.INFO.${e.stream}.${t}`,s=await e.api._request(r);return e.last=s,s}}class _s extends vs{constructor(e,t,r){super(e,t,r)}pull(e={batch:1}){const{stream:t,config:r,name:s}=this.sub.info,i=r.durable_name??s,n={};if(n.batch=e.batch||1,n.no_wait=e.no_wait||!1,(e.max_bytes??0)>0){const t=this.js.nc.features.get(Rt.JS_PULL_MAX_BYTES);if(!t.ok)throw new Error(`max_bytes is only supported on servers ${t.min} or better`);n.max_bytes=e.max_bytes}let o=0;e.expires&&e.expires>0&&(o=e.expires,n.expires=re(o));let a=0;if(e.idle_heartbeat&&e.idle_heartbeat>0&&(a=e.idle_heartbeat,n.idle_heartbeat=re(a)),a&&0===o)throw new Error("idle_heartbeat requires expires");if(a>o)throw new Error("expires must be greater than idle_heartbeat");if(this.info){this.monitor&&this.monitor.cancel(),o&&a&&(this.monitor?this.monitor._change(a,o):this._setupHbMonitoring(a,o));const e=this.info.api,r=`${e.prefix}.CONSUMER.MSG.NEXT.${t}.${i}`,s=this.sub.subject;e.nc.publish(r,e.jc.encode(n),{reply:s})}}}function ws(e){if(null!==e)switch(e.code){case F.JetStream404NoMessages:case F.JetStream408RequestTimeout:return null;case F.JetStream409:return function(e){if(e.code!==F.JetStream409)return!1;return void 0!==[ve.MaxBatchExceeded,ve.MaxExpiresExceeded,ve.MaxBytesExceeded,ve.MaxMessageSizeExceeded,ve.PushConsumer,ve.IdleHeartbeatMissed,ve.ConsumerDeleted].find((t=>-1!==e.message.indexOf(t)))}(e)?e:null;default:return e}return null}function Ss(e){e&&e.ack()}class Cs{msg;di;didAck;timeout;constructor(e,t){this.msg=e,this.didAck=!1,this.timeout=t}get subject(){return this.msg.subject}get sid(){return this.msg.sid}get data(){return this.msg.data}get headers(){return this.msg.headers}get info(){return this.di||(this.di=function(e){const t=e.split(".");if(9===t.length&&t.splice(2,0,"_",""),t.length<11||"$JS"!==t[0]||"ACK"!==t[1])throw new Error("not js message");const r={};return r.domain="_"===t[2]?"":t[2],r.account_hash=t[3],r.stream=t[4],r.consumer=t[5],r.deliveryCount=parseInt(t[6],10),r.redeliveryCount=r.deliveryCount,r.redelivered=r.deliveryCount>1,r.streamSequence=parseInt(t[7],10),r.deliverySequence=parseInt(t[8],10),r.timestampNanos=parseInt(t[9],10),r.pending=parseInt(t[10],10),r}(this.reply)),this.di}get redelivered(){return this.info.deliveryCount>1}get reply(){return this.msg.reply||""}get seq(){return this.info.streamSequence}doAck(e){this.didAck||(this.didAck=!this.isWIP(e),this.msg.respond(e))}isWIP(e){return 4===e.length&&e[0]===Wr[0]&&e[1]===Wr[1]&&e[2]===Wr[2]&&e[3]===Wr[3]}async ackAck(e){(e=e||{}).timeout=e.timeout||this.timeout;const t=X();if(this.didAck)t.resolve(!1);else if(this.didAck=!0,this.msg.reply){const r=this.msg.publisher,s=!r.options?.noAsyncTraces,i=new Ct(r.muxSubscriptions,this.msg.reply,{timeout:e.timeout},s);r.request(i);try{r.publish(this.msg.reply,Vr,{reply:`${r.muxSubscriptions.baseInbox}${i.token}`})}catch(e){i.cancel(e)}try{await Promise.race([i.timer,i.deferred]),t.resolve(!0)}catch(e){i.cancel(e),t.reject(e)}}else t.resolve(!1);return t}ack(){this.doAck(Vr)}nak(e){let t=Hr;e&&(t=ce().encode(`-NAK ${JSON.stringify({delay:re(e)})}`)),this.doAck(t)}working(){this.doAck(Wr)}next(e,t={batch:1}){const r={};r.batch=t.batch||1,r.no_wait=t.no_wait||!1,t.expires&&t.expires>0&&(r.expires=re(t.expires));const s=ue().encode(r),i=Be.concat(Zr,Kr,s),n=e?{reply:e}:void 0;this.msg.respond(i,n)}term(e=""){let t=Jr;e?.length>0&&(t=ce().encode(`+TERM ${e}`)),this.doAck(t)}json(){return this.msg.json()}string(){return this.msg.string()}}class Es{version;lang;closeError;connected;done;socket;options;socketClosed;encrypted;peeked;yields;signal;closedNotification;constructor(){this.version="1.30.3",this.lang="nats.ws",this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=X(),this.closedNotification=X()}async connect(e,t){const r=X();if(t.tls)return r.reject(new U("tls",F.InvalidOption)),r;this.options=t;const s=e.src;if(t.wsFactory){const{socket:r,encrypted:s}=await t.wsFactory(e.src,t);this.socket=r,this.encrypted=s}else this.encrypted=0===s.indexOf("wss://"),this.socket=new WebSocket(s);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{this.isDiscarded()},this.socket.onmessage=e=>{if(this.isDiscarded())return;if(this.yields.push(new Uint8Array(e.data)),this.peeked)return void this.signal.resolve();const s=Be.concat(...this.yields),i=qt(s);if(""!==i){const e=mr.exec(i);if(!e)return t.debug&&console.error("!!!",K(s)),void r.reject(new Error("unexpected response from server"));try{!function(e,t){const{proto:r,tls_required:s,tls_available:i}=e;if((void 0===r||r<1)&&t.noEcho)throw new U("noEcho",F.ServerOptionNotAvailable);const n=s||i||!1;if(t.tls&&!n)throw new U("tls",F.ServerOptionNotAvailable)}(JSON.parse(e[1]),this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),r.resolve()}catch(e){return void r.reject(e)}}},this.socket.onclose=e=>{if(this.isDiscarded())return;let t;this.socketClosed=!0,this.done||(e.wasClean||(t=new Error(e.reason)),this._closed(t))},this.socket.onerror=e=>{if(this.isDiscarded())return;const t=e,s=new U(t.message,F.Unknown,new Error(t.error));r.reject(s)},r}disconnect(){this._closed(void 0,!0)}async _closed(e,t=!0){if(!this.isDiscarded()&&this.connected&&!this.done){if(this.closeError=e,!e)for(;!this.socketClosed&&this.socket.bufferedAmount>0;)await Q(100);this.done=!0;try{this.socket.close(e?1002:1e3,e?e.message:void 0)}catch(e){}t&&this.closedNotification.resolve(e)}}get isClosed(){return this.done}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){for(;;){if(this.isDiscarded())return;0===this.yields.length&&await this.signal;const e=this.yields;this.yields=[];for(let t=0;t<e.length;t++)this.options.debug&&console.info(`> ${K(e[t])}`),yield e[t];if(this.done)break;0===this.yields.length&&(e.length=0,this.yields=e,this.signal=X())}}isEncrypted(){return this.connected&&this.encrypted}send(e){if(!this.isDiscarded())try{return this.socket.send(e.buffer),void(this.options.debug&&console.info(`< ${K(e)}`))}catch(t){this.options.debug&&console.error(`!!! ${K(e)}: ${t}`)}}close(e){return this._closed(e,!1)}closed(){return this.closedNotification}isDiscarded(){return!!this.done&&(this.discard(),!0)}discard(){this.done=!0;try{this.socket?.close()}catch(e){}}}function xs(e,t){/^(.*:\/\/)(.*)/.test(e)||(e="boolean"==typeof t?`${!0===t?"https":"http"}://${e}`:`https://${e}`);let r=new URL(e);const s=r.protocol.toLowerCase();let i,n;"ws:"===s&&(t=!1),"wss:"===s&&(t=!0),"https:"!==s&&"http"!==s&&(e=e.replace(/^(.*:\/\/)(.*)/gm,"$2"),r=new URL(`http://${e}`));const o=r.hostname,a=r.pathname,c=r.search||"";switch(s){case"http:":case"ws:":case"nats:":n=r.port||"80",i="ws:";break;case"https:":case"wss:":case"tls:":n=r.port||"443",i="wss:";break;default:n=r.port||!0===t?"443":"80",i=!0===t?"wss:":"ws:"}return`${i}//${o}:${n}${a}${c}`}function ks(e={}){return function(e){Mt=e}({defaultPort:443,urlParseFn:xs,factory:()=>new Es}),ms.connect(e)}const Ts={HEALTH:{PING:"health.ping",PONG:"health.pong"},SERVER:{STATUS:"server.status",BROADCAST:"server.broadcast"},PLUGIN:{REGISTER:"plugin.register",UNREGISTER:"plugin.unregister",STATUS:"plugin.status"},SERVICE:{REGISTER:"service.register",UNREGISTER:"service.unregister",STATUS:"service.status"},METRICS:{UPDATE:"metrics.update"}},Rs="running",Os="stopping",As="stopped",Ps={REQUEST:"request",RESPONSE:"response",BROADCAST:"broadcast",RPC_REQUEST:"rpcrequest",RPC_RESPONSE:"rpcresponse",RPC_STREAM_REQUEST:"rpcstreamrequest"},Is={CONNECTION:5e3,REQUEST:5e3,RPC:5e3},Ms={HEARTBEAT:15e3,CLEANUP:6e4,METRICS:6e4},Ns={MAX_RECONNECT_ATTEMPTS:-1,DELAY:2e3},js={TTL:3e4},Fs=(Date.now(),Date.now(),{requests:{total:0,active:0,errors:0,timings:new Map,inWindow:{count:0,errors:0,responseTimes:[],startTime:Date.now()}},messages:{published:0,received:0,errors:0},rpc:{total:0,active:0,errors:0},subscriptions:{active:0,messageHandlers:0,requestHandlers:0,rpcHandlers:0}}),$s=x("camera:ui:metrics");class Ls{startTime=Date.now();metricsWindow=js.TTL;metrics={...Fs};trackRequestStart(e){$s("Tracking request start",e),this.metrics.requests.active++,this.metrics.requests.total++,this.metrics.requests.timings.set(e,Date.now()),this.metrics.requests.inWindow.count++}trackRequestEnd(e,t){$s("Tracking request end",e);const r=this.metrics.requests.timings.get(e);r&&(this.metrics.requests.inWindow.responseTimes.push(Date.now()-r),this.metrics.requests.timings.delete(e)),this.metrics.requests.active--,t&&(this.metrics.requests.errors++,this.metrics.requests.inWindow.errors++)}trackPublish(){$s("Tracking message publish"),this.metrics.messages.published++}trackReceive(){$s("Tracking message receive"),this.metrics.messages.received++}trackMessageError(){$s("Tracking message error"),this.metrics.messages.errors++}trackRPCStart(){$s("Tracking RPC start"),this.metrics.rpc.active++,this.metrics.rpc.total++}trackRPCEnd(e){$s("Tracking RPC end"),this.metrics.rpc.active--,e&&this.metrics.rpc.errors++}trackSubscriptionChange(e,t){switch($s("Tracking subscription change",e,t),t){case"message":this.metrics.subscriptions.messageHandlers=Math.max(0,this.metrics.subscriptions.messageHandlers+e);break;case"request":this.metrics.subscriptions.requestHandlers=Math.max(0,this.metrics.subscriptions.requestHandlers+e);break;case"rpc":case"generator":this.metrics.subscriptions.rpcHandlers=Math.max(0,this.metrics.subscriptions.rpcHandlers+e)}this.metrics.subscriptions.active=this.metrics.subscriptions.messageHandlers+this.metrics.subscriptions.requestHandlers+this.metrics.subscriptions.rpcHandlers}getMetrics(){this.cleanOldMetrics();const e=Date.now(),t=(e-this.metrics.requests.inWindow.startTime)/1e3,r=t>0?this.metrics.requests.inWindow.count/Math.max(1,t):0,s=this.metrics.requests.inWindow.responseTimes.length>0?this.metrics.requests.inWindow.responseTimes.reduce(((e,t)=>e+t),0)/this.metrics.requests.inWindow.responseTimes.length:0;return{timestamp:e,startTime:this.startTime,requests:{total:this.metrics.requests.total,active:this.metrics.requests.active,errors:this.metrics.requests.errors,perSecond:Number.isFinite(r)?r:0,avgResponseTime:s},messages:{published:this.metrics.messages.published,received:this.metrics.messages.received,errors:this.metrics.messages.errors},rpc:{total:this.metrics.rpc.total,active:this.metrics.rpc.active,errors:this.metrics.rpc.errors},subscriptions:{active:this.metrics.subscriptions.active,messageHandlers:this.metrics.subscriptions.messageHandlers,requestHandlers:this.metrics.subscriptions.requestHandlers,rpcHandlers:this.metrics.subscriptions.rpcHandlers}}}resetMetrics(){this.metrics={...Fs}}cleanOldMetrics(){const e=Date.now();e-this.metrics.requests.inWindow.startTime>=this.metricsWindow&&(this.metrics.requests.inWindow={count:0,errors:0,responseTimes:[],startTime:e})}}var Us,Ds,qs;try{Us=new TextDecoder}catch(e){}var Bs=0;const zs=[];var Gs,Vs,Hs,Ws,Zs,Js=zs,Ks=0,Ys={},Qs=0,Xs=0,ei=[],ti={useRecords:!1,mapsAsObjects:!0};class ri{}const si=new ri;si.name="MessagePack 0xC1";var ii,ni,oi,ai=!1,ci=2;try{new Function("")}catch(e){ci=1/0}class ui{constructor(e){e&&(!1===e.useRecords&&void 0===e.mapsAsObjects&&(e.mapsAsObjects=!0),e.sequential&&!1!==e.trusted&&(e.trusted=!0,e.structures||0==e.useRecords||(e.structures=[],e.maxSharedStructures||(e.maxSharedStructures=0))),e.structures?e.structures.sharedLength=e.structures.length:e.getStructures&&((e.structures=[]).uninitialized=!0,e.structures.sharedLength=0),e.int64AsNumber&&(e.int64AsType="number")),Object.assign(this,e)}unpack(e,t){if(Ds)return Li((()=>(Ui(),this?this.unpack(e,t):ui.prototype.unpack.call(ti,e,t))));e.buffer||e.constructor!==ArrayBuffer||(e="undefined"!=typeof Buffer?Buffer.from(e):new Uint8Array(e)),"object"==typeof t?(qs=t.end||e.length,Bs=t.start||0):(Bs=0,qs=t>-1?t:e.length),Ks=0,Xs=0,Vs=null,Js=zs,Hs=null,Ds=e;try{Zs=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(t){if(Ds=null,e instanceof Uint8Array)throw t;throw new Error("Source must be a Uint8Array or Buffer but was a "+(e&&"object"==typeof e?e.constructor.name:typeof e))}if(this instanceof ui){if(Ys=this,this.structures)return Gs=this.structures,hi(t);(!Gs||Gs.length>0)&&(Gs=[])}else Ys=ti,(!Gs||Gs.length>0)&&(Gs=[]);return hi(t)}unpackMultiple(e,t){let r,s=0;try{ai=!0;let i=e.length,n=this?this.unpack(e,i):qi.unpack(e,i);if(!t){for(r=[n];Bs<i;)s=Bs,r.push(hi());return r}if(!1===t(n,s,Bs))return;for(;Bs<i;)if(s=Bs,!1===t(hi(),s,Bs))return}catch(e){throw e.lastPosition=s,e.values=r,e}finally{ai=!1,Ui()}}_mergeStructures(e,t){ni&&(e=ni.call(this,e)),e=e||[],Object.isFrozen(e)&&(e=e.map((e=>e.slice(0))));for(let t=0,r=e.length;t<r;t++){let r=e[t];r&&(r.isShared=!0,t>=32&&(r.highByte=t-32>>5))}e.sharedLength=e.length;for(let r in t||[])if(r>=0){let s=e[r],i=t[r];i&&(s&&((e.restoreStructures||(e.restoreStructures=[]))[r]=s),e[r]=i)}return this.structures=e}decode(e,t){return this.unpack(e,t)}}function hi(e){try{if(!Ys.trusted&&!ai){let e=Gs.sharedLength||0;e<Gs.length&&(Gs.length=e)}let t;if(Ys.randomAccessStructure&&Ds[Bs]<64&&Ds[Bs]>=32&&ii?(t=ii(Ds,Bs,qs,Ys),Ds=null,e&&e.lazy||!t||(t=t.toJSON()),Bs=qs):t=di(),Hs&&(Bs=Hs.postBundlePosition,Hs=null),ai&&(Gs.restoreStructures=null),Bs==qs)Gs&&Gs.restoreStructures&&li(),Gs=null,Ds=null,Ws&&(Ws=null);else{if(Bs>qs)throw new Error("Unexpected end of MessagePack data");if(!ai){let e;try{e=JSON.stringify(t,((e,t)=>"bigint"==typeof t?`${t}n`:t)).slice(0,100)}catch(t){e="(JSON view not available "+t+")"}throw new Error("Data read, but end of buffer not reached "+e)}}return t}catch(e){throw Gs&&Gs.restoreStructures&&li(),Ui(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")||Bs>qs)&&(e.incomplete=!0),e}}function li(){for(let e in Gs.restoreStructures)Gs[e]=Gs.restoreStructures[e];Gs.restoreStructures=null}function di(){let e=Ds[Bs++];if(e<160){if(e<128){if(e<64)return e;{let t=Gs[63&e]||Ys.getStructures&&gi()[63&e];return t?(t.read||(t.read=fi(t,63&e)),t.read()):e}}if(e<144){if(e-=128,Ys.mapsAsObjects){let t={};for(let r=0;r<e;r++){let e=Pi();"__proto__"===e&&(e="__proto_"),t[e]=di()}return t}{let t=new Map;for(let r=0;r<e;r++)t.set(di(),di());return t}}{e-=144;let t=new Array(e);for(let r=0;r<e;r++)t[r]=di();return Ys.freezeData?Object.freeze(t):t}}if(e<192){let t=e-160;if(Xs>=Bs)return Vs.slice(Bs-Qs,(Bs+=t)-Qs);if(0==Xs&&qs<140){let e=t<16?ki(t):xi(t);if(null!=e)return e}return yi(t)}{let t;switch(e){case 192:return null;case 193:return Hs?(t=di(),t>0?Hs[1].slice(Hs.position1,Hs.position1+=t):Hs[0].slice(Hs.position0,Hs.position0-=t)):si;case 194:return!1;case 195:return!0;case 196:if(t=Ds[Bs++],void 0===t)throw new Error("Unexpected end of buffer");return Ri(t);case 197:return t=Zs.getUint16(Bs),Bs+=2,Ri(t);case 198:return t=Zs.getUint32(Bs),Bs+=4,Ri(t);case 199:return Oi(Ds[Bs++]);case 200:return t=Zs.getUint16(Bs),Bs+=2,Oi(t);case 201:return t=Zs.getUint32(Bs),Bs+=4,Oi(t);case 202:if(t=Zs.getFloat32(Bs),Ys.useFloat32>2){let e=Di[(127&Ds[Bs])<<1|Ds[Bs+1]>>7];return Bs+=4,(e*t+(t>0?.5:-.5)|0)/e}return Bs+=4,t;case 203:return t=Zs.getFloat64(Bs),Bs+=8,t;case 204:return Ds[Bs++];case 205:return t=Zs.getUint16(Bs),Bs+=2,t;case 206:return t=Zs.getUint32(Bs),Bs+=4,t;case 207:return"number"===Ys.int64AsType?(t=4294967296*Zs.getUint32(Bs),t+=Zs.getUint32(Bs+4)):"string"===Ys.int64AsType?t=Zs.getBigUint64(Bs).toString():"auto"===Ys.int64AsType?(t=Zs.getBigUint64(Bs),t<=BigInt(2)<<BigInt(52)&&(t=Number(t))):t=Zs.getBigUint64(Bs),Bs+=8,t;case 208:return Zs.getInt8(Bs++);case 209:return t=Zs.getInt16(Bs),Bs+=2,t;case 210:return t=Zs.getInt32(Bs),Bs+=4,t;case 211:return"number"===Ys.int64AsType?(t=4294967296*Zs.getInt32(Bs),t+=Zs.getUint32(Bs+4)):"string"===Ys.int64AsType?t=Zs.getBigInt64(Bs).toString():"auto"===Ys.int64AsType?(t=Zs.getBigInt64(Bs),t>=BigInt(-2)<<BigInt(52)&&t<=BigInt(2)<<BigInt(52)&&(t=Number(t))):t=Zs.getBigInt64(Bs),Bs+=8,t;case 212:if(t=Ds[Bs++],114==t)return Mi(63&Ds[Bs++]);{let e=ei[t];if(e)return e.read?(Bs++,e.read(di())):e.noBuffer?(Bs++,e()):e(Ds.subarray(Bs,++Bs));throw new Error("Unknown extension "+t)}case 213:return t=Ds[Bs],114==t?(Bs++,Mi(63&Ds[Bs++],Ds[Bs++])):Oi(2);case 214:return Oi(4);case 215:return Oi(8);case 216:return Oi(16);case 217:return t=Ds[Bs++],Xs>=Bs?Vs.slice(Bs-Qs,(Bs+=t)-Qs):bi(t);case 218:return t=Zs.getUint16(Bs),Xs>=(Bs+=2)?Vs.slice(Bs-Qs,(Bs+=t)-Qs):vi(t);case 219:return t=Zs.getUint32(Bs),Xs>=(Bs+=4)?Vs.slice(Bs-Qs,(Bs+=t)-Qs):_i(t);case 220:return t=Zs.getUint16(Bs),Bs+=2,Si(t);case 221:return t=Zs.getUint32(Bs),Bs+=4,Si(t);case 222:return t=Zs.getUint16(Bs),Bs+=2,Ci(t);case 223:return t=Zs.getUint32(Bs),Bs+=4,Ci(t);default:if(e>=224)return e-256;if(void 0===e){let e=new Error("Unexpected end of MessagePack data");throw e.incomplete=!0,e}throw new Error("Unknown MessagePack token "+e)}}}const pi=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function fi(e,t){function r(){if(r.count++>ci){let r=e.read=new Function("r","return function(){return "+(Ys.freezeData?"Object.freeze":"")+"({"+e.map((e=>"__proto__"===e?"__proto_:r()":pi.test(e)?e+":r()":"["+JSON.stringify(e)+"]:r()")).join(",")+"})}")(di);return 0===e.highByte&&(e.read=mi(t,e.read)),r()}let s={};for(let t=0,r=e.length;t<r;t++){let r=e[t];"__proto__"===r&&(r="__proto_"),s[r]=di()}return Ys.freezeData?Object.freeze(s):s}return r.count=0,0===e.highByte?mi(t,r):r}const mi=(e,t)=>function(){let r=Ds[Bs++];if(0===r)return t();let s=e<32?-(e+(r<<5)):e+(r<<5),i=Gs[s]||gi()[s];if(!i)throw new Error("Record id is not defined for "+s);return i.read||(i.read=fi(i,e)),i.read()};function gi(){let e=Li((()=>(Ds=null,Ys.getStructures())));return Gs=Ys._mergeStructures(e,Gs)}var yi=wi,bi=wi,vi=wi,_i=wi;function wi(e){let t;if(e<16&&(t=ki(e)))return t;if(e>64&&Us)return Us.decode(Ds.subarray(Bs,Bs+=e));const r=Bs+e,s=[];for(t="";Bs<r;){const e=Ds[Bs++];if(128&e)if(192==(224&e)){const t=63&Ds[Bs++];s.push((31&e)<<6|t)}else if(224==(240&e)){const t=63&Ds[Bs++],r=63&Ds[Bs++];s.push((31&e)<<12|t<<6|r)}else if(240==(248&e)){let t=(7&e)<<18|(63&Ds[Bs++])<<12|(63&Ds[Bs++])<<6|63&Ds[Bs++];t>65535&&(t-=65536,s.push(t>>>10&1023|55296),t=56320|1023&t),s.push(t)}else s.push(e);else s.push(e);s.length>=4096&&(t+=Ei.apply(String,s),s.length=0)}return s.length>0&&(t+=Ei.apply(String,s)),t}function Si(e){let t=new Array(e);for(let r=0;r<e;r++)t[r]=di();return Ys.freezeData?Object.freeze(t):t}function Ci(e){if(Ys.mapsAsObjects){let t={};for(let r=0;r<e;r++){let e=Pi();"__proto__"===e&&(e="__proto_"),t[e]=di()}return t}{let t=new Map;for(let r=0;r<e;r++)t.set(di(),di());return t}}var Ei=String.fromCharCode;function xi(e){let t=Bs,r=new Array(e);for(let s=0;s<e;s++){const e=Ds[Bs++];if((128&e)>0)return void(Bs=t);r[s]=e}return Ei.apply(String,r)}function ki(e){if(e<4){if(e<2){if(0===e)return"";{let e=Ds[Bs++];return(128&e)>1?void(Bs-=1):Ei(e)}}{let t=Ds[Bs++],r=Ds[Bs++];if((128&t)>0||(128&r)>0)return void(Bs-=2);if(e<3)return Ei(t,r);let s=Ds[Bs++];return(128&s)>0?void(Bs-=3):Ei(t,r,s)}}{let t=Ds[Bs++],r=Ds[Bs++],s=Ds[Bs++],i=Ds[Bs++];if((128&t)>0||(128&r)>0||(128&s)>0||(128&i)>0)return void(Bs-=4);if(e<6){if(4===e)return Ei(t,r,s,i);{let e=Ds[Bs++];return(128&e)>0?void(Bs-=5):Ei(t,r,s,i,e)}}if(e<8){let n=Ds[Bs++],o=Ds[Bs++];if((128&n)>0||(128&o)>0)return void(Bs-=6);if(e<7)return Ei(t,r,s,i,n,o);let a=Ds[Bs++];return(128&a)>0?void(Bs-=7):Ei(t,r,s,i,n,o,a)}{let n=Ds[Bs++],o=Ds[Bs++],a=Ds[Bs++],h=Ds[Bs++];if((128&n)>0||(128&o)>0||(128&a)>0||(128&h)>0)return void(Bs-=8);if(e<10){if(8===e)return Ei(t,r,s,i,n,o,a,h);{let e=Ds[Bs++];return(128&e)>0?void(Bs-=9):Ei(t,r,s,i,n,o,a,h,e)}}if(e<12){let c=Ds[Bs++],u=Ds[Bs++];if((128&c)>0||(128&u)>0)return void(Bs-=10);if(e<11)return Ei(t,r,s,i,n,o,a,h,c,u);let l=Ds[Bs++];return(128&l)>0?void(Bs-=11):Ei(t,r,s,i,n,o,a,h,c,u,l)}{let c=Ds[Bs++],u=Ds[Bs++],l=Ds[Bs++],d=Ds[Bs++];if((128&c)>0||(128&u)>0||(128&l)>0||(128&d)>0)return void(Bs-=12);if(e<14){if(12===e)return Ei(t,r,s,i,n,o,a,h,c,u,l,d);{let e=Ds[Bs++];return(128&e)>0?void(Bs-=13):Ei(t,r,s,i,n,o,a,h,c,u,l,d,e)}}{let p=Ds[Bs++],f=Ds[Bs++];if((128&p)>0||(128&f)>0)return void(Bs-=14);if(e<15)return Ei(t,r,s,i,n,o,a,h,c,u,l,d,p,f);let m=Ds[Bs++];return(128&m)>0?void(Bs-=15):Ei(t,r,s,i,n,o,a,h,c,u,l,d,p,f,m)}}}}}function Ti(){let e,t=Ds[Bs++];if(t<192)e=t-160;else switch(t){case 217:e=Ds[Bs++];break;case 218:e=Zs.getUint16(Bs),Bs+=2;break;case 219:e=Zs.getUint32(Bs),Bs+=4;break;default:throw new Error("Expected string")}return wi(e)}function Ri(e){return Ys.copyBuffers?Uint8Array.prototype.slice.call(Ds,Bs,Bs+=e):Ds.subarray(Bs,Bs+=e)}function Oi(e){let t=Ds[Bs++];if(ei[t]){let r;return ei[t](Ds.subarray(Bs,r=Bs+=e),(e=>{Bs=e;try{return di()}finally{Bs=r}}))}throw new Error("Unknown extension type "+t)}var Ai=new Array(4096);function Pi(){let e=Ds[Bs++];if(!(e>=160&&e<192))return Bs--,Ii(di());if(e-=160,Xs>=Bs)return Vs.slice(Bs-Qs,(Bs+=e)-Qs);if(!(0==Xs&&qs<180))return yi(e);let t,r=4095&(e<<5^(e>1?Zs.getUint16(Bs):e>0?Ds[Bs]:0)),s=Ai[r],i=Bs,n=Bs+e-3,o=0;if(s&&s.bytes==e){for(;i<n;){if(t=Zs.getUint32(i),t!=s[o++]){i=1879048192;break}i+=4}for(n+=3;i<n;)if(t=Ds[i++],t!=s[o++]){i=1879048192;break}if(i===n)return Bs=i,s.string;n-=3,i=Bs}for(s=[],Ai[r]=s,s.bytes=e;i<n;)t=Zs.getUint32(i),s.push(t),i+=4;for(n+=3;i<n;)t=Ds[i++],s.push(t);let a=e<16?ki(e):xi(e);return s.string=null!=a?a:yi(e)}function Ii(e){if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return e.toString();if(null==e)return e+"";throw new Error("Invalid property type for record",typeof e)}const Mi=(e,t)=>{let r=di().map(Ii),s=e;void 0!==t&&(e=e<32?-((t<<5)+e):(t<<5)+e,r.highByte=t);let i=Gs[e];return i&&(i.isShared||ai)&&((Gs.restoreStructures||(Gs.restoreStructures=[]))[e]=i),Gs[e]=r,r.read=fi(r,s),r.read()};ei[0]=()=>{},ei[0].noBuffer=!0,ei[66]=e=>{let t=e.length,r=BigInt(128&e[0]?e[0]-256:e[0]);for(let s=1;s<t;s++)r<<=BigInt(8),r+=BigInt(e[s]);return r};let Ni={Error,TypeError,ReferenceError};ei[101]=()=>{let e=di();return(Ni[e[0]]||Error)(e[1],{cause:e[2]})},ei[105]=e=>{if(!1===Ys.structuredClone)throw new Error("Structured clone extension is disabled");let t=Zs.getUint32(Bs-4);Ws||(Ws=new Map);let r,s=Ds[Bs];r=s>=144&&s<160||220==s||221==s?[]:{};let i={target:r};Ws.set(t,i);let n=di();return i.used?Object.assign(r,n):(i.target=n,n)},ei[112]=e=>{if(!1===Ys.structuredClone)throw new Error("Structured clone extension is disabled");let t=Zs.getUint32(Bs-4),r=Ws.get(t);return r.used=!0,r.target},ei[115]=()=>new Set(di());const ji=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map((e=>e+"Array"));let Fi="object"==typeof globalThis?globalThis:window;ei[116]=e=>{let t=e[0],r=ji[t];if(!r){if(16===t){let t=new ArrayBuffer(e.length-1);return new Uint8Array(t).set(e.subarray(1)),t}throw new Error("Could not find typed array for code "+t)}return new Fi[r](Uint8Array.prototype.slice.call(e,1).buffer)},ei[120]=()=>{let e=di();return new RegExp(e[0],e[1])};const $i=[];function Li(e){oi&&oi();let t=qs,r=Bs,s=Ks,i=Qs,n=Xs,o=Vs,a=Js,c=Ws,u=Hs,l=new Uint8Array(Ds.slice(0,qs)),d=Gs,p=Gs.slice(0,Gs.length),f=Ys,m=ai,g=e();return qs=t,Bs=r,Ks=s,Qs=i,Xs=n,Vs=o,Js=a,Ws=c,Hs=u,Ds=l,ai=m,(Gs=d).splice(0,Gs.length,...p),Ys=f,Zs=new DataView(Ds.buffer,Ds.byteOffset,Ds.byteLength),g}function Ui(){Ds=null,Ws=null,Gs=null}ei[98]=e=>{let t=(e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3],r=Bs;return Bs+=t-e.length,Hs=$i,(Hs=[Ti(),Ti()]).position0=0,Hs.position1=0,Hs.postBundlePosition=Bs,Bs=r,di()},ei[255]=e=>4==e.length?new Date(1e3*(16777216*e[0]+(e[1]<<16)+(e[2]<<8)+e[3])):8==e.length?new Date(((e[0]<<22)+(e[1]<<14)+(e[2]<<6)+(e[3]>>2))/1e6+1e3*(4294967296*(3&e[3])+16777216*e[4]+(e[5]<<16)+(e[6]<<8)+e[7])):12==e.length?new Date(((e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3])/1e6+1e3*((128&e[4]?-281474976710656:0)+1099511627776*e[6]+4294967296*e[7]+16777216*e[8]+(e[9]<<16)+(e[10]<<8)+e[11])):new Date("invalid");const Di=new Array(147);for(let e=0;e<256;e++)Di[e]=+("1e"+Math.floor(45.15-.30103*e));var qi=new ui({useRecords:!1});qi.unpack,qi.unpackMultiple,qi.unpack;let Bi,zi,Gi,Vi=new Float32Array(1);new Uint8Array(Vi.buffer,0,4);try{Bi=new TextEncoder}catch(e){}const Hi="undefined"!=typeof Buffer,Wi=Hi?function(e){return Buffer.allocUnsafeSlow(e)}:Uint8Array,Zi=Hi?Buffer:Uint8Array,Ji=Hi?4294967296:2144337920;let Ki,Yi,Qi,Xi,en,tn=0,rn=null;const sn=/[\u0080-\uFFFF]/,nn=Symbol("record-id");class on extends ui{constructor(e){let t,r,s,i;super(e),this.offset=0;let n=Zi.prototype.utf8Write?function(e,t){return Ki.utf8Write(e,t,Ki.byteLength-t)}:!(!Bi||!Bi.encodeInto)&&function(e,t){return Bi.encodeInto(e,Ki.subarray(t)).written},o=this;e||(e={});let a=e&&e.sequential,c=e.structures||e.saveStructures,u=e.maxSharedStructures;if(null==u&&(u=c?32:0),u>8160)throw new Error("Maximum maxSharedStructure is 8160");e.structuredClone&&null==e.moreTypes&&(this.moreTypes=!0);let l=e.maxOwnStructures;null==l&&(l=c?32:64),this.structures||0==e.useRecords||(this.structures=[]);let d=u>32||l+u>64,p=u+64,f=u+l+64;if(f>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let m=[],g=0,y=0;this.pack=this.encode=function(e,n){if(Ki||(Ki=new Wi(8192),Qi=Ki.dataView||(Ki.dataView=new DataView(Ki.buffer,0,8192)),tn=0),Xi=Ki.length-10,Xi-tn<2048?(Ki=new Wi(Ki.length),Qi=Ki.dataView||(Ki.dataView=new DataView(Ki.buffer,0,Ki.length)),Xi=Ki.length-10,tn=0):tn=tn+7&2147483640,t=tn,n&vn&&(tn+=255&n),i=o.structuredClone?new Map:null,o.bundleStrings&&"string"!=typeof e?(rn=[],rn.size=1/0):rn=null,s=o.structures,s){s.uninitialized&&(s=o._mergeStructures(o.getStructures()));let e=s.sharedLength||0;if(e>u)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+s.sharedLength);if(!s.transitions){s.transitions=Object.create(null);for(let t=0;t<e;t++){let e=s[t];if(!e)continue;let r,i=s.transitions;for(let t=0,s=e.length;t<s;t++){let s=e[t];r=i[s],r||(r=i[s]=Object.create(null)),i=r}i[nn]=t+64}this.lastNamedStructuresLength=e}a||(s.nextId=e+64)}let c;r&&(r=!1);try{o.randomAccessStructure&&e&&e.constructor&&e.constructor===Object?R(e):_(e);let r=rn;if(rn&&hn(t,_,0),i&&i.idsToInsert){let e=i.idsToInsert.sort(((e,t)=>e.offset>t.offset?1:-1)),s=e.length,n=-1;for(;r&&s>0;){let i=e[--s].offset+t;i<r.stringsPosition+t&&-1===n&&(n=0),i>r.position+t?n>=0&&(n+=6):(n>=0&&(Qi.setUint32(r.position+t,Qi.getUint32(r.position+t)+n),n=-1),r=r.previous,s++)}n>=0&&r&&Qi.setUint32(r.position+t,Qi.getUint32(r.position+t)+n),tn+=6*e.length,tn>Xi&&x(tn),o.offset=tn;let a=function(e,t){let r,s=6*t.length,i=e.length-s;for(;r=t.pop();){let t=r.offset,n=r.id;e.copyWithin(t+s,t,i),s-=6;let o=t+s;e[o++]=214,e[o++]=105,e[o++]=n>>24,e[o++]=n>>16&255,e[o++]=n>>8&255,e[o++]=255&n,i=t}return e}(Ki.subarray(t,tn),e);return i=null,a}return o.offset=tn,n&yn?(Ki.start=t,Ki.end=tn,Ki):Ki.subarray(t,tn)}catch(e){throw c=e,e}finally{if(s&&(b(),r&&o.saveStructures)){let r=s.sharedLength||0,i=Ki.subarray(t,tn),a=ln(s,o);if(!c)return!1===o.saveStructures(a,a.isCompatible)?o.pack(e,n):(o.lastNamedStructuresLength=r,Ki.length>1073741824&&(Ki=null),i)}Ki.length>1073741824&&(Ki=null),n&bn&&(tn=t)}};const b=()=>{y<10&&y++;let e=s.sharedLength||0;if(s.length>e&&!a&&(s.length=e),g>1e4)s.transitions=null,y=0,g=0,m.length>0&&(m=[]);else if(m.length>0&&!a){for(let e=0,t=m.length;e<t;e++)m[e][nn]=0;m=[]}},v=e=>{var t=e.length;t<16?Ki[tn++]=144|t:t<65536?(Ki[tn++]=220,Ki[tn++]=t>>8,Ki[tn++]=255&t):(Ki[tn++]=221,Qi.setUint32(tn,t),tn+=4);for(let r=0;r<t;r++)_(e[r])},_=e=>{tn>Xi&&(Ki=x(tn));var r,s=typeof e;if("string"===s){let s,i=e.length;if(rn&&i>=4&&i<4096){if((rn.size+=i)>21760){let e,r,s=(rn[0]?3*rn[0].length+rn[1].length:0)+10;tn+s>Xi&&(Ki=x(tn+s)),rn.position?(r=rn,Ki[tn]=200,tn+=3,Ki[tn++]=98,e=tn-t,tn+=4,hn(t,_,0),Qi.setUint16(e+t-3,tn-t-e)):(Ki[tn++]=214,Ki[tn++]=98,e=tn-t,tn+=4),rn=["",""],rn.previous=r,rn.size=0,rn.position=e}let r=sn.test(e);return rn[r?0:1]+=e,Ki[tn++]=193,void _(r?-i:i)}s=i<32?1:i<256?2:i<65536?3:5;let o=3*i;if(tn+o>Xi&&(Ki=x(tn+o)),i<64||!n){let t,n,o,a=tn+s;for(t=0;t<i;t++)n=e.charCodeAt(t),n<128?Ki[a++]=n:n<2048?(Ki[a++]=n>>6|192,Ki[a++]=63&n|128):55296==(64512&n)&&56320==(64512&(o=e.charCodeAt(t+1)))?(n=65536+((1023&n)<<10)+(1023&o),t++,Ki[a++]=n>>18|240,Ki[a++]=n>>12&63|128,Ki[a++]=n>>6&63|128,Ki[a++]=63&n|128):(Ki[a++]=n>>12|224,Ki[a++]=n>>6&63|128,Ki[a++]=63&n|128);r=a-tn-s}else r=n(e,tn+s);r<32?Ki[tn++]=160|r:r<256?(s<2&&Ki.copyWithin(tn+2,tn+1,tn+1+r),Ki[tn++]=217,Ki[tn++]=r):r<65536?(s<3&&Ki.copyWithin(tn+3,tn+2,tn+2+r),Ki[tn++]=218,Ki[tn++]=r>>8,Ki[tn++]=255&r):(s<5&&Ki.copyWithin(tn+5,tn+3,tn+3+r),Ki[tn++]=219,Qi.setUint32(tn,r),tn+=4),tn+=r}else if("number"===s)if(e>>>0===e)e<32||e<128&&!1===this.useRecords||e<64&&!this.randomAccessStructure?Ki[tn++]=e:e<256?(Ki[tn++]=204,Ki[tn++]=e):e<65536?(Ki[tn++]=205,Ki[tn++]=e>>8,Ki[tn++]=255&e):(Ki[tn++]=206,Qi.setUint32(tn,e),tn+=4);else if((e|0)===e)e>=-32?Ki[tn++]=256+e:e>=-128?(Ki[tn++]=208,Ki[tn++]=e+256):e>=-32768?(Ki[tn++]=209,Qi.setInt16(tn,e),tn+=2):(Ki[tn++]=210,Qi.setInt32(tn,e),tn+=4);else{let t;if((t=this.useFloat32)>0&&e<4294967296&&e>=-2147483648){let r;if(Ki[tn++]=202,Qi.setFloat32(tn,e),t<4||((r=e*Di[(127&Ki[tn])<<1|Ki[tn+1]>>7])|0)===r)return void(tn+=4);tn--}Ki[tn++]=203,Qi.setFloat64(tn,e),tn+=8}else if("object"===s||"function"===s)if(e){if(i){let r=i.get(e);if(r){if(!r.id){let e=i.idsToInsert||(i.idsToInsert=[]);r.id=e.push(r)}return Ki[tn++]=214,Ki[tn++]=112,Qi.setUint32(tn,r.id),void(tn+=4)}i.set(e,{offset:tn-t})}let n=e.constructor;if(n===Object)E(e);else if(n===Array)v(e);else if(n===Map)if(this.mapAsEmptyObject)Ki[tn++]=128;else{(r=e.size)<16?Ki[tn++]=128|r:r<65536?(Ki[tn++]=222,Ki[tn++]=r>>8,Ki[tn++]=255&r):(Ki[tn++]=223,Qi.setUint32(tn,r),tn+=4);for(let[t,r]of e)_(t),_(r)}else{for(let t=0,r=zi.length;t<r;t++){if(e instanceof Gi[t]){let r=zi[t];if(r.write){r.type&&(Ki[tn++]=212,Ki[tn++]=r.type,Ki[tn++]=0);let t=r.write.call(this,e);return void(t===e?Array.isArray(e)?v(e):E(e):_(t))}let s,i=Ki,n=Qi,o=tn;Ki=null;try{s=r.pack.call(this,e,(e=>(Ki=i,i=null,tn+=e,tn>Xi&&x(tn),{target:Ki,targetView:Qi,position:tn-e})),_)}finally{i&&(Ki=i,Qi=n,tn=o,Xi=Ki.length-10)}return void(s&&(s.length+tn>Xi&&x(s.length+tn),tn=un(s,Ki,tn,r.type)))}}if(Array.isArray(e))v(e);else{if(e.toJSON){const t=e.toJSON();if(t!==e)return _(t)}if("function"===s)return _(this.writeFunction&&this.writeFunction(e));E(e)}}}else Ki[tn++]=192;else if("boolean"===s)Ki[tn++]=e?195:194;else if("bigint"===s){if(e<BigInt(1)<<BigInt(63)&&e>=-(BigInt(1)<<BigInt(63)))Ki[tn++]=211,Qi.setBigInt64(tn,e);else if(e<BigInt(1)<<BigInt(64)&&e>0)Ki[tn++]=207,Qi.setBigUint64(tn,e);else{if(!this.largeBigIntToFloat){if(this.largeBigIntToString)return _(e.toString());if(this.useBigIntExtension&&e<BigInt(2)**BigInt(1023)&&e>-(BigInt(2)**BigInt(1023))){Ki[tn++]=199,tn++,Ki[tn++]=66;let t,r=[];do{let s=e&BigInt(255);t=(s&BigInt(128))===(e<BigInt(0)?BigInt(128):BigInt(0)),r.push(s),e>>=BigInt(8)}while(e!==BigInt(0)&&e!==BigInt(-1)||!t);Ki[tn-2]=r.length;for(let e=r.length;e>0;)Ki[tn++]=Number(r[--e]);return}throw new RangeError(e+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string")}Ki[tn++]=203,Qi.setFloat64(tn,Number(e))}tn+=8}else{if("undefined"!==s)throw new Error("Unknown type: "+s);this.encodeUndefinedAsNil?Ki[tn++]=192:(Ki[tn++]=212,Ki[tn++]=0,Ki[tn++]=0)}},w=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?e=>{let t;if(this.skipValues){t=[];for(let r in e)"function"==typeof e.hasOwnProperty&&!e.hasOwnProperty(r)||this.skipValues.includes(e[r])||t.push(r)}else t=Object.keys(e);let r,s=t.length;if(s<16?Ki[tn++]=128|s:s<65536?(Ki[tn++]=222,Ki[tn++]=s>>8,Ki[tn++]=255&s):(Ki[tn++]=223,Qi.setUint32(tn,s),tn+=4),this.coercibleKeyAsNumber)for(let i=0;i<s;i++){r=t[i];let s=Number(r);_(isNaN(s)?r:s),_(e[r])}else for(let i=0;i<s;i++)_(r=t[i]),_(e[r])}:e=>{Ki[tn++]=222;let r=tn-t;tn+=2;let s=0;for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&(_(t),_(e[t]),s++);if(s>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');Ki[r+++t]=s>>8,Ki[r+t]=255&s},S=!1===this.useRecords?w:e.progressiveRecords&&!d?e=>{let r,i,n=s.transitions||(s.transitions=Object.create(null)),o=tn++-t;for(let a in e)if("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(a)){if(r=n[a],r)n=r;else{let c=Object.keys(e),u=n;n=s.transitions;let l=0;for(let e=0,t=c.length;e<t;e++){let t=c[e];r=n[t],r||(r=n[t]=Object.create(null),l++),n=r}o+t+1==tn?(tn--,k(n,c,l)):T(n,c,o,l),i=!0,n=u[a]}_(e[a])}if(!i){let r=n[nn];r?Ki[o+t]=r:T(n,Object.keys(e),o,0)}}:e=>{let t,r=s.transitions||(s.transitions=Object.create(null)),i=0;for(let s in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(s))&&(t=r[s],t||(t=r[s]=Object.create(null),i++),r=t);let n=r[nn];n?n>=96&&d?(Ki[tn++]=96+(31&(n-=96)),Ki[tn++]=n>>5):Ki[tn++]=n:k(r,r.__keys__||Object.keys(e),i);for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&_(e[t])},C="function"==typeof this.useRecords&&this.useRecords,E=C?e=>{C(e)?S(e):w(e)}:S,x=e=>{let r;if(e>16777216){if(e-t>Ji)throw new Error("Packed buffer would be larger than maximum buffer size");r=Math.min(Ji,4096*Math.round(Math.max((e-t)*(e>67108864?1.25:2),4194304)/4096))}else r=1+(Math.max(e-t<<2,Ki.length-1)>>12)<<12;let s=new Wi(r);return Qi=s.dataView||(s.dataView=new DataView(s.buffer,0,r)),e=Math.min(e,Ki.length),Ki.copy?Ki.copy(s,0,t,e):s.set(Ki.slice(t,e)),tn-=t,t=0,Xi=s.length-10,Ki=s},k=(e,t,i)=>{let n=s.nextId;n||(n=64),n<p&&this.shouldShareStructure&&!this.shouldShareStructure(t)?(n=s.nextOwnId,n<f||(n=p),s.nextOwnId=n+1):(n>=f&&(n=p),s.nextId=n+1);let o=t.highByte=n>=96&&d?n-96>>5:-1;e[nn]=n,e.__keys__=t,s[n-64]=t,n<p?(t.isShared=!0,s.sharedLength=n-63,r=!0,o>=0?(Ki[tn++]=96+(31&n),Ki[tn++]=o):Ki[tn++]=n):(o>=0?(Ki[tn++]=213,Ki[tn++]=114,Ki[tn++]=96+(31&n),Ki[tn++]=o):(Ki[tn++]=212,Ki[tn++]=114,Ki[tn++]=n),i&&(g+=y*i),m.length>=l&&(m.shift()[nn]=0),m.push(e),_(t))},T=(e,r,s,i)=>{let n=Ki,o=tn,a=Xi,c=t;Ki=Yi,tn=0,t=0,Ki||(Yi=Ki=new Wi(8192)),Xi=Ki.length-10,k(e,r,i),Yi=Ki;let u=tn;if(Ki=n,tn=o,Xi=a,t=c,u>1){let e=tn+u-1;e>Xi&&x(e);let r=s+t;Ki.copyWithin(r+u,r+1,tn),Ki.set(Yi.slice(0,u),r),tn=e}else Ki[s+t]=Yi[0]},R=e=>{let i=en(e,Ki,t,tn,s,x,((e,t,s)=>{if(s)return r=!0;tn=t;let i=Ki;return _(e),b(),i!==Ki?{position:tn,targetView:Qi,target:Ki}:tn}),this);if(0===i)return E(e);tn=i}}useBuffer(e){Ki=e,Ki.dataView||(Ki.dataView=new DataView(Ki.buffer,Ki.byteOffset,Ki.byteLength)),tn=0}set position(e){tn=e}get position(){return tn}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}}function an(e,t,r,s){let i=e.byteLength;if(i+1<256){var{target:n,position:o}=r(4+i);n[o++]=199,n[o++]=i+1}else if(i+1<65536){var{target:n,position:o}=r(5+i);n[o++]=200,n[o++]=i+1>>8,n[o++]=i+1&255}else{var{target:n,position:o,targetView:a}=r(7+i);n[o++]=201,a.setUint32(o,i+1),o+=4}n[o++]=116,n[o++]=t,e.buffer||(e=new Uint8Array(e)),n.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),o)}function cn(e,t){let r=e.byteLength;var s,i;if(r<256){var{target:s,position:i}=t(r+2);s[i++]=196,s[i++]=r}else if(r<65536){var{target:s,position:i}=t(r+3);s[i++]=197,s[i++]=r>>8,s[i++]=255&r}else{var{target:s,position:i,targetView:n}=t(r+5);s[i++]=198,n.setUint32(i,r),i+=4}s.set(e,i)}function un(e,t,r,s){let i=e.length;switch(i){case 1:t[r++]=212;break;case 2:t[r++]=213;break;case 4:t[r++]=214;break;case 8:t[r++]=215;break;case 16:t[r++]=216;break;default:i<256?(t[r++]=199,t[r++]=i):i<65536?(t[r++]=200,t[r++]=i>>8,t[r++]=255&i):(t[r++]=201,t[r++]=i>>24,t[r++]=i>>16&255,t[r++]=i>>8&255,t[r++]=255&i)}return t[r++]=s,t.set(e,r),r+=i}function hn(e,t,r){if(rn.length>0){Qi.setUint32(rn.position+e,tn+r-rn.position-e),rn.stringsPosition=tn-e;let s=rn;rn=null,t(s[0]),t(s[1])}}function ln(e,t){return e.isCompatible=e=>{let r=!e||(t.lastNamedStructuresLength||0)===e.length;return r||t._mergeStructures(e),r},e}Gi=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,ri],zi=[{pack(e,t,r){let s=e.getTime()/1e3;if((this.useTimestamp32||0===e.getMilliseconds())&&s>=0&&s<4294967296){let{target:e,targetView:r,position:i}=t(6);e[i++]=214,e[i++]=255,r.setUint32(i,s)}else if(s>0&&s<4294967296){let{target:r,targetView:i,position:n}=t(10);r[n++]=215,r[n++]=255,i.setUint32(n,4e6*e.getMilliseconds()+(s/1e3/4294967296|0)),i.setUint32(n+4,s)}else if(isNaN(s)){if(this.onInvalidDate)return t(0),r(this.onInvalidDate());let{target:e,targetView:s,position:i}=t(3);e[i++]=212,e[i++]=255,e[i++]=255}else{let{target:r,targetView:i,position:n}=t(15);r[n++]=199,r[n++]=12,r[n++]=255,i.setUint32(n,1e6*e.getMilliseconds()),i.setBigInt64(n+4,BigInt(Math.floor(s)))}}},{pack(e,t,r){if(this.setAsEmptyObject)return t(0),r({});let s=Array.from(e),{target:i,position:n}=t(this.moreTypes?3:0);this.moreTypes&&(i[n++]=212,i[n++]=115,i[n++]=0),r(s)}},{pack(e,t,r){let{target:s,position:i}=t(this.moreTypes?3:0);this.moreTypes&&(s[i++]=212,s[i++]=101,s[i++]=0),r([e.name,e.message,e.cause])}},{pack(e,t,r){let{target:s,position:i}=t(this.moreTypes?3:0);this.moreTypes&&(s[i++]=212,s[i++]=120,s[i++]=0),r([e.source,e.flags])}},{pack(e,t){this.moreTypes?an(e,16,t):cn(Hi?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let r=e.constructor;r!==Zi&&this.moreTypes?an(e,ji.indexOf(r.name),t):cn(e,t)}},{pack(e,t){let{target:r,position:s}=t(1);r[s]=193}}];let dn=new on({useRecords:!1});dn.pack,dn.pack;const{NEVER:pn,ALWAYS:fn,DECIMAL_ROUND:mn,DECIMAL_FIT:gn}={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},yn=512,bn=1024,vn=2048;const _n=new on({useRecords:!1,encodeUndefinedAsNil:!0,int64AsType:"number"}),wn=new ui({useRecords:!1,int64AsType:"number"});class Sn{subject;handlerId;unsubscribeFn;constructor(e,t,r){this.subject=e,this.handlerId=t,this.unsubscribeFn=r}unsubscribe(){try{this.unsubscribeFn(this.subject,this.handlerId)}catch{}}}let Cn=256;const En=[];let xn;for(;Cn--;)En[Cn]=(Cn+256).toString(16).substring(1);function kn(e){let t=0;const r=e??11;if(!xn||Cn+r>512)for(xn="",Cn=0;t<256;t++)xn+=En[256*Math.random()|0];return xn.substring(Cn,Cn+++r)}const Tn=x("camera:ui:connection");class Rn{type;options;connection=null;connectionPromise;subscriptionGroups=new Map;metricsTracker;isDisconnected=!1;constructor(e,t){this.type=e,this.options=t,E.validateConnectionOptions(t),this.metricsTracker=new Ls}async connect(){this.isConnected()||(this.connectionPromise?await this.connectionPromise:(Tn(`[${this.options.metadata.id}] Establishing connection...`),this.connectionPromise=this.establishConnection(),await this.connectionPromise,Tn(`[${this.options.metadata.id}] Connection established successfully.`)))}async disconnect(){this.isDisconnected=!0,Tn(`[${this.options.metadata.id}] Disconnecting...`),await this.drainConnection(),this.connection=null,Tn(`[${this.options.metadata.id}] Disconnected.`)}isConnected(){return null!==this.connection&&!this.connection.isClosed()&&!this.connection.isDraining()}isClosed(){return null===this.connection||this.connection.isClosed()||this.connection.isDraining()}getConnection(){if(!this.isConnected())throw S.connection.invalidState(void 0,{description:"Connection is not established",code:i.INVALID_STATE});return this.connection}publish(e,t,r,s){if(this.isClosed())throw Tn(`[${this.options.metadata.id}] Publish skipped: Connection closed or draining`),S.connection.notConnected(void 0,{description:"Failed to publish message: Connection closed or draining",code:i.NOT_CONNECTED,subject:e});const n={id:kn(),type:Ps.BROADCAST,data:t,metadata:this.options.metadata,timestamp:Date.now(),routing:s,error:r};try{this.getConnection().publish(e,this.packMessage(n)),this.metricsTracker.trackPublish(),Tn("Published message to",e,n.id)}catch(r){throw this.metricsTracker.trackMessageError(),S.message.deliveryFailed(r,{description:"Failed to publish message",code:c.DELIVERY_FAILED,subject:e})}}async request(e,t,r,s){if(this.isClosed())throw Tn(`[${this.options.metadata.id}] Request skipped: Connection closed or draining. Subject: ${e}`),S.connection.notConnected(void 0,{description:"Failed to send request: Connection closed or draining",code:i.NOT_CONNECTED,subject:e});const n=kn(),o={id:n,type:Ps.REQUEST,subject:e,data:t,metadata:this.options.metadata,timestamp:Date.now(),routing:s};this.metricsTracker.trackRequestStart(n);try{const t=await this.getConnection().request(e,this.packMessage(o),{timeout:r??this.getTimeoutOptions().request}),s=this.unpackMessage(t);if(this.metricsTracker.trackRequestEnd(n,!!s.error),s.error)throw p.fromJSON(s.error);return s}catch(t){if(this.metricsTracker.trackRequestEnd(n,!0),t instanceof p)throw t;throw S.connection.requestFailed(t,{description:"Failed to send request or process response",code:"CONNECTION_REQUEST_FAILED",subject:e})}}async requestRPC(e,t,r){if(this.isClosed())throw Tn(`[${this.options.metadata.id}] RPC Request skipped: Connection closed or draining. Subject: ${e}`),S.connection.notConnected(void 0,{description:"Failed to send RPC request: Connection closed or draining",code:i.NOT_CONNECTED,subject:e});const s={id:kn(),type:Ps.RPC_REQUEST,subject:e,data:t,metadata:this.options.metadata,timestamp:Date.now()};this.metricsTracker.trackRPCStart();try{const t=await this.getConnection().request(e,this.packMessage(s),{timeout:r??this.getTimeoutOptions().rpc}),i=this.unpackMessage(t);if(this.metricsTracker.trackRPCEnd(!!i.error),i.error)throw p.fromJSON(i.error);return i}catch(t){if(this.metricsTracker.trackRPCEnd(!0),t instanceof p)throw t;throw S.rpc.requestFailed(t,{description:"Failed to send RPC request or process response",code:"RPC_REQUEST_FAILED",subject:e})}}handleRequest(e,t){return this.subscribe(e,t,void 0,"request")}subscribe(e,t,r=kn(),s="message"){if(this.isClosed())throw Tn(`[${this.options.metadata.id}] Subscribe skipped: Connection closed or draining. Subject: ${e}`),S.connection.notConnected(void 0,{description:"Failed to subscribe: Connection closed or draining",code:i.NOT_CONNECTED,subject:e});let n=this.subscriptionGroups.get(e);if(n){if(n.type!==s)throw new Error(`Cannot mix on subject ${e}`);if(("request"===s||"rpc"===s||"generator"===s)&&n.handlers.size>0)throw new Error(`Request/RPC/Generator handler already registered for subject ${e}`)}else{let t;try{t=this.getConnection().subscribe(e)}catch(t){throw S.connection.subscribeFailed(t,{description:`Failed to create NATS subscription for subject ${e}`,code:"CONNECTION_SUBSCRIBE_FAILED",subject:e,metadata:{type:s}})}n={subscription:t,handlers:new Map,type:s,refCount:0},this.subscriptionGroups.set(e,n),this.handleSubscription(t,e,n),Tn(`[${this.options.metadata.id}] Created subscription group for %s`,e)}return n.handlers.has(r)&&Tn(`[${this.options.metadata.id}] Handler %s already registered for subject %s`,r,e),n.handlers.set(r,t),n.refCount++,this.metricsTracker.trackSubscriptionChange(1,s),Tn(`[${this.options.metadata.id}] Subscribed to %s (handler: %s, type: %s, refCount: %d)`,e,r,s,n.refCount),new Sn(e,r,this.unsubscribe.bind(this))}unsubscribe(e,t){const r=this.subscriptionGroups.get(e);if(r&&r.handlers.delete(t)&&(r.refCount--,this.metricsTracker.trackSubscriptionChange(-1,r.type),r.refCount<=0))try{r.subscription.unsubscribe(),this.subscriptionGroups.delete(e)}catch{this.subscriptionGroups.delete(e)}}getMetrics(){return this.metricsTracker.getMetrics()}async establishConnection(){try{this.isDisconnected=!1;const e=this.getTimeoutOptions(),{waitForServer:t}=this.getConnectOptions(),{maxAttempts:r,delay:s,enabled:n}=this.getReconnectOptions();let o=0;for(;!this.isDisconnected;){o++;try{Tn(`[${this.options.metadata.id}] Connection attempt ${o}...`);const t=await ks({...this.getNatsAuthOptions(),name:this.options.metadata.id,servers:this.options.endpoints,tls:this.options.tls,timeout:e.connection,maxReconnectAttempts:n?r:0,reconnect:n,reconnectTimeWait:s,noEcho:!0,noAsyncTraces:!0,waitOnFirstConnect:!0});return Tn(`[${this.options.metadata.id}] NATS connect() successful.`),(async()=>{for await(const e of t.status())e.type===N.Reconnect&&Tn(`[${this.options.metadata.id}] Connection reconnected.`)})().catch((e=>{Tn(`[${this.options.metadata.id}] Error in status monitoring:`,e)})),t.closed().then((e=>{Tn(`[${this.options.metadata.id}] Connection closed:`,e),this.subscriptionGroups.clear(),this.metricsTracker.resetMetrics(),this.isDisconnected=!0,this.connection=null})),void(this.connection=t)}catch(e){if(this.isDisconnected)return;if(!t)throw Tn(`[${this.options.metadata.id}] Connection attempt ${o} failed:`,e),S.connection.connectionFailed(e,{description:"Failed to connect to NATS server",code:i.FAILED,metadata:{attempts:o}});Tn(`[${this.options.metadata.id}] Connection attempt ${o} failed:`,e),await new Promise((e=>setTimeout(e,s)))}}}finally{this.connectionPromise=void 0}}async drainConnection(){if(this.connection&&!this.connection.isClosed())try{await this.connection.drain()}catch(e){Tn("Error draining connection:",e)}}async handleSubscription(e,t,r){Tn(`[${this.options.metadata.id}] Starting message loop for subscription ${t}`);for await(const s of e){if(!this.subscriptionGroups.has(t)){Tn(`[${this.options.metadata.id}] Message loop for ${t} exiting: Group removed.`);break}let e;try{e=this.unpackMessage(s);const t={subject:s.subject,timestamp:Date.now(),id:e.id};switch(this.metricsTracker.trackReceive(),r.type){case"request":this.handleRequestMessage(s,e,r);break;case"rpc":this.handleRPCMessage(s,e,r);break;case"generator":this.handleGeneratorInitiationMessage(s,e,r);break;default:this.handleNormalMessage(e,t,r)}}catch(e){this.metricsTracker.trackMessageError(),Tn(`[${this.options.metadata.id}] Error processing message for ${t}:`,e)}}Tn(`[${this.options.metadata.id}] Message loop for subscription ${t} terminated.`),this.subscriptionGroups.has(t)&&this.subscriptionGroups.delete(t)}async handleRequestMessage(e,t,r){const s=r.handlers.values().next().value;if(s)try{const r=await s(t);this.respondTo(e,r,t.id)}catch(r){this.metricsTracker.trackMessageError();const s=S.message.executionFailed(r,{description:"Handler execution failed"});this.respondTo(e,null,t.id,s.toJSON())}}async handleRPCMessage(e,t,r){const s=r.handlers.values().next().value;if(s)try{const r=Array.isArray(t.data)?t.data:void 0!==t.data?[t.data]:[],i=await s(...r);this.respondToRPC(e,i,t.id)}catch(r){this.metricsTracker.trackMessageError();const s=S.rpc.executionFailed(r,{description:"RPC handler execution failed"});this.respondToRPC(e,null,t.id,void 0,!0,s.toJSON())}}async handleGeneratorInitiationMessage(e,t,r){const s=r.handlers.values().next().value;if(s)try{await s(t)}catch(e){this.metricsTracker.trackMessageError(),Tn("Error processing generator request:",e)}}async handleNormalMessage(e,t,r){const s=Array.from(r.handlers.values());if(0===s.length)return;const i=[];for(const t of s)try{const r=t(e);r instanceof Promise&&i.push(r.catch(this.metricsTracker.trackMessageError.bind(this)))}catch(e){this.metricsTracker.trackMessageError(),Tn("Error in sync handler:",e)}await Promise.allSettled(i)}respondTo(e,t,r,s){try{if(this.isClosed())throw Tn(`[${this.options.metadata.id}] Respond skipped: Connection closed or draining. Subject: ${e.subject}`),S.connection.notConnected(void 0,{description:"Failed to respond: Connection closed or draining",code:i.NOT_CONNECTED,subject:e.subject});const n={id:kn(),type:Ps.RESPONSE,requestId:r,data:t,metadata:this.options.metadata,error:s,timestamp:Date.now()};e.respond(this.packMessage(n))}catch(s){this.metricsTracker.trackMessageError(),Tn("Error sending request response:",s)}}respondToRPC(e,t,r,s,n,o){try{if(this.isClosed())throw Tn(`[${this.options.metadata.id}] RPC Respond skipped: Connection closed or draining. Subject: ${e.subject}`),S.connection.notConnected(void 0,{description:"Failed to respond: Connection closed or draining",code:i.NOT_CONNECTED,subject:e.subject});const a={id:kn(),type:Ps.RPC_RESPONSE,requestId:r,data:t,metadata:this.options.metadata,streamId:s,done:n,error:o,timestamp:Date.now()};e.respond(this.packMessage(a))}catch(o){this.metricsTracker.trackMessageError(),Tn("Error sending RPC response:",o)}}packMessage(e){try{return t=e,_n.pack(t)}catch(t){throw this.metricsTracker.trackMessageError(),S.message.invalidFormat(t,{description:"Failed to pack message",code:c.INVALID_FORMAT,metadata:{raw:e}})}var t}unpackMessage(e){try{return t=e.data,wn.unpack(t)}catch{throw S.message.invalidFormat(void 0,{description:"Failed to parse message",code:c.INVALID_FORMAT,subject:e.subject,metadata:{raw:e.data}})}var t}getNatsAuthOptions(){return"server"in this.options.auth?{user:this.options.auth.server.user,pass:this.options.auth.server.password}:{user:this.options.auth.user,pass:this.options.auth.password}}getConnectOptions(){return{waitForServer:!1,...this.options.connect}}getReconnectOptions(){return{enabled:!1,maxAttempts:Ns.MAX_RECONNECT_ATTEMPTS,delay:Ns.DELAY,...this.options.reconnect}}getTimeoutOptions(){return{rpc:Is.RPC,request:Is.REQUEST,connection:Is.CONNECTION,...this.options.timeout}}}class On{constructor(){}publish(e,t,r){this.getConnectionManager().publish(e,t,void 0,r)}async request(e,t,r,s){return this.getConnectionManager().request(e,t,r,s)}handleRequest(e,t){return this.getConnectionManager().handleRequest(e,t)}subscribe(e,t){return this.getConnectionManager().subscribe(e,t)}unsubscribe(e,t){return this.getConnectionManager().unsubscribe(e,t)}}r(779);function An(e={name:void 0,public:!0}){return function(t,r){const s="object"==typeof r?r.name:r,i=e.name??s.toString();if("object"==typeof r){const r=t;return Reflect.defineMetadata("rpc:config",{name:i,public:e.public??!0},r,s),r}{const r=t[s];Reflect.defineMetadata("rpc:config",{name:i,public:e.public??!0},t,s),Object.defineProperty(t,s,{value:function(...e){return r.apply(this,e)},enumerable:!0,configurable:!0})}}}class Pn{static extractMethods(e){const t={},r=(r,s)=>{if(!((e,t)=>"function"==typeof t&&!e.startsWith("_")&&!e.startsWith("#")&&"constructor"!==e&&!Object.prototype.hasOwnProperty.call(Object.prototype,e))(r,s))return;const i=Reflect.getMetadata("rpc:config",Object.getPrototypeOf(e),r)??Reflect.getMetadata("rpc:config",s,r);i?.public&&(t[i.name]={name:i.name,public:!0,type:Pn.getMethodType(s),method:s})};let s=e;const i=new Set;for(;s&&s!==Object.prototype;)Object.getOwnPropertyNames(s).forEach((t=>{if(!i.has(t)){i.add(t);const s=e[t];r(t,s)}})),s=Object.getPrototypeOf(s);return t._discover={name:"_discover",public:!0,type:"async",method:async()=>Object.entries(Pn.extractMethods(e)).reduce(((e,[t,r])=>(e[t]={name:t,type:r.type},e)),{})},t}static isAsyncFunction(e){return!!e&&(e.constructor?"AsyncFunction"===e.constructor.name:e.toString().includes("async ")&&!e.toString().includes("async*"))}static isGeneratorFunction(e){return!!e&&(e.constructor?"GeneratorFunction"===e.constructor.name:e.toString().includes("function*"))}static isAsyncGeneratorFunction(e){return!!e&&(e.constructor?"AsyncGeneratorFunction"===e.constructor.name:e.toString().includes("async*"))}static getMethodType(e){return Pn.isAsyncGeneratorFunction(e)||Pn.isGeneratorFunction(e)?"asyncGenerator":(Pn.isAsyncFunction(e),"async")}}const In=x("camera:ui:rpc:generator");class Mn{namespace;mainConnection;options;MAX_QUEUE_SIZE=100;pendingReadySignals=new Map;consumerGeneratorStates=new Map;producerGeneratorStates=new Map;handlerSubscriptions=new Map;constructor(e,t,r){this.namespace=e,this.mainConnection=t,this.options=r}async*createGenerator(e,...t){const r=kn(),s=`${this.namespace}.${e}.generator`,i=`${s}.stream.${r}`,n=`${s}.control.${r}`;In(`[C:${r}] Starting generator stream for ${e}`);let o=null,a=null;try{In(`[C:${r}] Creating dedicated consumer connection...`),o=new Rn(this.mainConnection.type,{...this.options,metadata:{...this.options.metadata,id:`${this.options.metadata.id}-cg-${r.substring(0,8)}`},bundledConnection:!1,timeout:this.options.timeout}),await o.connect(),In(`[C:${r}] Dedicated consumer connection established.`);const e=o.subscribe(i,(e=>this.handleStreamMessage(r,e)),kn(),"generator");for(In(`[C:${r}] Subscribed to data stream: ${i}`),a={messageQueue:[],resolveNext:null,error:void 0,isDone:!1,streamSubscription:e,controlSubject:n,lastProcessedTime:Date.now(),isProcessing:!1,dedicatedConnection:o},this.consumerGeneratorStates.set(r,a),In(`[C:${r}] Sending initiation request via main connection to ${s}`),this.mainConnection.publish(s,{streamId:r,args:t});!a.isDone;){if(a.error)throw a.error;if(a.messageQueue.length>0){const e=a.messageQueue.shift();a.isProcessing=!0;try{yield e.value}finally{a.isProcessing=!1,a.lastProcessedTime=Date.now(),this.sendReadySignal(r,a.controlSubject,a.dedicatedConnection)}continue}a.isProcessing=!1;const e=await new Promise((e=>{const t=this.consumerGeneratorStates.get(r);t?t.resolveNext=e:e({done:!0,value:void 0})}));if(e.done||this.consumerGeneratorStates.get(r)?.isDone)break;a=this.consumerGeneratorStates.get(r),a.isProcessing=!0;try{yield e.value.value}finally{a.isProcessing=!1,a.lastProcessedTime=Date.now(),this.sendReadySignal(r,a.controlSubject,a.dedicatedConnection)}}In(`[C:${r}] Consumption loop finished.`)}finally{In(`[C:${r}] Cleaning up consumer side...`);const t=this.consumerGeneratorStates.get(r);if(t)await this.cleanupConsumerGenerator(r,t);else if(o&&!o.isClosed()){const t=`${this.namespace}.${e}.generator.control.${r}`;await this.cleanupConsumerConnection(r,o,t)}this.consumerGeneratorStates.delete(r),In(`[C:${r}] Consumer cleanup finished.`)}}async handleGenerator(e,t){const r=`${this.namespace}.${e}.generator`;In(`[P] Setting up generator handler for: ${r}`),this.handlerSubscriptions.get(r)?.unsubscribe();const s=this.mainConnection.subscribe(r,(async r=>{try{await this.handleGeneratorRequest(e,t,r)}catch(t){In(`[P:${r.data?.streamId||"unknown"}] Critical error setting up generator handler for ${e}:`,t)}}),kn(),"generator");this.handlerSubscriptions.set(r,s)}async handleGeneratorRequest(e,t,r){const s=r.data?.streamId;if(!s)return void In(`[P:unknown] Received generator request for ${e} without streamId. Discarding.`);const i=`${this.namespace}.${e}.generator`,n=`${i}.stream.${s}`,o=`${i}.control.${s}`;In(`[P:${s}] Received generator request for ${e}`);let a=null,c=null,u=null;try{In(`[P:${s}] Creating dedicated producer connection...`),a=new Rn(this.mainConnection.type,{...this.options,metadata:{...this.options.metadata,id:`${this.options.metadata.id}-pg-${s.substring(0,8)}`},bundledConnection:!1,timeout:this.options.timeout}),await a.connect(),In(`[P:${s}] Dedicated producer connection established.`),this.pendingReadySignals.has(s)||this.pendingReadySignals.set(s,new Set);const e=a.subscribe(o,(e=>this.handleControlMessage(s,e)),kn(),"generator");In(`[P:${s}] Subscribed to control subject: ${o}`);u=t(...r.data.args?Array.isArray(r.data.args)?r.data.args:[r.data.args]:[]),c={streamSubject:n,controlSubject:o,requestId:r.id,streamId:s,generator:u,isWaitingForClient:!1,lastSentTime:Date.now(),dedicatedConnection:a,controlSubscription:e},this.producerGeneratorStates.set(s,c),In(`[P:${s}] Generator handler invoked. Processing frames...`);let i=await u.next();for(;;){if(this.producerGeneratorStates.get(s)!==c){In(`[P:${s}] Producer state removed. Aborting loop.`);break}if(i.done){a.publish(n,{requestId:r.id,streamId:s,done:!0}),In(`[P:${s}] Generator completed normally.`);break}a.publish(n,{requestId:r.id,streamId:s,value:i.value,done:!1}),c.lastSentTime=Date.now(),c.isWaitingForClient=!0;const e=new Promise((e=>this.pendingReadySignals.get(s)?.add(e)));let t;const o=new Promise((e=>{t=setTimeout((()=>{In(`[P:${s}] Ready signal timeout.`),e()}),1e4)}));if(await Promise.race([e.finally((()=>clearTimeout(t))),o]),clearTimeout(t),this.producerGeneratorStates.get(s)!==c){In(`[P:${s}] Producer state changed during wait. Aborting loop.`);break}i=await u.next()}}catch(e){if(In(`[P:${s}] Error during generator execution:`,e),a&&this.producerGeneratorStates.has(s)){const t=S.rpc.internalError(e,{description:"Error processing generator request"});try{a.publish(n,{requestId:r.id,streamId:s,done:!0,error:t.toJSON()})}catch(e){In(`[P:${s}] Error sending error message:`,e)}}}finally{In(`[P:${s}] Cleaning up producer side...`);const e=this.producerGeneratorStates.get(s);e?await this.cleanupProducerGenerator(s,e):a&&!a.isClosed()&&await this.cleanupProducerConnection(a,null),this.producerGeneratorStates.delete(s),this.pendingReadySignals.delete(s),In(`[P:${s}] Producer side cleanup finished.`)}}async dispose(){In("Disposing RPCGeneratorManager..."),await Promise.allSettled([...Array.from(this.consumerGeneratorStates.entries()).map((([e,t])=>this.cleanupConsumerGenerator(e,t))),...Array.from(this.producerGeneratorStates.entries()).map((([e,t])=>this.cleanupProducerGenerator(e,t)))]),this.consumerGeneratorStates.clear(),this.producerGeneratorStates.clear(),this.pendingReadySignals.clear(),this.handlerSubscriptions.forEach((e=>e.unsubscribe())),this.handlerSubscriptions.clear(),In("RPCGeneratorManager disposed.")}handleStreamMessage(e,t){const r=this.consumerGeneratorStates.get(e);if(r)return t.error?(r.error=p.fromJSON(t.error),r.isDone=!0,void(r.resolveNext&&(r.resolveNext({done:!0,value:void 0}),r.resolveNext=null))):t.data.done?(r.isDone=!0,void(r.resolveNext&&(r.resolveNext({done:!0,value:t.data}),r.resolveNext=null))):void(r.resolveNext?(r.resolveNext({done:!1,value:t.data}),r.resolveNext=null):(r.messageQueue.length>=this.MAX_QUEUE_SIZE&&r.messageQueue.shift(),r.messageQueue.push(t.data)))}handleControlMessage(e,t){const r=this.producerGeneratorStates.get(e);if(r)if("return"===t.data.type||"throw"===t.data.type)this.cleanupProducerGenerator(e,r).catch((()=>{}));else if("ready"===t.data.type){r.isWaitingForClient=!1;const t=this.pendingReadySignals.get(e);t&&(t.forEach((e=>e())),t.clear())}}sendReadySignal(e,t,r){r.isClosed()||r.publish(t,{type:"ready"})}async cleanupConsumerGenerator(e,t){this.consumerGeneratorStates.has(e)&&(this.consumerGeneratorStates.delete(e),In(`[C:${e}] Cleaning up consumer generator...`),t.streamSubscription.unsubscribe(),await this.cleanupConsumerConnection(e,t.dedicatedConnection,t.controlSubject))}async cleanupConsumerConnection(e,t,r){if(In(`[C:${e}] Cleaning up consumer connection...`),r&&!t.isClosed())try{t.publish(r,{type:"return"})}catch{}t.isClosed()||await t.disconnect().catch((t=>In(`[C:${e}] Error disconnecting consumer connection:`,t)))}async cleanupProducerGenerator(e,t){this.producerGeneratorStates.has(e)&&(this.producerGeneratorStates.delete(e),this.pendingReadySignals.delete(e),In(`[P:${e}] Cleaning up producer generator...`),await t.generator.return(void 0).catch((()=>{})),await this.cleanupProducerConnection(t.dedicatedConnection,t.controlSubscription))}async cleanupProducerConnection(e,t){const r=e?.options?.metadata?.id||"unknown-producer";In(`[P:${r}] Cleaning up producer connection...`),t?.unsubscribe(),e&&!e.isClosed()&&await e.disconnect().catch((e=>In(`[P:${r}] Error disconnecting producer connection:`,e)))}}const Nn=x("camera:ui:rpc");class jn{namespace;connection;options;rpcOptions;generatorManager;handlers=new Map;remoteMethodTypes=new Map;constructor(e,t,r,s){this.namespace=e,this.connection=t,this.options=r,this.rpcOptions=s,this.generatorManager=new Mn(this.namespace,this.connection,this.options)}async connect(){if(this.options.bundledConnection)Nn(`[${this.namespace}] Main connection is bundled, skipping connect.`);else try{await this.connection.connect(),Nn(`[${this.namespace}] Main connection established.`)}catch(e){throw Nn(`[${this.namespace}] Failed to establish main connection:`,e),e}}async disconnect(){if(Nn(`[${this.namespace}] Disconnecting RPCConnection...`),await this.dispose(),this.options.bundledConnection)Nn(`[${this.namespace}] Skipping disconnect of bundled main connection.`);else{if(!this.connection.isClosed())try{await this.connection.disconnect(),Nn(`[${this.namespace}] Main connection disconnected.`)}catch(e){Nn(`[${this.namespace}] Error disconnecting main connection:`,e)}Nn(`[${this.namespace}] RPCConnection disconnected.`)}}isConnected(){return this.connection.isConnected()}registerHandler(e){const t=Pn.extractMethods(e);Object.entries(t).forEach((([t,r])=>{const s=r.name||t;if(this.handlers.has(s))return void Nn(`[${this.namespace}] Handler for method '${s}' already registered.`);const i={handler:e,subscriptions:[]};if(this.handlers.set(s,i),Nn(`[${this.namespace}] Registering handler for method: ${s} (${r.type})`),"asyncGenerator"===r.type)this.generatorManager.handleGenerator(s,r.method.bind(e));else{const t=`${this.namespace}.${s}`,n=kn();try{this.connection.subscribe(t,r.method.bind(e),n,"rpc"),i.subscriptions.push({subject:t,handlerId:n})}catch(e){console.error(`[${this.namespace}] Failed to register handler for method: "${s}":`,e),this.handlers.delete(s)}}}))}async call(e,...t){const r=`${this.namespace}.${e}`;return this.connection.requestRPC(r,t,this.rpcOptions?.timeout).then((e=>e.data))}callGenerator(e,...t){return this.generatorManager.createGenerator(e,...t)}createProxy(){const e=new Set(["toString","toJSON","valueOf","constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","then","catch","finally"]);return new Proxy({},{get:(t,r)=>{if("symbol"!=typeof r&&!e.has(r))return(...e)=>{const t=e[0]?.isGenerator;return t?(Nn("Creating generator proxy for:",r),this.callGenerator(r,...e.slice(1))):(Nn("Creating async proxy for:",r),this.connection.requestRPC(`${this.namespace}.${r}`,e,this.rpcOptions?.timeout).then((e=>e.data)))}}})}getConnectionManager(){return this.connection}async dispose(){Nn(`[${this.namespace}] Disposing RPCConnection resources...`),this.generatorManager&&await this.generatorManager.dispose();const e=[];this.handlers.forEach((t=>{t.subscriptions.forEach((({subject:t,handlerId:r})=>{e.push(new Promise((e=>{try{this.connection.unsubscribe(t,r)}finally{e()}})))}))})),await Promise.allSettled(e),this.handlers.clear(),this.remoteMethodTypes.clear(),Nn(`[${this.namespace}] Finished disposing RPCConnection resources.`)}}class Fn extends On{type;options;rpcManagers=new Map;remoteRpcManagers=new Map;connection;constructor(e,t){super(),this.type=e,this.options=t,E.validateConnectionOptions(t),this.connection=new Rn(this.type,t)}sendToPlugin(e,t){const r=C.createRoutingMetadata(this.type,this.options.metadata.id,"plugin",e);this.publish(this.getPluginSubject(e),t,r)}sendToService(e,t){const r=C.createRoutingMetadata(this.type,this.options.metadata.id,"service",e);this.publish(this.getServiceSubject(e),t,r)}async requestFromPlugin(e,t,r){const s=C.createRoutingMetadata(this.type,this.options.metadata.id,"plugin",e);return this.request(this.getPluginSubject(e),t,r,s)}async requestFromService(e,t,r){const s=C.createRoutingMetadata(this.type,this.options.metadata.id,"service",e);return this.request(this.getServiceSubject(e),t,r,s)}onPluginMessage(e="*",t){const r="plugin"===this.type?C.getPluginToPluginSubject(e,this.options.metadata.id):"service"===this.type?C.getPluginToServiceSubject(e,this.options.metadata.id):C.getPluginToServerSubject(e,this.options.metadata.id);return this.handleRequest(r,(async e=>await t(e.data)))}onServiceMessage(e="*",t){const r="plugin"===this.type?C.getServiceToPluginSubject(e,this.options.metadata.id):"service"===this.type?C.getServiceToServiceSubject(e,this.options.metadata.id):C.getServiceToServerSubject(e,this.options.metadata.id);return this.handleRequest(r,(async e=>await t(e.data)))}async registerRPCHandler(e,t,r){let s=this.rpcManagers.get(e);if(s)return;const i=this.options.bundledConnection??!0?this.connection:new Rn(this.type,this.options);s=new jn(e,i,this.options,r),await s.connect(),s.registerHandler(t),this.rpcManagers.set(e,s)}async unregisterRPCHandler(e){const t=this.rpcManagers.get(e);await(t?.disconnect()),this.rpcManagers.delete(e)}async createRPCProxy(e,t){return(await this.createRPCConnection(e,t)).createProxy()}async createRPCConnection(e,t){try{let r=this.remoteRpcManagers.get(e);if(!r){const s=this.options.bundledConnection??!0?this.connection:new Rn(this.type,this.options);r=new jn(e,s,this.options,t),await r.connect(),this.remoteRpcManagers.set(e,r)}return r}catch(r){throw S.rpc.connectionFailed(r,{description:"Failed to connect to remote RPC",code:u.CONNECTION_FAILED,metadata:{namespace:e,rpcOptions:t}})}}async disconnectRPCConnection(e){const t=this.remoteRpcManagers.get(e);await(t?.disconnect()),this.remoteRpcManagers.delete(e)}async cleanup(){await this.cleanupRPCConnections(),await this.cleanupRemoteRPCConnections()}async cleanupRPCConnections(e){if(e){const t=this.rpcManagers.get(e);await(t?.disconnect()),this.rpcManagers.delete(e)}else await Promise.allSettled([...this.rpcManagers.values()].map((e=>e.disconnect()))),this.rpcManagers.clear()}async cleanupRemoteRPCConnections(e){if(e){const t=this.remoteRpcManagers.get(e);await(t?.disconnect()),this.remoteRpcManagers.delete(e)}else await Promise.allSettled([...this.remoteRpcManagers.values()].map((e=>e.disconnect()))),this.remoteRpcManagers.clear()}getPluginSubject(e){return"plugin"===this.type?C.getPluginToPluginSubject(this.options.metadata.id,e):"service"===this.type?C.getServiceToPluginSubject(this.options.metadata.id,e):C.getServerToPluginSubject(this.options.metadata.id,e)}getServiceSubject(e){return"plugin"===this.type?C.getPluginToServiceSubject(this.options.metadata.id,e):"service"===this.type?C.getServiceToServiceSubject(this.options.metadata.id,e):C.getServerToServiceSubject(this.options.metadata.id,e)}}const $n=x("camera:ui:client");class Ln extends Fn{type;options;isProxy;serverStatus=As;registered=!1;serverMetadata;constructor(e,t,r=!1){super(e,t),this.type=e,this.options=t,this.isProxy=r}async connect(){await this.initialize(),this.setupSubscriptions(),$n("Connected successfully")}async disconnect(){await super.cleanup(),await this.connection.disconnect(),this.registered=!1,$n("Disconnected from NATS")}sendToServer(e){if(!this.serverMetadata)throw S.client.invalidState(void 0,{description:"Server metadata is not available",code:a.INVALID_STATE});const t="plugin"===this.type?C.getPluginToServerSubject(this.options.metadata.id,this.serverMetadata.id):C.getServiceToServerSubject(this.options.metadata.id,this.serverMetadata.id),r=C.createRoutingMetadata(this.type,this.options.metadata.id,"server",this.serverMetadata.id);this.publish(t,e,r)}async requestFromServer(e,t){if(!this.serverMetadata)throw S.client.invalidState(void 0,{description:"Server metadata is not available",code:a.INVALID_STATE});const r="plugin"===this.type?C.getPluginToServerSubject(this.options.metadata.id,this.serverMetadata.id):C.getServiceToServerSubject(this.options.metadata.id,this.serverMetadata.id),s=C.createRoutingMetadata(this.type,this.options.metadata.id,"server",this.serverMetadata.id);return this.request(r,e,t,s)}onServerMessage(e){if(!this.serverMetadata)throw S.client.invalidState(void 0,{description:"Server metadata is not available",code:a.INVALID_STATE});const t="plugin"===this.type?C.getServerToPluginSubject(this.serverMetadata.id,this.options.metadata.id):C.getServerToServiceSubject(this.serverMetadata.id,this.options.metadata.id);return this.handleRequest(t,(async t=>await e(t.data)))}isServerRunning(){return"running"===this.serverStatus}isConnected(){return this.connection.isConnected()}isRegistered(){return this.registered}async createRPCProxy(e,t){return super.createRPCProxy(e,t)}createRPCConnection(e,t){return super.createRPCConnection(e,t)}disconnectRPCConnection(e){return super.disconnectRPCConnection(e)}getConnectionManager(){return this.connection}getRPCConnectionManagers(){const e=Array.from(this.rpcManagers.values()).map((e=>e.getConnectionManager()));return[this.connection,...e]}async initialize(){await this.connection.connect(),await this.register()}setupSubscriptions(){this.isProxy||this.handleRequest(`${Ts.HEALTH.PING}.${this.options.metadata.id}`,(async()=>({clientId:this.options.metadata.id}))),this.subscribe(Ts.SERVER.STATUS,(async e=>{$n("Server status update:",e),this.serverStatus=e.data,this.serverStatus===Os||this.serverStatus===As?this.registered=!1:this.serverStatus!==Rs||this.isRegistered()||(this.isProxy?(this.registered=!0,this.serverStatus="running"):await this.register())}))}async register(){if(this.isRegistered()||this.isProxy)return;const e=this.type.toUpperCase(),t=Ts[e].REGISTER;try{const e=await this.request(t,this.options.metadata);if(e.error)throw p.fromJSON(e.error);if(!e.data.success)throw S.client.registrationFailed(void 0,{description:"Failed to register client",subject:t,code:a.REGISTRATION_FAILED,metadata:{response:e,isProxy:this.isProxy,registered:this.registered,type:this.type,metadata:this.options.metadata}});this.serverMetadata=e.data.serverMetadata,this.registered=!0,this.serverStatus="running",$n("Registration successful")}catch(e){throw this.registered=!1,S.client.registrationFailed(e,{description:"Failed to register client",code:a.REGISTRATION_FAILED,subject:t,metadata:{isProxy:this.isProxy,registered:this.registered,type:this.type,metadata:this.options.metadata}})}}}x("camera:ui:connection:state");const Un=r(413)("camera:ui:client:instance");class Dn extends Ln{type;options;status=As;error;metricsInterval;constructor(e,t){super(e,t),this.type=e,this.options=t,E.validateConnectionOptions(t)}async start(){try{if(this.status===Rs)return;await this.connect(),this.setupSubscriptions(),this.options.metrics&&this.startMetricsInterval(),this.updateStatus(Rs),this.onStart(),Un(`Client ${this.options.metadata.id} started successfully`)}catch(e){throw S.connection.connectionFailed(e,{description:"Failed to start client",code:i.FAILED,metadata:{type:this.type,metadata:this.options.metadata}})}}async stop(){try{if(this.status===As||this.status===Os)return;this.stopMetricsInterval(),this.updateStatus(Os),await(this.onBeforeStop?.()),this.updateStatus(As),await this.disconnect();try{await async function(e,t,r,s){let i;const n=new Promise(((e,n)=>{i=setTimeout((()=>{r?.(),n(new Error(s??`Operation timed out after ${t}ms`))}),t)}));try{const t="function"==typeof e?e:()=>e;return await Promise.race([t(),n])}finally{clearTimeout(i)}}(this.onStop(),3e3,void 0,"Failed to stop client")}catch{}Un(`Client ${this.options.metadata.name} stopped successfully`)}catch(e){throw S.connection.connectionFailed(e,{description:"Failed to stop client",code:i.FAILED,metadata:{type:this.type,metadata:this.options.metadata}})}}getStatus(){return{id:this.options.metadata.id,type:this.type,state:this.status,error:this.error,metadata:this.options.metadata}}isRunning(){return this.status===Rs}setupSubscriptions(){this.subscribe(`${Ts.HEALTH.PING}.${this.type}.${this.options.metadata.id}`,(async()=>{const e="plugin"===this.type?Ts.PLUGIN.STATUS:Ts.SERVICE.STATUS;this.publish(`${e}.${this.options.metadata.id}`,this.getStatus().state)}))}updateStatus(e,t){if(this.status!==e){this.status=e,this.error=t,Un(`Client ${this.options.metadata.name} state changed to ${e}`);try{if(this.isConnected()){const e="plugin"===this.type?Ts.PLUGIN.STATUS:Ts.SERVICE.STATUS;this.publish(`${e}.${this.options.metadata.id}`,this.getStatus().state)}else Un("Skipping status update: Not connected to server")}catch(t){Un("Failed to update state:",t)}}}startMetricsInterval(){this.stopMetricsInterval(),this.metricsInterval=setInterval((()=>{try{const e=this.aggregateMetrics(),t=`${Ts.METRICS.UPDATE}.${this.type}.${this.options.metadata.id}`;this.publish(t,e),Un(`Published metrics for ${this.options.metadata.id}:`,e)}catch(e){Un(`Failed to publish metrics for ${this.options.metadata.id}:`,e)}}),Ms.METRICS)}stopMetricsInterval(){this.metricsInterval&&(clearInterval(this.metricsInterval),this.metricsInterval=void 0)}aggregateMetrics(){const e=this.getRPCConnectionManagers();Un(`Aggregating metrics from connection managers: ${e.length}`);const t={timestamp:Date.now(),startTime:Math.min(...e.map((e=>e.getMetrics().startTime))),requests:{total:0,active:0,errors:0,perSecond:0,avgResponseTime:0},messages:{published:0,received:0,errors:0},rpc:{total:0,active:0,errors:0},subscriptions:{active:0,messageHandlers:0,requestHandlers:0,rpcHandlers:0}};let r=0,s=0;for(const i of e){const e=i.getMetrics();t.requests.total+=e.requests.total,t.requests.active+=e.requests.active,t.requests.errors+=e.requests.errors;const n=e.requests.total;n>0&&(r+=n,s+=e.requests.avgResponseTime*n,t.requests.perSecond+=e.requests.perSecond),t.messages.published+=e.messages.published,t.messages.received+=e.messages.received,t.messages.errors+=e.messages.errors,t.rpc.total+=e.rpc.total,t.rpc.active+=e.rpc.active,t.rpc.errors+=e.rpc.errors,t.subscriptions.active+=e.subscriptions.active,t.subscriptions.messageHandlers+=e.subscriptions.messageHandlers,t.subscriptions.requestHandlers+=e.subscriptions.requestHandlers,t.subscriptions.rpcHandlers+=e.subscriptions.rpcHandlers}return r>0&&(t.requests.avgResponseTime=s/r),t.requests.perSecond=t.requests.perSecond/e.length,t}}class qn extends Dn{constructor(e){super("service",e)}async onStart(){console.log("Proxy started")}async onStop(){console.log("Proxy stopped")}}process.env.CAMERA_UI_RUNMODE,process.env.CAMERA_UI_RUNMODE,process.env.CAMERA_UI_RUNMODE;class Bn{subscriptions=[];additionalSubscriptions=[];addSubscriptions(...e){this.subscriptions.push(...e)}addAdditionalSubscriptions(...e){this.additionalSubscriptions.push(...e)}unsubscribe(){this.subscriptions.forEach((e=>e.unsubscribe()))}unsubscribeAdditional(){this.additionalSubscriptions.forEach((e=>e.unsubscribe()))}}function zn(e,t,r=!1){if(e===t)return!0;if((void 0===e||void 0===t||null===e||null===t)&&(e||t))return!1;const s=e?.constructor.name,i=t?.constructor.name;if(s!==i)return!1;if("Array"===s&&"Array"===i){if(e.length!==t.length)return!1;if(r){const s=[...t];return e.every((e=>{const t=s.findIndex((t=>zn(e,t,r)));return-1!==t&&(s.splice(t,1),!0)}))}{let s=!0;for(let i=0;i<e.length;i++)if(!zn(e[i],t[i],r)){s=!1;break}return s}}if("Object"===s&&"Object"===i){let s=!0;const i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(let n=0;n<i.length;n++)if(e[i[n]]&&t[i[n]]){if(e[i[n]]===t[i[n]])continue;if(!e[i[n]]||"Array"!==e[i[n]].constructor.name&&"Object"!==e[i[n]].constructor.name){if(e[i[n]]!==t[i[n]]){s=!1;break}}else if(s=zn(e[i[n]],t[i[n]],r),!s)break}else if(e[i[n]]&&!t[i[n]]||!e[i[n]]&&t[i[n]]){s=!1;break}return s}return e===t}function Gn(e){return JSON.parse(JSON.stringify(e))}var Vn,Hn,Wn;!function(e){e.MotionSensor="MotionSensor",e.MotionDetector="MotionDetector",e.AudioSensor="AudioSensor",e.ObjectSensor="ObjectSensor",e.ObjectDetector="ObjectDetector",e.Light="Light",e.Siren="Siren",e.Doorbell="Doorbell",e.Battery="Battery",e.PTZ="PTZ",e.PTZZoom="PTZZoom",e.PTZHome="PTZHome",e.PTZPresets="PTZPresets",e.Snapshot="Snapshot",e.StreamUrl="StreamUrl",e.Reboot="Reboot"}(Vn||(Vn={})),function(e){e.Opened="Opened",e.Closed="Closed",e.Jammed="Jammed",e.Unknown="Unknown"}(Hn||(Hn={})),function(e){e.MotionDetector="MotionDetector",e.ObjectDetector="ObjectDetector",e.AudioDetector="AudioDetector"}(Wn||(Wn={}));var Zn=r(672),Jn=r.n(Zn),Kn=function(e,t){return Kn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},Kn(e,t)};function Yn(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}Kn(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Qn(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))}function Xn(e,t){var r,s,i,n={label:0,sent:function(){if(1&i[0])throw i[1];return i[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(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(n=0)),n;)try{if(r=1,s&&(i=2&a[0]?s.return:a[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,a[1])).done)return i;switch(s=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return n.label++,{value:a[1],done:!1};case 5:n.label++,s=a[1],a=[0];continue;case 7:a=n.ops.pop(),n.trys.pop();continue;default:if(!(i=n.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){n=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){n.label=a[1];break}if(6===a[0]&&n.label<i[1]){n.label=i[1],i=a;break}if(i&&n.label<i[2]){n.label=i[2],n.ops.push(a);break}i[2]&&n.ops.pop(),n.trys.pop();continue}a=t.call(e,n)}catch(e){a=[6,e],s=0}finally{r=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}Object.create;function eo(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],s=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function to(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var s,i,n=r.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(e){i={error:e}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return o}function ro(e,t,r){if(r||2===arguments.length)for(var s,i=0,n=t.length;i<n;i++)!s&&i in t||(s||(s=Array.prototype.slice.call(t,0,i)),s[i]=t[i]);return e.concat(s||Array.prototype.slice.call(t))}function so(e){return this instanceof so?(this.v=e,this):new so(e)}function io(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s,i=r.apply(e,t||[]),n=[];return s=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",(function(e){return function(t){return Promise.resolve(t).then(e,u)}})),s[Symbol.asyncIterator]=function(){return this},s;function o(e,t){i[e]&&(s[e]=function(t){return new Promise((function(r,s){n.push([e,t,r,s])>1||a(e,t)}))},t&&(s[e]=t(s[e])))}function a(e,t){try{!function(e){e.value instanceof so?Promise.resolve(e.value.v).then(c,u):l(n[0][2],e)}(i[e](t))}catch(e){l(n[0][3],e)}}function c(e){a("next",e)}function u(e){a("throw",e)}function l(e,t){e(t),n.shift(),n.length&&a(n[0][0],n[0][1])}}function no(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=eo(e),t={},s("next"),s("throw"),s("return"),t[Symbol.asyncIterator]=function(){return this},t);function s(r){t[r]=e[r]&&function(t){return new Promise((function(s,i){(function(e,t,r,s){Promise.resolve(s).then((function(t){e({value:t,done:r})}),t)})(s,i,(t=e[r](t)).done,t.value)}))}}}Object.create;"function"==typeof SuppressedError&&SuppressedError;function oo(e){return"function"==typeof e}function ao(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var co=ao((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function uo(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var ho=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,r,s,i;if(!this.closed){this.closed=!0;var n=this._parentage;if(n)if(this._parentage=null,Array.isArray(n))try{for(var o=eo(n),a=o.next();!a.done;a=o.next()){a.value.remove(this)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else n.remove(this);var c=this.initialTeardown;if(oo(c))try{c()}catch(e){i=e instanceof co?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=eo(u),d=l.next();!d.done;d=l.next()){var p=d.value;try{fo(p)}catch(e){i=null!=i?i:[],e instanceof co?i=ro(ro([],to(i)),to(e.errors)):i.push(e)}}}catch(e){r={error:e}}finally{try{d&&!d.done&&(s=l.return)&&s.call(l)}finally{if(r)throw r.error}}}if(i)throw new co(i)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)fo(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&uo(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&uo(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}(),lo=ho.EMPTY;function po(e){return e instanceof ho||e&&"closed"in e&&oo(e.remove)&&oo(e.add)&&oo(e.unsubscribe)}function fo(e){oo(e)?e():e.unsubscribe()}var mo={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},go={setTimeout:function(e,t){for(var r=[],s=2;s<arguments.length;s++)r[s-2]=arguments[s];var i=go.delegate;return(null==i?void 0:i.setTimeout)?i.setTimeout.apply(i,ro([e,t],to(r))):setTimeout.apply(void 0,ro([e,t],to(r)))},clearTimeout:function(e){var t=go.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function yo(e){go.setTimeout((function(){var t=mo.onUnhandledError;if(!t)throw e;t(e)}))}function bo(){}var vo=_o("C",void 0,void 0);function _o(e,t,r){return{kind:e,value:t,error:r}}var wo=null;function So(e){if(mo.useDeprecatedSynchronousErrorHandling){var t=!wo;if(t&&(wo={errorThrown:!1,error:null}),e(),t){var r=wo,s=r.errorThrown,i=r.error;if(wo=null,s)throw i}}else e()}var Co=function(e){function t(t){var r=e.call(this)||this;return r.isStopped=!1,t?(r.destination=t,po(t)&&t.add(r)):r.destination=Ao,r}return Yn(t,e),t.create=function(e,t,r){return new To(e,t,r)},t.prototype.next=function(e){this.isStopped?Oo(function(e){return _o("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?Oo(_o("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?Oo(vo,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(ho),Eo=Function.prototype.bind;function xo(e,t){return Eo.call(e,t)}var ko=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){Ro(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){Ro(e)}else Ro(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){Ro(e)}},e}(),To=function(e){function t(t,r,s){var i,n,o=e.call(this)||this;oo(t)||!t?i={next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=s?s:void 0}:o&&mo.useDeprecatedNextContext?((n=Object.create(t)).unsubscribe=function(){return o.unsubscribe()},i={next:t.next&&xo(t.next,n),error:t.error&&xo(t.error,n),complete:t.complete&&xo(t.complete,n)}):i=t;return o.destination=new ko(i),o}return Yn(t,e),t}(Co);function Ro(e){var t;mo.useDeprecatedSynchronousErrorHandling?(t=e,mo.useDeprecatedSynchronousErrorHandling&&wo&&(wo.errorThrown=!0,wo.error=t)):yo(e)}function Oo(e,t){var r=mo.onStoppedNotification;r&&go.setTimeout((function(){return r(e,t)}))}var Ao={closed:!0,next:bo,error:function(e){throw e},complete:bo},Po="function"==typeof Symbol&&Symbol.observable||"@@observable";function Io(e){return e}function Mo(e){return 0===e.length?Io:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var No=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(e,t,r){var s,i=this,n=(s=e)&&s instanceof Co||function(e){return e&&oo(e.next)&&oo(e.error)&&oo(e.complete)}(s)&&po(s)?e:new To(e,t,r);return So((function(){var e=i,t=e.operator,r=e.source;n.add(t?t.call(n,r):r?i._subscribe(n):i._trySubscribe(n))})),n},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var r=this;return new(t=jo(t))((function(t,s){var i=new To({next:function(t){try{e(t)}catch(e){s(e),i.unsubscribe()}},error:s,complete:t});r.subscribe(i)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[Po]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Mo(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=jo(e))((function(e,r){var s;t.subscribe((function(e){return s=e}),(function(e){return r(e)}),(function(){return e(s)}))}))},e.create=function(t){return new e(t)},e}();function jo(e){var t;return null!==(t=null!=e?e:mo.Promise)&&void 0!==t?t:Promise}var Fo=ao((function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})),$o=function(e){function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return Yn(t,e),t.prototype.lift=function(e){var t=new Lo(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new Fo},t.prototype.next=function(e){var t=this;So((function(){var r,s;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var i=eo(t.currentObservers),n=i.next();!n.done;n=i.next()){n.value.next(e)}}catch(e){r={error:e}}finally{try{n&&!n.done&&(s=i.return)&&s.call(i)}finally{if(r)throw r.error}}}}))},t.prototype.error=function(e){var t=this;So((function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var r=t.observers;r.length;)r.shift().error(e)}}))},t.prototype.complete=function(){var e=this;So((function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}}))},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,r=this,s=r.hasError,i=r.isStopped,n=r.observers;return s||i?lo:(this.currentObservers=null,n.push(e),new ho((function(){t.currentObservers=null,uo(n,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,r=t.hasError,s=t.thrownError,i=t.isStopped;r?e.error(s):i&&e.complete()},t.prototype.asObservable=function(){var e=new No;return e.source=this,e},t.create=function(e,t){return new Lo(e,t)},t}(No),Lo=function(e){function t(t,r){var s=e.call(this)||this;return s.destination=t,s.source=r,s}return Yn(t,e),t.prototype.next=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===r||r.call(t,e)},t.prototype.error=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===r||r.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,r;return null!==(r=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==r?r:lo},t}($o),Uo=function(e){function t(t){var r=e.call(this)||this;return r._value=t,r}return Yn(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(t){var r=e.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},t.prototype.getValue=function(){var e=this,t=e.hasError,r=e.thrownError,s=e._value;if(t)throw r;return this._throwIfClosed(),s},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}($o),Do={now:function(){return(Do.delegate||Date).now()},delegate:void 0},qo=function(e){function t(t,r,s){void 0===t&&(t=1/0),void 0===r&&(r=1/0),void 0===s&&(s=Do);var i=e.call(this)||this;return i._bufferSize=t,i._windowTime=r,i._timestampProvider=s,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=r===1/0,i._bufferSize=Math.max(1,t),i._windowTime=Math.max(1,r),i}return Yn(t,e),t.prototype.next=function(t){var r=this,s=r.isStopped,i=r._buffer,n=r._infiniteTimeWindow,o=r._timestampProvider,a=r._windowTime;s||(i.push(t),!n&&i.push(o.now()+a)),this._trimBuffer(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){this._throwIfClosed(),this._trimBuffer();for(var t=this._innerSubscribe(e),r=this._infiniteTimeWindow,s=this._buffer.slice(),i=0;i<s.length&&!e.closed;i+=r?1:2)e.next(s[i]);return this._checkFinalizedStatuses(e),t},t.prototype._trimBuffer=function(){var e=this,t=e._bufferSize,r=e._timestampProvider,s=e._buffer,i=e._infiniteTimeWindow,n=(i?1:2)*t;if(t<1/0&&n<s.length&&s.splice(0,s.length-n),!i){for(var o=r.now(),a=0,c=1;c<s.length&&s[c]<=o;c+=2)a=c;a&&s.splice(0,a+1)}},t}($o);function Bo(e){return function(t){if(function(e){return oo(null==e?void 0:e.lift)}(t))return t.lift((function(t){try{return e(t,this)}catch(e){this.error(e)}}));throw new TypeError("Unable to lift unknown Observable type")}}function zo(e,t,r,s,i){return new Go(e,t,r,s,i)}var Go=function(e){function t(t,r,s,i,n,o){var a=e.call(this,t)||this;return a.onFinalize=n,a.shouldUnsubscribe=o,a._next=r?function(e){try{r(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=i?function(e){try{i(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=s?function(){try{s()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return Yn(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;e.prototype.unsubscribe.call(this),!r&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(Co);function Vo(){return Bo((function(e,t){var r,s=!1;e.subscribe(zo(t,(function(e){var i=r;r=e,s&&t.next([i,e]),s=!0})))}))}function Ho(e,t){return Bo((function(r,s){var i=0;r.subscribe(zo(s,(function(r){return e.call(t,r,i++)&&s.next(r)})))}))}function Wo(e,t){return Bo((function(r,s){var i=0;r.subscribe(zo(s,(function(r){s.next(e.call(t,r,i++))})))}))}var Zo="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function Jo(e){if(e instanceof No)return e;if(null!=e){if(function(e){return oo(e[Po])}(e))return n=e,new No((function(e){var t=n[Po]();if(oo(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(function(e){return e&&"number"==typeof e.length&&"function"!=typeof e}(e))return i=e,new No((function(e){for(var t=0;t<i.length&&!e.closed;t++)e.next(i[t]);e.complete()}));if(oo(null==(s=e)?void 0:s.then))return r=e,new No((function(e){r.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,yo)}));if(function(e){return Symbol.asyncIterator&&oo(null==e?void 0:e[Symbol.asyncIterator])}(e))return Ko(e);if(function(e){return oo(null==e?void 0:e[Zo])}(e))return t=e,new No((function(e){var r,s;try{for(var i=eo(t),n=i.next();!n.done;n=i.next()){var o=n.value;if(e.next(o),e.closed)return}}catch(e){r={error:e}}finally{try{n&&!n.done&&(s=i.return)&&s.call(i)}finally{if(r)throw r.error}}e.complete()}));if(function(e){return oo(null==e?void 0:e.getReader)}(e))return Ko(function(e){return io(this,arguments,(function(){var t,r,s;return Xn(this,(function(i){switch(i.label){case 0:t=e.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,so(t.read())];case 3:return r=i.sent(),s=r.value,r.done?[4,so(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,so(s)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}}))}))}(e))}var t,r,s,i,n;throw function(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}(e)}function Ko(e){return new No((function(t){(function(e,t){var r,s,i,n;return Qn(this,void 0,void 0,(function(){var o,a;return Xn(this,(function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),r=no(e),c.label=1;case 1:return[4,r.next()];case 2:if((s=c.sent()).done)return[3,4];if(o=s.value,t.next(o),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),i={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),s&&!s.done&&(n=r.return)?[4,n.call(r)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}}))}))})(e,t).catch((function(e){return t.error(e)}))}))}function Yo(e){void 0===e&&(e={});var t=e.connector,r=void 0===t?function(){return new $o}:t,s=e.resetOnError,i=void 0===s||s,n=e.resetOnComplete,o=void 0===n||n,a=e.resetOnRefCountZero,c=void 0===a||a;return function(e){var t,s,n,a=0,u=!1,l=!1,d=function(){null==s||s.unsubscribe(),s=void 0},p=function(){d(),t=n=void 0,u=l=!1},f=function(){var e=t;p(),null==e||e.unsubscribe()};return Bo((function(e,m){a++,l||u||d();var g=n=null!=n?n:r();m.add((function(){0!==--a||l||u||(s=Qo(f,c))})),g.subscribe(m),!t&&a>0&&(t=new To({next:function(e){return g.next(e)},error:function(e){l=!0,d(),s=Qo(p,i,e),g.error(e)},complete:function(){u=!0,d(),s=Qo(p,o),g.complete()}}),Jo(e).subscribe(t))}))(e)}}function Qo(e,t){for(var r=[],s=2;s<arguments.length;s++)r[s-2]=arguments[s];if(!0!==t){if(!1!==t){var i=new To({next:function(){i.unsubscribe(),e()}});return Jo(t.apply(void 0,ro([],to(r)))).subscribe(i)}}else e()}function Xo(e,t,r){return void 0===r&&(r=1/0),oo(t)?Xo((function(r,s){return Wo((function(e,i){return t(r,e,s,i)}))(Jo(e(r,s)))}),r):("number"==typeof t&&(r=t),Bo((function(t,s){return function(e,t,r,s,i,n,o,a){var c=[],u=0,l=0,d=!1,p=function(){!d||c.length||u||t.complete()},f=function(e){return u<s?m(e):c.push(e)},m=function(e){n&&t.next(e),u++;var a=!1;Jo(r(e,l++)).subscribe(zo(t,(function(e){null==i||i(e),n?f(e):t.next(e)}),(function(){a=!0}),void 0,(function(){if(a)try{u--;for(var e=function(){var e=c.shift();o?function(e,t,r,s,i){void 0===s&&(s=0),void 0===i&&(i=!1);var n=t.schedule((function(){r(),i?e.add(this.schedule(null,s)):this.unsubscribe()}),s);e.add(n)}(t,o,(function(){return m(e)})):m(e)};c.length&&u<s;)e();p()}catch(e){t.error(e)}})))};return e.subscribe(zo(t,f,(function(){d=!0,p()}))),function(){null==a||a()}}(t,s,e,r)})))}function ea(e,t){return e===t}const ta=e=>{if("person"===e)return"person";if("motion"===e)return"motion";if(new Set(["bird","cat","dog","horse","sheep","cow","elephant","bear","zebra","giraffe","teddy bear"]).has(e))return"animal";return new Set(["bicycle","car","motorcycle","airplane","bus","train","truck","boat"]).has(e)?"vehicle":"other"};function ra(e){return e.map((e=>({...e,label:ta(e.label)})))}class sa{cells=new Map;cellSize;constructor(e=100){this.cellSize=e}getCellsForBox(e,t=0){const r=Math.floor((e[0]-t)/this.cellSize),s=Math.floor((e[1]-t)/this.cellSize),i=Math.floor((e[2]+t)/this.cellSize),n=Math.floor((e[3]+t)/this.cellSize),o=[];for(let e=r;e<=i;e++)for(let t=s;t<=n;t++)o.push(`${e},${t}`);return o}insert(e){const t=e.boundingBox,r=this.getCellsForBox(t);for(const t of r)this.cells.has(t)||this.cells.set(t,[]),this.cells.get(t).push(e)}search(e,t=0){const r=this.getCellsForBox(e,t),s=new Set;for(const e of r){const t=this.cells.get(e)??[];for(const e of t)s.add(e)}return Array.from(s)}}function ia(e,t){const r=Math.max(e[0],t[0]),s=Math.max(e[1],t[1]),i=Math.min(e[2],t[2]),n=Math.min(e[3],t[3]);if(i<r||n<s)return 0;const o=(i-r)*(n-s);return o/((e[2]-e[0])*(e[3]-e[1])+(t[2]-t[0])*(t[3]-t[1])-o)}function na(e){return e[0]<e[2]&&e[1]<e[3]}function oa(e,t=.01,r=100){if(0===e.length)return[];const s=new sa(r),i=new Set,n=[],o=e.map((e=>({...e,id:e.id??Math.random().toString(36).slice(2,9)})));for(const e of o)s.insert(e);for(const e of o){if(i.has(e.id))continue;const o={...e};let c=o.confidence;const u=[o.boundingBox],l=Math.max(r,10),d=s.search(o.boundingBox,l);for(const e of d){if(e.id===o.id||i.has(e.id)||e.label!==o.label)continue;const s=ia(o.boundingBox,e.boundingBox),n=Math.abs(o.boundingBox[0]-e.boundingBox[0])<=r&&Math.abs(o.boundingBox[1]-e.boundingBox[1])<=r;(s>t||n)&&(u.push(e.boundingBox),i.add(e.id),c=Math.max(c,e.confidence))}if(u.length>1){const e=(a=u,[Math.max(0,Math.round(Math.min(...a.map((e=>e[0]))))),Math.max(0,Math.round(Math.min(...a.map((e=>e[1]))))),Math.min(1e3,Math.round(Math.max(...a.map((e=>e[2]))))),Math.min(1e3,Math.round(Math.max(...a.map((e=>e[3])))))]);na(e)&&(o.boundingBox=e,o.confidence=c)}na(o.boundingBox)&&n.push(o),i.add(o.id)}var a;return n}function aa(e,t){return[[e[0],e[1]],[e[2],e[1]],[e[2],e[3]],[e[0],e[3]]].every((e=>ua(e,t)))}function ca(e,t){const r=[[e[0],e[1]],[e[2],e[1]],[e[2],e[3]],[e[0],e[3]]];return!la(e,t)&&r.every((e=>!ua(e,t)))}function ua(e,t){const[r,s]=e;let i=!1;for(let e=0;e<t.length;e++){const n=(e+1)%t.length,[o,a]=t[e],[c,u]=t[n];if(r>=Math.min(o,c)&&r<=Math.max(o,c)&&s>=Math.min(a,u)&&s<=Math.max(a,u))if(Math.abs(o-c)<1e-6){if(Math.abs(r-o)<1e-6)return!0}else{const e=(u-a)/(c-o),t=e*r+(a-e*o);if(Math.abs(s-t)<1e-6)return!0}a>s!=u>s&&r<(c-o)*(s-a)/(u-a)+o&&(i=!i)}return i}function ha(e,t,r,s){const i=(s[1]-r[1])*(t[0]-e[0])-(s[0]-r[0])*(t[1]-e[1]);if(0===i)return!1;const n=((s[0]-r[0])*(e[1]-r[1])-(s[1]-r[1])*(e[0]-r[0]))/i,o=((t[0]-e[0])*(e[1]-r[1])-(t[1]-e[1])*(e[0]-r[0]))/i;return n>=0&&n<=1&&o>=0&&o<=1}function la(e,t){const r=[[e[0],e[1]],[e[2],e[1]],[e[2],e[3]],[e[0],e[3]],[e[0],e[1]]];if(r.some((e=>ua(e,t))))return!0;if(t.some((t=>t[0]>=e[0]&&t[0]<=e[2]&&t[1]>=e[1]&&t[1]<=e[3])))return!0;for(let e=0;e<r.length-1;e++)for(let s=0;s<t.length-1;s++)if(ha(r[e],r[e+1],t[s],t[s+1]))return!0;return!1}const da=(e,t)=>{const{origWidth:r,origHeight:s}=t,i=e.points.map((([e,t])=>[e*r/100,t*s/100]));var n,o;return i.length>0&&(n=i[0],o=i[i.length-1],n[0]!==o[0]||n[1]!==o[1])&&i.push(i[0]),{...e,points:i}},pa=(e,t,r)=>{if(0===t.length)return[];if(0===e.length)return[];const s=new Set;for(const e of t)e.classes.length>0&&e.classes.forEach((e=>s.add(e)));return e.filter((e=>{if(e.confidence<r.object.confidence)return!1;if(!s.has(e.label))return!1;const i=(e=>{const{origWidth:t,origHeight:r,inputWidth:s,inputHeight:i}=e;let[n,o,a,c]=e.boundingBox;return n=n*t/s,o=o*r/i,a=a*t/s,c=c*r/i,n=Math.max(0,Math.min(n,t)),o=Math.max(0,Math.min(o,r)),a=Math.max(0,Math.min(a,t)),c=Math.max(0,Math.min(c,r)),{...e,boundingBox:[n,o,a,c]}})(e);for(const e of t){if(!e.isPrivacyMask)continue;const t=da(e,i);if(aa(i.boundingBox,t.points))return!1}let n=!1,o=!1;for(const r of t){if(r.isPrivacyMask)continue;if(!r.classes.includes(e.label))continue;const t=da(r,i),s=la(i.boundingBox,t.points),a=aa(i.boundingBox,t.points);if("include"===r.filter){if(n=!0,"contain"===r.type&&a||"intersect"===r.type&&(s||a)){o=!0;break}}else if("contain"===r.type){if(!ca(i.boundingBox,t.points))return!1}else if(s||a)return!1}return!n||o}))};class fa extends Bn{logger;snapshotCache;cameraSubject;cameraState=new Uo(!1);frameWorkerState=new Uo(!1);lightState=new Uo(this.#e({state:!1},!0));motionState=new Uo(this.#t({detections:[],state:!1},!0));audioState=new Uo(this.#r({state:!1,db:0},!0));objectState=new Uo(this.#s({detections:[]},!0));doorbellState=new Uo(this.#i({state:!1},!0));sirenState=new Uo(this.#n({state:!1,level:0},!0));batteryState=new Uo(this.#o({level:100,charging:!1,lowBattery:!1},!0));capabilities=new Uo([]);onConnected=this.#a(this.cameraState);onFrameWorkerConnected=this.#a(this.frameWorkerState);onLightSwitched=this.#a(this.lightState);onMotionDetected=this.#a(this.motionState);onAudioDetected=this.#a(this.audioState);onObjectDetected=this.#a(this.objectState);onDoorbellPressed=this.#a(this.doorbellState);onSirenDetected=this.#a(this.sirenState);onBatteryChanged=this.#a(this.batteryState);get cameraObject(){return Gn(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 frameWorkerConnected(){return this.frameWorkerState.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 Gn(this.cameraSubject.getValue().info)}get isCloud(){return this.cameraSubject.getValue().isCloud}get hasLight(){return this.hasCapability(Vn.Light)}get hasSiren(){return this.hasCapability(Vn.Siren)}get hasDoorbell(){return this.hasCapability(Vn.Doorbell)}get hasBattery(){return this.hasCapability(Vn.Battery)}get hasAudioDetector(){return this.hasCapability(Vn.AudioSensor)}get hasMotionDetector(){return this.hasCapability(Vn.MotionSensor)||this.hasCapability(Vn.MotionDetector)}get hasObjectDetector(){return this.hasCapability(Vn.ObjectSensor)||this.hasCapability(Vn.ObjectDetector)}get hasPtz(){return this.hasCapability(Vn.PTZ)}get snapshotTTL(){return this.cameraSubject.getValue().snapshotTTL}get detectionZones(){return Gn(this.cameraSubject.getValue().detectionZones)}get detectionSettings(){return Gn(this.cameraSubject.getValue().detectionSettings)}get frameWorkerSettings(){return Gn(this.cameraSubject.getValue().frameWorkerSettings)}get streamSource(){return this.highResolutionSource??this.midResolutionSource??this.lowResolutionSource}get snapshotSource(){return this.sources.find((e=>"snapshot"==e.role))??this.sources.find((e=>e.useForSnapshot))}get highResolutionSource(){return this.sources.find((e=>"high-resolution"===e.role))}get midResolutionSource(){return this.sources.find((e=>"mid-resolution"===e.role))}get lowResolutionSource(){return this.sources.find((e=>"low-resolution"===e.role))}get interfaces(){return this.cameraInterfaces}constructor(e,t){super(),this.logger=t,this.cameraSubject=new Uo(e),this.snapshotCache=new(Jn())({max:100,ttl:1e3*this.snapshotTTL}),"native"===e.pluginId&&this.cameraState.next(!0)}getCapabilities(){return Gn(this.capabilities.getValue().map((e=>e.capabilities)).flat())}hasCapability(e){return this.getCapabilities().some((t=>t===e))}getValue(e){switch(e){case"light":return Gn(this.lightState.getValue());case"motion":return Gn(this.motionState.getValue());case"audio":return Gn(this.audioState.getValue());case"object":return Gn(this.objectState.getValue());case"doorbell":return Gn(this.doorbellState.getValue());case"siren":return Gn(this.sirenState.getValue());case"battery":return Gn(this.batteryState.getValue());default:throw new Error(`Unknown state: ${e}`)}}onStateChange(e){return this[`${e}State`].pipe(Vo(),Ho((([t,r])=>this.stateChanged(t,r,e))),Wo((([e,t])=>({oldState:e,newState:t}))),Yo({connector:()=>new qo(1)}))}onPropertyChange(e){return this.cameraSubject.pipe(Vo(),Xo((([t,r])=>(Array.isArray(e)?e:[e]).map((e=>({property:e,oldData:t[e],newData:r[e]}))))),Ho((({oldData:e,newData:t})=>!zn(e,t,!0))),Yo({connector:()=>new qo(1)}))}onCapabilitiesChange(){return this.capabilities.pipe(Vo(),Ho((([e,t])=>!zn(e,t,!0))),Wo((([e,t])=>({oldCapabilities:e.map((e=>e.capabilities)).flat(),newCapabilities:t.map((e=>e.capabilities)).flat()}))),Yo({connector:()=>new qo(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(),this.frameWorkerState.complete(),this.capabilities.complete(),this.snapshotCache.clear()}updateCamera(e){e.snapshotTTL!==this.snapshotTTL&&this.snapshotCache.clear(),this.cameraSubject.next(e)}updateCameraState(e){this.cameraState.next(e)}updateFrameWorkerState(e){this.frameWorkerState.next(e)}updateCapabilities(e){this.capabilities.next(e)}updateStateInternal(e,t,r,s){let i,n=!1;if(r)n=!0,i=t;else{const r=this.checkStateInternal(e,t,s);n=r.changed,i=r.event}if(n)switch(e){case"light":this.lightState.next(this.#e(i));break;case"motion":this.motionState.next(this.#t(i));break;case"audio":this.audioState.next(this.#r(i));break;case"object":this.objectState.next(this.#s(i));break;case"doorbell":this.doorbellState.next(this.#i(i));break;case"siren":this.sirenState.next(this.#n(i));break;case"battery":this.batteryState.next(this.#o(i))}}checkStateInternal(e,t,r){let s,i=!1;switch(e){case"audio":const n=t;s=this.#r(n),i=this.stateChanged(this.getValue("audio"),s,"audio");break;case"light":const o=t;s=this.#e(o),i=this.stateChanged(this.getValue("light"),s,"light");break;case"motion":const a=t;if(a.state||(a.detections=[]),!r&&a.detections){const e=a.detections.length>0;a.detections=ra(a.detections),a.detections=oa(a.detections),a.detections=pa(a.detections,this.detectionZones,this.detectionSettings),e&&0===a.detections.length&&(a.state=!1)}s=this.#t(a),i=this.stateChanged(this.getValue("motion"),s,"motion");break;case"object":const c=t;r||(c.detections=ra(c.detections),c.detections=oa(c.detections),c.detections=pa(c.detections,this.detectionZones,this.detectionSettings)),s=this.#s(c),i=this.stateChanged(this.getValue("object"),s,"object");break;case"doorbell":const u=t;s=this.#i(u),i=this.stateChanged(this.getValue("doorbell"),s,"doorbell");break;case"siren":const l=t;s=this.#n(l),i=this.stateChanged(this.getValue("siren"),s,"siren");break;case"battery":const d=t;s=this.#o(d),i=this.stateChanged(this.getValue("battery"),s,"battery");break;default:throw new Error(`Unknown state: ${e}`)}return{changed:i,event:s}}stateChanged(e,t,r){if(void 0===e||void 0===t||void 0===r)return!1;if("audio"===r&&!this.hasAudioDetector)return!1;if("motion"===r&&!this.hasMotionDetector)return!1;if("object"===r&&!this.hasObjectDetector)return!1;if("siren"===r&&!this.hasSiren)return!1;if("battery"===r&&!this.hasBattery)return!1;if("doorbell"===r&&!this.hasDoorbell)return!1;if("light"===r&&!this.hasLight)return!1;return!zn(this.#c(e),this.#c(t),!0)}#r(e,t=!1){let r,s;if(t||(r=this.getValue("audio"),r&&r.lastEvent&&delete r.lastEvent),this.#u(e))s=e;else{const t={...e,timestamp:Date.now()};s={...t,db:t.db??r?.db??0,lastEvent:r}}return s}#t(e,t=!1){let r,s;if(t||(r=this.getValue("motion"),r?.lastEvent&&delete r.lastEvent),this.#u(e))s=e;else{s={...{...e,timestamp:Date.now()},lastEvent:r}}return s}#s(e,t=!1){let r,s;if(t||(r=this.getValue("object"),r&&r.lastEvent&&delete r.lastEvent),this.#u(e))s=e;else{s={...{...e,timestamp:Date.now()},lastEvent:r}}return s}#i(e,t=!1){let r,s;if(t||(r=this.getValue("doorbell"),r&&r.lastEvent&&delete r.lastEvent),this.#u(e))s=e;else{s={...{...e,timestamp:Date.now()},lastEvent:r}}return s}#e(e,t=!1){let r,s;if(t||(r=this.getValue("light"),r&&r.lastEvent&&delete r.lastEvent),this.#u(e))s=e;else{s={...{...e,timestamp:Date.now()},lastEvent:r}}return s}#n(e,t=!1){let r,s;if(t||(r=this.getValue("siren"),r&&r.lastEvent&&delete r.lastEvent),this.#u(e))s=e;else{const t={...e,timestamp:Date.now()};s={...t,level:t.level??r?.level??0,lastEvent:r}}return s}#o(e,t=!1){let r,s;if(t||(r=this.getValue("battery"),r&&r.lastEvent&&delete r.lastEvent),this.#u(e))s=e;else{s={...{...e,timestamp:Date.now()},charging:e.charging??r?.charging??!1,lowBattery:e.lowBattery??r?.lowBattery??!1,lastEvent:r}}return s}#c(e){const t=Gn(e);return"timestamp"in t&&delete t.timestamp,"lastEvent"in t&&delete t.lastEvent,t}#u(e){return"timestamp"in e}#a(e){return e.pipe((void 0===r&&(r=Io),t=null!=t?t:ea,Bo((function(e,s){var i,n=!0;e.subscribe(zo(s,(function(e){var o=r(e);!n&&t(i,o)||(n=!1,i=o,s.next(e))})))}))),Yo({connector:()=>new qo(1)}));var t,r}}class ma{static coreManagerNamespaces(){return{coreManagerSubject:"coreManager.subscriber",coreManagerRpc:"coreManager.rpc"}}static deviceManagerNamespaces(){return{deviceManagerSubject:"deviceManager.subscriber",deviceManagerRpc:"deviceManager.rpc"}}static frameWorkerNamespaces(e){return{frameWorkerChildRpc:`camera.${e}.frameWorker.child.rpc`,frameWorkerChild:`camera.${e}.frameWorker.child`}}static pluginNamespaces(e){return{pluginDeviceManagerSubject:`plugin.${e}.deviceManager.subscriber`,pluginChildRpc:`plugin.${e}.child.rpc`,pluginChild:`plugin.${e}.child`,pluginStorageRpc:`plugin.${e}.storage.rpc`}}static cameraNamespaces(e){return{cameraSubject:`camera.${e}.subscriber`,cameraMotionFrameSubject:`camera.${e}.motionFrame.subscriber`,cameraControllerRpc:`camera.${e}.controller.rpc`}}static pluginCameraNamespaces(e,t){return{cameraInterfacesRpc:`plugin.${e}.camera.${t}.cameraInterfaces.rpc`,cameraStorageRpc:`plugin.${e}.camera.${t}.cameraStorage.rpc`}}}var ga=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o},ya=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class ba{interfaces;#h;#l;#d;#p;#f=[];constructor(e,t,r,s){this.#h=e,this.#l=t,this.#d=r,this.#p=s}async streamUrl(e){const t=this.#l.getValue().find((e=>e.capabilities.some((e=>e===Vn.StreamUrl))));if(!t)throw new Error("No capability found for streamUrl");if(this.interfaces&&"streamUrl"in this.interfaces)return this.interfaces.streamUrl(e);return(await this.#m(t.pluginId)).streamUrl(e)}async snapshot(e,t){const r=this.#l.getValue().find((e=>e.capabilities.some((e=>e===Vn.Snapshot))));if(!r)throw new Error("No capability found for snapshot");if(this.interfaces&&"snapshot"in this.interfaces)return this.interfaces.snapshot(e,t);return(await this.#m(r.pluginId)).snapshot(e,t)}async ptzCommand(e){const t=this.#l.getValue().find((e=>e.capabilities.some((e=>e===Vn.PTZ))));if(!t)throw new Error("No capability found for PTZ");if(this.interfaces&&"ptzCommand"in this.interfaces)return this.interfaces.ptzCommand(e);return(await this.#m(t.pluginId)).ptzCommand(e)}async disconnect(){await Promise.allSettled(this.#f.map((e=>e.connection.disconnect()))),this.#f=[]}async#m(e){if(e===this.#p)throw new Error("Can not create camera proxy for the same plugin");const t=ma.pluginCameraNamespaces(e,this.#d).cameraInterfacesRpc,r=await this.#h.createRPCConnection(t);return this.#f.some((e=>e.namespace===t))||this.#f.push({namespace:t,connection:r}),r.createProxy()}}ga([An({public:!0}),ya("design:type",Function),ya("design:paramtypes",[String]),ya("design:returntype",Promise)],ba.prototype,"streamUrl",null),ga([An({public:!0}),ya("design:type",Function),ya("design:paramtypes",[String,Boolean]),ya("design:returntype",Promise)],ba.prototype,"snapshot",null),ga([An({public:!0}),ya("design:type",Function),ya("design:paramtypes",[Object]),ya("design:returntype",Promise)],ba.prototype,"ptzCommand",null);const va={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let _a;const wa=new Uint8Array(16);const Sa=[];for(let e=0;e<256;++e)Sa.push((e+256).toString(16).slice(1));function Ca(e,t=0){return(Sa[e[t+0]]+Sa[e[t+1]]+Sa[e[t+2]]+Sa[e[t+3]]+"-"+Sa[e[t+4]]+Sa[e[t+5]]+"-"+Sa[e[t+6]]+Sa[e[t+7]]+"-"+Sa[e[t+8]]+Sa[e[t+9]]+"-"+Sa[e[t+10]]+Sa[e[t+11]]+Sa[e[t+12]]+Sa[e[t+13]]+Sa[e[t+14]]+Sa[e[t+15]]).toLowerCase()}const Ea=function(e,t,r){if(va.randomUUID&&!t&&!e)return va.randomUUID();const s=(e=e||{}).random??e.rng?.()??function(){if(!_a){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");_a=crypto.getRandomValues.bind(crypto)}return _a(wa)}();if(s.length<16)throw new Error("Random bytes length must be >= 16");if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){if((r=r||0)<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=s[e];return t}return Ca(s)};var xa,ka;!function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),s={};for(const e of r)s[e]=t[e];return e.objectValues(s)},e.objectValues=t=>e.objectKeys(t).map((function(e){return t[e]})),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(xa||(xa={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(ka||(ka={}));const Ta=xa.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ra=e=>{switch(typeof e){case"undefined":return Ta.undefined;case"string":return Ta.string;case"number":return isNaN(e)?Ta.nan:Ta.number;case"boolean":return Ta.boolean;case"function":return Ta.function;case"bigint":return Ta.bigint;case"symbol":return Ta.symbol;case"object":return Array.isArray(e)?Ta.array:null===e?Ta.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?Ta.promise:"undefined"!=typeof Map&&e instanceof Map?Ta.map:"undefined"!=typeof Set&&e instanceof Set?Ta.set:"undefined"!=typeof Date&&e instanceof Date?Ta.date:Ta.object;default:return Ta.unknown}},Oa=xa.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Aa extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},s=e=>{for(const i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(s);else if("invalid_return_type"===i.code)s(i.returnTypeError);else if("invalid_arguments"===i.code)s(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,s=0;for(;s<i.path.length;){const r=i.path[s];s===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):e[r]=e[r]||{_errors:[]},e=e[r],s++}}};return s(this),r}static assert(e){if(!(e instanceof Aa))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,xa.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Aa.create=e=>new Aa(e);const Pa=(e,t)=>{let r;switch(e.code){case Oa.invalid_type:r=e.received===Ta.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Oa.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,xa.jsonStringifyReplacer)}`;break;case Oa.unrecognized_keys:r=`Unrecognized key(s) in object: ${xa.joinValues(e.keys,", ")}`;break;case Oa.invalid_union:r="Invalid input";break;case Oa.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${xa.joinValues(e.options)}`;break;case Oa.invalid_enum_value:r=`Invalid enum value. Expected ${xa.joinValues(e.options)}, received '${e.received}'`;break;case Oa.invalid_arguments:r="Invalid function arguments";break;case Oa.invalid_return_type:r="Invalid function return type";break;case Oa.invalid_date:r="Invalid date";break;case Oa.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:xa.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Oa.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case Oa.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case Oa.custom:r="Invalid input";break;case Oa.invalid_intersection_types:r="Intersection results could not be merged";break;case Oa.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case Oa.not_finite:r="Number must be finite";break;default:r=t.defaultError,xa.assertNever(e)}return{message:r}};let Ia=Pa;function Ma(){return Ia}const Na=e=>{const{data:t,path:r,errorMaps:s,issueData:i}=e,n=[...r,...i.path||[]],o={...i,path:n};if(void 0!==i.message)return{...i,path:n,message:i.message};let a="";const c=s.filter((e=>!!e)).slice().reverse();for(const e of c)a=e(o,{data:t,defaultError:a}).message;return{...i,path:n,message:a}};function ja(e,t){const r=Ma(),s=Na({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Pa?void 0:Pa].filter((e=>!!e))});e.common.issues.push(s)}class Fa{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if("aborted"===s.status)return $a;"dirty"===s.status&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,s=await e.value;r.push({key:t,value:s})}return Fa.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:t,value:i}=s;if("aborted"===t.status)return $a;if("aborted"===i.status)return $a;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"===t.value||void 0===i.value&&!s.alwaysSet||(r[t.value]=i.value)}return{status:e.value,value:r}}}const $a=Object.freeze({status:"aborted"}),La=e=>({status:"dirty",value:e}),Ua=e=>({status:"valid",value:e}),Da=e=>"aborted"===e.status,qa=e=>"dirty"===e.status,Ba=e=>"valid"===e.status,za=e=>"undefined"!=typeof Promise&&e instanceof Promise;function Ga(e,t,r,s){if("a"===r&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?s:"a"===r?s.call(e):s?s.value:t.get(e)}function Va(e,t,r,s,i){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?i.call(e,r):i?i.value=r:t.set(e,r),r}var Ha,Wa,Za;"function"==typeof SuppressedError&&SuppressedError,function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(Ha||(Ha={}));class Ja{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ka=(e,t)=>{if(Ba(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Aa(e.common.issues);return this._error=t,this._error}}};function Ya(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:s,description:i}=e;if(t&&(r||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:i};return{errorMap:(t,i)=>{var n,o;const{message:a}=e;return"invalid_enum_value"===t.code?{message:null!=a?a:i.defaultError}:void 0===i.data?{message:null!==(n=null!=a?a:s)&&void 0!==n?n:i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:null!==(o=null!=a?a:r)&&void 0!==o?o:i.defaultError}},description:i}}class Qa{get description(){return this._def.description}_getType(e){return Ra(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ra(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Fa,ctx:{common:e.parent.common,data:e.data,parsedType:Ra(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(za(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const s={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ra(e)},i=this._parseSync({data:e,path:s.path,parent:s});return Ka(s,i)}"~validate"(e){var t,r;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ra(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:s});return Ba(t)?{value:t.value}:{issues:s.common.issues}}catch(e){(null===(r=null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.toLowerCase())||void 0===r?void 0:r.includes("encountered"))&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:s}).then((e=>Ba(e)?{value:e.value}:{issues:s.common.issues}))}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ra(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(za(s)?s:Promise.resolve(s));return Ka(r,i)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,s)=>{const i=e(t),n=()=>s.addIssue({code:Oa.custom,...r(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then((e=>!!e||(n(),!1))):!!i||(n(),!1)}))}refinement(e,t){return this._refinement(((r,s)=>!!e(r)||(s.addIssue("function"==typeof t?t(r,s):t),!1)))}_refinement(e){return new Jc({schema:this,typeName:ou.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Kc.create(this,this._def)}nullable(){return Yc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Mc.create(this)}promise(){return Zc.create(this,this._def)}or(e){return Fc.create([this,e],this._def)}and(e){return Lc.create(this,e,this._def)}transform(e){return new Jc({...Ya(this._def),schema:this,typeName:ou.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Qc({...Ya(this._def),innerType:this,defaultValue:t,typeName:ou.ZodDefault})}brand(){return new tu({typeName:ou.ZodBranded,type:this,...Ya(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Xc({...Ya(this._def),innerType:this,catchValue:t,typeName:ou.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return ru.create(this,e)}readonly(){return su.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Xa=/^c[^\s-]{8,}$/i,ec=/^[0-9a-z]+$/,tc=/^[0-9A-HJKMNP-TV-Z]{26}$/i,rc=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,sc=/^[a-z0-9_-]{21}$/i,ic=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,nc=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,oc=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let ac;const cc=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,uc=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,hc=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,lc=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,dc=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pc=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,fc="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",mc=new RegExp(`^${fc}$`);function gc(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),t}function yc(e){let t=`${fc}T${gc(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function bc(e,t){if(!ic.test(e))return!1;try{const[r]=e.split("."),s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(s));return"object"==typeof i&&null!==i&&(!(!i.typ||!i.alg)&&(!t||i.alg===t))}catch(e){return!1}}function vc(e,t){return!("v4"!==t&&t||!uc.test(e))||!("v6"!==t&&t||!lc.test(e))}class _c extends Qa{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==Ta.string){const t=this._getOrReturnCtx(e);return ja(t,{code:Oa.invalid_type,expected:Ta.string,received:t.parsedType}),$a}const t=new Fa;let r;for(const n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),ja(r,{code:Oa.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("max"===n.kind)e.data.length>n.value&&(r=this._getOrReturnCtx(e,r),ja(r,{code:Oa.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("length"===n.kind){const s=e.data.length>n.value,i=e.data.length<n.value;(s||i)&&(r=this._getOrReturnCtx(e,r),s?ja(r,{code:Oa.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):i&&ja(r,{code:Oa.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)oc.test(e.data)||(r=this._getOrReturnCtx(e,r),ja(r,{validation:"email",code:Oa.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.kind)ac||(ac=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ac.test(e.data)||(r=this._getOrReturnCtx(e,r),ja(r,{validation:"emoji",code:Oa.invalid_string,message:n.message}),t.dirty());else if("uuid"===n.kind)rc.test(e.data)||(r=this._getOrReturnCtx(e,r),ja(r,{validation:"uuid",code:Oa.invalid_string,message:n.message}),t.dirty());else if("nanoid"===n.kind)sc.test(e.data)||(r=this._getOrReturnCtx(e,r),ja(r,{validation:"nanoid",code:Oa.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)Xa.test(e.data)||(r=this._getOrReturnCtx(e,r),ja(r,{validation:"cuid",code:Oa.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)ec.test(e.data)||(r=this._getOrReturnCtx(e,r),ja(r,{validation:"cuid2",code:Oa.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)tc.test(e.data)||(r=this._getOrReturnCtx(e,r),ja(r,{validation:"ulid",code:Oa.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch(s){r=this._getOrReturnCtx(e,r),ja(r,{validation:"url",code:Oa.invalid_string,message:n.message}),t.dirty()}else if("regex"===n.kind){n.regex.lastIndex=0;n.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),ja(r,{validation:"regex",code:Oa.invalid_string,message:n.message}),t.dirty())}else if("trim"===n.kind)e.data=e.data.trim();else if("includes"===n.kind)e.data.includes(n.value,n.position)||(r=this._getOrReturnCtx(e,r),ja(r,{code:Oa.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),t.dirty());else if("toLowerCase"===n.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===n.kind)e.data=e.data.toUpperCase();else if("startsWith"===n.kind)e.data.startsWith(n.value)||(r=this._getOrReturnCtx(e,r),ja(r,{code:Oa.invalid_string,validation:{startsWith:n.value},message:n.message}),t.dirty());else if("endsWith"===n.kind)e.data.endsWith(n.value)||(r=this._getOrReturnCtx(e,r),ja(r,{code:Oa.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty());else if("datetime"===n.kind){yc(n).test(e.data)||(r=this._getOrReturnCtx(e,r),ja(r,{code:Oa.invalid_string,validation:"datetime",message:n.message}),t.dirty())}else if("date"===n.kind){mc.test(e.data)||(r=this._getOrReturnCtx(e,r),ja(r,{code:Oa.invalid_string,validation:"date",message:n.message}),t.dirty())}else if("time"===n.kind){new RegExp(`^${gc(n)}$`).test(e.data)||(r=this._getOrReturnCtx(e,r),ja(r,{code:Oa.invalid_string,validation:"time",message:n.message}),t.dirty())}else"duration"===n.kind?nc.test(e.data)||(r=this._getOrReturnCtx(e,r),ja(r,{validation:"duration",code:Oa.invalid_string,message:n.message}),t.dirty()):"ip"===n.kind?(s=e.data,("v4"!==(i=n.version)&&i||!cc.test(s))&&("v6"!==i&&i||!hc.test(s))&&(r=this._getOrReturnCtx(e,r),ja(r,{validation:"ip",code:Oa.invalid_string,message:n.message}),t.dirty())):"jwt"===n.kind?bc(e.data,n.alg)||(r=this._getOrReturnCtx(e,r),ja(r,{validation:"jwt",code:Oa.invalid_string,message:n.message}),t.dirty()):"cidr"===n.kind?vc(e.data,n.version)||(r=this._getOrReturnCtx(e,r),ja(r,{validation:"cidr",code:Oa.invalid_string,message:n.message}),t.dirty()):"base64"===n.kind?dc.test(e.data)||(r=this._getOrReturnCtx(e,r),ja(r,{validation:"base64",code:Oa.invalid_string,message:n.message}),t.dirty()):"base64url"===n.kind?pc.test(e.data)||(r=this._getOrReturnCtx(e,r),ja(r,{validation:"base64url",code:Oa.invalid_string,message:n.message}),t.dirty()):xa.assertNever(n);var s,i;return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement((t=>e.test(t)),{validation:t,code:Oa.invalid_string,...Ha.errToObj(r)})}_addCheck(e){return new _c({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Ha.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Ha.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Ha.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Ha.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Ha.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Ha.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Ha.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Ha.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Ha.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Ha.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Ha.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Ha.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Ha.errToObj(e)})}datetime(e){var t,r;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(r=null==e?void 0:e.local)&&void 0!==r&&r,...Ha.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...Ha.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...Ha.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Ha.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...Ha.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Ha.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Ha.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Ha.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Ha.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Ha.errToObj(t)})}nonempty(e){return this.min(1,Ha.errToObj(e))}trim(){return new _c({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new _c({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new _c({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function wc(e,t){const r=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,i=r>s?r:s;return parseInt(e.toFixed(i).replace(".",""))%parseInt(t.toFixed(i).replace(".",""))/Math.pow(10,i)}_c.create=e=>{var t;return new _c({checks:[],typeName:ou.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...Ya(e)})};class Sc extends Qa{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==Ta.number){const t=this._getOrReturnCtx(e);return ja(t,{code:Oa.invalid_type,expected:Ta.number,received:t.parsedType}),$a}let t;const r=new Fa;for(const s of this._def.checks)if("int"===s.kind)xa.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),ja(t,{code:Oa.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty());else if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),ja(t,{code:Oa.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),ja(t,{code:Oa.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==wc(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),ja(t,{code:Oa.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),ja(t,{code:Oa.not_finite,message:s.message}),r.dirty()):xa.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Ha.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Ha.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Ha.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Ha.toString(t))}setLimit(e,t,r,s){return new Sc({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Ha.toString(s)}]})}_addCheck(e){return new Sc({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Ha.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ha.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ha.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ha.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ha.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Ha.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Ha.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ha.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ha.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&xa.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Sc.create=e=>new Sc({checks:[],typeName:ou.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...Ya(e)});class Cc extends Qa{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch(t){return this._getInvalidInput(e)}if(this._getType(e)!==Ta.bigint)return this._getInvalidInput(e);let t;const r=new Fa;for(const s of this._def.checks)if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),ja(t,{code:Oa.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),ja(t,{code:Oa.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),ja(t,{code:Oa.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):xa.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return ja(t,{code:Oa.invalid_type,expected:Ta.bigint,received:t.parsedType}),$a}gte(e,t){return this.setLimit("min",e,!0,Ha.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Ha.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Ha.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Ha.toString(t))}setLimit(e,t,r,s){return new Cc({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Ha.toString(s)}]})}_addCheck(e){return new Cc({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ha.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ha.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ha.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ha.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Ha.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Cc.create=e=>{var t;return new Cc({checks:[],typeName:ou.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...Ya(e)})};class Ec extends Qa{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==Ta.boolean){const t=this._getOrReturnCtx(e);return ja(t,{code:Oa.invalid_type,expected:Ta.boolean,received:t.parsedType}),$a}return Ua(e.data)}}Ec.create=e=>new Ec({typeName:ou.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...Ya(e)});class xc extends Qa{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==Ta.date){const t=this._getOrReturnCtx(e);return ja(t,{code:Oa.invalid_type,expected:Ta.date,received:t.parsedType}),$a}if(isNaN(e.data.getTime())){return ja(this._getOrReturnCtx(e),{code:Oa.invalid_date}),$a}const t=new Fa;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),ja(r,{code:Oa.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(r=this._getOrReturnCtx(e,r),ja(r,{code:Oa.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):xa.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new xc({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Ha.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Ha.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}xc.create=e=>new xc({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:ou.ZodDate,...Ya(e)});class kc extends Qa{_parse(e){if(this._getType(e)!==Ta.symbol){const t=this._getOrReturnCtx(e);return ja(t,{code:Oa.invalid_type,expected:Ta.symbol,received:t.parsedType}),$a}return Ua(e.data)}}kc.create=e=>new kc({typeName:ou.ZodSymbol,...Ya(e)});class Tc extends Qa{_parse(e){if(this._getType(e)!==Ta.undefined){const t=this._getOrReturnCtx(e);return ja(t,{code:Oa.invalid_type,expected:Ta.undefined,received:t.parsedType}),$a}return Ua(e.data)}}Tc.create=e=>new Tc({typeName:ou.ZodUndefined,...Ya(e)});class Rc extends Qa{_parse(e){if(this._getType(e)!==Ta.null){const t=this._getOrReturnCtx(e);return ja(t,{code:Oa.invalid_type,expected:Ta.null,received:t.parsedType}),$a}return Ua(e.data)}}Rc.create=e=>new Rc({typeName:ou.ZodNull,...Ya(e)});class Oc extends Qa{constructor(){super(...arguments),this._any=!0}_parse(e){return Ua(e.data)}}Oc.create=e=>new Oc({typeName:ou.ZodAny,...Ya(e)});class Ac extends Qa{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ua(e.data)}}Ac.create=e=>new Ac({typeName:ou.ZodUnknown,...Ya(e)});class Pc extends Qa{_parse(e){const t=this._getOrReturnCtx(e);return ja(t,{code:Oa.invalid_type,expected:Ta.never,received:t.parsedType}),$a}}Pc.create=e=>new Pc({typeName:ou.ZodNever,...Ya(e)});class Ic extends Qa{_parse(e){if(this._getType(e)!==Ta.undefined){const t=this._getOrReturnCtx(e);return ja(t,{code:Oa.invalid_type,expected:Ta.void,received:t.parsedType}),$a}return Ua(e.data)}}Ic.create=e=>new Ic({typeName:ou.ZodVoid,...Ya(e)});class Mc extends Qa{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==Ta.array)return ja(t,{code:Oa.invalid_type,expected:Ta.array,received:t.parsedType}),$a;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,i=t.data.length<s.exactLength.value;(e||i)&&(ja(t,{code:e?Oa.too_big:Oa.too_small,minimum:i?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(ja(t,{code:Oa.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(ja(t,{code:Oa.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map(((e,r)=>s.type._parseAsync(new Ja(t,e,t.path,r))))).then((e=>Fa.mergeArray(r,e)));const i=[...t.data].map(((e,r)=>s.type._parseSync(new Ja(t,e,t.path,r))));return Fa.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new Mc({...this._def,minLength:{value:e,message:Ha.toString(t)}})}max(e,t){return new Mc({...this._def,maxLength:{value:e,message:Ha.toString(t)}})}length(e,t){return new Mc({...this._def,exactLength:{value:e,message:Ha.toString(t)}})}nonempty(e){return this.min(1,e)}}function Nc(e){if(e instanceof jc){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=Kc.create(Nc(s))}return new jc({...e._def,shape:()=>t})}return e instanceof Mc?new Mc({...e._def,type:Nc(e.element)}):e instanceof Kc?Kc.create(Nc(e.unwrap())):e instanceof Yc?Yc.create(Nc(e.unwrap())):e instanceof Uc?Uc.create(e.items.map((e=>Nc(e)))):e}Mc.create=(e,t)=>new Mc({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ou.ZodArray,...Ya(t)});class jc extends Qa{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=xa.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==Ta.object){const t=this._getOrReturnCtx(e);return ja(t,{code:Oa.invalid_type,expected:Ta.object,received:t.parsedType}),$a}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),n=[];if(!(this._def.catchall instanceof Pc&&"strip"===this._def.unknownKeys))for(const e in r.data)i.includes(e)||n.push(e);const o=[];for(const e of i){const t=s[e],i=r.data[e];o.push({key:{status:"valid",value:e},value:t._parse(new Ja(r,i,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof Pc){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of n)o.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)n.length>0&&(ja(r,{code:Oa.unrecognized_keys,keys:n}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of n){const s=r.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new Ja(r,s,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of o){const r=await t.key,s=await t.value;e.push({key:r,value:s,alwaysSet:t.alwaysSet})}return e})).then((e=>Fa.mergeObjectSync(t,e))):Fa.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return Ha.errToObj,new jc({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var s,i,n,o;const a=null!==(n=null===(i=(s=this._def).errorMap)||void 0===i?void 0:i.call(s,t,r).message)&&void 0!==n?n:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(o=Ha.errToObj(e).message)&&void 0!==o?o:a}:{message:a}}}:{}})}strip(){return new jc({...this._def,unknownKeys:"strip"})}passthrough(){return new jc({...this._def,unknownKeys:"passthrough"})}extend(e){return new jc({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new jc({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ou.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new jc({...this._def,catchall:e})}pick(e){const t={};return xa.objectKeys(e).forEach((r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])})),new jc({...this._def,shape:()=>t})}omit(e){const t={};return xa.objectKeys(this.shape).forEach((r=>{e[r]||(t[r]=this.shape[r])})),new jc({...this._def,shape:()=>t})}deepPartial(){return Nc(this)}partial(e){const t={};return xa.objectKeys(this.shape).forEach((r=>{const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()})),new jc({...this._def,shape:()=>t})}required(e){const t={};return xa.objectKeys(this.shape).forEach((r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Kc;)e=e._def.innerType;t[r]=e}})),new jc({...this._def,shape:()=>t})}keyof(){return Vc(xa.objectKeys(this.shape))}}jc.create=(e,t)=>new jc({shape:()=>e,unknownKeys:"strip",catchall:Pc.create(),typeName:ou.ZodObject,...Ya(t)}),jc.strictCreate=(e,t)=>new jc({shape:()=>e,unknownKeys:"strict",catchall:Pc.create(),typeName:ou.ZodObject,...Ya(t)}),jc.lazycreate=(e,t)=>new jc({shape:e,unknownKeys:"strip",catchall:Pc.create(),typeName:ou.ZodObject,...Ya(t)});class Fc extends Qa{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map((async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map((e=>new Aa(e.ctx.common.issues)));return ja(t,{code:Oa.invalid_union,unionErrors:r}),$a}));{let e;const s=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},n=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const i=s.map((e=>new Aa(e)));return ja(t,{code:Oa.invalid_union,unionErrors:i}),$a}}get options(){return this._def.options}}Fc.create=(e,t)=>new Fc({options:e,typeName:ou.ZodUnion,...Ya(t)});function $c(e,t){const r=Ra(e),s=Ra(t);if(e===t)return{valid:!0,data:e};if(r===Ta.object&&s===Ta.object){const r=xa.objectKeys(t),s=xa.objectKeys(e).filter((e=>-1!==r.indexOf(e))),i={...e,...t};for(const r of s){const s=$c(e[r],t[r]);if(!s.valid)return{valid:!1};i[r]=s.data}return{valid:!0,data:i}}if(r===Ta.array&&s===Ta.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let s=0;s<e.length;s++){const i=$c(e[s],t[s]);if(!i.valid)return{valid:!1};r.push(i.data)}return{valid:!0,data:r}}return r===Ta.date&&s===Ta.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Lc extends Qa{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(Da(e)||Da(s))return $a;const i=$c(e.value,s.value);return i.valid?((qa(e)||qa(s))&&t.dirty(),{status:t.value,value:i.data}):(ja(r,{code:Oa.invalid_intersection_types}),$a)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then((([e,t])=>s(e,t))):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Lc.create=(e,t,r)=>new Lc({left:e,right:t,typeName:ou.ZodIntersection,...Ya(r)});class Uc extends Qa{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ta.array)return ja(r,{code:Oa.invalid_type,expected:Ta.array,received:r.parsedType}),$a;if(r.data.length<this._def.items.length)return ja(r,{code:Oa.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$a;!this._def.rest&&r.data.length>this._def.items.length&&(ja(r,{code:Oa.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...r.data].map(((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new Ja(r,e,r.path,t)):null})).filter((e=>!!e));return r.common.async?Promise.all(s).then((e=>Fa.mergeArray(t,e))):Fa.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new Uc({...this._def,rest:e})}}Uc.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Uc({items:e,typeName:ou.ZodTuple,rest:null,...Ya(t)})};class Dc extends Qa{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ta.object)return ja(r,{code:Oa.invalid_type,expected:Ta.object,received:r.parsedType}),$a;const s=[],i=this._def.keyType,n=this._def.valueType;for(const e in r.data)s.push({key:i._parse(new Ja(r,e,r.path,e)),value:n._parse(new Ja(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?Fa.mergeObjectAsync(t,s):Fa.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new Dc(t instanceof Qa?{keyType:e,valueType:t,typeName:ou.ZodRecord,...Ya(r)}:{keyType:_c.create(),valueType:e,typeName:ou.ZodRecord,...Ya(t)})}}class qc extends Qa{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ta.map)return ja(r,{code:Oa.invalid_type,expected:Ta.map,received:r.parsedType}),$a;const s=this._def.keyType,i=this._def.valueType,n=[...r.data.entries()].map((([e,t],n)=>({key:s._parse(new Ja(r,e,r.path,[n,"key"])),value:i._parse(new Ja(r,t,r.path,[n,"value"]))})));if(r.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const r of n){const s=await r.key,i=await r.value;if("aborted"===s.status||"aborted"===i.status)return $a;"dirty"!==s.status&&"dirty"!==i.status||t.dirty(),e.set(s.value,i.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const r of n){const s=r.key,i=r.value;if("aborted"===s.status||"aborted"===i.status)return $a;"dirty"!==s.status&&"dirty"!==i.status||t.dirty(),e.set(s.value,i.value)}return{status:t.value,value:e}}}}qc.create=(e,t,r)=>new qc({valueType:t,keyType:e,typeName:ou.ZodMap,...Ya(r)});class Bc extends Qa{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ta.set)return ja(r,{code:Oa.invalid_type,expected:Ta.set,received:r.parsedType}),$a;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(ja(r,{code:Oa.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&r.data.size>s.maxSize.value&&(ja(r,{code:Oa.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const i=this._def.valueType;function n(e){const r=new Set;for(const s of e){if("aborted"===s.status)return $a;"dirty"===s.status&&t.dirty(),r.add(s.value)}return{status:t.value,value:r}}const o=[...r.data.values()].map(((e,t)=>i._parse(new Ja(r,e,r.path,t))));return r.common.async?Promise.all(o).then((e=>n(e))):n(o)}min(e,t){return new Bc({...this._def,minSize:{value:e,message:Ha.toString(t)}})}max(e,t){return new Bc({...this._def,maxSize:{value:e,message:Ha.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Bc.create=(e,t)=>new Bc({valueType:e,minSize:null,maxSize:null,typeName:ou.ZodSet,...Ya(t)});class zc extends Qa{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}zc.create=(e,t)=>new zc({getter:e,typeName:ou.ZodLazy,...Ya(t)});class Gc extends Qa{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return ja(t,{received:t.data,code:Oa.invalid_literal,expected:this._def.value}),$a}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Vc(e,t){return new Hc({values:e,typeName:ou.ZodEnum,...Ya(t)})}Gc.create=(e,t)=>new Gc({value:e,typeName:ou.ZodLiteral,...Ya(t)});class Hc extends Qa{constructor(){super(...arguments),Wa.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return ja(t,{expected:xa.joinValues(r),received:t.parsedType,code:Oa.invalid_type}),$a}if(Ga(this,Wa,"f")||Va(this,Wa,new Set(this._def.values),"f"),!Ga(this,Wa,"f").has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return ja(t,{received:t.data,code:Oa.invalid_enum_value,options:r}),$a}return Ua(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Hc.create(e,{...this._def,...t})}exclude(e,t=this._def){return Hc.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}Wa=new WeakMap,Hc.create=Vc;class Wc extends Qa{constructor(){super(...arguments),Za.set(this,void 0)}_parse(e){const t=xa.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Ta.string&&r.parsedType!==Ta.number){const e=xa.objectValues(t);return ja(r,{expected:xa.joinValues(e),received:r.parsedType,code:Oa.invalid_type}),$a}if(Ga(this,Za,"f")||Va(this,Za,new Set(xa.getValidEnumValues(this._def.values)),"f"),!Ga(this,Za,"f").has(e.data)){const e=xa.objectValues(t);return ja(r,{received:r.data,code:Oa.invalid_enum_value,options:e}),$a}return Ua(e.data)}get enum(){return this._def.values}}Za=new WeakMap,Wc.create=(e,t)=>new Wc({values:e,typeName:ou.ZodNativeEnum,...Ya(t)});class Zc extends Qa{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Ta.promise&&!1===t.common.async)return ja(t,{code:Oa.invalid_type,expected:Ta.promise,received:t.parsedType}),$a;const r=t.parsedType===Ta.promise?t.data:Promise.resolve(t.data);return Ua(r.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}Zc.create=(e,t)=>new Zc({type:e,typeName:ou.ZodPromise,...Ya(t)});class Jc extends Qa{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ou.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:e=>{ja(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===s.type){const e=s.transform(r.data,i);if(r.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return $a;const s=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===s.status?$a:"dirty"===s.status||"dirty"===t.value?La(s.value):s}));{if("aborted"===t.value)return $a;const s=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===s.status?$a:"dirty"===s.status||"dirty"===t.value?La(s.value):s}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,i);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===s.status?$a:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((r=>"aborted"===r.status?$a:("dirty"===r.status&&t.dirty(),e(r.value).then((()=>({status:t.value,value:r.value}))))))}if("transform"===s.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Ba(e))return e;const n=s.transform(e.value,i);if(n instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((e=>Ba(e)?Promise.resolve(s.transform(e.value,i)).then((e=>({status:t.value,value:e}))):e))}xa.assertNever(s)}}Jc.create=(e,t,r)=>new Jc({schema:e,typeName:ou.ZodEffects,effect:t,...Ya(r)}),Jc.createWithPreprocess=(e,t,r)=>new Jc({schema:t,effect:{type:"preprocess",transform:e},typeName:ou.ZodEffects,...Ya(r)});class Kc extends Qa{_parse(e){return this._getType(e)===Ta.undefined?Ua(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Kc.create=(e,t)=>new Kc({innerType:e,typeName:ou.ZodOptional,...Ya(t)});class Yc extends Qa{_parse(e){return this._getType(e)===Ta.null?Ua(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Yc.create=(e,t)=>new Yc({innerType:e,typeName:ou.ZodNullable,...Ya(t)});class Qc extends Qa{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===Ta.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Qc.create=(e,t)=>new Qc({innerType:e,typeName:ou.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...Ya(t)});class Xc extends Qa{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return za(s)?s.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Aa(r.common.issues)},input:r.data})}))):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new Aa(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Xc.create=(e,t)=>new Xc({innerType:e,typeName:ou.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...Ya(t)});class eu extends Qa{_parse(e){if(this._getType(e)!==Ta.nan){const t=this._getOrReturnCtx(e);return ja(t,{code:Oa.invalid_type,expected:Ta.nan,received:t.parsedType}),$a}return{status:"valid",value:e.data}}}eu.create=e=>new eu({typeName:ou.ZodNaN,...Ya(e)});Symbol("zod_brand");class tu extends Qa{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class ru extends Qa{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?$a:"dirty"===e.status?(t.dirty(),La(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?$a:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new ru({in:e,out:t,typeName:ou.ZodPipeline})}}class su extends Qa{_parse(e){const t=this._def.innerType._parse(e),r=e=>(Ba(e)&&(e.value=Object.freeze(e.value)),e);return za(t)?t.then((e=>r(e))):r(t)}unwrap(){return this._def.innerType}}function iu(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function nu(e,t={},r){return e?Oc.create().superRefine(((s,i)=>{var n,o;const a=e(s);if(a instanceof Promise)return a.then((e=>{var n,o;if(!e){const e=iu(t,s),a=null===(o=null!==(n=e.fatal)&&void 0!==n?n:r)||void 0===o||o;i.addIssue({code:"custom",...e,fatal:a})}}));if(!a){const e=iu(t,s),a=null===(o=null!==(n=e.fatal)&&void 0!==n?n:r)||void 0===o||o;i.addIssue({code:"custom",...e,fatal:a})}})):Oc.create()}su.create=(e,t)=>new su({innerType:e,typeName:ou.ZodReadonly,...Ya(t)});jc.lazycreate;var ou;!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(ou||(ou={}));const au=_c.create,cu=Sc.create,uu=(eu.create,Cc.create,Ec.create),hu=(xc.create,kc.create,Tc.create,Rc.create,Oc.create),lu=(Ac.create,Pc.create,Ic.create,Mc.create,jc.create),du=(jc.strictCreate,Fc.create),pu=(Lc.create,Uc.create),fu=Dc.create,mu=(qc.create,Bc.create,zc.create,Gc.create),gu=(Hc.create,Wc.create,Zc.create,Jc.create,Kc.create);Yc.create,Jc.createWithPreprocess,ru.create;function yu(e){const t=["kasa://","nest:","ring:","tapo://"];return e.some((e=>t.some((t=>e.startsWith(t)))))}const bu=lu({enabled:uu().default(!1)}).strict(),vu=du([mu("animal"),mu("person"),mu("vehicle"),mu("other"),mu("motion")]),_u=pu([cu(),cu()]),wu=lu({name:au().min(1,"Zone Name is required"),points:_u.array().min(3,"At least 3 points are required"),type:du([mu("intersect"),mu("contain")]),filter:du([mu("include"),mu("exclude")]),classes:vu.array(),isPrivacyMask:uu(),color:au().regex(/^#([0-9A-Fa-f]{3}){1,2}$/,"Must be a valid hex color (e.g. #FF0000 or #F00)").default("#df2a4c")}).array(),Su=lu({motion:lu({timeout:cu().min(10,"Minimum 10 seconds")}),object:lu({confidence:cu().min(.3,"Minimum 0.3").max(1,"Maximum 1")})}),Cu=du([mu("high-resolution"),mu("mid-resolution"),mu("low-resolution"),mu("snapshot")]),Eu=du([mu("high-resolution"),mu("mid-resolution"),mu("low-resolution"),mu("auto")]),xu=du([mu("bubble://"),mu("cui://"),mu("doorbird://"),mu("dvrip://"),mu("echo:"),mu("eseecloud://"),mu("exec:"),mu("expr:"),mu("ffmpeg:"),mu("flussonic://"),mu("gopro://"),mu("hass:"),mu("homekit://"),mu("http://"),mu("https://"),mu("httpx://"),mu("isapi://"),mu("ivideon:"),mu("kasa://"),mu("nest:"),mu("onvif://"),mu("ring:"),mu("roborock://"),mu("rtmp://"),mu("rtsp://"),mu("rtspx://"),mu("tapo://"),mu("tcp://"),mu("webrtc:"),mu("webtorrent:")]).options.map((e=>e.value)),ku=new RegExp(`^(${xu.join("|")})`),Tu=au().refine((e=>{if(!ku.test(e))return!1;try{return new URL(e),!0}catch{return!1}}),{message:"Invalid URL format or unsupported protocol"}),Ru=lu({_id:au().default(Ea()).transform((()=>Ea())),name:au().min(1,"Camera Source Name is required").transform((e=>e.replace(/ /g,"_").toLowerCase())),role:Cu,useForSnapshot:uu().default(!1),hotMode:uu().default(!1),urls:Tu.array().min(1,"At least one valid URL is required")}).strict(),Ou=lu({_id:au().default(Ea()).transform((()=>Ea())),name:au().min(1,"Camera Source Name is required").transform((e=>e.replace(/ /g,"_").toLowerCase())),role:Cu,useForSnapshot:uu().default(!1),hotMode:uu().default(!1),urls:Tu.array().min(1,"At least one valid URL is required")}).strict(),Au=lu({id:au(),name:au()}),Pu=lu({hub:Au.array().optional(),cameraController:Au.optional(),motionDetection:Au.optional(),audioDetection:Au.optional(),objectDetection:Au.optional(),ptz:Au.optional(),plugins:Au.array()}).strict(),Iu=du([mu("auto"),mu("mse"),mu("webrtc"),mu("webrtc/tcp")]),Mu=du([mu("16:9"),mu("8:3"),mu("4:3"),mu("auto")]),Nu=lu({decoder:du([mu("pillow"),mu("wasm"),mu("rust"),mu("gpu")]),fps:cu().min(0,"Minimum 0 fps").max(30,"Maximum 30 fps"),resolution:du([mu("640x480"),mu("640x360"),mu("320x240"),mu("320x180")])}),ju=du([mu("camera"),mu("doorbell")]),Fu=lu({streamingMode:Iu,streamingSource:Eu,aspectRatio:Mu}),$u=lu({model:au().optional(),manufacturer:au().optional(),hardware:au().optional(),serialNumber:au().optional(),firmwareVersion:au().optional(),supportUrl:au().optional()}),Lu=(lu({name:au().min(1,"Camera name is required"),url:au().url().min(1,"Camera URL is required"),type:du([mu("Google"),mu("Ring"),mu("HomeKit"),mu("Onvif"),mu("Hass"),mu("GoPro"),mu("Roborock"),mu("FFmpeg"),mu("DVRip"),mu("Webtorrent")]),username:au().optional(),email:au().email().optional(),password:au().optional(),pin:au().length(8,{message:"PIN must be 8 characters long"}).optional(),clientId:au().optional(),clientSecret:au().optional(),refreshToken:au().optional(),projectId:au().optional()}).strict().refine((e=>"HomeKit"!==e.type||!!e.pin),{message:"PIN is required for HomeKit cameras",path:["pin"]}).refine((e=>"Google"!==e.type||!!e.clientId),{message:"Client ID is required for Google cameras",path:["clientId"]}).refine((e=>"Google"!==e.type||!!e.clientSecret),{message:"Client Secret is required for Google cameras",path:["clientSecret"]}).refine((e=>"Google"!==e.type||!!e.projectId),{message:"Project ID is required for Google cameras",path:["projectId"]}).refine((e=>"Google"!==e.type||!!e.refreshToken),{message:"Refresh Token is required for Google cameras",path:["refreshToken"]}).refine((e=>"Ring"!==e.type||!!e.email),{message:"Email is required",path:["email"]}).refine((e=>"Roborock"!==e.type||!!e.username),{message:"Username is required",path:["username"]}).refine((e=>"Roborock"!==e.type&&"Ring"!==e.type||!!e.password),{message:"Password is required",path:["password"]}),lu({_id:au().default(Ea()).transform((()=>Ea())),nativeId:au().optional(),pluginId:au().default("native"),disabled:uu().default(!1),name:au().min(1,"Camera name is required"),type:ju.default("camera"),isCloud:uu().default(!1),snapshotTTL:cu().min(30,"Minimum cache time must be 30").default(600),info:$u.default({model:"IP Camera",manufacturer:"camera.ui",hardware:"Camera",serialNumber:"Unknown",firmwareVersion:"Unknown",supportUrl:"Unknown"}),sources:Ru.array().refine((e=>e.some((e=>"high-resolution"===e.role||"mid-resolution"===e.role||"low-resolution"===e.role))),{path:["sources[].role"],message:'One of the roles "high-resolution", "mid-resolution" or "low-resolution" is required'}).refine((e=>e.filter((e=>e.useForSnapshot)).length<=1),{message:"Only one source can be used for snapshot",path:["sources"]}).refine((e=>e.filter((e=>"snapshot"===e.role)).every((e=>!e.useForSnapshot))),{message:"Snapshot source can not be used with useForSnapshot",path:["sources"]}).refine((e=>e.filter((e=>"snapshot"===e.role)).every((e=>!e.hotMode))),{message:"Snapshot source can not be used with hotMode"}),extensions:Pu.default({hub:[],plugins:[]}),recording:bu.default({enabled:!1}),interface:Fu.default({streamingMode:"auto",streamingSource:"auto",aspectRatio:"16:9"}),detectionZones:wu.default([]),detectionSettings:Su.default({motion:{timeout:60},object:{confidence:.7}}),frameWorkerSettings:Nu.default({decoder:"rust",fps:10,resolution:"320x180"})}).strict().transform((e=>{const t=e.sources.flatMap((e=>e.urls));return e.isCloud||yu(t)?{...e,isCloud:!0}:e})),lu({disabled:uu().optional(),type:ju.optional(),name:au().min(1,"Camera name is required").optional(),isCloud:uu().optional(),snapshotTTL:cu().min(30,"Minimum cache time must be 30").optional(),info:$u.partial().optional(),sources:Ou.array().refine((e=>e.some((e=>"high-resolution"===e.role||"mid-resolution"===e.role||"low-resolution"===e.role))),{path:["sources[].role"],message:'One of the roles "high-resolution", "mid-resolution" or "low-resolution" is required'}).refine((e=>e.filter((e=>e.useForSnapshot)).length<=1),{message:"Only one source can be used for snapshot",path:["sources"]}).refine((e=>e.filter((e=>"snapshot"===e.role)).every((e=>!e.useForSnapshot))),{message:"Snapshot source can not be used with useForSnapshot",path:["sources"]}).refine((e=>e.filter((e=>"snapshot"===e.role)).every((e=>!e.hotMode))),{message:"Snapshot source can not be used with hotMode"}).optional(),extensions:Pu.partial().optional(),interface:Fu.partial().optional(),recording:bu.partial().optional(),detectionZones:wu.optional(),detectionSettings:Su.partial().optional(),frameWorkerSettings:Nu.partial().optional()}).strict().transform((e=>{if(e.sources){const t=e.sources.flatMap((e=>e.urls));if(!0===e.isCloud||yu(t))return{...e,isCloud:!0}}return e})),lu({url:au()}).strict(),/^((@[\w-.]*)\/)?(camera-ui-[\w-]*)$/);var Uu,Du;!function(e){e.READY="ready",e.STARTING="starting",e.STARTED="started",e.STOPPING="stopping",e.STOPPED="stopped",e.ERROR="error",e.UNKNOWN="unknown",e.DISABLED="disabled"}(Uu||(Uu={})),function(e){e.START="start",e.STOP="stop"}(Du||(Du={}));const qu=["image/jpeg","image/png"],Bu=2097152,zu=["video/mp4","video/quicktime"],Gu=10485760,Vu=["audio/mpeg","audio/wav","audio/ogg"],Hu=2097152,Wu=(lu({pluginname:au().refine((e=>Lu.test(e)),"Not a valid plugin name"),pluginversion:au().optional().default("latest")}).strict(),lu({actionId:au(),payload:hu()}).strict(),fu(hu(),hu()),lu({upload:nu().refine((e=>(e=>void 0!==e.mimetype)(e)?Buffer.byteLength(e._buf)<=Bu:e.size<=Bu),"Max file size is 2 MB").refine((e=>(e=>void 0!==e.mimetype)(e)?qu.includes(e.mimetype):qu.includes(e.type)),".jpeg and .png files are accepted"),metadata:nu().transform((e=>JSON.parse(e.value))),config:nu().transform((e=>JSON.parse(e.value)))}),lu({upload:nu().refine((e=>(e=>void 0!==e.mimetype)(e)?Buffer.byteLength(e._buf)<=Hu:e.size<=Hu),"Max file size is 2 MB").refine((e=>(e=>void 0!==e.mimetype)(e)?Vu.includes(e.mimetype):Vu.includes(e.type)),".mp3, .wav and .ogg files are accepted"),metadata:nu().transform((e=>JSON.parse(e.value))),config:nu().transform((e=>JSON.parse(e.value)))}),lu({upload:nu().refine((e=>(e=>void 0!==e.mimetype)(e)?Buffer.byteLength(e._buf)<=Gu:e.size<=Gu),"Max file size is 5 MB").refine((e=>(e=>void 0!==e.mimetype)(e)?zu.includes(e.mimetype):zu.includes(e.type)),".mp4 files are accepted"),config:nu().transform((e=>JSON.parse(e.value)))}),fu(au(),hu()),lu({key:au()}).strict(),lu({key:au(),payload:hu()}).strict(),lu({version:au().optional().default("latest")}).strict(),lu({mode:du([mu("disabled"),mu("port-forward"),mu("router-forward"),mu("cloudflare"),mu("custom-domain")]).default("disabled"),cloudflare:lu({tunnelToken:au(),customDomain:au(),tunnelUrl:au(),tunnelCredentials:lu({username:au(),password:au()}).partial()}).partial().strict(),customDomain:lu({url:au().optional()}).partial().strict()}).strict()),Zu=(lu({serverAddresses:au().ip().array().default([]),remoteAccess:Wu}).strict(),["image/jpeg","image/jpg","image/png"]),Ju=5242880,Ku=lu({index:cu(),cameraId:au()}),Yu=du([mu(1),mu(4),mu(6),mu(7),mu(9),mu(10),mu(12),mu(13),mu(15),mu(16),mu(20),mu(26)]),Qu=du([mu("dnd"),mu("view")]),Xu=lu({_id:au().default(Ea()).transform((()=>Ea())),name:au().min(1,"Layout name is required"),viewSize:Yu,cameras:Ku.array(),type:Qu}),eh=(lu({name:au().min(1,"Layout name is required"),viewSize:Yu,cameras:Ku.array()}).partial().optional(),lu({views:Xu.array()})),th=lu({_id:au().default(Ea()).transform((()=>Ea())),cameraId:au(),points:_u}),rh=(lu({cameraId:au(),points:_u}).partial().optional(),lu({shortcuts:th.array()})),sh=lu({camview:eh,cameras:fu(au(),rh)});lu({_id:au().default(Ea()).transform((()=>Ea())),username:au().min(1,"Username is required"),password:au().min(10,"Password must be at least 10 characters long").regex(/[A-Z]/,"Password must contain at least one uppercase letter").regex(/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/,"Password must contain at least one special character (!@#$%^&*()_+-=[]{};:'\"\\|,.<>/?)").max(32,"Password cannot be more than 32 characters"),passwordConfirm:au().min(1,"Please confirm your password"),role:du([mu("admin"),mu("user")]),sessionTimer:cu().min(3600,"Session timer must not be less than 3600 seconds (1h)").max(86400,"Session timer must not be greater than 86400 seconds (24h)").default(14400),rememberMe:uu().default(!1),singleSession:uu().default(!1),firstLogin:uu().default(!0),preferences:sh.default({camview:{views:[]},cameras:{}})}).strict().refine((e=>e.password===e.passwordConfirm),{path:["passwordConfirm"],message:"Passwords do not match"}),lu({username:au().min(1,"Username is required"),password:au().min(1,"Password is required"),rememberMe:uu().default(!1)}).strict(),lu({username:au().min(1,"Username is required").optional(),password:au().min(10,"Password must be at least 10 characters long").regex(/[A-Z]/,"Password must contain at least one uppercase letter").regex(/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/,"Password must contain at least one special character (!@#$%^&*()_+-=[]{};:'\"\\|,.<>/?)").max(32,"Password cannot be more than 32 characters").optional(),passwordConfirm:au().optional(),role:du([mu("admin"),mu("user")]).optional(),sessionTimer:cu().min(3600,"Session timer must not be less than 3600 seconds (1h)").max(86400,"Session timer must not be greater than 86400 seconds (24h)").optional(),upload:gu(nu().refine((e=>(e=>void 0!==e.mimetype)(e)?Buffer.byteLength(e._buf)<=Ju:e.size<=Ju),"Max file size is 5MB.").refine((e=>(e=>void 0!==e.mimetype)(e)?Zu.includes(e.mimetype):Zu.includes(e.type)),".jpg, .jpeg, .png files are accepted.")),rememberMe:uu().optional(),singleSession:uu().optional(),firstLogin:uu().optional(),preferences:sh.partial().optional()}).strict().refine((e=>e.password===e.passwordConfirm),{path:["passwordConfirm"],message:"Passwords do not match"});var ih;!function(e){e.READY="ready",e.RESTARTING="restarting",e.STARTING="starting",e.STARTED="started",e.STOPPED="stopped",e.ERROR="error",e.UNKNOWN="unknown"}(ih||(ih={}));class nh extends EventTarget{cameraDevice;logger;config;token;initialOptions;videoPlayer;CONFIG={WEBRTC:{RECONNECT_TIMER:1e3,TIMEOUT_TIMER:1e4,ICE_SERVERS:[{urls:"stun:stun.l.google.com:19302"}]},QUALITY:{METRICS_INTERVAL:5e3,METRICS_WINDOW:6e4,STABILITY_PERIOD:3e4,PACKET_LOSS_THRESHOLD:.05,FRAME_DROP_THRESHOLD:.1,QUALITY_CHANGE_COOLDOWN:5e3},MEDIA:{BUFFER_SIZE:2097152,DEFAULT_CODECS:["avc1.640029","avc1.64002A","avc1.640033","hvc1.1.6.L153.B0","mp4a.40.2","mp4a.40.5","flac","opus"]}};ws;pc=null;micTransceiver=null;mediaSource=null;sourceBuffer=null;buf=new Uint8Array(0);bufLen=0;codecList;streamProbe;metrics=[];metricsInterval;lastQualityChange=0;isMonitoring=!1;wsReconnectTimer;wsReconnectTimeout;webrtcConnectTimeout;webrtcReconnectTimeout;firstFrameReceived=!1;animationFrameId;userRequestedMode;internalMode;activeMode;isAutoSwitchingInProgress=!1;_closed=!0;_hasBackchannel=!1;_hasAudio=!0;_hasVideo=!0;_finishLoading=!1;userRequestedRole;effectiveRole;_streamingSource;get streamingSource(){return this._streamingSource}get closed(){return this._closed}get hasBackchannel(){return this._hasBackchannel}get hasAudio(){return this._hasAudio}get hasVideo(){return this._hasVideo}get finishLoading(){return this._finishLoading}get mode(){return this.userRequestedMode}get currentMode(){return this.activeMode}get currentResolution(){return this.effectiveRole}get logPrefix(){const e=new Date,t=e.toLocaleTimeString()+"."+e.getMilliseconds().toString().padStart(3,"0");return"auto"===this.userRequestedMode?`[${t}] [${this.cameraDevice.name}] [auto→${this.activeMode}]`:`[${t}] [${this.cameraDevice.name}] [${this.activeMode}]`}get wsUrl(){const e=new URL(this.config.endpoint),t=""!==e.port,r="https:"===e.protocol?"wss:":"ws:",s=t?e.port:"https:"===e.protocol?"443":"80";return`${r}//${e.hostname}:${s}/go2rtc?src=${this.createWsSourceName()}&token=${this.token}`}constructor(e,t,r,s,i){super(),this.cameraDevice=e,this.config=t,this.token=r,this.logger=s,this.initialOptions={...i},this.videoPlayer=i.videoElement,this.CONFIG.WEBRTC.RECONNECT_TIMER=i.webrtcConnectTimeout??this.CONFIG.WEBRTC.RECONNECT_TIMER,this.userRequestedMode=i.mode,this.userRequestedRole=i.role,this.internalMode=i.mode,this.activeMode="auto"===i.mode?"webrtc":i.mode,this.setActiveMode(this.activeMode,!0),this.effectiveRole="auto"===i.role?"low-resolution":i.role,this.buf=new Uint8Array(this.CONFIG.MEDIA.BUFFER_SIZE),this.codecList=this.createCodecsList()}async start(e){console.log(this.logPrefix,"Starting session..."),this.reset(),this._closed=!1,this.videoPlayer.addEventListener("loadeddata",this.onLoadedData.bind(this)),e&&(this.userRequestedMode=e,this.internalMode=e,this.setActiveMode("auto"===e?"webrtc":e)),await this.initializeStreamingSource(),this.streamProbe=await this.probeStream(),this.streamProbe&&"auto"===this.userRequestedMode&&this.selectInitialMode(),this.connectWs()}close(){this._closed||(console.log(this.logPrefix,"Closing session..."),this._closed=!0,this.stopQualityMonitoring(),this.reset(),this.disconnectWs())}async restart(e,t=!1){console.log(this.logPrefix,"Restarting session..."),t?this.dispatchEvent(new Event("onSourceChange")):this.dispatchEvent(new Event("reconnect")),this.close(),await new Promise((e=>setTimeout(e,1e3))),await this.start(e)}async toggleMicrophone(e){if(this.micTransceiver)try{await this.micTransceiver.sender.replaceTrack(e)}catch(t){if(!this.micTransceiver||!e)return;console.error(this.logPrefix,"Microphone error:",t)}}async toggleRole(e){if(this.userRequestedRole!==e)if(console.log(this.logPrefix,`Switching source resolution to "${e}"...`),this.userRequestedRole=e,"auto"===e)await this.initializeAdaptiveStreaming();else{this.effectiveRole=e;const{source:t}=this.getSourceForResolution(e);this._streamingSource?._id!==t._id&&(this._streamingSource=t,await this.restart(void 0,!0))}}async toggleMode(e){this.userRequestedMode!==e&&(console.log(this.logPrefix,`Switching transport mode to "${e}"...`),this.userRequestedMode=e,this.internalMode=e,this.setActiveMode("auto"===e?"webrtc":e),await this.restart())}async initializeStreamingSource(){if("auto"===this.userRequestedRole)await this.initializeAdaptiveStreaming();else{const{source:e}=this.getSourceForResolution(this.userRequestedRole);if(this._streamingSource=e,"auto"===this.userRequestedMode&&e){const e=await this.probeStream();if(e){this.checkWebRTCCompatibility(e).compatible||(console.log(`${this.logPrefix} Source not compatible with WebRTC, starting with MSE...`),this.setActiveMode("mse"))}}}}checkWebRTCCompatibility(e){const t=e.audio.filter((e=>"sendonly"===e.direction)),r=e.video.filter((e=>"sendonly"===e.direction)),s=t.some((e=>this.isWebRtcCompatibleAudioCodec(e.codec))),i=r.some((e=>this.isWebRtcCompatibleVideoCodec(e.codec))),n=t.length>0,o=r.length>0;return{compatible:(!n||s)&&(!o||i),audioCompatible:s,videoCompatible:i}}async initializeAdaptiveStreaming(){"auto"===this.userRequestedRole&&(await this.setStreamResolution(this.effectiveRole,void 0,!0),this.startQualityMonitoring())}selectInitialMode(){if(!this.streamProbe||"auto"!==this.userRequestedMode)return;const e=this.checkWebRTCCompatibility(this.streamProbe);if(e.compatible)this.internalMode="auto";else{if(e.videoCompatible){if(!e.audioCompatible){const e=this.streamProbe.audio.filter((e=>"sendonly"===e.direction));console.warn(this.logPrefix,`Incompatible audio codec(s): "${e.map((e=>e.codec)).join(", ")}" - Using MSE directly`)}}else{const e=this.streamProbe.video.filter((e=>"sendonly"===e.direction));console.warn(this.logPrefix,`Incompatible video codec(s): "${e.map((e=>e.codec)).join(", ")}" - Using MSE directly`)}this.setActiveMode("mse")}}connectWs(){this.ws=new WebSocket(this.wsUrl),this.ws.binaryType="arraybuffer",this.ws.addEventListener("open",this.onWsOpen.bind(this)),this.ws.addEventListener("close",this.onWsClose.bind(this)),this.ws.addEventListener("message",this.onWsMessage.bind(this))}disconnectWs(){this.ws&&(this.ws.removeEventListener("open",this.onWsOpen.bind(this)),this.ws.removeEventListener("close",this.onWsClose.bind(this)),this.ws.removeEventListener("message",this.onWsMessage.bind(this)),this.ws.close(),this.ws=void 0)}reset(){this.videoPlayer?.removeEventListener("loadeddata",this.onLoadedData.bind(this)),clearTimeout(this.wsReconnectTimeout),clearTimeout(this.webrtcConnectTimeout),clearTimeout(this.webrtcReconnectTimeout),this._finishLoading=!1,this.firstFrameReceived=!1,this.isAutoSwitchingInProgress=!1,this.micTransceiver&&(this.micTransceiver.sender.replaceTrack(null).catch((()=>{})),this.micTransceiver=null),this.pc&&(this.pc.getTransceivers().forEach((e=>e.sender?.track?.stop())),this.pc.close(),this.pc=null),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)}onWsOpen(){switch(this.internalMode){case"webrtc":case"webrtc/tcp":console.log(this.logPrefix,"Requesting WebRTC session..."),this.requestWebrtc();break;case"mse":console.log(this.logPrefix,"Requesting MSE session..."),this.requestMse();break;case"auto":console.log(this.logPrefix,"Requesting auto session (both WebRTC and MSE)..."),this.requestAuto();break;default:console.error(this.logPrefix,"Unknown mode!"),this.dispatchEvent(new ErrorEvent("error",{message:"Unknown mode!"}))}}onWsClose(){this._closed||void 0===this.wsReconnectTimer||(clearTimeout(this.wsReconnectTimeout),this.wsReconnectTimeout=setTimeout((()=>{this.restart()}),this.wsReconnectTimer))}onWsMessage(e){if("string"==typeof e.data){const t=JSON.parse(e.data);if(t.type)switch(t.type){case"mse":this.onMseData(t);break;case"webrtc/candidate":case"webrtc/answer":this.onWebrtcData(t);break;case"error":this.handleStreamError(t)}}else this.onMseBuffer(e.data),this.onFirstFrame()}handleStreamError(e){this.isAutoSwitchingInProgress||"auto"===this.internalMode||(this.dispatchEvent(new ErrorEvent("error",{error:e,message:e.value})),this.close())}async requestWebrtc(e){e||this.reset(),e&&this.mediaSource||(this.webrtcConnectTimeout=setTimeout((()=>{if(console.log(this.logPrefix,"WebRTC connection timeout"),this.pc&&"connected"!==this.pc.connectionState)if(this.pc.close(),this.pc=null,"auto"===this.userRequestedMode){if(this.mediaSource&&this.sourceBuffer&&this._finishLoading)return console.log(this.logPrefix,"WebRTC timed out but MSE is working - staying with MSE"),this.setActiveMode("mse"),void(this.isAutoSwitchingInProgress=!1);this.setActiveMode("mse"),this.requestMse()}else"webrtc"===this.userRequestedMode?this.restart("mse"):this.restart()}),this.CONFIG.WEBRTC.TIMEOUT_TIMER)),this.pc=new RTCPeerConnection({bundlePolicy:"max-bundle",iceServers:[{urls:"stun:stun.l.google.com:19302"}],sdpSemantics:"unified-plan"}),this.pc.onicecandidate=e=>{if("webrtc/tcp"===this.activeMode&&"udp"===e.candidate?.protocol)return;const t=e.candidate?.toJSON().candidate??"";t&&this.send({type:"webrtc/candidate",value:t})},this.pc.onconnectionstatechange=async()=>{if(console.log(this.logPrefix,"onconnectionstatechange:",this.pc?.connectionState),"connected"===this.pc?.connectionState){clearTimeout(this.webrtcConnectTimeout);const e=new MediaStream(this.pc.getTransceivers().filter((e=>"recvonly"===e.currentDirection)).map((e=>e.receiver.track))),t=e.getVideoTracks().length>0;"auto"===this.userRequestedMode?this.mediaSource&&this.sourceBuffer&&this._finishLoading&&"mse"===this.activeMode?t?(console.log(this.logPrefix,"WebRTC connected successfully - switching from MSE to WebRTC"),await this.switchToWebRTC(e)):console.log(this.logPrefix,"WebRTC connected but no video - staying with MSE"):t?(this.setActiveMode("webrtc"),this.videoPlayer.srcObject=e,this.onFinishLoading(void 0,"webrtc"),this.onFirstFrameWebrtc(e)):console.log(this.logPrefix,"WebRTC connected but no video - waiting for MSE"):(this.videoPlayer.srcObject=e,this.onFinishLoading(void 0,"webrtc"),this.onFirstFrameWebrtc(e))}else"failed"!==this.pc?.connectionState&&"disconnected"!==this.pc?.connectionState||(clearTimeout(this.webrtcConnectTimeout),clearTimeout(this.webrtcReconnectTimeout),this.webrtcReconnectTimeout=setTimeout((()=>{if("failed"===this.pc?.connectionState||"disconnected"===this.pc?.connectionState){if("auto"===this.userRequestedMode&&this.mediaSource&&this.sourceBuffer&&this._finishLoading)return console.log(this.logPrefix,"WebRTC failed but MSE is working - staying with MSE"),this.setActiveMode("mse"),this.pc?.close(),this.pc=null,void(this.isAutoSwitchingInProgress=!1);"auto"===this.userRequestedMode?(console.warn(this.logPrefix,"WebRTC failed - switching to MSE"),this.setActiveMode("mse"),this.restart()):"webrtc"===this.activeMode?(console.warn(this.logPrefix,"WebRTC failed - switching to MSE fallback"),this.restart("mse")):this.restart()}}),this.CONFIG.WEBRTC.RECONNECT_TIMER))},this.pc.oniceconnectionstatechange=()=>{console.log(this.logPrefix,"iceconnectionstatechange",this.pc?.iceConnectionState)},this.pc.onicecandidateerror=e=>{console.log(this.logPrefix,"onicecandidateerror",e)},this.pc.onsignalingstatechange=()=>{console.log(this.logPrefix,"onsignalingstatechange",this.pc?.signalingState)},this.pc.onicegatheringstatechange=()=>{console.log(this.logPrefix,"onicegatheringstatechange",this.pc?.iceGatheringState)},this.pc.onnegotiationneeded=e=>{console.log(this.logPrefix,"onnegotiationneeded",e)},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.logPrefix,"Offer:",{type:t.type,sdp:t.sdp}),t.sdp?this.send({type:"webrtc/offer",value:t.sdp}):this.dispatchEvent(new ErrorEvent("error",{message:"Failed to create offer"}))}async onWebrtcData(e){try{switch(e.type){case"webrtc/candidate":if(!e.value)return;if("webrtc/tcp"===this.activeMode&&e.value.indexOf(" udp ")>0)return;await(this.pc?.addIceCandidate({candidate:e.value,sdpMid:"0"}));break;case"webrtc/answer":console.log(this.logPrefix,"Answer:",{type:"answer",sdp:e.value}),await(this.pc?.setRemoteDescription({type:"answer",sdp:e.value}))}}catch(e){this.dispatchEvent(new ErrorEvent("error",{error:e,message:e.message}))}}requestMse(){"auto"===this.userRequestedMode&&this.pc||this.reset();const e="ManagedMediaSource"in window;let t;if(e)t=window.ManagedMediaSource;else{if(!("MediaSource"in window))return void this.dispatchEvent(new ErrorEvent("error",{message:"MediaSource not supported"}));t=window.MediaSource}this.mediaSource=new t,this.mediaSource.addEventListener("sourceopen",(()=>{e||URL.revokeObjectURL(this.videoPlayer.src),this.send({type:"mse",value:this.parseCodecs(t.isTypeSupported.bind(this))})}),{once:!0}),e?(this.videoPlayer.disableRemotePlayback=!0,this.videoPlayer.srcObject=this.mediaSource):(this.videoPlayer.src=URL.createObjectURL(this.mediaSource),this.videoPlayer.srcObject=null),this.play()}onMseData(e){if(this.mediaSource&&"open"===this.mediaSource.readyState)if("auto"===this.userRequestedMode&&this.pc&&"failed"!==this.pc.connectionState||this.setActiveMode("mse"),this.bufLen=0,this.buf=new Uint8Array(this.CONFIG.MEDIA.BUFFER_SIZE),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.value),this.sourceBuffer.mode="segments",this.sourceBuffer.addEventListener("updateend",(()=>{if(this.sourceBuffer&&!this.sourceBuffer.updating&&this.bufLen>0)try{const e=this.buf.slice(0,this.bufLen);this.sourceBuffer.appendBuffer(e),this.bufLen=0}catch{}if(this.sourceBuffer&&!this.sourceBuffer.updating&&this.sourceBuffer.buffered?.length){const e=this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1),t=e-5,r=this.sourceBuffer.buffered.start(0);t>r&&(this.sourceBuffer.remove(r,t),this.mediaSource?.setLiveSeekableRange(t,e)),this.videoPlayer.currentTime<t&&(this.videoPlayer.currentTime=t);const s=e-this.videoPlayer.currentTime;this.videoPlayer.playbackRate=s>.1?s:.1}})),"auto"===this.userRequestedMode){if(this.pc&&"connected"===this.pc.connectionState)return void console.log(this.logPrefix,"MSE ready but WebRTC already connected");console.log(this.logPrefix,"MSE ready - using while waiting for WebRTC"),this.setActiveMode("mse"),this.onFinishLoading(void 0,"mse")}else this.onFinishLoading(void 0,"mse")}async onMseBuffer(e){if("closed"!==this.mediaSource?.readyState)if(this.sourceBuffer?.updating||this.bufLen>0){const t=new Uint8Array(e);this.buf.set(t,this.bufLen),this.bufLen+=t.byteLength}else try{this.sourceBuffer?.appendBuffer(e)}catch{}else this._closed||"auto"===this.internalMode||(this.dispatchEvent(new ErrorEvent("error",{message:"MediaSource closed"})),"auto"===this.userRequestedMode?(this.setActiveMode("webrtc"),this.restart()):this.restart("webrtc"))}requestAuto(){if(this.isAutoSwitchingInProgress=!0,this.streamProbe){if(!this.checkWebRTCCompatibility(this.streamProbe).compatible)return console.log(this.logPrefix,"Stream not compatible with WebRTC, using MSE only"),void this.requestMse()}console.log(this.logPrefix,"Starting both WebRTC and MSE transports in parallel"),this.requestMse(),this.requestWebrtc(!0)}send(e){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}async switchToWebRTC(e){this.setActiveMode("webrtc"),this.videoPlayer.srcObject=e,this.play(),this.onFinishLoading(!0,"webrtc"),this.onFirstFrameWebrtc(e),this.mediaSource&&("open"===this.mediaSource.readyState&&this.mediaSource.endOfStream(),this.mediaSource=null,this.sourceBuffer=null),this.disconnectWs()}async play(){try{await this.videoPlayer.play()}catch(e){if(!this.videoPlayer.muted)return this.videoPlayer.muted=!0,this.play();this.logger.warn(this.cameraDevice.name,e)}}startQualityMonitoring(){this.isMonitoring||"auto"!==this.userRequestedRole||(clearInterval(this.metricsInterval),this.isMonitoring=!0,this.metrics=[],this.metricsInterval=setInterval((async()=>{if(this._closed)return void this.stopQualityMonitoring();const e=await this.gatherMetrics();if(e){this.metrics.push(e);const t=Date.now()-this.CONFIG.QUALITY.METRICS_WINDOW;this.metrics=this.metrics.filter((e=>e.timestamp>t)),"auto"===this.userRequestedRole&&this.analyzeAndAdaptQuality()}}),this.CONFIG.QUALITY.METRICS_INTERVAL))}stopQualityMonitoring(){clearInterval(this.metricsInterval),this.metricsInterval=void 0,this.isMonitoring=!1,this.metrics=[]}async gatherMetrics(){if(this._closed)return null;if(this.pc&&"webrtc"===this.activeMode)try{const e=await this.pc.getStats(),t={packetsLost:0,packetsReceived:0,framesDropped:0,framesReceived:0,timestamp:Date.now()};for(const[,r]of e.entries())"inbound-rtp"===r.type&&"video"===r.kind?(t.packetsLost=r.packetsLost,t.packetsReceived=r.packetsReceived):"media-source"===r.type&&"video"===r.kind&&(t.framesDropped=r.framesDropped,t.framesReceived=r.framesReceived);return t}catch(e){return console.warn(`${this.logPrefix} Error gathering WebRTC metrics:`,e),null}else if("mse"===this.activeMode&&this.videoPlayer)try{const e=this.videoPlayer.getVideoPlaybackQuality();return{packetsLost:0,packetsReceived:0,framesDropped:e.droppedVideoFrames,framesReceived:e.totalVideoFrames,timestamp:Date.now()}}catch(e){return console.warn(`${this.logPrefix} Error gathering MSE metrics:`,e),null}return null}analyzeQualityMetrics(){if(Date.now()-this.lastQualityChange<this.CONFIG.QUALITY.QUALITY_CHANGE_COOLDOWN)return{packetLossRate:0,frameDropRate:0,isStable:!0};if(this.metrics.length<2)return{packetLossRate:0,frameDropRate:0,isStable:!0};const e=this.metrics[this.metrics.length-1],t=this.metrics[0],r=(e.packetsLost-t.packetsLost)/Math.max(e.packetsReceived-t.packetsReceived,1),s=(e.framesDropped-t.framesDropped)/Math.max(e.framesReceived-t.framesReceived,1);return{packetLossRate:r,frameDropRate:s,isStable:r<this.CONFIG.QUALITY.PACKET_LOSS_THRESHOLD&&s<this.CONFIG.QUALITY.FRAME_DROP_THRESHOLD}}async analyzeAndAdaptQuality(){if("auto"!==this.userRequestedRole||this._closed)return;const e=this.analyzeQualityMetrics(),t=Date.now()-this.lastQualityChange;if(e.isStable){if(e.isStable&&t>this.CONFIG.QUALITY.STABILITY_PERIOD){const t=e.packetLossRate,r=e.frameDropRate;t<this.CONFIG.QUALITY.PACKET_LOSS_THRESHOLD/2&&r<this.CONFIG.QUALITY.FRAME_DROP_THRESHOLD/2&&("low-resolution"===this.effectiveRole?await this.setStreamResolution("mid-resolution","upgrade"):"mid-resolution"===this.effectiveRole&&await this.setStreamResolution("high-resolution","upgrade"))}}else"high-resolution"===this.effectiveRole?await this.setStreamResolution("mid-resolution","downgrade"):"mid-resolution"===this.effectiveRole&&await this.setStreamResolution("low-resolution","downgrade")}async setStreamResolution(e,t,r){if(this._closed)return;const{source:s,sourceResolution:i,isRequestedSource:n}=this.getSourceForResolution(e);if(s._id!==this._streamingSource?._id){if("upgrade"===t?console.log(`${this.logPrefix} Quality stable, upgrading to "${e}" source...`):"downgrade"===t&&console.log(`${this.logPrefix} Quality unstable, downgrading to "${e}" source...`),n||r?console.log(`${this.logPrefix} Switching to "${i}" source...`):console.log(`${this.logPrefix} Source "${e}" not available, switching to next best available: ${i}`),this.effectiveRole=i,this._streamingSource=s,this.lastQualityChange=Date.now(),!r&&"auto"===this.userRequestedMode){const e=await this.probeStream();if(e){const t=this.checkWebRTCCompatibility(e);if(this.activeMode.startsWith("webrtc")&&!t.compatible)return console.log(`${this.logPrefix} New source not compatible with WebRTC, switching to MSE...`),this.isAutoSwitchingInProgress=!0,void await this.restart("mse",!0);if("mse"===this.activeMode&&t.compatible)return console.log(`${this.logPrefix} New source compatible with WebRTC, switching back...`),this.isAutoSwitchingInProgress=!0,void await this.restart("webrtc",!0)}}r||await this.restart(this.activeMode,!0)}else this.effectiveRole=r||n?i:e}getSourceForResolution(e){const t=["high-resolution","mid-resolution","low-resolution"],r=this.cameraDevice.sources.map((e=>e.role)).filter((e=>t.includes(e))),s=r.reduce(((e,r)=>t.indexOf(e)>t.indexOf(r)?e:r),"low-resolution"),i=this.cameraDevice.sources.find((t=>t.role===e)),n=this.cameraDevice.sources.find((e=>e.role===s)),o=i??n??this.cameraDevice.streamSource;if(this._streamingSource){if(this._streamingSource.role===e)return{source:this._streamingSource,sourceResolution:e,isRequestedSource:!0};const r=t.indexOf(e);if(-1===r)return{source:o,sourceResolution:o.role,isRequestedSource:!0};for(let s=r;s<t.length;s++){const r=t[s],i=`${r.split("-")[0]}ResolutionSource`,n=this.cameraDevice[i];if(n)return n._id===this._streamingSource._id?{source:this._streamingSource,sourceResolution:this._streamingSource.role,isRequestedSource:this._streamingSource.role===e}:{source:n,sourceResolution:r,isRequestedSource:r===e}}}return{source:o,sourceResolution:o.role,isRequestedSource:!1}}onFirstFrameWebrtc(e){const t=this.isAutoSwitchingInProgress,r=e.getVideoTracks()[0];if((!this.firstFrameReceived||t)&&r)if("requestVideoFrameCallback"in this.videoPlayer)this.animationFrameId=this.videoPlayer.requestVideoFrameCallback((()=>{this.onFirstFrame(t)}));else{const e=()=>{this.videoPlayer.readyState>=2&&this.videoPlayer.videoWidth>0?this.onFirstFrame(t):this.animationFrameId=requestAnimationFrame(e)};this.animationFrameId=requestAnimationFrame(e)}}setActiveMode(e,t){(this.activeMode!==e||t)&&(this.activeMode=e,this.dispatchEvent(new Event("onModeChange")))}onFirstFrame(e){this.firstFrameReceived&&!e||(console.log(this.logPrefix,"First frame received"),this.firstFrameReceived=!0,this.dispatchEvent(new Event("onFirstFrame")))}onLoadedData(){console.log(this.logPrefix,"Loaded data"),this.dispatchEvent(new Event("onLoadedData"))}onFinishLoading(e,t){this._finishLoading&&!e||(this._finishLoading=!0,this.dispatchEvent(new Event("onFinishLoading"))),t&&"auto"!==t&&this.setActiveMode(t)}createCodecsList(){const e=[...this.CONFIG.MEDIA.DEFAULT_CODECS],t="undefined"==typeof window?null:/Version\/(\d+).+Safari/.exec(navigator.userAgent);if(t?.[1]){const r=t[1]<"13"?"mp4a.40.2":t[1]<"14"?"flac":"opus";e.splice(e.indexOf(r))}return e}parseCodecs(e){return this.codecList.filter((e=>["video","audio","microphone"].includes(e.indexOf("vc1")>0?"video":"audio"))).filter((t=>e(`video/mp4; codecs="${t}"`))).join()}async probeStream(){try{if(!this.streamingSource)throw new Error("No streaming source set");const e=await this.cameraDevice.probeStream(this.streamingSource._id,{video:!0,audio:["pcma","opus"],microphone:!0});return console.log(this.logPrefix,"Stream probe:",e),e&&(this._hasBackchannel=e.audio.some((e=>"recvonly"===e.direction)),this._hasAudio=e.audio.filter((e=>"sendonly"===e.direction)).length>0,this._hasVideo=e.video.filter((e=>"sendonly"===e.direction)).length>0,this.dispatchEvent(new Event("onStreamProbe"))),e}catch(e){return void console.error("Error probing stream",e)}}isWebRtcCompatibleAudioCodec(e){return["opus","G722","PCMU","PCMA"].includes(e)}isWebRtcCompatibleVideoCodec(e){return["H264","VP8","VP9"].includes(e)||"H265"===e&&this.isWebRTCH265Supported()}createWsSourceName(){if(!this.cameraDevice||!this.streamingSource)throw new Error("Camera device or streaming source not set");return`${this.cameraDevice.name.replace(/ /g,"_").toLowerCase()}_${this.streamingSource.name.replace(/ /g,"_").toLowerCase()}`}isWebRTCH265Supported(){try{console.log(this.logPrefix,"Checking for H.265 support...",RTCRtpSender?.getCapabilities("video"));const e=RTCRtpSender?.getCapabilities("video")?.codecs;return!!e&&e.some((e=>e.mimeType.toLowerCase().includes("h265")||e.mimeType.toLowerCase().includes("hevc")))}catch{return!1}}}class oh extends fa{proxy;config;token;subscription;namespaces;cameraInterfaces;get sources(){return JSON.parse(JSON.stringify(this.cameraSubject.getValue().sources)).map((e=>({...e,snapshot:async t=>this.snapshot(e._id,t),probeStream:async(t,r=!1)=>this.probeStream(e._id,t,r)})))}constructor(e,t,r,s,i){super(s,i),this.proxy=e,this.config=t,this.token=r,this.namespaces=ma.cameraNamespaces(this.id),this.cameraInterfaces=new ba(this.proxy,this.capabilities,this.id)}async init(){this.subscription?.unsubscribe(),this.subscription=this.proxy.subscribe(this.namespaces.cameraSubject,this.onEventMessage.bind(this)),await this.refreshStates()}async close(){await this.cleanup()}createWebRTCSession(e){return new nh(this,this.config,this.token,this.logger,e)}async refreshStates(){const e=await this.cameraControllerProxy(),t=await e.refreshStates();super.updateCamera(t.camera),super.updateCameraState(t.cameraState),super.updateFrameWorkerState(t.frameWorkerState),super.updateCapabilities(t.capabilities);for(const[e,r]of Object.entries(t.states))super.updateStateInternal(e,r,!0)}async cleanup(){this.removeAllListeners(),this.unsubscribe(),this.subscription?.unsubscribe(),this.subscription=void 0,await this.disconnectRpc()}async snapshot(e,t){const r=this.snapshotCache.get(e);if(!t&&r)return r;const s=await this.cameraControllerProxy(),i=await s.snapshot(e,t);return i&&i.byteLength>0?(this.snapshotCache.set(e,i),i):void 0}async probeStream(e,t,r=!1){return(await this.cameraControllerProxy()).probeStream(e,t,r)}async onEventMessage(e){const t=e.data;if("type"in t)switch(t.type){case"removed":this.cleanup();break;case"updated":super.updateCamera(t.data);break;case"cameraState":super.updateCameraState(t.data);break;case"frameWorkerState":super.updateFrameWorkerState(t.data);break;case"capabilities":super.updateCapabilities(t.data)}else{const e=t.stateName,r=t.data.newEvent;super.updateStateInternal(e,r,!0)}}async cameraControllerProxy(){return await this.proxy.createRPCProxy(this.namespaces.cameraControllerRpc,{timeout:1e4})}async disconnectRpc(){await this.proxy.disconnectRPCConnection(this.namespaces.cameraControllerRpc),await this.cameraInterfaces.disconnect()}}class ah{proxy;namespaces;rpcConnections=new Map;constructor(e){this.proxy=e,this.namespaces=ma.coreManagerNamespaces()}async connectToPlugin(e){const t=await this.coreManagerProxy(),r=await t.getPlugin(e);if(r){const e=ma.pluginNamespaces(r.id);try{let t;return this.rpcConnections.has(e.pluginChildRpc)?(t=this.rpcConnections.get(e.pluginChildRpc),await t.connect()):(t=await this.proxy.createRPCConnection(e.pluginChildRpc),this.rpcConnections.set(e.pluginChildRpc,t)),t.createProxy()}catch{return}}}async getFFmpegPath(){const e=await this.coreManagerProxy();return await e.getFFmpegPath()}async getHwaccelInfo(e){const t=await this.coreManagerProxy();return await t.getHwaccelInfo(e)}async getServerAddresses(){const e=await this.coreManagerProxy();return await e.getServerAddresses()}async getIceServers(){const e=await this.coreManagerProxy();return await e.getIceServers()}async coreManagerProxy(){return await this.proxy.createRPCProxy(this.namespaces.coreManagerRpc)}}class ch{proxy;config;token;logger;namespaces;constructor(e,t,r,s){this.proxy=e,this.config=t,this.token=r,this.logger=s,this.namespaces=ma.deviceManagerNamespaces()}async getCamera(e){const t=await this.deviceManagerProxy(),r=await t.getCamera(e,"@camera.ui/client");if(r){const e=new oh(this.proxy,this.config,this.token,r,this.logger);return await e.init(),e}}async deviceManagerProxy(){return await this.proxy.createRPCProxy(this.namespaces.deviceManagerRpc)}}class uh{interceptor;config;logger;proxy;token;_api;get api(){return this._api}constructor(e){this.config=e,this.logger=e.logger??{...console,attention:console.warn,success:console.log},this.interceptor=new s(e.endpoint)}async connect(){if(this._api)return this._api;this.token=await this.login(),this.proxy=new qn({endpoints:this.getNatsEndpoint(this.token),tls:void 0,auth:{user:"secret",password:"secret"},metadata:{id:"@camera-ui/browser-client",name:"@camera-ui/browser-client"},connect:{waitForServer:!0},reconnect:{enabled:!0},metrics:!1,bundledConnection:!0}),await this.proxy.start();const e=new ah(this.proxy),t=new ch(this.proxy,this.config,this.token,this.logger);return this._api={coreManager:e,deviceManager:t},this._api}async disconnect(){if(await(this.proxy?.stop()),this.token)try{await this.interceptor.post("/auth/logout",void 0,{headers:{Authorization:`Bearer ${this.token}`}})}catch{}this._api=void 0,this.token=void 0}async updateCredentials(e){this.config={...this.config,...e}}async login(){if(this.config.username&&this.config.password)try{const e=await this.interceptor.post("/auth/login",{username:this.config.username,password:this.config.password});return(await e.json()).access_token}catch(e){throw new Error(`Invalid credentials: ${e.message}`)}else{if(this.config.skipCheck)return this.config.token;try{return await this.interceptor.get("/auth/check",{headers:{Authorization:`Bearer ${this.config.token}`}}),this.config.token}catch(e){throw new Error(`Invalid token: ${e.message}`)}}}getNatsEndpoint(e){const t=new URL(this.config.endpoint),r=""!==t.port,s="https:"===t.protocol?"wss:":"ws:",i=r?t.port:"https:"===t.protocol?"443":"80";return[`${s}//${t.hostname}:${i}/proxy?token=${e}`]}}export{Vn as CameraDeviceCapability,uh as CameraUiClient,Wn as CuiPluginCapability,Hn as SensorState};
|