@jokio/sdk 0.0.1

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.
@@ -0,0 +1,39 @@
1
+ (function(me,Y){typeof exports=="object"&&typeof module<"u"?Y(exports):typeof define=="function"&&define.amd?define(["exports"],Y):(me=typeof globalThis<"u"?globalThis:me||self,Y(me["@jokio/sdk"]={}))})(this,function(me){"use strict";var Fo=Object.defineProperty;var Bo=(me,Y,Me)=>Y in me?Fo(me,Y,{enumerable:!0,configurable:!0,writable:!0,value:Me}):me[Y]=Me;var h=(me,Y,Me)=>Bo(me,typeof Y!="symbol"?Y+"":Y,Me);function Y(r){const e=new Uint8Array(r);let t="";for(const i of e)t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Me(r){const e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,s=e.padEnd(e.length+t,"="),i=atob(s),n=new ArrayBuffer(i.length),o=new Uint8Array(n);for(let a=0;a<i.length;a++)o[a]=i.charCodeAt(a);return n}function is(){return ni.stubThis((globalThis==null?void 0:globalThis.PublicKeyCredential)!==void 0&&typeof globalThis.PublicKeyCredential=="function")}const ni={stubThis:r=>r};function Vs(r){const{id:e}=r;return{...r,id:Me(e),transports:r.transports}}function Ws(r){return r==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(r)}class ce extends Error{constructor({message:e,code:t,cause:s,name:i}){super(e,{cause:s}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i??s.name,this.code=t}}function oi({error:r,options:e}){var s,i,n;const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ce({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else if(r.name==="ConstraintError"){if(((s=t.authenticatorSelection)==null?void 0:s.requireResidentKey)===!0)return new ce({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:r});if(e.mediation==="conditional"&&((i=t.authenticatorSelection)==null?void 0:i.userVerification)==="required")return new ce({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:r});if(((n=t.authenticatorSelection)==null?void 0:n.userVerification)==="required")return new ce({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:r})}else{if(r.name==="InvalidStateError")return new ce({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:r});if(r.name==="NotAllowedError")return new ce({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="NotSupportedError")return t.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new ce({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:r}):new ce({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:r});if(r.name==="SecurityError"){const o=globalThis.location.hostname;if(Ws(o)){if(t.rp.id!==o)return new ce({message:`The RP ID "${t.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new ce({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="TypeError"){if(t.user.id.byteLength<1||t.user.id.byteLength>64)return new ce({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:r})}else if(r.name==="UnknownError")return new ce({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return r}class ai{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){const t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const Ys=new ai,ci=["cross-platform","platform"];function Xs(r){if(r&&!(ci.indexOf(r)<0))return r}async function hi(r){var j;!r.optionsJSON&&r.challenge&&(console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),r={optionsJSON:r});const{optionsJSON:e,useAutoRegister:t=!1}=r;if(!is())throw new Error("WebAuthn is not supported in this browser");const s={...e,challenge:Me(e.challenge),user:{...e.user,id:Me(e.user.id)},excludeCredentials:(j=e.excludeCredentials)==null?void 0:j.map(Vs)},i={};t&&(i.mediation="conditional"),i.publicKey=s,i.signal=Ys.createNewAbortSignal();let n;try{n=await navigator.credentials.create(i)}catch(T){throw oi({error:T,options:i})}if(!n)throw new Error("Registration was not completed");const{id:o,rawId:a,response:d,type:p}=n;let _;typeof d.getTransports=="function"&&(_=d.getTransports());let y;if(typeof d.getPublicKeyAlgorithm=="function")try{y=d.getPublicKeyAlgorithm()}catch(T){ns("getPublicKeyAlgorithm()",T)}let x;if(typeof d.getPublicKey=="function")try{const T=d.getPublicKey();T!==null&&(x=Y(T))}catch(T){ns("getPublicKey()",T)}let P;if(typeof d.getAuthenticatorData=="function")try{P=Y(d.getAuthenticatorData())}catch(T){ns("getAuthenticatorData()",T)}return{id:o,rawId:Y(a),response:{attestationObject:Y(d.attestationObject),clientDataJSON:Y(d.clientDataJSON),transports:_,publicKeyAlgorithm:y,publicKey:x,authenticatorData:P},type:p,clientExtensionResults:n.getClientExtensionResults(),authenticatorAttachment:Xs(n.authenticatorAttachment)}}function ns(r,e){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${r}. You should report this error to them.
2
+ `,e)}function ui(){if(!is())return os.stubThis(new Promise(e=>e(!1)));const r=globalThis.PublicKeyCredential;return(r==null?void 0:r.isConditionalMediationAvailable)===void 0?os.stubThis(new Promise(e=>e(!1))):os.stubThis(r.isConditionalMediationAvailable())}const os={stubThis:r=>r};function li({error:r,options:e}){const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ce({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new ce({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){const s=globalThis.location.hostname;if(Ws(s)){if(t.rpId!==s)return new ce({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new ce({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new ce({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return r}async function fi(r){var P,j;!r.optionsJSON&&r.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),r={optionsJSON:r});const{optionsJSON:e,useBrowserAutofill:t=!1,verifyBrowserAutofillInput:s=!0}=r;if(!is())throw new Error("WebAuthn is not supported in this browser");let i;((P=e.allowCredentials)==null?void 0:P.length)!==0&&(i=(j=e.allowCredentials)==null?void 0:j.map(Vs));const n={...e,challenge:Me(e.challenge),allowCredentials:i},o={};if(t){if(!await ui())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&s)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');o.mediation="conditional",n.allowCredentials=[]}o.publicKey=n,o.signal=Ys.createNewAbortSignal();let a;try{a=await navigator.credentials.get(o)}catch(T){throw li({error:T,options:o})}if(!a)throw new Error("Authentication was not completed");const{id:d,rawId:p,response:_,type:y}=a;let x;return _.userHandle&&(x=Y(_.userHandle)),{id:d,rawId:Y(p),response:{authenticatorData:Y(_.authenticatorData),clientDataJSON:Y(_.clientDataJSON),signature:Y(_.signature),userHandle:x},type:y,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:Xs(a.authenticatorAttachment)}}class Zs{constructor(e){this.config=e}async requestEmailLogin(e,t){return await fetch(this.config.authUrl+`/email-verification-request/${e}?returnUrl=${t}`,{credentials:"include"}).then(ut)}async completeEmailLogin(e,t){return await fetch(this.config.authUrl+`/email-verification-complete/${e}/${t}`,{credentials:"include"}).then(ut)}async requestPasskeyLogin(e="",t=!1,s=!1){var a;const i=await fetch(this.config.authUrl+`/webauth-challenge-request?registration=${t?"true":""}&displayName=${e}`,{credentials:"include"}).then(ut);let n;try{(a=i.user)!=null&&a.id?n=await hi({optionsJSON:i}):n=await fi({optionsJSON:i})}catch(d){throw d.name==="InvalidStateError"?alert("Error: Authenticator was probably already registered by user"):alert(d.message),d}return await fetch(this.config.authUrl+`/webauth-challenge-complete?displayName=${e}&addAsAdditionalDevice=${s?"true":""}`,{method:"POST",body:JSON.stringify(n),headers:{"Content-Type":"application/json"},credentials:"include"}).then(ut)}async signOut(){return await fetch(this.config.authUrl+"/sign-out",{credentials:"include"}).then(ut)}}const ut=async r=>{const e=await r.json();if(!r.ok)throw new Error(e.message);return e},as=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),Qs=r=>new Uint8Array(r.match(/.{1,2}/g).map(e=>parseInt(e,16))),er=r=>btoa(String.fromCharCode(...new Uint8Array(r))),di=r=>Uint8Array.from(atob(r),e=>e.charCodeAt(0)).buffer,pi=async r=>await crypto.subtle.digest("SHA-256",r),mi=new TextEncoder;class bi{async createSessionKeyPair(){return await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey","deriveBits"])}async exportPublicKey(e){const t=await crypto.subtle.exportKey("spki",e);return er(t)}async deriveAESKey(e,t){const s=di(t),i=await crypto.subtle.importKey("spki",s,{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveKey({name:"ECDH",public:i},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async exportRawKey(e){const t=await crypto.subtle.exportKey("raw",e);return as(new Uint8Array(t))}async encrypt(e,t){const s=crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},t,i);return`${as(new Uint8Array(n))}_${as(s)}`}async decrypt(e,t){const s=e.split("_"),i=Qs(s[0]).buffer,n=Qs(s[1]),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},t,i);return new TextDecoder().decode(o)}async hashString(e){const t=await pi(mi.encode(e).buffer);return er(t)}}function tr(r){const e=new Blob([r],{type:"audio/mpeg"}),t=URL.createObjectURL(e),s=new Audio;return s.src=t,s.onended=()=>{URL.revokeObjectURL(t)},s}class gi{async getAudioBuffer(e,t,s){const i=[],n=crypto.randomUUID();return new Promise((o,a)=>{const d=new WebSocket(`${jt.WSS_URL}?trustedclienttoken=${jt.TRUSTED_CLIENT_TOKEN}&ConnectionId=${n}`);d.binaryType="arraybuffer";const p=yi(e,t,s);d.addEventListener("open",()=>{const _=_i();d.send(_);const y=`X-RequestId:${n}\r
3
+ Content-Type:application/ssml+xml\r
4
+ X-Timestamp:${new Date().toISOString()}Z\r
5
+ Path:ssml\r
6
+ \r
7
+ `+p;d.send(y)}),d.addEventListener("message",_=>{const y=_.data;if(y instanceof ArrayBuffer){const x=new Uint8Array(y),P=new TextEncoder().encode(`Path:audio\r
8
+ `),j=wi(x,P);if(j!==-1){const J=x.subarray(j+P.length);i.push(J)}new TextDecoder().decode(x).includes("Path:turn.end")&&d.close()}else y.includes("Path:turn.end")&&d.close()}),d.addEventListener("close",()=>{if(!i.length){a("No audio data available to save.");return}const _=i.reduce((P,j)=>P+j.length,0),y=new Uint8Array(_);let x=0;for(const P of i)y.set(P,x),x+=P.length;o(y.buffer)}),d.addEventListener("error",_=>{a(_)})})}async getAudio(e,t,s){return this.getAudioBuffer(e,t,s).then(i=>tr(i))}async getVoices(){return(await(await fetch(`${jt.VOICES_URL}?trustedclienttoken=${jt.TRUSTED_CLIENT_TOKEN}`)).json()).map(s=>({id:s.ShortName,locale:s.Locale,description:s.FriendlyName}))}}const jt={TRUSTED_CLIENT_TOKEN:"6A5AA1D4EAFF4E9FB37E23D68491D6F4",WSS_URL:"wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1",VOICES_URL:"https://speech.platform.bing.com/consumer/speech/synthesize/readaloud/voices/list"},_i=()=>`X-Timestamp:${new Date().toISOString()}Z\r
9
+ Content-Type:application/json; charset=utf-8\r
10
+ Path:speech.config\r
11
+ \r
12
+ {"context":{"synthesis":{"audio":{"metadataoptions":{"sentenceBoundaryEnabled":false,"wordBoundaryEnabled":true},"outputFormat":"audio-24khz-48kbitrate-mono-mp3"}}}}`,yi=(r,e,t={})=>{var o;t.pitch=(o=t.pitch)==null?void 0:o.replace("hz","Hz");const s=t.pitch||"0Hz",i=t.rate||"0%",n=t.volume||"0%";return`<speak version='1.0' xml:lang='en-US'><voice name='${e}'><prosody pitch='${s}' rate='${i}' volume='${n}'>${r}</prosody></voice></speak>`};function wi(r,e){for(let t=0;t<=r.length-e.length;t++){let s=!0;for(let i=0;i<e.length;i++)if(r[t+i]!==e[i]){s=!1;break}if(s)return t}return-1}const be=new Uint8Array(0),Ge=new TextEncoder,ge=new TextDecoder;function xi(...r){let e=0;for(let i=0;i<r.length;i++)e+=r[i].length;const t=new Uint8Array(e);let s=0;for(let i=0;i<r.length;i++)t.set(r[i],s),s+=r[i].length;return t}function lt(...r){const e=[];for(let t=0;t<r.length;t++)e.push(Ge.encode(r[t]));return e.length===0?be:e.length===1?e[0]:xi(...e)}function sr(r){return!r||r.length===0?"":ge.decode(r)}const rr="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",ir=36,Si=0xcfd41b9100000,nr=33,vi=333,or=22;function Ei(r){for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*255)}function Ai(r){var e;(e=globalThis==null?void 0:globalThis.crypto)!=null&&e.getRandomValues?globalThis.crypto.getRandomValues(r):Ei(r)}class Pi{constructor(){h(this,"buf");h(this,"seq");h(this,"inc");h(this,"inited");this.buf=new Uint8Array(or),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){this.seq=Math.floor(Math.random()*Si),this.inc=Math.floor(Math.random()*(vi-nr)+nr)}setPre(){const e=new Uint8Array(12);Ai(e);for(let t=0;t<12;t++){const s=e[t]%36;this.buf[t]=rr.charCodeAt(s)}}fillSeq(){let e=this.seq;for(let t=or-1;t>=12;t--)this.buf[t]=rr.charCodeAt(e%ir),e=Math.floor(e/ir)}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()}}const Le=new Pi;var Se;(function(r){r.Disconnect="disconnect",r.Reconnect="reconnect",r.Update="update",r.LDM="ldm",r.Error="error"})(Se||(Se={}));var Fe;(function(r){r.Reconnecting="reconnecting",r.PingTimer="pingTimer",r.StaleConnection="staleConnection",r.ClientInitiatedReconnect="client initiated reconnect"})(Fe||(Fe={}));var k;(function(r){r.ApiError="BAD API",r.BadAuthentication="BAD_AUTHENTICATION",r.BadCreds="BAD_CREDS",r.BadHeader="BAD_HEADER",r.BadJson="BAD_JSON",r.BadPayload="BAD_PAYLOAD",r.BadSubject="BAD_SUBJECT",r.Cancelled="CANCELLED",r.ConnectionClosed="CONNECTION_CLOSED",r.ConnectionDraining="CONNECTION_DRAINING",r.ConnectionRefused="CONNECTION_REFUSED",r.ConnectionTimeout="CONNECTION_TIMEOUT",r.Disconnect="DISCONNECT",r.InvalidOption="INVALID_OPTION",r.InvalidPayload="INVALID_PAYLOAD",r.MaxPayloadExceeded="MAX_PAYLOAD_EXCEEDED",r.NoResponders="503",r.NotFunction="NOT_FUNC",r.RequestError="REQUEST_ERROR",r.ServerOptionNotAvailable="SERVER_OPT_NA",r.SubClosed="SUB_CLOSED",r.SubDraining="SUB_DRAINING",r.Timeout="TIMEOUT",r.Tls="TLS",r.Unknown="UNKNOWN_ERROR",r.WssRequired="WSS_REQUIRED",r.JetStreamInvalidAck="JESTREAM_INVALID_ACK",r.JetStream404NoMessages="404",r.JetStream408RequestTimeout="408",r.JetStream409MaxAckPendingExceeded="409",r.JetStream409="409",r.JetStreamNotEnabled="503",r.JetStreamIdleHeartBeat="IDLE_HEARTBEAT",r.AuthorizationViolation="AUTHORIZATION_VIOLATION",r.AuthenticationExpired="AUTHENTICATION_EXPIRED",r.ProtocolError="NATS_PROTOCOL_ERR",r.PermissionsViolation="PERMISSIONS_VIOLATION",r.AuthenticationTimeout="AUTHENTICATION_TIMEOUT",r.AccountExpired="ACCOUNT_EXPIRED"})(k||(k={}));function ki(r){return typeof r.code=="string"}class ar{constructor(){h(this,"messages");this.messages=new Map,this.messages.set(k.InvalidPayload,"Invalid payload type - payloads can be 'binary', 'string', or 'json'"),this.messages.set(k.BadJson,"Bad JSON"),this.messages.set(k.WssRequired,"TLS is required, therefore a secure websocket connection is also required")}static getMessage(e){return Oi.getMessage(e)}getMessage(e){return this.messages.get(e)||e}}const Oi=new ar;class N extends Error{constructor(t,s,i){super(t);h(this,"name");h(this,"message");h(this,"code");h(this,"permissionContext");h(this,"chainedError");h(this,"api_error");this.name="NatsError",this.message=t,this.code=s,this.chainedError=i}static errorForCode(t,s){const i=ar.getMessage(t);return new N(i,t,s)}isAuthError(){return this.code===k.AuthenticationExpired||this.code===k.AuthorizationViolation||this.code===k.AccountExpired}isAuthTimeout(){return this.code===k.AuthenticationTimeout}isPermissionError(){return this.code===k.PermissionsViolation}isProtocolError(){return this.code===k.ProtocolError}isJetStreamError(){return this.api_error!==void 0}jsError(){return this.api_error?this.api_error:null}}var _e;(function(r){r[r.Exact=0]="Exact",r[r.CanonicalMIME=1]="CanonicalMIME",r[r.IgnoreCase=2]="IgnoreCase"})(_e||(_e={}));var ke;(function(r){r.Timer="timer",r.Count="count",r.JitterTimer="jitterTimer",r.SentinelMsg="sentinelMsg"})(ke||(ke={}));var ft;(function(r){r.STATS="io.nats.micro.v1.stats_response",r.INFO="io.nats.micro.v1.info_response",r.PING="io.nats.micro.v1.ping_response"})(ft||(ft={}));const It="Nats-Service-Error",Rt="Nats-Service-Error-Code";class Nt extends Error{constructor(t,s){super(s);h(this,"code");this.code=t}static isServiceError(t){return Nt.toServiceError(t)!==null}static toServiceError(t){var i,n;const s=((i=t==null?void 0:t.headers)==null?void 0:i.get(Rt))||"";if(s!==""){const o=parseInt(s)||400,a=((n=t==null?void 0:t.headers)==null?void 0:n.get(It))||"";return new Nt(o,a.length?a:s)}return null}}function $e(r=""){if(r=r||"_INBOX",typeof r!="string")throw new Error("prefix must be a string");return r.split(".").forEach(e=>{if(e==="*"||e===">")throw new Error(`inbox prefixes cannot have wildcards '${r}'`)}),`${r}.${Le.next()}`}const cs="127.0.0.1";var Be;(function(r){r.PING="PING",r.STATS="STATS",r.INFO="INFO"})(Be||(Be={}));function Tt(r,...e){for(let t=0;t<e.length;t++){const s=e[t];Object.keys(s).forEach(function(i){r[i]=s[i]})}return r}function Mt(r){return ge.decode(r).replace(/\n/g,"␊").replace(/\r/g,"␍")}function Ye(r,e=!0){const t=e?N.errorForCode(k.Timeout):null;let s,i;const n=new Promise((o,a)=>{s={cancel:()=>{i&&clearTimeout(i)}},i=setTimeout(()=>{a(t===null?N.errorForCode(k.Timeout):t)},r)});return Object.assign(n,s)}function Xe(r=0){let e;const t=new Promise(s=>{const i=setTimeout(()=>{s()},r);e={cancel:()=>{i&&clearTimeout(i)}}});return Object.assign(t,e)}function z(){let r={};const e=new Promise((t,s)=>{r={resolve:t,reject:s}});return Object.assign(e,r)}function cr(r){for(let e=r.length-1;e>0;e--){const t=Math.floor(Math.random()*(e+1));[r[e],r[t]]=[r[t],r[e]]}return r}function Ci(r){return r===0?0:Math.floor(r/2+Math.random()*r)}function hs(r=[0,250,250,500,500,3e3,5e3]){Array.isArray(r)||(r=[0,250,250,500,500,3e3,5e3]);const e=r.length-1;return{backoff(t){return Ci(t>e?r[e]:r[t])}}}function G(r){return r*1e6}function us(r){return Math.floor(r/1e6)}function hr(r){let s=!0;const i=new Array(r.length);for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);if(o===58||o<33||o>126)throw new N(`'${r[n]}' is not a valid character for a header key`,k.BadHeader);s&&97<=o&&o<=122?o-=32:!s&&65<=o&&o<=90&&(o+=32),i[n]=o,s=o==45}return String.fromCharCode(...i)}function Ue(r=0,e=""){if(r===0&&e!==""||r>0&&e==="")throw new Error("setting status requires both code and description");return new De(r,e)}const ls="NATS/1.0";class De{constructor(e=0,t=""){h(this,"_code");h(this,"headers");h(this,"_description");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,s]of this.headers){const i=e.values(t);if(s.length!==i.length)return!1;const n=[...s].sort(),o=[...i].sort();for(let a=0;a<n.length;a++)if(n[a]!==o[a])return!1}return!0}return!1}static decode(e){const t=new De,i=ge.decode(e).split(`\r
13
+ `),n=i[0];if(n!==ls){let o=n.replace(ls,"").trim();if(o.length>0){t._code=parseInt(o,10),isNaN(t._code)&&(t._code=0);const a=t._code.toString();o=o.replace(a,""),t._description=o.trim()}}return i.length>=1&&i.slice(1).map(o=>{if(o){const a=o.indexOf(":");if(a>-1){const d=o.slice(0,a),p=o.slice(a+1).trim();t.append(d,p)}}}),t}toString(){if(this.headers.size===0&&this._code===0)return"";let e=ls;this._code>0&&this._description!==""&&(e+=` ${this._code} ${this._description}`);for(const[t,s]of this.headers)for(let i=0;i<s.length;i++)e=`${e}\r
14
+ ${t}: ${s[i]}`;return`${e}\r
15
+ \r
16
+ `}encode(){return Ge.encode(this.toString())}static validHeaderValue(e){if(/[\r\n]/.test(e))throw new N("invalid header value - \\r and \\n are not allowed.",k.BadHeader);return e.trim()}keys(){const e=[];for(const t of this.headers.keys())e.push(t);return e}findKeys(e,t=_e.Exact){const s=this.keys();switch(t){case _e.Exact:return s.filter(i=>i===e);case _e.CanonicalMIME:return e=hr(e),s.filter(i=>i===e);default:{const i=e.toLowerCase();return s.filter(n=>i===n.toLowerCase())}}}get(e,t=_e.Exact){const s=this.findKeys(e,t);if(s.length){const i=this.headers.get(s[0]);if(i)return Array.isArray(i)?i[0]:i}return""}last(e,t=_e.Exact){const s=this.findKeys(e,t);if(s.length){const i=this.headers.get(s[0]);if(i)return Array.isArray(i)?i[i.length-1]:i}return""}has(e,t=_e.Exact){return this.findKeys(e,t).length>0}set(e,t,s=_e.Exact){this.delete(e,s),this.append(e,t,s)}append(e,t,s=_e.Exact){const i=hr(e);s===_e.CanonicalMIME&&(e=i);const n=this.findKeys(e,s);e=n.length>0?n[0]:e;const o=De.validHeaderValue(t);let a=this.headers.get(e);a||(a=[],this.headers.set(e,a)),a.push(o)}values(e,t=_e.Exact){const s=[];return this.findKeys(e,t).forEach(n=>{const o=this.headers.get(n);o&&s.push(...o)}),s}delete(e,t=_e.Exact){this.findKeys(e,t).forEach(i=>{this.headers.delete(i)})}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 t=new De;for(const s in e)t.headers.set(s,e[s]);return t}}function ur(){return{encode(r){return Ge.encode(r)},decode(r){return ge.decode(r)}}}function ve(r){return{encode(e){try{return e===void 0&&(e=null),Ge.encode(JSON.stringify(e))}catch(t){throw N.errorForCode(k.BadJson,t)}},decode(e){try{return JSON.parse(ge.decode(e),r)}catch(t){throw N.errorForCode(k.BadJson,t)}}}}function lr(r){var e;return r&&r.data.length===0&&((e=r.headers)==null?void 0:e.code)===503?N.errorForCode(k.NoResponders):null}class fs{constructor(e,t,s){h(this,"_headers");h(this,"_msg");h(this,"_rdata");h(this,"_reply");h(this,"_subject");h(this,"publisher");this._msg=e,this._rdata=t,this.publisher=s}get subject(){return this._subject?this._subject:(this._subject=ge.decode(this._msg.subject),this._subject)}get reply(){return this._reply?this._reply:(this._reply=ge.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=De.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=be,t){return this.reply?(this.publisher.publish(this.reply,e,t),!0):!1}size(){var i;const e=this._msg.subject.length,t=((i=this._msg.reply)==null?void 0:i.length)||0,s=this._msg.size===-1?0:this._msg.size;return e+t+s}json(e){return ve(e).decode(this.data)}string(){return ge.decode(this.data)}requestInfo(){var t;const e=(t=this.headers)==null?void 0:t.get("Nats-Request-Info");return e?JSON.parse(e,function(s,i){return(s==="start"||s==="stop")&&i!==""?new Date(Date.parse(i)):i}):null}}h(fs,"jc");function Ze(r){return $t("durable",r)}function le(r){return $t("stream",r)}function $t(r,e=""){if(e==="")throw Error(`${r} name required`);return[".","*",">","/","\\"," "," ",`
17
+ `,"\r"].forEach(s=>{if(e.indexOf(s)!==-1){switch(s){case`
18
+ `:s="\\n";break;case"\r":s="\\r";break;case" ":s="\\t";break}throw Error(`invalid ${r} name - ${r} name cannot contain '${s}'`)}}),""}function dt(r,e=""){if(e==="")throw Error(`${r} name required`);const t=ji(e);if(t.length)throw new Error(`invalid ${r} name - ${r} name ${t}`)}function ji(r=""){if(r==="")throw Error("name required");const e=/^[-\w]+$/g;if(r.match(e)===null){for(const s of r.split(""))if(s.match(e)===null)return`cannot contain '${s}'`}return""}function ds(r){if(r.data.length>0)return!1;const e=r.headers;return e?e.code>=100&&e.code<200:!1}function ps(r){var e;return ds(r)&&((e=r.headers)==null?void 0:e.description)==="Idle Heartbeat"}function Ii(r,e,t){const s=Ue(r,e),i={hdr:1,sid:0,size:0},n=new fs(i,be,{});return n._headers=s,n._subject=t,n}function Qe(r){if(r.data.length!==0)return null;const e=r.headers;return e?fr(e.code,e.description):null}var Ee;(function(r){r.MaxBatchExceeded="exceeded maxrequestbatch of",r.MaxExpiresExceeded="exceeded maxrequestexpires of",r.MaxBytesExceeded="exceeded maxrequestmaxbytes of",r.MaxMessageSizeExceeded="message size exceeds maxbytes",r.PushConsumer="consumer is push based",r.MaxWaitingExceeded="exceeded maxwaiting",r.IdleHeartbeatMissed="idle heartbeats missed",r.ConsumerDeleted="consumer deleted"})(Ee||(Ee={}));function Ri(r){return r.code!==k.JetStream409?!1:[Ee.MaxBatchExceeded,Ee.MaxExpiresExceeded,Ee.MaxBytesExceeded,Ee.MaxMessageSizeExceeded,Ee.PushConsumer,Ee.IdleHeartbeatMissed,Ee.ConsumerDeleted].find(t=>r.message.indexOf(t)!==-1)!==void 0}function fr(r,e=""){if(r<300)return null;switch(e=e.toLowerCase(),r){case 404:return new N(e,k.JetStream404NoMessages);case 408:return new N(e,k.JetStream408RequestTimeout);case 409:{const t=e.startsWith(Ee.IdleHeartbeatMissed)?k.JetStreamIdleHeartBeat:k.JetStream409;return new N(e,t)}case 503:return N.errorForCode(k.JetStreamNotEnabled,new Error(e));default:return e===""&&(e=k.Unknown),new N(e,`${r}`)}}class re{constructor(){h(this,"inflight");h(this,"processed");h(this,"received");h(this,"noIterator");h(this,"iterClosed");h(this,"done");h(this,"signal");h(this,"yields");h(this,"filtered");h(this,"pendingFiltered");h(this,"ingestionFilterFn");h(this,"protocolFilterFn");h(this,"dispatchedFn");h(this,"ctx");h(this,"_data");h(this,"err");h(this,"time");h(this,"yielding");this.inflight=0,this.filtered=0,this.pendingFiltered=0,this.processed=0,this.received=0,this.noIterator=!1,this.done=!1,this.signal=z(),this.yields=[],this.iterClosed=z(),this.time=0,this.yielding=!1}[Symbol.asyncIterator](){return this.iterate()}push(e){if(this.done)return;if(typeof e=="function"){this.yields.push(e),this.signal.resolve();return}const{ingest:t,protocol:s}=this.ingestionFilterFn?this.ingestionFilterFn(e,this.ctx||this):{ingest:!0,protocol:!1};t&&(s&&(this.filtered++,this.pendingFiltered++),this.yields.push(e),this.signal.resolve())}async*iterate(){if(this.noIterator)throw new N("unsupported iterator",k.ApiError);if(this.yielding)throw new N("already yielding",k.ApiError);this.yielding=!0;try{for(;;){if(this.yields.length===0&&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(typeof e[t]=="function"){const i=e[t];try{i()}catch(n){throw n}if(this.err)throw this.err;continue}if(this.protocolFilterFn?this.protocolFilterFn(e[t]):!0){this.processed++;const i=Date.now();yield e[t],this.time=Date.now()-i,this.dispatchedFn&&e[t]&&this.dispatchedFn(e[t])}else this.pendingFiltered--;this.inflight--}if(this.done)break;this.yields.length===0&&(e.length=0,this.yields=e,this.signal=z())}}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 ms{constructor(e,t,s={maxOut:2}){h(this,"interval");h(this,"maxOut");h(this,"cancelAfter");h(this,"timer");h(this,"autoCancelTimer");h(this,"last");h(this,"missed");h(this,"count");h(this,"callback");this.interval=e,this.maxOut=(s==null?void 0:s.maxOut)||2,this.cancelAfter=(s==null?void 0:s.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,s=2){this.interval=e,this.maxOut=s,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{this.callback(this.missed)===!0&&this.cancel()}catch(e){console.log(e)}},this.interval)}}var bs;(function(r){r.Limits="limits",r.Interest="interest",r.Workqueue="workqueue"})(bs||(bs={}));var pt;(function(r){r.Old="old",r.New="new"})(pt||(pt={}));var gs;(function(r){r.File="file",r.Memory="memory"})(gs||(gs={}));var Z;(function(r){r.All="all",r.Last="last",r.New="new",r.StartSequence="by_start_sequence",r.StartTime="by_start_time",r.LastPerSubject="last_per_subject"})(Z||(Z={}));var ie;(function(r){r.None="none",r.All="all",r.Explicit="explicit",r.NotSet=""})(ie||(ie={}));var et;(function(r){r.Instant="instant",r.Original="original"})(et||(et={}));var He;(function(r){r.None="none",r.S2="s2"})(He||(He={}));var Ut;(function(r){r.CreateOrUpdate="",r.Update="update",r.Create="create"})(Ut||(Ut={}));function Ni(r,e={}){return Object.assign({name:r,deliver_policy:Z.All,ack_policy:ie.Explicit,ack_wait:G(30*1e3),replay_policy:et.Instant},e)}var dr;(function(r){r.API="api_audit",r.StreamAction="stream_action",r.ConsumerAction="consumer_action",r.SnapshotCreate="snapshot_create",r.SnapshotComplete="snapshot_complete",r.RestoreCreate="restore_create",r.RestoreComplete="restore_complete",r.MaxDeliver="max_deliver",r.Terminated="terminated",r.Ack="consumer_ack",r.StreamLeaderElected="stream_leader_elected",r.StreamQuorumLost="stream_quorum_lost",r.ConsumerLeaderElected="consumer_leader_elected",r.ConsumerQuorumLost="consumer_quorum_lost"})(dr||(dr={}));var fe;(function(r){r.StreamSourceHdr="Nats-Stream-Source",r.LastConsumerSeqHdr="Nats-Last-Consumer",r.LastStreamSeqHdr="Nats-Last-Stream",r.ConsumerStalledHdr="Nats-Consumer-Stalled",r.MessageSizeHdr="Nats-Msg-Size",r.RollupHdr="Nats-Rollup",r.RollupValueSubject="sub",r.RollupValueAll="all",r.PendingMessagesHdr="Nats-Pending-Messages",r.PendingBytesHdr="Nats-Pending-Bytes"})(fe||(fe={}));var Oe;(function(r){r.LastValue="",r.AllHistory="history",r.UpdatesOnly="updates"})(Oe||(Oe={}));var tt;(function(r){r.Stream="Nats-Stream",r.Sequence="Nats-Sequence",r.TimeStamp="Nats-Time-Stamp",r.Subject="Nats-Subject"})(tt||(tt={}));var pr;(function(r){r.Stream="Nats-Stream",r.Subject="Nats-Subject",r.Sequence="Nats-Sequence",r.LastSequence="Nats-Last-Sequence",r.Size="Nats-Msg-Size"})(pr||(pr={}));const ye="KV_";class Ti{constructor(e){h(this,"config");h(this,"ordered");h(this,"mack");h(this,"stream");h(this,"callbackFn");h(this,"max");h(this,"qname");h(this,"isBind");h(this,"filters");this.stream="",this.mack=!1,this.ordered=!1,this.config=Ni("",e||{})}getOpts(){var t;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&&((t=e.config.filter_subjects)==null||t.forEach(s=>{this.filterSubject(s)}),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?ie.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 Ze(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=Z.StartSequence,this.config.opt_start_seq=e,this}startTime(e){return this.config.deliver_policy=Z.StartTime,this.config.opt_start_time=e.toISOString(),this}deliverAll(){return this.config.deliver_policy=Z.All,this}deliverLastPerSubject(){return this.config.deliver_policy=Z.LastPerSubject,this}deliverLast(){return this.config.deliver_policy=Z.Last,this}deliverNew(){return this.config.deliver_policy=Z.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=ie.None,this}ackAll(){return this.config.ack_policy=ie.All,this}ackExplicit(){return this.config.ack_policy=ie.Explicit,this}ackWait(e){return this.config.ack_wait=G(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=et.Instant,this}replayOriginal(){return this.config.replay_policy=et.Original,this}sample(e){if(e=Math.trunc(e),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=G(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=G(e),this}maxPullBatch(e){return this.config.max_batch=e,this}maxPullRequestExpires(e){return this.config.max_expires=G(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 Je(r){return new Ti(r)}function mr(r){return typeof r.getOpts=="function"}class Mi{static encode(e){if(typeof e=="string")return btoa(e);const t=Array.from(e);return btoa(String.fromCharCode(...t))}static decode(e,t=!1){const s=atob(e);return t?Uint8Array.from(s,i=>i.charCodeAt(0)):s}}class st{static encode(e){return st.toB64URLEncoding(Mi.encode(e))}static decode(e,t=!1){return st.decode(st.fromB64URLEncoding(e),t)}static toB64URLEncoding(e){return e.replace(/\+/g,"-").replace(/\//g,"_")}static fromB64URLEncoding(e){return e.replace(/_/g,"/").replace(/-/g,"+")}}class rt{constructor(){h(this,"buffers");h(this,"byteLength");this.buffers=[],this.byteLength=0}static concat(...e){let t=0;for(let n=0;n<e.length;n++)t+=e[n].length;const s=new Uint8Array(t);let i=0;for(let n=0;n<e.length;n++)s.set(e[n],i),i+=e[n].length;return s}static fromAscii(e){return e||(e=""),Ge.encode(e)}static toAscii(e){return ge.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 s=0;s<this.buffers.length;s++)e.set(this.buffers[s],t),t+=this.buffers[s].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 s=this.byteLength;(e===void 0||e>s)&&(e=s);const i=t.subarray(0,e);return s>e&&this.buffers.push(t.subarray(e)),this.byteLength=s-e,i}}return new Uint8Array(0)}fill(e,...t){e&&(this.buffers.push(e),this.byteLength+=e.length);for(let s=0;s<t.length;s++)t[s]&&t[s].length&&(this.buffers.push(t[s]),this.byteLength+=t[s].length)}peek(){return this.buffers.length?(this.pack(),this.buffers[0]):new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}function $i(r,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(s){if(s!=="default"&&!(s in r)){var i=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(r,s,i.get?i:{enumerable:!0,get:function(){return t[s]}})}})}),Object.freeze(r)}var Ui=typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{},mt=Ui.performance||{};mt.now||mt.mozNow||mt.msNow||mt.oNow||mt.webkitNow;var br={versions:{}},qi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Li(r){if(r.__esModule)return r;var e=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(r).forEach(function(t){var s=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:function(){return r[t]}})}),e}var _s,qt={exports:{}},gr={},_r=Li($i({__proto__:null,default:gr},[gr]));_s=qt,function(){var r="input is invalid type",e=typeof window=="object",t=e?window:{};t.JS_SHA256_NO_WINDOW&&(e=!1);var s=!e&&typeof self=="object",i=!t.JS_SHA256_NO_NODE_JS&&br.versions&&br.versions.node;i?t=qi:s&&(t=self);var n=!t.JS_SHA256_NO_COMMON_JS&&_s.exports,o=!t.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",a="0123456789abcdef".split(""),d=[-2147483648,8388608,32768,128],p=[24,16,8,0],_=[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],y=["hex","array","digest","arrayBuffer"],x=[];!t.JS_SHA256_NO_NODE_JS&&Array.isArray||(Array.isArray=function(w){return Object.prototype.toString.call(w)==="[object Array]"}),!o||!t.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(w){return typeof w=="object"&&w.buffer&&w.buffer.constructor===ArrayBuffer});var P=function(w,I){return function(F){return new q(I,!0).update(F)[w]()}},j=function(w){var I=P("hex",w);i&&(I=T(I,w)),I.create=function(){return new q(w)},I.update=function(A){return I.create().update(A)};for(var F=0;F<y.length;++F){var R=y[F];I[R]=P(R,w)}return I},T=function(w,I){var F,R=_r,A=_r.Buffer,$=I?"sha224":"sha256";return F=A.from&&!t.JS_SHA256_NO_BUFFER_FROM?A.from:function(L){return new A(L)},function(L){if(typeof L=="string")return R.createHash($).update(L,"utf8").digest("hex");if(L==null)throw new Error(r);return L.constructor===ArrayBuffer&&(L=new Uint8Array(L)),Array.isArray(L)||ArrayBuffer.isView(L)||L.constructor===A?R.createHash($).update(F(L)).digest("hex"):w(L)}},J=function(w,I){return function(F,R){return new X(F,I,!0).update(R)[w]()}},Q=function(w){var I=J("hex",w);I.create=function(A){return new X(A,w)},I.update=function(A,$){return I.create(A).update($)};for(var F=0;F<y.length;++F){var R=y[F];I[R]=J(R,w)}return I};function q(w,I){I?(x[0]=x[16]=x[1]=x[2]=x[3]=x[4]=x[5]=x[6]=x[7]=x[8]=x[9]=x[10]=x[11]=x[12]=x[13]=x[14]=x[15]=0,this.blocks=x):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],w?(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=w}function X(w,I,F){var R,A=typeof w;if(A==="string"){var $,L=[],U=w.length,K=0;for(R=0;R<U;++R)($=w.charCodeAt(R))<128?L[K++]=$:$<2048?(L[K++]=192|$>>>6,L[K++]=128|63&$):$<55296||$>=57344?(L[K++]=224|$>>>12,L[K++]=128|$>>>6&63,L[K++]=128|63&$):($=65536+((1023&$)<<10|1023&w.charCodeAt(++R)),L[K++]=240|$>>>18,L[K++]=128|$>>>12&63,L[K++]=128|$>>>6&63,L[K++]=128|63&$);w=L}else{if(A!=="object")throw new Error(r);if(w===null)throw new Error(r);if(o&&w.constructor===ArrayBuffer)w=new Uint8Array(w);else if(!(Array.isArray(w)||o&&ArrayBuffer.isView(w)))throw new Error(r)}w.length>64&&(w=new q(I,!0).update(w).array());var te=[],ne=[];for(R=0;R<64;++R){var se=w[R]||0;te[R]=92^se,ne[R]=54^se}q.call(this,I,F),this.update(ne),this.oKeyPad=te,this.inner=!0,this.sharedMemory=F}q.prototype.update=function(w){if(!this.finalized){var I,F=typeof w;if(F!=="string"){if(F!=="object")throw new Error(r);if(w===null)throw new Error(r);if(o&&w.constructor===ArrayBuffer)w=new Uint8Array(w);else if(!(Array.isArray(w)||o&&ArrayBuffer.isView(w)))throw new Error(r);I=!0}for(var R,A,$=0,L=w.length,U=this.blocks;$<L;){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),I)for(A=this.start;$<L&&A<64;++$)U[A>>>2]|=w[$]<<p[3&A++];else for(A=this.start;$<L&&A<64;++$)(R=w.charCodeAt($))<128?U[A>>>2]|=R<<p[3&A++]:R<2048?(U[A>>>2]|=(192|R>>>6)<<p[3&A++],U[A>>>2]|=(128|63&R)<<p[3&A++]):R<55296||R>=57344?(U[A>>>2]|=(224|R>>>12)<<p[3&A++],U[A>>>2]|=(128|R>>>6&63)<<p[3&A++],U[A>>>2]|=(128|63&R)<<p[3&A++]):(R=65536+((1023&R)<<10|1023&w.charCodeAt(++$)),U[A>>>2]|=(240|R>>>18)<<p[3&A++],U[A>>>2]|=(128|R>>>12&63)<<p[3&A++],U[A>>>2]|=(128|R>>>6&63)<<p[3&A++],U[A>>>2]|=(128|63&R)<<p[3&A++]);this.lastByteIndex=A,this.bytes+=A-this.start,A>=64?(this.block=U[16],this.start=A-64,this.hash(),this.hashed=!0):this.start=A}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this}},q.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var w=this.blocks,I=this.lastByteIndex;w[16]=this.block,w[I>>>2]|=d[3&I],this.block=w[16],I>=56&&(this.hashed||this.hash(),w[0]=this.block,w[16]=w[1]=w[2]=w[3]=w[4]=w[5]=w[6]=w[7]=w[8]=w[9]=w[10]=w[11]=w[12]=w[13]=w[14]=w[15]=0),w[14]=this.hBytes<<3|this.bytes>>>29,w[15]=this.bytes<<3,this.hash()}},q.prototype.hash=function(){var w,I,F,R,A,$,L,U,K,te=this.h0,ne=this.h1,se=this.h2,oe=this.h3,he=this.h4,ue=this.h5,V=this.h6,ee=this.h7,ae=this.blocks;for(w=16;w<64;++w)I=((A=ae[w-15])>>>7|A<<25)^(A>>>18|A<<14)^A>>>3,F=((A=ae[w-2])>>>17|A<<15)^(A>>>19|A<<13)^A>>>10,ae[w]=ae[w-16]+I+ae[w-7]+F|0;for(K=ne&se,w=0;w<64;w+=4)this.first?(this.is224?($=300032,ee=(A=ae[0]-1413257819)-150054599|0,oe=A+24177077|0):($=704751109,ee=(A=ae[0]-210244248)-1521486534|0,oe=A+143694565|0),this.first=!1):(I=(te>>>2|te<<30)^(te>>>13|te<<19)^(te>>>22|te<<10),R=($=te&ne)^te&se^K,ee=oe+(A=ee+(F=(he>>>6|he<<26)^(he>>>11|he<<21)^(he>>>25|he<<7))+(he&ue^~he&V)+_[w]+ae[w])|0,oe=A+(I+R)|0),I=(oe>>>2|oe<<30)^(oe>>>13|oe<<19)^(oe>>>22|oe<<10),R=(L=oe&te)^oe&ne^$,V=se+(A=V+(F=(ee>>>6|ee<<26)^(ee>>>11|ee<<21)^(ee>>>25|ee<<7))+(ee&he^~ee&ue)+_[w+1]+ae[w+1])|0,I=((se=A+(I+R)|0)>>>2|se<<30)^(se>>>13|se<<19)^(se>>>22|se<<10),R=(U=se&oe)^se&te^L,ue=ne+(A=ue+(F=(V>>>6|V<<26)^(V>>>11|V<<21)^(V>>>25|V<<7))+(V&ee^~V&he)+_[w+2]+ae[w+2])|0,I=((ne=A+(I+R)|0)>>>2|ne<<30)^(ne>>>13|ne<<19)^(ne>>>22|ne<<10),R=(K=ne&se)^ne&oe^U,he=te+(A=he+(F=(ue>>>6|ue<<26)^(ue>>>11|ue<<21)^(ue>>>25|ue<<7))+(ue&V^~ue&ee)+_[w+3]+ae[w+3])|0,te=A+(I+R)|0,this.chromeBugWorkAround=!0;this.h0=this.h0+te|0,this.h1=this.h1+ne|0,this.h2=this.h2+se|0,this.h3=this.h3+oe|0,this.h4=this.h4+he|0,this.h5=this.h5+ue|0,this.h6=this.h6+V|0,this.h7=this.h7+ee|0},q.prototype.hex=function(){this.finalize();var w=this.h0,I=this.h1,F=this.h2,R=this.h3,A=this.h4,$=this.h5,L=this.h6,U=this.h7,K=a[w>>>28&15]+a[w>>>24&15]+a[w>>>20&15]+a[w>>>16&15]+a[w>>>12&15]+a[w>>>8&15]+a[w>>>4&15]+a[15&w]+a[I>>>28&15]+a[I>>>24&15]+a[I>>>20&15]+a[I>>>16&15]+a[I>>>12&15]+a[I>>>8&15]+a[I>>>4&15]+a[15&I]+a[F>>>28&15]+a[F>>>24&15]+a[F>>>20&15]+a[F>>>16&15]+a[F>>>12&15]+a[F>>>8&15]+a[F>>>4&15]+a[15&F]+a[R>>>28&15]+a[R>>>24&15]+a[R>>>20&15]+a[R>>>16&15]+a[R>>>12&15]+a[R>>>8&15]+a[R>>>4&15]+a[15&R]+a[A>>>28&15]+a[A>>>24&15]+a[A>>>20&15]+a[A>>>16&15]+a[A>>>12&15]+a[A>>>8&15]+a[A>>>4&15]+a[15&A]+a[$>>>28&15]+a[$>>>24&15]+a[$>>>20&15]+a[$>>>16&15]+a[$>>>12&15]+a[$>>>8&15]+a[$>>>4&15]+a[15&$]+a[L>>>28&15]+a[L>>>24&15]+a[L>>>20&15]+a[L>>>16&15]+a[L>>>12&15]+a[L>>>8&15]+a[L>>>4&15]+a[15&L];return this.is224||(K+=a[U>>>28&15]+a[U>>>24&15]+a[U>>>20&15]+a[U>>>16&15]+a[U>>>12&15]+a[U>>>8&15]+a[U>>>4&15]+a[15&U]),K},q.prototype.toString=q.prototype.hex,q.prototype.digest=function(){this.finalize();var w=this.h0,I=this.h1,F=this.h2,R=this.h3,A=this.h4,$=this.h5,L=this.h6,U=this.h7,K=[w>>>24&255,w>>>16&255,w>>>8&255,255&w,I>>>24&255,I>>>16&255,I>>>8&255,255&I,F>>>24&255,F>>>16&255,F>>>8&255,255&F,R>>>24&255,R>>>16&255,R>>>8&255,255&R,A>>>24&255,A>>>16&255,A>>>8&255,255&A,$>>>24&255,$>>>16&255,$>>>8&255,255&$,L>>>24&255,L>>>16&255,L>>>8&255,255&L];return this.is224||K.push(U>>>24&255,U>>>16&255,U>>>8&255,255&U),K},q.prototype.array=q.prototype.digest,q.prototype.arrayBuffer=function(){this.finalize();var w=new ArrayBuffer(this.is224?28:32),I=new DataView(w);return I.setUint32(0,this.h0),I.setUint32(4,this.h1),I.setUint32(8,this.h2),I.setUint32(12,this.h3),I.setUint32(16,this.h4),I.setUint32(20,this.h5),I.setUint32(24,this.h6),this.is224||I.setUint32(28,this.h7),w},X.prototype=new q,X.prototype.finalize=function(){if(q.prototype.finalize.call(this),this.inner){this.inner=!1;var w=this.array();q.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(w),q.prototype.finalize.call(this)}};var pe=j();pe.sha256=pe,pe.sha224=j(!0),pe.sha256.hmac=Q(),pe.sha224.hmac=Q(!0),n?_s.exports=pe:(t.sha256=pe.sha256,t.sha224=pe.sha224)}(),qt.exports,qt.exports.sha224;var yr=qt.exports.sha256;function ys(r){return zi(r)}function Fi(r){if(!/^[0-9A-Fa-f]+$/.test(r))return!1;const t=/^[0-9A-F]+$/.test(r),s=/^[0-9a-f]+$/.test(r);return t||s?r.length%2===0:!1}function Bi(r){return/^[A-Za-z0-9\-_]*(={0,2})?$/.test(r)||/^[A-Za-z0-9+/]*(={0,2})?$/.test(r)}function Di(r){return Fi(r)?"hex":Bi(r)?"b64":""}function Hi(r){if(r.length%2!==0)throw new Error("hex string must have an even length");const e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.substring(t,t+2),16);return e}function Ji(r){r=r.replace(/-/g,"+"),r=r.replace(/_/g,"/");const e=atob(r);return Uint8Array.from(e,t=>t.charCodeAt(0))}function zi(r){switch(Di(r)){case"hex":return Hi(r);case"b64":return Ji(r)}return null}function Gi(r,e){const t=typeof r=="string"?ys(r):r,s=typeof e=="string"?ys(e):e;if(t===null||s===null||t.length!==s.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==s[i])return!1;return!0}class wr{constructor(e,t,s=!0){h(this,"token");h(this,"received");h(this,"ctx");h(this,"requestSubject");h(this,"mux");this.mux=e,this.requestSubject=t,this.received=0,this.token=Le.next(),s&&(this.ctx=new Error)}}class Ki extends wr{constructor(t,s,i={maxWait:1e3}){super(t,s);h(this,"callback");h(this,"done");h(this,"timer");h(this,"max");h(this,"opts");if(this.opts=i,typeof this.opts.callback!="function")throw new Error("callback is required");this.callback=this.opts.callback,this.max=typeof i.maxMessages=="number"&&i.maxMessages>0?i.maxMessages:-1,this.done=z(),this.done.then(()=>{this.callback(null,null)}),this.timer=setTimeout(()=>{this.cancel()},i.maxWait)}cancel(t){t&&this.callback(t,null),clearTimeout(this.timer),this.mux.cancel(this),this.done.resolve()}resolver(t,s){t?(this.ctx&&(t.stack+=`
19
+
20
+ ${this.ctx.stack}`),this.cancel(t)):(this.callback(null,s),this.opts.strategy===ke.Count&&(this.max--,this.max===0&&this.cancel()),this.opts.strategy===ke.JitterTimer&&(clearTimeout(this.timer),this.timer=setTimeout(()=>{this.cancel()},this.opts.jitter||300)),this.opts.strategy===ke.SentinelMsg&&s&&s.data.length===0&&this.cancel())}}class xr extends wr{constructor(t,s,i={timeout:1e3},n=!0){super(t,s,n);h(this,"deferred");h(this,"timer");this.deferred=z(),this.timer=Ye(i.timeout,n)}resolver(t,s){this.timer&&this.timer.cancel(),t?(this.ctx&&(t.stack+=`
21
+
22
+ ${this.ctx.stack}`),this.deferred.reject(t)):this.deferred.resolve(s),this.cancel()}cancel(t){this.timer&&this.timer.cancel(),this.mux.cancel(this),this.deferred.reject(t||N.errorForCode(k.Cancelled))}}const Vi="$JS.API";function Wi(r){return r=r||{},r.domain&&(r.apiPrefix=`$JS.${r.domain}.API`,delete r.domain),Tt({apiPrefix:Vi,timeout:5e3},r)}class bt{constructor(e,t){h(this,"nc");h(this,"opts");h(this,"prefix");h(this,"timeout");h(this,"jc");this.nc=e,this.opts=Wi(t),this._parseOpts(),this.prefix=this.opts.apiPrefix,this.timeout=this.opts.timeout,this.jc=ve()}getOptions(){return Object.assign({},this.opts)}_parseOpts(){let e=this.opts.apiPrefix;if(!e||e.length===0)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,s){s=s||{},s.timeout=this.timeout;let i=be;t&&(i=this.jc.encode(t));let{retries:n}=s;n=n||1,n=n===-1?Number.MAX_SAFE_INTEGER:n;const o=hs();for(let a=0;a<n;a++)try{const d=await this.nc.request(e,i,s);return this.parseJsResponse(d)}catch(d){const p=d;if((p.code==="503"||p.code===k.Timeout)&&a+1<n)await Xe(o.backoff(a));else throw d}}async findStream(e){const t={subject:e},i=await this._request(`${this.prefix}.STREAM.NAMES`,t);if(!i.streams||i.streams.length!==1)throw new Error("no stream matches subject");return i.streams[0]}getConnection(){return this.nc}parseJsResponse(e){const t=this.jc.decode(e.data),s=t;if(s.error){const i=fr(s.error.code,s.error.description);if(i!==null)throw i.api_error=s.error,i}return t}}class gt{constructor(e,t,s,i){h(this,"err");h(this,"offset");h(this,"pageInfo");h(this,"subject");h(this,"jsm");h(this,"filter");h(this,"payload");if(!e)throw new Error("subject is required");this.subject=e,this.jsm=s,this.offset=0,this.pageInfo={},this.filter=t,this.payload=i||{}}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 s=this.countResponse(t);return s===0?[]:(this.offset+=s,this.filter(t))}catch(t){throw this.err=t,t}}countResponse(e){var t,s,i;switch(e==null?void 0:e.type){case"io.nats.jetstream.api.v1.stream_names_response":case"io.nats.jetstream.api.v1.stream_list_response":return((t=e.streams)==null?void 0:t.length)||0;case"io.nats.jetstream.api.v1.consumer_list_response":return((s=e.consumers)==null?void 0:s.length)||0;default:return console.error(`jslister.ts: unknown API response for paged output: ${e==null?void 0:e.type}`),((i=e.streams)==null?void 0:i.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 Ke(r=""){const e=r.match(/(\d+).(\d+).(\d+)/);if(e)return{major:parseInt(e[1]),minor:parseInt(e[2]),micro:parseInt(e[3])};throw new Error(`'${r}' is not a semver value`)}function ws(r,e){return r.major<e.major?-1:r.major>e.major?1:r.minor<e.minor?-1:r.minor>e.minor?1:r.micro<e.micro?-1:r.micro>e.micro?1:0}var H;(function(r){r.JS_KV="js_kv",r.JS_OBJECTSTORE="js_objectstore",r.JS_PULL_MAX_BYTES="js_pull_max_bytes",r.JS_NEW_CONSUMER_CREATE_API="js_new_consumer_create",r.JS_ALLOW_DIRECT="js_allow_direct",r.JS_MULTIPLE_CONSUMER_FILTER="js_multiple_consumer_filter",r.JS_SIMPLIFICATION="js_simplification",r.JS_STREAM_CONSUMER_METADATA="js_stream_consumer_metadata",r.JS_CONSUMER_FILTER_SUBJECTS="js_consumer_filter_subjects",r.JS_STREAM_FIRST_SEQ="js_stream_first_seq",r.JS_STREAM_SUBJECT_TRANSFORM="js_stream_subject_transform",r.JS_STREAM_SOURCE_SUBJECT_TRANSFORM="js_stream_source_subject_transform",r.JS_STREAM_COMPRESSION="js_stream_compression",r.JS_DEFAULT_CONSUMER_LIMITS="js_default_consumer_limits",r.JS_BATCH_DIRECT_GET="js_batch_direct_get"})(H||(H={}));class Yi{constructor(e){h(this,"server");h(this,"features");h(this,"disabled");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 this.disabled.indexOf(e)!==-1}update(e){typeof e=="string"&&(e=Ke(e)),this.server=e,this.set(H.JS_KV,"2.6.2"),this.set(H.JS_OBJECTSTORE,"2.6.3"),this.set(H.JS_PULL_MAX_BYTES,"2.8.3"),this.set(H.JS_NEW_CONSUMER_CREATE_API,"2.9.0"),this.set(H.JS_ALLOW_DIRECT,"2.9.0"),this.set(H.JS_MULTIPLE_CONSUMER_FILTER,"2.10.0"),this.set(H.JS_SIMPLIFICATION,"2.9.4"),this.set(H.JS_STREAM_CONSUMER_METADATA,"2.10.0"),this.set(H.JS_CONSUMER_FILTER_SUBJECTS,"2.10.0"),this.set(H.JS_STREAM_FIRST_SEQ,"2.10.0"),this.set(H.JS_STREAM_SUBJECT_TRANSFORM,"2.10.0"),this.set(H.JS_STREAM_SOURCE_SUBJECT_TRANSFORM,"2.10.0"),this.set(H.JS_STREAM_COMPRESSION,"2.10.0"),this.set(H.JS_DEFAULT_CONSUMER_LIMITS,"2.10.0"),this.set(H.JS_BATCH_DIRECT_GET,"2.11.0"),this.disabled.forEach(t=>{this.features.delete(t)})}set(e,t){this.features.set(e,{min:t,ok:ws(this.server,Ke(t))>=0})}get(e){return this.features.get(e)||{min:"unknown",ok:!1}}supports(e){var t;return((t=this.get(e))==null?void 0:t.ok)||!1}require(e){return typeof e=="string"&&(e=Ke(e)),ws(this.server,e)>=0}}class Lt extends bt{constructor(e,t){super(e,t)}async add(e,t,s=Ut.Create){if(le(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 i={};i.config=t,i.stream_name=e,i.action=s,i.config.durable_name&&Ze(i.config.durable_name);const n=this.nc;let{min:o,ok:a}=n.features.get(H.JS_NEW_CONSUMER_CREATE_API);const d=t.name===""?void 0:t.name;if(d&&!a)throw new Error(`consumer 'name' requires server ${o}`);if(d)try{$t("name",d)}catch(x){const P=x.message,j=P.indexOf("cannot contain");throw j!==-1?new Error(`consumer 'name' ${P.substring(j)}`):x}let p,_="";if(Array.isArray(t.filter_subjects)){const{min:x,ok:P}=n.features.get(H.JS_MULTIPLE_CONSUMER_FILTER);if(!P)throw new Error(`consumer 'filter_subjects' requires server ${x}`);a=!1}if(t.metadata){const{min:x,ok:P}=n.features.get(H.JS_STREAM_CONSUMER_METADATA);if(!P)throw new Error(`consumer 'metadata' requires server ${x}`)}if(a&&(_=t.name??t.durable_name??""),_!==""){let x=t.filter_subject??void 0;x===">"&&(x=void 0),p=x!==void 0?`${this.prefix}.CONSUMER.CREATE.${e}.${_}.${x}`:`${this.prefix}.CONSUMER.CREATE.${e}.${_}`}else p=t.durable_name?`${this.prefix}.CONSUMER.DURABLE.CREATE.${e}.${t.durable_name}`:`${this.prefix}.CONSUMER.CREATE.${e}`;return await this._request(p,i)}async update(e,t,s){const i=await this.info(e,t),n=s;return this.add(e,Object.assign(i.config,n),Ut.Update)}async info(e,t){return le(e),Ze(t),await this._request(`${this.prefix}.CONSUMER.INFO.${e}.${t}`)}async delete(e,t){return le(e),Ze(t),(await this._request(`${this.prefix}.CONSUMER.DELETE.${e}.${t}`)).success}list(e){le(e);const t=i=>i.consumers,s=`${this.prefix}.CONSUMER.LIST.${e}`;return new gt(s,t,this)}pause(e,t,s){const i=`${this.prefix}.CONSUMER.PAUSE.${e}.${t}`,n={pause_until:s.toISOString()};return this._request(i,n)}resume(e,t){return this.pause(e,t,new Date(0))}}function it(r,e,t=!1){if(t===!0&&!r)throw N.errorForCode(k.ApiError,new Error(`${e} is not a function`));if(r&&typeof r!="function")throw N.errorForCode(k.ApiError,new Error(`${e} is not a function`))}class Xi extends re{constructor(t,s,i){super();h(this,"sub");h(this,"adapter");h(this,"subIterDone");it(i.adapter,"adapter",!0),this.adapter=i.adapter,i.callback&&it(i.callback,"callback"),this.noIterator=typeof i.callback=="function",i.ingestionFilterFn&&(it(i.ingestionFilterFn,"ingestionFilterFn"),this.ingestionFilterFn=i.ingestionFilterFn),i.protocolFilterFn&&(it(i.protocolFilterFn,"protocolFilterFn"),this.protocolFilterFn=i.protocolFilterFn),i.dispatchedFn&&(it(i.dispatchedFn,"dispatchedFn"),this.dispatchedFn=i.dispatchedFn),i.cleanupFn&&it(i.cleanupFn,"cleanupFn");let n=(_,y)=>{this.callback(_,y)};if(i.callback){const _=i.callback;n=(y,x)=>{const[P,j]=this.adapter(y,x);if(P){_(P,null);return}const{ingest:T}=this.ingestionFilterFn?this.ingestionFilterFn(j,this):{ingest:!0};T&&(!this.protocolFilterFn||this.protocolFilterFn(j))&&(_(P,j),this.dispatchedFn&&j&&this.dispatchedFn(j))}}const{max:o,queue:a,timeout:d}=i,p={queue:a,timeout:d,callback:n};o&&o>0&&(p.max=o),this.sub=t.subscribe(s,p),i.cleanupFn&&(this.sub.cleanupFn=i.cleanupFn),this.noIterator||this.iterClosed.then(()=>{this.unsubscribe()}),this.subIterDone=z(),Promise.all([this.sub.closed,this.iterClosed]).then(()=>{this.subIterDone.resolve()}).catch(()=>{this.subIterDone.resolve()}),(async _=>{await _.closed,this.stop()})(this.sub).then().catch()}unsubscribe(t){this.sub.unsubscribe(t)}drain(){return this.sub.drain()}isDraining(){return this.sub.isDraining()}isClosed(){return this.sub.isClosed()}callback(t,s){this.sub.cancelTimeout();const[i,n]=this.adapter(t,s);i&&this.stop(i),n&&this.push(n)}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 we;function Zi(r){we=r}function Sr(){return we!==void 0&&we.defaultPort!==void 0?we.defaultPort:4222}function xs(){return we!==void 0&&we.urlParseFn?we.urlParseFn:void 0}function Qi(){if(!we||typeof we.factory!="function")throw new Error("transport fn is not set");return we.factory()}function Ss(){return we!==void 0&&we.dnsResolveFn?we.dnsResolveFn:void 0}const Ft=`\r
23
+ `,Bt=rt.fromAscii(Ft),en=new Uint8Array(Bt)[0],tn=new Uint8Array(Bt)[1];function sn(r){for(let e=0;e<r.length;e++){const t=e+1;if(r.byteLength>t&&r[e]===en&&r[t]===tn)return t+1}return 0}function rn(r){const e=sn(r);if(e>0){const s=new Uint8Array(r).slice(0,e);return ge.decode(s)}return""}const nn=4,vr=48,on=65,an=97;function cn(r,e,t,s){const i=new Uint8Array(16);return[0,0,0,0,0,0,0,0,0,0,255,255].forEach((o,a)=>{i[a]=o}),i[12]=r,i[13]=e,i[14]=t,i[15]=s,i}function vs(r){return hn(r)!==void 0}function hn(r){for(let e=0;e<r.length;e++)switch(r[e]){case".":return Er(r);case":":return un(r)}}function Er(r){const e=new Uint8Array(4);for(let t=0;t<4;t++){if(r.length===0)return;if(t>0){if(r[0]!==".")return;r=r.substring(1)}const{n:s,c:i,ok:n}=ln(r);if(!n||s>255)return;r=r.substring(i),e[t]=s}return cn(e[0],e[1],e[2],e[3])}function un(r){const e=new Uint8Array(16);let t=-1;if(r.length>=2&&r[0]===":"&&r[1]===":"&&(t=0,r=r.substring(2),r.length===0))return e;let s=0;for(;s<16;){const{n:i,c:n,ok:o}=fn(r);if(!o||i>65535)return;if(n<r.length&&r[n]==="."){if(t<0&&s!=12||s+4>16)return;const a=Er(r);if(a===void 0)return;e[s]=a[12],e[s+1]=a[13],e[s+2]=a[14],e[s+3]=a[15],r="",s+=nn;break}if(e[s]=i>>8,e[s+1]=i,s+=2,r=r.substring(n),r.length===0)break;if(r[0]!==":"||r.length==1)return;if(r=r.substring(1),r[0]===":"){if(t>=0)return;if(t=s,r=r.substring(1),r.length===0)break}}if(r.length===0){if(s<16){if(t<0)return;const i=16-s;for(let n=s-1;n>=t;n--)e[n+i]=e[n];for(let n=t+i-1;n>=t;n--)e[n]=0}else if(t>=0)return;return e}}function ln(r){let e=0,t=0;for(e=0;e<r.length&&48<=r.charCodeAt(e)&&r.charCodeAt(e)<=57;e++)if(t=t*10+(r.charCodeAt(e)-vr),t>=16777215)return{n:16777215,c:e,ok:!1};return e===0?{n:0,c:0,ok:!1}:{n:t,c:e,ok:!0}}function fn(r){let e=0,t=0;for(t=0;t<r.length;t++){if(48<=r.charCodeAt(t)&&r.charCodeAt(t)<=57)e*=16,e+=r.charCodeAt(t)-vr;else if(97<=r.charCodeAt(t)&&r.charCodeAt(t)<=102)e*=16,e+=r.charCodeAt(t)-an+10;else if(65<=r.charCodeAt(t)&&r.charCodeAt(t)<=70)e*=16,e+=r.charCodeAt(t)-on+10;else break;if(e>=16777215)return{n:0,c:t,ok:!1}}return t===0?{n:0,c:t,ok:!1}:{n:e,c:t,ok:!0}}function dn(r){return r.indexOf("[")!==-1||r.indexOf("::")!==-1?!1:r.indexOf(".")!==-1||r.split(":").length<=2}function Es(r){return!dn(r)}function pn(r){const e="::FFFF:",t=r.toUpperCase().indexOf(e);if(t!==-1&&r.indexOf(".")!==-1){let s=r.substring(t+e.length);return s=s.replace("[",""),s.replace("]","")}return r}function mn(r){r=r.trim(),r.match(/^(.*:\/\/)(.*)/m)&&(r=r.replace(/^(.*:\/\/)(.*)/gm,"$2")),r=pn(r),Es(r)&&r.indexOf("[")===-1&&(r=`[${r}]`);const e=Es(r)?r.match(/(]:)(\d+)/):r.match(/(:)(\d+)/),t=e&&e.length===3&&e[1]&&e[2]?parseInt(e[2]):4222,s=t===80?"https":"http",i=new URL(`${s}://${r}`);i.port=`${t}`;let n=i.hostname;return n.charAt(0)==="["&&(n=n.substring(1,n.length-1)),{listen:i.host,hostname:n,port:t}}class _t{constructor(e,t=!1){h(this,"src");h(this,"listen");h(this,"hostname");h(this,"port");h(this,"didConnect");h(this,"reconnects");h(this,"lastConnect");h(this,"gossiped");h(this,"tlsName");h(this,"resolves");this.src=e,this.tlsName="";const s=mn(e);this.listen=s.listen,this.hostname=s.hostname,this.port=s.port,this.didConnect=!1,this.reconnects=0,this.lastConnect=0,this.gossiped=t}toString(){return this.listen}async resolve(e){if(!e.fn||e.resolve===!1)return[this];const t=[];if(vs(this.hostname))return[this];{const s=await e.fn(this.hostname);e.debug&&console.log(`resolve ${this.hostname} = ${s.join(",")}`);for(const i of s){const n=this.port===80?"https":"http",o=new URL(`${n}://${Es(i)?"["+i+"]":i}`);o.port=`${this.port}`;const a=new _t(o.host,!1);a.tlsName=this.hostname,t.push(a)}}return e.randomize&&cr(t),this.resolves=t,t}}class bn{constructor(e=[],t={}){h(this,"firstSelect");h(this,"servers");h(this,"currentServer");h(this,"tlsName");h(this,"randomize");this.firstSelect=!0,this.servers=[],this.tlsName="",this.randomize=t.randomize||!1;const s=xs();e&&(e.forEach(i=>{i=s?s(i):i,this.servers.push(new _t(i))}),this.randomize&&(this.servers=cr(this.servers))),this.servers.length===0&&this.addServer(`${cs}:${Sr()}`,!1),this.currentServer=this.servers[0]}clear(){this.servers.length=0}updateTLSName(){const e=this.getCurrentServer();vs(e.hostname)||(this.tlsName=e.hostname,this.servers.forEach(t=>{t.gossiped&&(t.tlsName=this.tlsName)}))}getCurrentServer(){return this.currentServer}addServer(e,t=!1){const s=xs();e=s?s(e):e;const i=new _t(e,t);vs(i.hostname)&&(i.tlsName=this.tlsName),this.servers.push(i)}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 s=[];let i=[];const n=xs(),o=new Map;e.connect_urls&&e.connect_urls.length>0&&e.connect_urls.forEach(d=>{d=n?n(d,t):d;const p=new _t(d,!0);o.set(d,p)});const a=[];return this.servers.forEach((d,p)=>{const _=d.listen;d.gossiped&&this.currentServer.listen!==_&&o.get(_)===void 0&&a.push(p),o.delete(_)}),a.reverse(),a.forEach(d=>{const p=this.servers.splice(d,1);i=i.concat(p[0].listen)}),o.forEach((d,p)=>{this.servers.push(d),s.push(p)}),{added:s,deleted:i}}}class gn{constructor(){h(this,"baseInbox");h(this,"reqs");this.reqs=new Map}size(){return this.reqs.size}init(e){return this.baseInbox=`${$e(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 t.indexOf(this.baseInbox)===0?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(i=>{i.resolver(t,{})}),!0;const s=t.permissionContext;if(s.operation==="publish"){const i=this.all().find(n=>n.requestSubject===s.subject);if(i)return i.resolver(t,{}),!0}}return!1}dispatcher(){return(e,t)=>{const s=this.getToken(t);if(s){const i=this.get(s);i&&(e===null&&t.headers&&(e=lr(t)),i.resolver(e,t))}}}close(){const e=N.errorForCode(k.Timeout);this.reqs.forEach(t=>{t.resolver(e,{})})}}class _n{constructor(e,t,s){h(this,"ph");h(this,"interval");h(this,"maxOut");h(this,"timer");h(this,"pendings");this.ph=e,this.interval=t,this.maxOut=s,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:Fe.PingTimer,data:`${this.pendings.length+1}`}),this.pendings.length===this.maxOut){this.cancel(!0);return}const e=z();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 yn extends Error{constructor(e){super(e),this.name="AssertionError"}}function wn(r,e="Assertion failed."){if(!r)throw new yn(e)}const Ar=32*1024,As=2**32-2;function Dt(r,e,t=0){const s=e.byteLength-t;return r.byteLength>s&&(r=r.subarray(0,s)),e.set(r,t),r.byteLength}class Ps{constructor(e){h(this,"_buf");h(this,"_off");if(this._off=0,e==null){this._buf=new Uint8Array(0);return}this._buf=new Uint8Array(e)}bytes(e={copy:!0}){return e.copy===!1?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(e===0){this.reset();return}if(e<0||e>this.length)throw Error("bytes.Buffer: truncation out of range");this._reslice(this._off+e)}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){wn(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(),e.byteLength===0?0:null;const t=Dt(this._buf.subarray(this._off),e);return this._off+=t,t}writeByte(e){return this.write(Uint8Array.of(e))}writeString(e){return this.write(Ge.encode(e))}write(e){const t=this._grow(e.byteLength);return Dt(e,this._buf,t)}_grow(e){const t=this.length;t===0&&this._off!==0&&this.reset();const s=this._tryGrowByReslice(e);if(s>=0)return s;const i=this.capacity;if(e<=Math.floor(i/2)-t)Dt(this._buf.subarray(this._off),this._buf);else{if(i+e>As)throw new Error("The buffer cannot be grown beyond the maximum size.");{const n=new Uint8Array(Math.min(2*i+e,As));Dt(this._buf.subarray(this._off),n),this._buf=n}}return this._off=0,this._reslice(Math.min(t+e,As)),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 s=new Uint8Array(Ar);for(;;){const i=this.capacity-this.length<Ar,n=i?s:new Uint8Array(this._buf.buffer,this.length),o=e.read(n);if(o===null)return t;i?this.write(n.subarray(0,o)):this._reslice(this.length+o),t+=o}}}var de;(function(r){r[r.OK=0]="OK",r[r.ERR=1]="ERR",r[r.MSG=2]="MSG",r[r.INFO=3]="INFO",r[r.PING=4]="PING",r[r.PONG=5]="PONG"})(de||(de={}));function Pr(){const r={};return r.sid=-1,r.hdr=-1,r.size=-1,r}const xn=48;class kr{constructor(e){h(this,"dispatcher");h(this,"state");h(this,"as");h(this,"drop");h(this,"hdr");h(this,"ma");h(this,"argBuf");h(this,"msgBuf");this.dispatcher=e,this.state=O.OP_START,this.as=0,this.drop=0,this.hdr=0}parse(e){let t;for(t=0;t<e.length;t++){const s=e[t];switch(this.state){case O.OP_START:switch(s){case C.M:case C.m:this.state=O.OP_M,this.hdr=-1,this.ma=Pr();break;case C.H:case C.h:this.state=O.OP_H,this.hdr=0,this.ma=Pr();break;case C.P:case C.p:this.state=O.OP_P;break;case C.PLUS:this.state=O.OP_PLUS;break;case C.MINUS:this.state=O.OP_MINUS;break;case C.I:case C.i:this.state=O.OP_I;break;default:throw this.fail(e.subarray(t))}break;case O.OP_H:switch(s){case C.M:case C.m:this.state=O.OP_M;break;default:throw this.fail(e.subarray(t))}break;case O.OP_M:switch(s){case C.S:case C.s:this.state=O.OP_MS;break;default:throw this.fail(e.subarray(t))}break;case O.OP_MS:switch(s){case C.G:case C.g:this.state=O.OP_MSG;break;default:throw this.fail(e.subarray(t))}break;case O.OP_MSG:switch(s){case C.SPACE:case C.TAB:this.state=O.OP_MSG_SPC;break;default:throw this.fail(e.subarray(t))}break;case O.OP_MSG_SPC:switch(s){case C.SPACE:case C.TAB:continue;default:this.state=O.MSG_ARG,this.as=t}break;case O.MSG_ARG:switch(s){case C.CR:this.drop=1;break;case C.NL:{const i=this.argBuf?this.argBuf.bytes():e.subarray(this.as,t-this.drop);this.processMsgArgs(i),this.drop=0,this.as=t+1,this.state=O.MSG_PAYLOAD,t=this.as+this.ma.size-1;break}default:this.argBuf&&this.argBuf.writeByte(s)}break;case O.MSG_PAYLOAD:if(this.msgBuf)if(this.msgBuf.length>=this.ma.size){const i=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:de.MSG,msg:this.ma,data:i}),this.argBuf=void 0,this.msgBuf=void 0,this.state=O.MSG_END}else{let i=this.ma.size-this.msgBuf.length;const n=e.length-t;n<i&&(i=n),i>0?(this.msgBuf.write(e.subarray(t,t+i)),t=t+i-1):this.msgBuf.writeByte(s)}else t-this.as>=this.ma.size&&(this.dispatcher.push({kind:de.MSG,msg:this.ma,data:e.subarray(this.as,t)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=O.MSG_END);break;case O.MSG_END:switch(s){case C.NL:this.drop=0,this.as=t+1,this.state=O.OP_START;break;default:continue}break;case O.OP_PLUS:switch(s){case C.O:case C.o:this.state=O.OP_PLUS_O;break;default:throw this.fail(e.subarray(t))}break;case O.OP_PLUS_O:switch(s){case C.K:case C.k:this.state=O.OP_PLUS_OK;break;default:throw this.fail(e.subarray(t))}break;case O.OP_PLUS_OK:switch(s){case C.NL:this.dispatcher.push({kind:de.OK}),this.drop=0,this.state=O.OP_START;break}break;case O.OP_MINUS:switch(s){case C.E:case C.e:this.state=O.OP_MINUS_E;break;default:throw this.fail(e.subarray(t))}break;case O.OP_MINUS_E:switch(s){case C.R:case C.r:this.state=O.OP_MINUS_ER;break;default:throw this.fail(e.subarray(t))}break;case O.OP_MINUS_ER:switch(s){case C.R:case C.r:this.state=O.OP_MINUS_ERR;break;default:throw this.fail(e.subarray(t))}break;case O.OP_MINUS_ERR:switch(s){case C.SPACE:case C.TAB:this.state=O.OP_MINUS_ERR_SPC;break;default:throw this.fail(e.subarray(t))}break;case O.OP_MINUS_ERR_SPC:switch(s){case C.SPACE:case C.TAB:continue;default:this.state=O.MINUS_ERR_ARG,this.as=t}break;case O.MINUS_ERR_ARG:switch(s){case C.CR:this.drop=1;break;case C.NL:{let i;this.argBuf?(i=this.argBuf.bytes(),this.argBuf=void 0):i=e.subarray(this.as,t-this.drop),this.dispatcher.push({kind:de.ERR,data:i}),this.drop=0,this.as=t+1,this.state=O.OP_START;break}default:this.argBuf&&this.argBuf.write(Uint8Array.of(s))}break;case O.OP_P:switch(s){case C.I:case C.i:this.state=O.OP_PI;break;case C.O:case C.o:this.state=O.OP_PO;break;default:throw this.fail(e.subarray(t))}break;case O.OP_PO:switch(s){case C.N:case C.n:this.state=O.OP_PON;break;default:throw this.fail(e.subarray(t))}break;case O.OP_PON:switch(s){case C.G:case C.g:this.state=O.OP_PONG;break;default:throw this.fail(e.subarray(t))}break;case O.OP_PONG:switch(s){case C.NL:this.dispatcher.push({kind:de.PONG}),this.drop=0,this.state=O.OP_START;break}break;case O.OP_PI:switch(s){case C.N:case C.n:this.state=O.OP_PIN;break;default:throw this.fail(e.subarray(t))}break;case O.OP_PIN:switch(s){case C.G:case C.g:this.state=O.OP_PING;break;default:throw this.fail(e.subarray(t))}break;case O.OP_PING:switch(s){case C.NL:this.dispatcher.push({kind:de.PING}),this.drop=0,this.state=O.OP_START;break}break;case O.OP_I:switch(s){case C.N:case C.n:this.state=O.OP_IN;break;default:throw this.fail(e.subarray(t))}break;case O.OP_IN:switch(s){case C.F:case C.f:this.state=O.OP_INF;break;default:throw this.fail(e.subarray(t))}break;case O.OP_INF:switch(s){case C.O:case C.o:this.state=O.OP_INFO;break;default:throw this.fail(e.subarray(t))}break;case O.OP_INFO:switch(s){case C.SPACE:case C.TAB:this.state=O.OP_INFO_SPC;break;default:throw this.fail(e.subarray(t))}break;case O.OP_INFO_SPC:switch(s){case C.SPACE:case C.TAB:continue;default:this.state=O.INFO_ARG,this.as=t}break;case O.INFO_ARG:switch(s){case C.CR:this.drop=1;break;case C.NL:{let i;this.argBuf?(i=this.argBuf.bytes(),this.argBuf=void 0):i=e.subarray(this.as,t-this.drop),this.dispatcher.push({kind:de.INFO,data:i}),this.drop=0,this.as=t+1,this.state=O.OP_START;break}default:this.argBuf&&this.argBuf.writeByte(s)}break;default:throw this.fail(e.subarray(t))}}(this.state===O.MSG_ARG||this.state===O.MINUS_ERR_ARG||this.state===O.INFO_ARG)&&!this.argBuf&&(this.argBuf=new Ps(e.subarray(this.as,t-this.drop))),this.state===O.MSG_PAYLOAD&&!this.msgBuf&&(this.argBuf||this.cloneMsgArg(),this.msgBuf=new Ps(e.subarray(this.as)))}cloneMsgArg(){const e=this.ma.subject.length,t=this.ma.reply?this.ma.reply.length:0,s=new Uint8Array(e+t);s.set(this.ma.subject),this.ma.reply&&s.set(this.ma.reply,e),this.argBuf=new Ps(s),this.ma.subject=s.subarray(0,e),this.ma.reply&&(this.ma.reply=s.subarray(e))}processMsgArgs(e){if(this.hdr>=0)return this.processHeaderMsgArgs(e);const t=[];let s=-1;for(let i=0;i<e.length;i++)switch(e[i]){case C.SPACE:case C.TAB:case C.CR:case C.NL:s>=0&&(t.push(e.subarray(s,i)),s=-1);break;default:s<0&&(s=i)}switch(s>=0&&t.push(e.subarray(s)),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}]`:t=`parse error [${this.state}]`,new Error(`${t}: ${ge.decode(e)}`)}processHeaderMsgArgs(e){const t=[];let s=-1;for(let i=0;i<e.length;i++)switch(e[i]){case C.SPACE:case C.TAB:case C.CR:case C.NL:s>=0&&(t.push(e.subarray(s,i)),s=-1);break;default:s<0&&(s=i)}switch(s>=0&&t.push(e.subarray(s)),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(e.length===0)return-1;let t=0;for(let s=0;s<e.length;s++){if(e[s]<48||e[s]>57)return-1;t=t*10+(e[s]-xn)}return t}}var O;(function(r){r[r.OP_START=0]="OP_START",r[r.OP_PLUS=1]="OP_PLUS",r[r.OP_PLUS_O=2]="OP_PLUS_O",r[r.OP_PLUS_OK=3]="OP_PLUS_OK",r[r.OP_MINUS=4]="OP_MINUS",r[r.OP_MINUS_E=5]="OP_MINUS_E",r[r.OP_MINUS_ER=6]="OP_MINUS_ER",r[r.OP_MINUS_ERR=7]="OP_MINUS_ERR",r[r.OP_MINUS_ERR_SPC=8]="OP_MINUS_ERR_SPC",r[r.MINUS_ERR_ARG=9]="MINUS_ERR_ARG",r[r.OP_M=10]="OP_M",r[r.OP_MS=11]="OP_MS",r[r.OP_MSG=12]="OP_MSG",r[r.OP_MSG_SPC=13]="OP_MSG_SPC",r[r.MSG_ARG=14]="MSG_ARG",r[r.MSG_PAYLOAD=15]="MSG_PAYLOAD",r[r.MSG_END=16]="MSG_END",r[r.OP_H=17]="OP_H",r[r.OP_P=18]="OP_P",r[r.OP_PI=19]="OP_PI",r[r.OP_PIN=20]="OP_PIN",r[r.OP_PING=21]="OP_PING",r[r.OP_PO=22]="OP_PO",r[r.OP_PON=23]="OP_PON",r[r.OP_PONG=24]="OP_PONG",r[r.OP_I=25]="OP_I",r[r.OP_IN=26]="OP_IN",r[r.OP_INF=27]="OP_INF",r[r.OP_INFO=28]="OP_INFO",r[r.OP_INFO_SPC=29]="OP_INFO_SPC",r[r.INFO_ARG=30]="INFO_ARG"})(O||(O={}));var C;(function(r){r[r.CR=13]="CR",r[r.E=69]="E",r[r.e=101]="e",r[r.F=70]="F",r[r.f=102]="f",r[r.G=71]="G",r[r.g=103]="g",r[r.H=72]="H",r[r.h=104]="h",r[r.I=73]="I",r[r.i=105]="i",r[r.K=75]="K",r[r.k=107]="k",r[r.M=77]="M",r[r.m=109]="m",r[r.MINUS=45]="MINUS",r[r.N=78]="N",r[r.n=110]="n",r[r.NL=10]="NL",r[r.O=79]="O",r[r.o=111]="o",r[r.P=80]="P",r[r.p=112]="p",r[r.PLUS=43]="PLUS",r[r.R=82]="R",r[r.r=114]="r",r[r.S=83]="S",r[r.s=115]="s",r[r.SPACE=32]="SPACE",r[r.TAB=9]="TAB"})(C||(C={})),function(r){var e=function(c,l){this.hi=c|0,this.lo=l|0},t=function(c){var l,u=new Float64Array(16);if(c)for(l=0;l<c.length;l++)u[l]=c[l];return u},s=function(){throw new Error("no PRNG")},i=new Uint8Array(16),n=new Uint8Array(32);n[0]=9;var o=t(),a=t([1]),d=t([56129,1]),p=t([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),_=t([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),y=t([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),x=t([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),P=t([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function j(c,l){return c<<l|c>>>32-l}function T(c,l){var u=c[l+3]&255;return u=u<<8|c[l+2]&255,u=u<<8|c[l+1]&255,u<<8|c[l+0]&255}function J(c,l){var u=c[l]<<24|c[l+1]<<16|c[l+2]<<8|c[l+3],f=c[l+4]<<24|c[l+5]<<16|c[l+6]<<8|c[l+7];return new e(u,f)}function Q(c,l,u){var f;for(f=0;f<4;f++)c[l+f]=u&255,u>>>=8}function q(c,l,u){c[l]=u.hi>>24&255,c[l+1]=u.hi>>16&255,c[l+2]=u.hi>>8&255,c[l+3]=u.hi&255,c[l+4]=u.lo>>24&255,c[l+5]=u.lo>>16&255,c[l+6]=u.lo>>8&255,c[l+7]=u.lo&255}function X(c,l,u,f,m){var b,v=0;for(b=0;b<m;b++)v|=c[l+b]^u[f+b];return(1&v-1>>>8)-1}function pe(c,l,u,f){return X(c,l,u,f,16)}function w(c,l,u,f){return X(c,l,u,f,32)}function I(c,l,u,f,m){var b=new Uint32Array(16),v=new Uint32Array(16),E=new Uint32Array(16),g=new Uint32Array(4),S,M,D;for(S=0;S<4;S++)v[5*S]=T(f,4*S),v[1+S]=T(u,4*S),v[6+S]=T(l,4*S),v[11+S]=T(u,16+4*S);for(S=0;S<16;S++)E[S]=v[S];for(S=0;S<20;S++){for(M=0;M<4;M++){for(D=0;D<4;D++)g[D]=v[(5*M+4*D)%16];for(g[1]^=j(g[0]+g[3]|0,7),g[2]^=j(g[1]+g[0]|0,9),g[3]^=j(g[2]+g[1]|0,13),g[0]^=j(g[3]+g[2]|0,18),D=0;D<4;D++)b[4*M+(M+D)%4]=g[D]}for(D=0;D<16;D++)v[D]=b[D]}if(m){for(S=0;S<16;S++)v[S]=v[S]+E[S]|0;for(S=0;S<4;S++)v[5*S]=v[5*S]-T(f,4*S)|0,v[6+S]=v[6+S]-T(l,4*S)|0;for(S=0;S<4;S++)Q(c,4*S,v[5*S]),Q(c,16+4*S,v[6+S])}else for(S=0;S<16;S++)Q(c,4*S,v[S]+E[S]|0)}function F(c,l,u,f){return I(c,l,u,f,!1),0}function R(c,l,u,f){return I(c,l,u,f,!0),0}var A=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function $(c,l,u,f,m,b,v){var E=new Uint8Array(16),g=new Uint8Array(64),S,M;if(!m)return 0;for(M=0;M<16;M++)E[M]=0;for(M=0;M<8;M++)E[M]=b[M];for(;m>=64;){for(F(g,E,v,A),M=0;M<64;M++)c[l+M]=(u?u[f+M]:0)^g[M];for(S=1,M=8;M<16;M++)S=S+(E[M]&255)|0,E[M]=S&255,S>>>=8;m-=64,l+=64,u&&(f+=64)}if(m>0)for(F(g,E,v,A),M=0;M<m;M++)c[l+M]=(u?u[f+M]:0)^g[M];return 0}function L(c,l,u,f,m){return $(c,l,null,0,u,f,m)}function U(c,l,u,f,m){var b=new Uint8Array(32);return R(b,f,m,A),L(c,l,u,f.subarray(16),b)}function K(c,l,u,f,m,b,v){var E=new Uint8Array(32);return R(E,b,v,A),$(c,l,u,f,m,b.subarray(16),E)}function te(c,l){var u,f=0;for(u=0;u<17;u++)f=f+(c[u]+l[u]|0)|0,c[u]=f&255,f>>>=8}var ne=new Uint32Array([5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252]);function se(c,l,u,f,m,b){var v,E,g,S,M=new Uint32Array(17),D=new Uint32Array(17),W=new Uint32Array(17),Ie=new Uint32Array(17),ht=new Uint32Array(17);for(g=0;g<17;g++)D[g]=W[g]=0;for(g=0;g<16;g++)D[g]=b[g];for(D[3]&=15,D[4]&=252,D[7]&=15,D[8]&=252,D[11]&=15,D[12]&=252,D[15]&=15;m>0;){for(g=0;g<17;g++)Ie[g]=0;for(g=0;g<16&&g<m;++g)Ie[g]=u[f+g];for(Ie[g]=1,f+=g,m-=g,te(W,Ie),E=0;E<17;E++)for(M[E]=0,g=0;g<17;g++)M[E]=M[E]+W[g]*(g<=E?D[E-g]:320*D[E+17-g]|0)|0|0;for(E=0;E<17;E++)W[E]=M[E];for(S=0,g=0;g<16;g++)S=S+W[g]|0,W[g]=S&255,S>>>=8;for(S=S+W[16]|0,W[16]=S&3,S=5*(S>>>2)|0,g=0;g<16;g++)S=S+W[g]|0,W[g]=S&255,S>>>=8;S=S+W[16]|0,W[16]=S}for(g=0;g<17;g++)ht[g]=W[g];for(te(W,ne),v=-(W[16]>>>7)|0,g=0;g<17;g++)W[g]^=v&(ht[g]^W[g]);for(g=0;g<16;g++)Ie[g]=b[g+16];for(Ie[16]=0,te(W,Ie),g=0;g<16;g++)c[l+g]=W[g];return 0}function oe(c,l,u,f,m,b){var v=new Uint8Array(16);return se(v,0,u,f,m,b),pe(c,l,v,0)}function he(c,l,u,f,m){var b;if(u<32)return-1;for(K(c,0,l,0,u,f,m),se(c,16,c,32,u-32,c),b=0;b<16;b++)c[b]=0;return 0}function ue(c,l,u,f,m){var b,v=new Uint8Array(32);if(u<32||(U(v,0,32,f,m),oe(l,16,l,32,u-32,v)!==0))return-1;for(K(c,0,l,0,u,f,m),b=0;b<32;b++)c[b]=0;return 0}function V(c,l){var u;for(u=0;u<16;u++)c[u]=l[u]|0}function ee(c){var l,u;for(u=0;u<16;u++)c[u]+=65536,l=Math.floor(c[u]/65536),c[(u+1)*(u<15?1:0)]+=l-1+37*(l-1)*(u===15?1:0),c[u]-=l*65536}function ae(c,l,u){for(var f,m=~(u-1),b=0;b<16;b++)f=m&(c[b]^l[b]),c[b]^=f,l[b]^=f}function ot(c,l){var u,f,m,b=t(),v=t();for(u=0;u<16;u++)v[u]=l[u];for(ee(v),ee(v),ee(v),f=0;f<2;f++){for(b[0]=v[0]-65517,u=1;u<15;u++)b[u]=v[u]-65535-(b[u-1]>>16&1),b[u-1]&=65535;b[15]=v[15]-32767-(b[14]>>16&1),m=b[15]>>16&1,b[14]&=65535,ae(v,b,1-m)}for(u=0;u<16;u++)c[2*u]=v[u]&255,c[2*u+1]=v[u]>>8}function Gr(c,l){var u=new Uint8Array(32),f=new Uint8Array(32);return ot(u,c),ot(f,l),w(u,0,f,0)}function Kr(c){var l=new Uint8Array(32);return ot(l,c),l[0]&1}function Us(c,l){var u;for(u=0;u<16;u++)c[u]=l[2*u]+(l[2*u+1]<<8);c[15]&=32767}function Ce(c,l,u){var f;for(f=0;f<16;f++)c[f]=l[f]+u[f]|0}function je(c,l,u){var f;for(f=0;f<16;f++)c[f]=l[f]-u[f]|0}function B(c,l,u){var f,m,b=new Float64Array(31);for(f=0;f<31;f++)b[f]=0;for(f=0;f<16;f++)for(m=0;m<16;m++)b[f+m]+=l[f]*u[m];for(f=0;f<15;f++)b[f]+=38*b[f+16];for(f=0;f<16;f++)c[f]=b[f];ee(c),ee(c)}function Pe(c,l){B(c,l,l)}function Vr(c,l){var u=t(),f;for(f=0;f<16;f++)u[f]=l[f];for(f=253;f>=0;f--)Pe(u,u),f!==2&&f!==4&&B(u,u,l);for(f=0;f<16;f++)c[f]=u[f]}function Wr(c,l){var u=t(),f;for(f=0;f<16;f++)u[f]=l[f];for(f=250;f>=0;f--)Pe(u,u),f!==1&&B(u,u,l);for(f=0;f<16;f++)c[f]=u[f]}function Wt(c,l,u){var f=new Uint8Array(32),m=new Float64Array(80),b,v,E=t(),g=t(),S=t(),M=t(),D=t(),W=t();for(v=0;v<31;v++)f[v]=l[v];for(f[31]=l[31]&127|64,f[0]&=248,Us(m,u),v=0;v<16;v++)g[v]=m[v],M[v]=E[v]=S[v]=0;for(E[0]=M[0]=1,v=254;v>=0;--v)b=f[v>>>3]>>>(v&7)&1,ae(E,g,b),ae(S,M,b),Ce(D,E,S),je(E,E,S),Ce(S,g,M),je(g,g,M),Pe(M,D),Pe(W,E),B(E,S,E),B(S,g,D),Ce(D,E,S),je(E,E,S),Pe(g,E),je(S,M,W),B(E,S,d),Ce(E,E,M),B(S,S,E),B(E,M,W),B(M,g,m),Pe(g,D),ae(E,g,b),ae(S,M,b);for(v=0;v<16;v++)m[v+16]=E[v],m[v+32]=S[v],m[v+48]=g[v],m[v+64]=M[v];var Ie=m.subarray(32),ht=m.subarray(16);return Vr(Ie,Ie),B(ht,ht,Ie),ot(c,ht),0}function Yt(c,l){return Wt(c,l,n)}function Yr(c,l){return s(l,32),Yt(c,l)}function Xt(c,l,u){var f=new Uint8Array(32);return Wt(f,u,l),R(c,i,f,A)}var Xr=he,Ao=ue;function Po(c,l,u,f,m,b){var v=new Uint8Array(32);return Xt(v,m,b),Xr(c,l,u,f,v)}function ko(c,l,u,f,m,b){var v=new Uint8Array(32);return Xt(v,m,b),Ao(c,l,u,f,v)}function At(){var c=0,l=0,u=0,f=0,m=65535,b,v,E;for(E=0;E<arguments.length;E++)b=arguments[E].lo,v=arguments[E].hi,c+=b&m,l+=b>>>16,u+=v&m,f+=v>>>16;return l+=c>>>16,u+=l>>>16,f+=u>>>16,new e(u&m|f<<16,c&m|l<<16)}function Zr(c,l){return new e(c.hi>>>l,c.lo>>>l|c.hi<<32-l)}function Zt(){var c=0,l=0,u;for(u=0;u<arguments.length;u++)c^=arguments[u].lo,l^=arguments[u].hi;return new e(l,c)}function Te(c,l){var u,f,m=32-l;return l<32?(u=c.hi>>>l|c.lo<<m,f=c.lo>>>l|c.hi<<m):l<64&&(u=c.lo>>>l|c.hi<<m,f=c.hi>>>l|c.lo<<m),new e(u,f)}function Oo(c,l,u){var f=c.hi&l.hi^~c.hi&u.hi,m=c.lo&l.lo^~c.lo&u.lo;return new e(f,m)}function Co(c,l,u){var f=c.hi&l.hi^c.hi&u.hi^l.hi&u.hi,m=c.lo&l.lo^c.lo&u.lo^l.lo&u.lo;return new e(f,m)}function jo(c){return Zt(Te(c,28),Te(c,34),Te(c,39))}function Io(c){return Zt(Te(c,14),Te(c,18),Te(c,41))}function Ro(c){return Zt(Te(c,1),Te(c,8),Zr(c,7))}function No(c){return Zt(Te(c,19),Te(c,61),Zr(c,6))}var To=[new e(1116352408,3609767458),new e(1899447441,602891725),new e(3049323471,3964484399),new e(3921009573,2173295548),new e(961987163,4081628472),new e(1508970993,3053834265),new e(2453635748,2937671579),new e(2870763221,3664609560),new e(3624381080,2734883394),new e(310598401,1164996542),new e(607225278,1323610764),new e(1426881987,3590304994),new e(1925078388,4068182383),new e(2162078206,991336113),new e(2614888103,633803317),new e(3248222580,3479774868),new e(3835390401,2666613458),new e(4022224774,944711139),new e(264347078,2341262773),new e(604807628,2007800933),new e(770255983,1495990901),new e(1249150122,1856431235),new e(1555081692,3175218132),new e(1996064986,2198950837),new e(2554220882,3999719339),new e(2821834349,766784016),new e(2952996808,2566594879),new e(3210313671,3203337956),new e(3336571891,1034457026),new e(3584528711,2466948901),new e(113926993,3758326383),new e(338241895,168717936),new e(666307205,1188179964),new e(773529912,1546045734),new e(1294757372,1522805485),new e(1396182291,2643833823),new e(1695183700,2343527390),new e(1986661051,1014477480),new e(2177026350,1206759142),new e(2456956037,344077627),new e(2730485921,1290863460),new e(2820302411,3158454273),new e(3259730800,3505952657),new e(3345764771,106217008),new e(3516065817,3606008344),new e(3600352804,1432725776),new e(4094571909,1467031594),new e(275423344,851169720),new e(430227734,3100823752),new e(506948616,1363258195),new e(659060556,3750685593),new e(883997877,3785050280),new e(958139571,3318307427),new e(1322822218,3812723403),new e(1537002063,2003034995),new e(1747873779,3602036899),new e(1955562222,1575990012),new e(2024104815,1125592928),new e(2227730452,2716904306),new e(2361852424,442776044),new e(2428436474,593698344),new e(2756734187,3733110249),new e(3204031479,2999351573),new e(3329325298,3815920427),new e(3391569614,3928383900),new e(3515267271,566280711),new e(3940187606,3454069534),new e(4118630271,4000239992),new e(116418474,1914138554),new e(174292421,2731055270),new e(289380356,3203993006),new e(460393269,320620315),new e(685471733,587496836),new e(852142971,1086792851),new e(1017036298,365543100),new e(1126000580,2618297676),new e(1288033470,3409855158),new e(1501505948,4234509866),new e(1607167915,987167468),new e(1816402316,1246189591)];function Qr(c,l,u){var f=[],m=[],b=[],v=[],E,g,S;for(g=0;g<8;g++)f[g]=b[g]=J(c,8*g);for(var M=0;u>=128;){for(g=0;g<16;g++)v[g]=J(l,8*g+M);for(g=0;g<80;g++){for(S=0;S<8;S++)m[S]=b[S];for(E=At(b[7],Io(b[4]),Oo(b[4],b[5],b[6]),To[g],v[g%16]),m[7]=At(E,jo(b[0]),Co(b[0],b[1],b[2])),m[3]=At(m[3],E),S=0;S<8;S++)b[(S+1)%8]=m[S];if(g%16===15)for(S=0;S<16;S++)v[S]=At(v[S],v[(S+9)%16],Ro(v[(S+1)%16]),No(v[(S+14)%16]))}for(g=0;g<8;g++)b[g]=At(b[g],f[g]),f[g]=b[g];M+=128,u-=128}for(g=0;g<8;g++)q(c,8*g,f[g]);return u}var Mo=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 Ve(c,l,u){var f=new Uint8Array(64),m=new Uint8Array(256),b,v=u;for(b=0;b<64;b++)f[b]=Mo[b];for(Qr(f,l,u),u%=128,b=0;b<256;b++)m[b]=0;for(b=0;b<u;b++)m[b]=l[v-u+b];for(m[u]=128,u=256-128*(u<112?1:0),m[u-9]=0,q(m,u-8,new e(v/536870912|0,v<<3)),Qr(f,m,u),b=0;b<64;b++)c[b]=f[b];return 0}function Qt(c,l){var u=t(),f=t(),m=t(),b=t(),v=t(),E=t(),g=t(),S=t(),M=t();je(u,c[1],c[0]),je(M,l[1],l[0]),B(u,u,M),Ce(f,c[0],c[1]),Ce(M,l[0],l[1]),B(f,f,M),B(m,c[3],l[3]),B(m,m,_),B(b,c[2],l[2]),Ce(b,b,b),je(v,f,u),je(E,b,m),Ce(g,b,m),Ce(S,f,u),B(c[0],v,E),B(c[1],S,g),B(c[2],g,E),B(c[3],v,S)}function ei(c,l,u){var f;for(f=0;f<4;f++)ae(c[f],l[f],u)}function qs(c,l){var u=t(),f=t(),m=t();Vr(m,l[2]),B(u,l[0],m),B(f,l[1],m),ot(c,f),c[31]^=Kr(u)<<7}function Ls(c,l,u){var f,m;for(V(c[0],o),V(c[1],a),V(c[2],a),V(c[3],o),m=255;m>=0;--m)f=u[m/8|0]>>(m&7)&1,ei(c,l,f),Qt(l,c),Qt(c,c),ei(c,l,f)}function es(c,l){var u=[t(),t(),t(),t()];V(u[0],y),V(u[1],x),V(u[2],a),B(u[3],y,x),Ls(c,u,l)}function Fs(c,l,u){var f=new Uint8Array(64),m=[t(),t(),t(),t()],b;for(u||s(l,32),Ve(f,l,32),f[0]&=248,f[31]&=127,f[31]|=64,es(m,f),qs(c,m),b=0;b<32;b++)l[b+32]=c[b];return 0}var ts=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 Bs(c,l){var u,f,m,b;for(f=63;f>=32;--f){for(u=0,m=f-32,b=f-12;m<b;++m)l[m]+=u-16*l[f]*ts[m-(f-32)],u=Math.floor((l[m]+128)/256),l[m]-=u*256;l[m]+=u,l[f]=0}for(u=0,m=0;m<32;m++)l[m]+=u-(l[31]>>4)*ts[m],u=l[m]>>8,l[m]&=255;for(m=0;m<32;m++)l[m]-=u*ts[m];for(f=0;f<32;f++)l[f+1]+=l[f]>>8,c[f]=l[f]&255}function Ds(c){var l=new Float64Array(64),u;for(u=0;u<64;u++)l[u]=c[u];for(u=0;u<64;u++)c[u]=0;Bs(c,l)}function ti(c,l,u,f){var m=new Uint8Array(64),b=new Uint8Array(64),v=new Uint8Array(64),E,g,S=new Float64Array(64),M=[t(),t(),t(),t()];Ve(m,f,32),m[0]&=248,m[31]&=127,m[31]|=64;var D=u+64;for(E=0;E<u;E++)c[64+E]=l[E];for(E=0;E<32;E++)c[32+E]=m[32+E];for(Ve(v,c.subarray(32),u+32),Ds(v),es(M,v),qs(c,M),E=32;E<64;E++)c[E]=f[E];for(Ve(b,c,u+64),Ds(b),E=0;E<64;E++)S[E]=0;for(E=0;E<32;E++)S[E]=v[E];for(E=0;E<32;E++)for(g=0;g<32;g++)S[E+g]+=b[E]*m[g];return Bs(c.subarray(32),S),D}function $o(c,l){var u=t(),f=t(),m=t(),b=t(),v=t(),E=t(),g=t();return V(c[2],a),Us(c[1],l),Pe(m,c[1]),B(b,m,p),je(m,m,c[2]),Ce(b,c[2],b),Pe(v,b),Pe(E,v),B(g,E,v),B(u,g,m),B(u,u,b),Wr(u,u),B(u,u,m),B(u,u,b),B(u,u,b),B(c[0],u,b),Pe(f,c[0]),B(f,f,b),Gr(f,m)&&B(c[0],c[0],P),Pe(f,c[0]),B(f,f,b),Gr(f,m)?-1:(Kr(c[0])===l[31]>>7&&je(c[0],o,c[0]),B(c[3],c[0],c[1]),0)}function Hs(c,l,u,f){var m,b=new Uint8Array(32),v=new Uint8Array(64),E=[t(),t(),t(),t()],g=[t(),t(),t(),t()];if(u<64||$o(g,f))return-1;for(m=0;m<u;m++)c[m]=l[m];for(m=0;m<32;m++)c[m+32]=f[m];if(Ve(v,c,u),Ds(v),Ls(E,g,v),es(g,l.subarray(32)),Qt(E,g),qs(b,E),u-=64,w(l,0,b,0)){for(m=0;m<u;m++)c[m]=0;return-1}for(m=0;m<u;m++)c[m]=l[m+64];return u}var Js=32,ss=24,Pt=32,at=16,kt=32,rs=32,Ot=32,Ct=32,zs=32,si=ss,Uo=Pt,qo=at,qe=64,We=32,ct=64,Gs=32,Ks=64;r.lowlevel={crypto_core_hsalsa20:R,crypto_stream_xor:K,crypto_stream:U,crypto_stream_salsa20_xor:$,crypto_stream_salsa20:L,crypto_onetimeauth:se,crypto_onetimeauth_verify:oe,crypto_verify_16:pe,crypto_verify_32:w,crypto_secretbox:he,crypto_secretbox_open:ue,crypto_scalarmult:Wt,crypto_scalarmult_base:Yt,crypto_box_beforenm:Xt,crypto_box_afternm:Xr,crypto_box:Po,crypto_box_open:ko,crypto_box_keypair:Yr,crypto_hash:Ve,crypto_sign:ti,crypto_sign_keypair:Fs,crypto_sign_open:Hs,crypto_secretbox_KEYBYTES:Js,crypto_secretbox_NONCEBYTES:ss,crypto_secretbox_ZEROBYTES:Pt,crypto_secretbox_BOXZEROBYTES:at,crypto_scalarmult_BYTES:kt,crypto_scalarmult_SCALARBYTES:rs,crypto_box_PUBLICKEYBYTES:Ot,crypto_box_SECRETKEYBYTES:Ct,crypto_box_BEFORENMBYTES:zs,crypto_box_NONCEBYTES:si,crypto_box_ZEROBYTES:Uo,crypto_box_BOXZEROBYTES:qo,crypto_sign_BYTES:qe,crypto_sign_PUBLICKEYBYTES:We,crypto_sign_SECRETKEYBYTES:ct,crypto_sign_SEEDBYTES:Gs,crypto_hash_BYTES:Ks,gf:t,D:p,L:ts,pack25519:ot,unpack25519:Us,M:B,A:Ce,S:Pe,Z:je,pow2523:Wr,add:Qt,set25519:V,modL:Bs,scalarmult:Ls,scalarbase:es};function ri(c,l){if(c.length!==Js)throw new Error("bad key size");if(l.length!==ss)throw new Error("bad nonce size")}function Lo(c,l){if(c.length!==Ot)throw new Error("bad public key size");if(l.length!==Ct)throw new Error("bad secret key size")}function xe(){for(var c=0;c<arguments.length;c++)if(!(arguments[c]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function ii(c){for(var l=0;l<c.length;l++)c[l]=0}r.randomBytes=function(c){var l=new Uint8Array(c);return s(l,c),l},r.secretbox=function(c,l,u){xe(c,l,u),ri(u,l);for(var f=new Uint8Array(Pt+c.length),m=new Uint8Array(f.length),b=0;b<c.length;b++)f[b+Pt]=c[b];return he(m,f,f.length,l,u),m.subarray(at)},r.secretbox.open=function(c,l,u){xe(c,l,u),ri(u,l);for(var f=new Uint8Array(at+c.length),m=new Uint8Array(f.length),b=0;b<c.length;b++)f[b+at]=c[b];return f.length<32||ue(m,f,f.length,l,u)!==0?null:m.subarray(Pt)},r.secretbox.keyLength=Js,r.secretbox.nonceLength=ss,r.secretbox.overheadLength=at,r.scalarMult=function(c,l){if(xe(c,l),c.length!==rs)throw new Error("bad n size");if(l.length!==kt)throw new Error("bad p size");var u=new Uint8Array(kt);return Wt(u,c,l),u},r.scalarMult.base=function(c){if(xe(c),c.length!==rs)throw new Error("bad n size");var l=new Uint8Array(kt);return Yt(l,c),l},r.scalarMult.scalarLength=rs,r.scalarMult.groupElementLength=kt,r.box=function(c,l,u,f){var m=r.box.before(u,f);return r.secretbox(c,l,m)},r.box.before=function(c,l){xe(c,l),Lo(c,l);var u=new Uint8Array(zs);return Xt(u,c,l),u},r.box.after=r.secretbox,r.box.open=function(c,l,u,f){var m=r.box.before(u,f);return r.secretbox.open(c,l,m)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var c=new Uint8Array(Ot),l=new Uint8Array(Ct);return Yr(c,l),{publicKey:c,secretKey:l}},r.box.keyPair.fromSecretKey=function(c){if(xe(c),c.length!==Ct)throw new Error("bad secret key size");var l=new Uint8Array(Ot);return Yt(l,c),{publicKey:l,secretKey:new Uint8Array(c)}},r.box.publicKeyLength=Ot,r.box.secretKeyLength=Ct,r.box.sharedKeyLength=zs,r.box.nonceLength=si,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(c,l){if(xe(c,l),l.length!==ct)throw new Error("bad secret key size");var u=new Uint8Array(qe+c.length);return ti(u,c,c.length,l),u},r.sign.open=function(c,l){if(xe(c,l),l.length!==We)throw new Error("bad public key size");var u=new Uint8Array(c.length),f=Hs(u,c,c.length,l);if(f<0)return null;for(var m=new Uint8Array(f),b=0;b<m.length;b++)m[b]=u[b];return m},r.sign.detached=function(c,l){for(var u=r.sign(c,l),f=new Uint8Array(qe),m=0;m<f.length;m++)f[m]=u[m];return f},r.sign.detached.verify=function(c,l,u){if(xe(c,l,u),l.length!==qe)throw new Error("bad signature size");if(u.length!==We)throw new Error("bad public key size");var f=new Uint8Array(qe+c.length),m=new Uint8Array(qe+c.length),b;for(b=0;b<qe;b++)f[b]=l[b];for(b=0;b<c.length;b++)f[b+qe]=c[b];return Hs(m,f,f.length,u)>=0},r.sign.keyPair=function(){var c=new Uint8Array(We),l=new Uint8Array(ct);return Fs(c,l),{publicKey:c,secretKey:l}},r.sign.keyPair.fromSecretKey=function(c){if(xe(c),c.length!==ct)throw new Error("bad secret key size");for(var l=new Uint8Array(We),u=0;u<l.length;u++)l[u]=c[32+u];return{publicKey:l,secretKey:new Uint8Array(c)}},r.sign.keyPair.fromSeed=function(c){if(xe(c),c.length!==Gs)throw new Error("bad seed size");for(var l=new Uint8Array(We),u=new Uint8Array(ct),f=0;f<32;f++)u[f]=c[f];return Fs(l,u,!0),{publicKey:l,secretKey:u}},r.sign.publicKeyLength=We,r.sign.secretKeyLength=ct,r.sign.seedLength=Gs,r.sign.signatureLength=qe,r.hash=function(c){xe(c);var l=new Uint8Array(Ks);return Ve(l,c,c.length),l},r.hash.hashLength=Ks,r.verify=function(c,l){return xe(c,l),c.length===0||l.length===0||c.length!==l.length?!1:X(c,0,l,0,c.length)===0},r.setPRNG=function(c){s=c},function(){var c=typeof globalThis<"u"?globalThis.crypto||globalThis.msCrypto:null;if(c&&c.getRandomValues){var l=65536;r.setPRNG(function(u,f){var m,b=new Uint8Array(f);for(m=0;m<f;m+=l)c.getRandomValues(b.subarray(m,m+Math.min(f-m,l)));for(m=0;m<f;m++)u[m]=b[m];ii(b)})}else typeof require<"u"&&(c=require("crypto"),c&&c.randomBytes&&r.setPRNG(function(u,f){var m,b=c.randomBytes(f);for(m=0;m<f;m++)u[m]=b[m];ii(b)}))}()}(typeof module<"u"&&module.exports?module.exports:globalThis.nacl=globalThis.nacl||{});const Ht=typeof module<"u"&&module.exports?module.exports:globalThis.nacl;Ht.sign.keyPair.fromSeed,Ht.sign.detached,Ht.sign.detached.verify,Ht.randomBytes;var Or;(function(r){r.InvalidPrefixByte="nkeys: invalid prefix byte",r.InvalidKey="nkeys: invalid key",r.InvalidPublicKey="nkeys: invalid public key",r.InvalidSeedLen="nkeys: invalid seed length",r.InvalidSeed="nkeys: invalid seed",r.InvalidEncoding="nkeys: invalid encoded key",r.InvalidSignature="nkeys: signature verification failed",r.CannotSign="nkeys: cannot sign, no private key available",r.PublicKeyOnly="nkeys: no seed or private key available",r.InvalidChecksum="nkeys: invalid checksum",r.SerializationError="nkeys: serialization error",r.ApiError="nkeys: api error",r.ClearedPair="nkeys: pair is cleared"})(Or||(Or={}));var Cr;(function(r){r[r.Seed=144]="Seed",r[r.Private=120]="Private",r[r.Operator=112]="Operator",r[r.Server=104]="Server",r[r.Cluster=16]="Cluster",r[r.Account=0]="Account",r[r.User=160]="User"})(Cr||(Cr={}));function Sn(r){return e=>{let t={};return r.forEach(s=>{const i=s(e)||{};t=Object.assign(t,i)}),t}}function vn(){return()=>{}}function En(r,e){return()=>{const t=typeof r=="function"?r():r,s=typeof e=="function"?e():e;return{user:t,pass:s}}}function An(r){return()=>({auth_token:typeof r=="function"?r():r})}const jr=2*60*1e3,Pn=2,Ir=2*1e3;function kn(){return{maxPingOut:2,maxReconnectAttempts:10,noRandomize:!1,pedantic:!1,pingInterval:jr,reconnect:!0,reconnectJitter:100,reconnectJitterTLS:1e3,reconnectTimeWait:Ir,tls:void 0,verbose:!1,waitOnFirstConnect:!1,ignoreAuthErrorAbort:!1}}function On(r){const e=[];return typeof r.authenticator=="function"&&e.push(r.authenticator),Array.isArray(r.authenticator)&&e.push(...r.authenticator),r.token&&e.push(An(r.token)),r.user&&e.push(En(r.user,r.pass)),e.length===0?vn():Sn(e)}function Cn(r){const e=`${cs}:${Sr()}`;if(r=r||{servers:[e]},r.servers=r.servers||[],typeof r.servers=="string"&&(r.servers=[r.servers]),r.servers.length>0&&r.port)throw new N("port and servers options are mutually exclusive",k.InvalidOption);r.servers.length===0&&r.port&&(r.servers=[`${cs}:${r.port}`]),r.servers&&r.servers.length===0&&(r.servers=[e]);const t=Tt(kn(),r);if(t.authenticator=On(t),["reconnectDelayHandler","authenticator"].forEach(s=>{if(t[s]&&typeof t[s]!="function")throw new N(`${s} option should be a function`,k.NotFunction)}),t.reconnectDelayHandler||(t.reconnectDelayHandler=()=>{let s=t.tls?t.reconnectJitterTLS:t.reconnectJitter;return s&&(s++,s=Math.floor(Math.random()*s)),t.reconnectTimeWait+s}),t.inboxPrefix)try{$e(t.inboxPrefix)}catch(s){throw new N(s.message,k.ApiError)}if(t.resolve===void 0&&(t.resolve=typeof Ss()=="function"),t.resolve&&typeof Ss()!="function")throw new N("'resolve' is not supported on this client",k.InvalidOption);return t}function jn(r,e){const{proto:t,tls_required:s,tls_available:i}=r;if((t===void 0||t<1)&&e.noEcho)throw new N("noEcho",k.ServerOptionNotAvailable);const n=s||i||!1;if(e.tls&&!n)throw new N("tls",k.ServerOptionNotAvailable)}const In=1024*32,Rn=/^INFO\s+([^\r\n]+)\r\n/i,Nn=lt(`PONG\r
24
+ `),Rr=lt(`PING\r
25
+ `);class Tn{constructor(e,t,s){h(this,"echo");h(this,"no_responders");h(this,"protocol");h(this,"verbose");h(this,"pedantic");h(this,"jwt");h(this,"nkey");h(this,"sig");h(this,"user");h(this,"pass");h(this,"auth_token");h(this,"tls_required");h(this,"name");h(this,"lang");h(this,"version");h(this,"headers");this.protocol=1,this.version=e.version,this.lang=e.lang,this.echo=t.noEcho?!1:void 0,this.verbose=t.verbose,this.pedantic=t.pedantic,this.tls_required=t.tls?!0:void 0,this.name=t.name;const i=(t&&typeof t.authenticator=="function"?t.authenticator(s):{})||{};Tt(this,i)}}class Nr extends re{constructor(t,s,i={}){var o;super();h(this,"sid");h(this,"queue");h(this,"draining");h(this,"max");h(this,"subject");h(this,"drained");h(this,"protocol");h(this,"timer");h(this,"info");h(this,"cleanupFn");h(this,"closed");h(this,"requestSubject");Tt(this,i),this.protocol=t,this.subject=s,this.draining=!1,this.noIterator=typeof i.callback=="function",this.closed=z();const n=!((o=t.options)!=null&&o.noAsyncTraces);i.timeout&&(this.timer=Ye(i.timeout,n),this.timer.then(()=>{this.timer=void 0}).catch(a=>{this.stop(a),this.noIterator&&this.callback(a,{})})),this.noIterator||this.iterClosed.then(()=>{this.closed.resolve(),this.unsubscribe()})}setPrePostHandlers(t){if(this.noIterator){const s=this.callback,i=t.ingestionFilterFn?t.ingestionFilterFn:()=>({ingest:!0,protocol:!1}),n=t.protocolFilterFn?t.protocolFilterFn:()=>!0,o=t.dispatchedFn?t.dispatchedFn:()=>{};this.callback=(a,d)=>{const{ingest:p}=i(d);p&&n(d)&&(s(a,d),o(d))}}else this.protocolFilterFn=t.protocolFilterFn,this.dispatchedFn=t.dispatchedFn}callback(t,s){this.cancelTimeout(),t?this.stop(t):this.push(s)}close(){if(!this.isClosed()){this.cancelTimeout();const t=()=>{if(this.stop(),this.cleanupFn)try{this.cleanupFn(this,this.info)}catch{}this.closed.resolve()};this.noIterator?t():this.push(t)}}unsubscribe(t){this.protocol.unsubscribe(this,t)}cancelTimeout(){this.timer&&(this.timer.cancel(),this.timer=void 0)}drain(){return this.protocol.isClosed()?Promise.reject(N.errorForCode(k.ConnectionClosed)):this.isClosed()?Promise.reject(N.errorForCode(k.SubClosed)):(this.drained||(this.draining=!0,this.protocol.unsub(this),this.drained=this.protocol.flush(z()).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 Mn{constructor(){h(this,"mux");h(this,"subs");h(this,"sidCounter");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,s=this.all();let i;if(t.operation==="subscription"&&(i=s.find(n=>n.subject===t.subject&&n.queue===t.queue)),t.operation==="publish"&&(i=s.find(n=>n.requestSubject===t.subject)),i)return i.callback(e,{}),i.close(),this.subs.delete(i.sid),i!==this.mux}return!1}close(){this.subs.forEach(e=>{e.close()})}}class Jt{constructor(e,t){h(this,"connected");h(this,"connectedOnce");h(this,"infoReceived");h(this,"info");h(this,"muxSubscriptions");h(this,"options");h(this,"outbound");h(this,"pongs");h(this,"subscriptions");h(this,"transport");h(this,"noMorePublishing");h(this,"connectError");h(this,"publisher");h(this,"_closed");h(this,"closed");h(this,"listeners");h(this,"heartbeats");h(this,"parser");h(this,"outMsgs");h(this,"inMsgs");h(this,"outBytes");h(this,"inBytes");h(this,"pendingLimit");h(this,"lastError");h(this,"abortReconnect");h(this,"whyClosed");h(this,"servers");h(this,"server");h(this,"features");h(this,"connectPromise");this._closed=!1,this.connected=!1,this.connectedOnce=!1,this.infoReceived=!1,this.noMorePublishing=!1,this.abortReconnect=!1,this.listeners=[],this.pendingLimit=In,this.outMsgs=0,this.inMsgs=0,this.outBytes=0,this.inBytes=0,this.options=e,this.publisher=t,this.subscriptions=new Mn,this.muxSubscriptions=new gn,this.outbound=new rt,this.pongs=[],this.whyClosed="",this.pendingLimit=e.pendingLimit||this.pendingLimit,this.features=new Yi({major:0,minor:0,micro:0}),this.connectPromise=null;const s=typeof e.servers=="string"?[e.servers]:e.servers;this.servers=new bn(s,{randomize:!e.noRandomize}),this.closed=z(),this.parser=new kr(this),this.heartbeats=new _n(this,this.options.pingInterval||jr,this.options.maxPingOut||Pn)}resetOutbound(){this.outbound.reset();const e=this.pongs;this.pongs=[];const t=N.errorForCode(k.Disconnect);t.stack="",e.forEach(s=>{s.reject(t)}),this.parser=new kr(this),this.infoReceived=!1}dispatchStatus(e){this.listeners.forEach(t=>{t.push(e)})}status(){const e=new re;return this.listeners.push(e),e}prepare(){this.transport&&this.transport.discard(),this.info=void 0,this.resetOutbound();const e=z();return e.catch(()=>{}),this.pongs.unshift(e),this.connectError=t=>{e.reject(t)},this.transport=Qi(),this.transport.closed().then(async t=>{if(this.connected=!1,!this.isClosed()){await this.disconnected(this.transport.closeError||this.lastError);return}}),e}disconnect(){this.dispatchStatus({type:Fe.StaleConnection,data:""}),this.transport.disconnect()}reconnect(){return this.connected&&(this.dispatchStatus({type:Fe.ClientInitiatedReconnect,data:""}),this.transport.disconnect()),Promise.resolve()}async disconnected(e){this.dispatchStatus({type:Se.Disconnect,data:this.servers.getCurrentServer().toString()}),this.options.reconnect?await this.dialLoop().then(()=>{var t;this.dispatchStatus({type:Se.Reconnect,data:this.servers.getCurrentServer().toString()}),((t=this.lastError)==null?void 0:t.code)===k.AuthenticationExpired&&(this.lastError=void 0)}).catch(t=>{this._close(t)}):await this._close(e)}async dial(e){const t=this.prepare();let s;try{s=Ye(this.options.timeout||2e4);const i=this.transport.connect(e,this.options);await Promise.race([i,s]),(async()=>{try{for await(const n of this.transport)this.parser.parse(n)}catch(n){console.log("reader closed",n)}})().then()}catch(i){t.reject(i)}try{await Promise.race([s,t]),s&&s.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(i){throw s&&s.cancel(),await this.transport.close(i),i}}async _doDial(e){const{resolve:t}=this.options,s=await e.resolve({fn:Ss(),debug:this.options.debug,randomize:!this.options.noRandomize,resolve:t});let i=null;for(const n of s)try{i=null,this.dispatchStatus({type:Fe.Reconnecting,data:n.toString()}),await this.dial(n);return}catch(o){i=o}throw i}dialLoop(){return this.connectPromise===null&&(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():Ir;let s=t;const i=this.selectServer();if(!i||this.abortReconnect)throw e||(this.lastError?this.lastError:N.errorForCode(k.ConnectionRefused));const n=Date.now();if(i.lastConnect===0||i.lastConnect+t<=n){i.lastConnect=Date.now();try{await this._doDial(i);break}catch(o){if(e=o,!this.connectedOnce){if(this.options.waitOnFirstConnect)continue;this.servers.removeCurrentServer()}i.reconnects++;const a=this.options.maxReconnectAttempts||0;a!==-1&&i.reconnects>=a&&this.servers.removeCurrentServer()}}else s=Math.min(s,i.lastConnect+t-n),await Xe(s)}}static async connect(e,t){const s=new Jt(e,t);return await s.dialLoop(),s}static toError(e){const t=e?e.toLowerCase():"";if(t.indexOf("permissions violation")!==-1){const s=new N(e,k.PermissionsViolation),i=e.match(/(Publish|Subscription) to "(\S+)"/);if(i){s.permissionContext={operation:i[1].toLowerCase(),subject:i[2],queue:void 0};const n=e.match(/using queue "(\S+)"/);n&&(s.permissionContext.queue=n[1])}return s}else return t.indexOf("authorization violation")!==-1?new N(e,k.AuthorizationViolation):t.indexOf("user authentication expired")!==-1?new N(e,k.AuthenticationExpired):t.indexOf("account authentication expired")!=-1?new N(e,k.AccountExpired):t.indexOf("authentication timeout")!==-1?new N(e,k.AuthenticationTimeout):new N(e,k.ProtocolError)}processMsg(e,t){if(this.inMsgs++,this.inBytes+=t.length,!this.subscriptions.sidCounter)return;const s=this.subscriptions.get(e.sid);s&&(s.received+=1,s.callback&&s.callback(null,new fs(e,t,this)),s.max!==void 0&&s.received>=s.max&&s.unsubscribe())}processError(e){const t=sr(e),s=Jt.toError(t),i={type:Se.Error,data:s.code};if(s.isPermissionError()){let n=!1;if(s.permissionContext){i.permissionContext=s.permissionContext;const o=this.subscriptions.getMux();n=(o==null?void 0:o.subject)===s.permissionContext.subject}this.subscriptions.handleError(s),this.muxSubscriptions.handleError(n,s),n&&this.subscriptions.setMux(null)}this.dispatchStatus(i),this.handleError(s)}handleError(e){e.isAuthError()?this.handleAuthError(e):e.isProtocolError()?this.lastError=e:e.isAuthTimeout()&&(this.lastError=e),e.isPermissionError()||(this.lastError=e)}handleAuthError(e){this.lastError&&e.code===this.lastError.code&&this.options.ignoreAuthErrorAbort===!1&&(this.abortReconnect=!0),this.connectError?this.connectError(e):this.disconnect()}processPing(){this.transport.send(Nn)}processPong(){const e=this.pongs.shift();e&&e.resolve()}processInfo(e){const t=JSON.parse(sr(e));this.info=t;const s=this.options&&this.options.ignoreClusterUpdates?void 0:this.servers.update(t,this.transport.isEncrypted());if(!this.infoReceived){this.features.update(Ke(t.version)),this.infoReceived=!0,this.transport.isEncrypted()&&this.servers.updateTLSName();const{version:n,lang:o}=this.transport;try{const a=new Tn({version:n,lang:o},this.options,t.nonce);t.headers&&(a.headers=!0,a.no_responders=!0);const d=JSON.stringify(a);this.transport.send(lt(`CONNECT ${d}${Ft}`)),this.transport.send(Rr)}catch(a){this._close(a)}}s&&this.dispatchStatus({type:Se.Update,data:s}),(t.ldm!==void 0?t.ldm:!1)&&this.dispatchStatus({type:Se.LDM,data:this.servers.getCurrentServer().toString()})}push(e){switch(e.kind){case de.MSG:{const{msg:t,data:s}=e;this.processMsg(t,s);break}case de.OK:break;case de.ERR:this.processError(e.data);break;case de.PING:this.processPing();break;case de.PONG:this.processPong();break;case de.INFO:this.processInfo(e.data);break}}sendCommand(e,...t){const s=this.outbound.length();let i;typeof e=="string"?i=lt(e):i=e,this.outbound.fill(i,...t),s===0?queueMicrotask(()=>{this.flushPending()}):this.outbound.size()>=this.pendingLimit&&this.flushPending()}publish(e,t=be,s){let i;if(t instanceof Uint8Array)i=t;else if(typeof t=="string")i=Ge.encode(t);else throw N.errorForCode(k.BadPayload);let n=i.length;s=s||{},s.reply=s.reply||"";let o=be,a=0;if(s.headers){if(this.info&&!this.info.headers)throw new N("headers",k.ServerOptionNotAvailable);o=s.headers.encode(),a=o.length,n=i.length+a}if(this.info&&n>this.info.max_payload)throw N.errorForCode(k.MaxPayloadExceeded);this.outBytes+=n,this.outMsgs++;let d;s.headers?(s.reply?d=`HPUB ${e} ${s.reply} ${a} ${n}\r
26
+ `:d=`HPUB ${e} ${a} ${n}\r
27
+ `,this.sendCommand(d,o,i,Bt)):(s.reply?d=`PUB ${e} ${s.reply} ${n}\r
28
+ `:d=`PUB ${e} ${n}\r
29
+ `,this.sendCommand(d,i,Bt))}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
30
+ `):this.sendCommand(`SUB ${e.subject} ${e.sid}\r
31
+ `)}_subunsub(e){return this._sub(e),e.max&&this.unsubscribe(e,e.max),e}unsubscribe(e,t){this.unsub(e,t),(e.max===void 0||e.received>=e.max)&&this.subscriptions.cancel(e)}unsub(e,t){!e||this.isClosed()||(t?this.sendCommand(`UNSUB ${e.sid} ${t}\r
32
+ `):this.sendCommand(`UNSUB ${e.sid}\r
33
+ `),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=z()),this.pongs.push(e),this.outbound.fill(Rr),this.flushPending(),e}sendSubscriptions(){const e=[];this.subscriptions.all().forEach(t=>{const s=t;s.queue?e.push(`SUB ${s.subject} ${s.queue} ${s.sid}${Ft}`):e.push(`SUB ${s.subject} ${s.sid}${Ft}`)}),e.length&&this.transport.send(lt(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(t=>{t.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(s=>{t.push(s.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 t=this.muxSubscriptions.init(this.options.inboxPrefix),s=new Nr(this,`${t}*`);s.callback=this.muxSubscriptions.dispatcher(),this.subscriptions.setMux(s),this.subscribe(s)}}selectServer(){const e=this.servers.selectServer();if(e!==void 0)return this.server=e,this.server}getServer(){return this.server}}const $n="$SRV";class Tr{constructor(e){h(this,"msg");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,s,i){var n,o;return i=i||{},i.headers=i.headers||Ue(),(n=i.headers)==null||n.set(Rt,`${e}`),(o=i.headers)==null||o.set(It,t),this.msg.respond(s,i)}json(e){return this.msg.json(e)}string(){return this.msg.string()}}class yt{constructor(e,t="",s=""){h(this,"subject");h(this,"queue");h(this,"srv");t!==""&&qn("service group",t);let i="";if(e instanceof wt)this.srv=e,i="";else if(e instanceof yt){const n=e;this.srv=n.srv,s===""&&n.queue!==""&&(s=n.queue),i=n.subject}else throw new Error("unknown ServiceGroup type");this.subject=this.calcSubject(i,t),this.queue=s}calcSubject(e,t=""){return t===""?e:e!==""?`${e}.${t}`:t}addEndpoint(e="",t){t=t||{subject:e};const s=typeof t=="function"?{handler:t,subject:e}:t;dt("endpoint",e);let{subject:i,handler:n,metadata:o,queue:a}=s;i=i||e,a=a||this.queue,Un("endpoint subject",i),i=this.calcSubject(this.subject,i);const d={name:e,subject:i,queue:a,handler:n,metadata:o};return this.srv._addEndpoint(d)}addGroup(e="",t=""){return new yt(this,e,t)}}function Un(r,e){if(e==="")throw new Error(`${r} cannot be empty`);if(e.indexOf(" ")!==-1)throw new Error(`${r} cannot contain spaces: '${e}'`);const t=e.split(".");t.forEach((s,i)=>{if(s===">"&&i!==t.length-1)throw new Error(`${r} cannot have internal '>': '${e}'`)})}function qn(r,e){if(e.indexOf(" ")!==-1)throw new Error(`${r} cannot contain spaces: '${e}'`);e.split(".").forEach(s=>{if(s===">")throw new Error(`${r} name cannot contain internal '>': '${e}'`)})}class wt{constructor(e,t={name:"",version:""}){h(this,"nc");h(this,"_id");h(this,"config");h(this,"handlers");h(this,"internal");h(this,"_stopped");h(this,"_done");h(this,"started");this.nc=e,this.config=Object.assign({},t),this.config.queue||(this.config.queue="q"),dt("name",this.config.name),dt("queue",this.config.queue),Ke(this.config.version),this._id=Le.next(),this.internal=[],this._done=z(),this._stopped=!1,this.handlers=[],this.started=new Date().toISOString(),this.reset(),this.nc.closed().then(()=>{this.close().catch()}).catch(s=>{this.close(s).catch()})}static controlSubject(e,t="",s="",i){const n=i??$n;return t===""&&s===""?`${n}.${e}`:(dt("control subject name",t),s!==""?(dt("control subject id",s),`${n}.${e}.${t}.${s}`):`${n}.${e}.${t}`)}get subjects(){return this.handlers.filter(e=>e.internal===!1).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 t=Ue();if(e instanceof Nt){const s=e;t.set(It,s.message),t.set(Rt,`${s.code}`)}else t.set(It,e.message),t.set(Rt,"500");return t}setupHandler(e,t=!1){const s=t?"":e.queue?e.queue:this.config.queue,{name:i,subject:n,handler:o}=e,a=e;a.internal=t,t&&this.internal.push(a),a.stats=new Ln(i,n,s),a.queue=s;const d=o?(p,_)=>{if(p){this.close(p);return}const y=Date.now();try{o(p,new Tr(_))}catch(x){a.stats.countError(x),_==null||_.respond(be,{headers:this.errorToHeader(x)})}finally{a.stats.countLatency(y)}}:void 0;return a.sub=this.nc.subscribe(n,{callback:d,queue:s}),a.sub.closed.then(()=>{this._stopped||this.close(new Error(`required subscription ${e.subject} stopped`)).catch()}).catch(p=>{if(!this._stopped){const _=new Error(`required subscription ${e.subject} errored: ${p.message}`);_.stack=p.stack,this.close(_).catch()}}),a}info(){return{type:ft.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:s,name:i,queue:n}=e;return{subject:t,metadata:s,name:i,queue_group:n}})}async stats(){const e=[];for(const t of this.handlers){if(typeof this.config.statsHandler=="function")try{t.stats.data=await this.config.statsHandler(t)}catch(s){t.stats.countError(s)}e.push(t.stats.stats(t.qi))}return{type:ft.STATS,name:this.name,id:this.id,version:this.version,started:this.started,metadata:this.metadata,endpoints:e}}addInternalHandler(e,t){const s=`${e}`.toUpperCase();this._doAddInternalHandler(`${s}-all`,e,t),this._doAddInternalHandler(`${s}-kind`,e,t,this.name),this._doAddInternalHandler(`${s}`,e,t,this.name,this.id)}_doAddInternalHandler(e,t,s,i="",n=""){const o={};o.name=e,o.subject=wt.controlSubject(t,i,n),o.handler=s,this.setupHandler(o,!0)}start(){const e=ve(),t=(o,a)=>o?(this.close(o),Promise.reject(o)):this.stats().then(d=>(a==null||a.respond(e.encode(d)),Promise.resolve())),s=(o,a)=>o?(this.close(o),Promise.reject(o)):(a==null||a.respond(e.encode(this.info())),Promise.resolve()),i=e.encode(this.ping()),n=(o,a)=>o?(this.close(o).then().catch(),Promise.reject(o)):(a.respond(i),Promise.resolve());return this.addInternalHandler(Be.PING,n),this.addInternalHandler(Be.STATS,t),this.addInternalHandler(Be.INFO,s),this.handlers.forEach(o=>{const{subject:a}=o;typeof a=="string"&&o.handler!==null&&this.setupHandler(o)}),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(s=>s.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:ft.PING,name:this.name,id:this.id,version:this.version,metadata:this.metadata}}reset(){if(this.started=new Date().toISOString(),this.handlers)for(const e of this.handlers)e.stats.reset(e.qi)}addGroup(e,t){return new yt(this,e,t)}addEndpoint(e,t){return new yt(this).addEndpoint(e,t)}_addEndpoint(e){const t=new re;t.noIterator=typeof e.handler=="function",t.noIterator||(e.handler=(i,n)=>{i?this.stop(i).catch():t.push(new Tr(n))},t.iterClosed.then(()=>{this.close().catch()}));const s=this.setupHandler(e,!1);return s.qi=t,this.handlers.push(s),t}}class Ln{constructor(e,t,s=""){h(this,"name");h(this,"subject");h(this,"average_processing_time");h(this,"num_requests");h(this,"processing_time");h(this,"num_errors");h(this,"last_error");h(this,"data");h(this,"metadata");h(this,"queue");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=s}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+=G(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:s,num_errors:i,num_requests:n,processing_time:o,last_error:a,data:d,queue:p}=this;return{name:e,subject:t,average_processing_time:s,num_errors:i,num_requests:n,processing_time:o,last_error:a,data:d,queue_group:p}}stats(e){const t=e;return(t==null?void 0:t.noIterator)===!1&&(this.processing_time=G(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 Fn{constructor(e,t={strategy:ke.JitterTimer,maxWait:2e3},s){h(this,"nc");h(this,"prefix");h(this,"opts");this.nc=e,this.prefix=s,this.opts=t}ping(e="",t=""){return this.q(Be.PING,e,t)}stats(e="",t=""){return this.q(Be.STATS,e,t)}info(e="",t=""){return this.q(Be.INFO,e,t)}async q(e,t="",s=""){const i=new re,n=ve(),o=wt.controlSubject(e,t,s,this.prefix),a=await this.nc.requestMany(o,be,this.opts);return(async()=>{for await(const d of a)try{const p=n.decode(d.data);i.push(p)}catch(p){i.push(()=>{i.stop(p)})}i.push(()=>{i.stop()})})().catch(d=>{i.stop(d)}),i}}function Mr(){return{key:{encode(r){return r},decode(r){return r}},value:{encode(r){return r},decode(r){return r}}}}function Bn(){return{replicas:1,history:1,timeout:2e3,max_bytes:-1,maxValueSize:-1,codec:Mr(),storage:gs.File}}const zt="KV-Operation",$r="$KV",Dn=/^[-/=.\w]+$/,Hn=/^[-/=.>*\w]+$/,Jn=/^[-\w]+$/;function zn(r){if(r.startsWith(".")||r.endsWith(".")||!Dn.test(r))throw new Error(`invalid key: ${r}`)}function Gn(r){if(r.startsWith(".")||r.endsWith(".")||!Hn.test(r))throw new Error(`invalid key: ${r}`)}function Kn(r){if(r.startsWith(".")||r.endsWith("."))throw new Error(`invalid key: ${r}`);const e=r.split(".");let t=!1;for(let s=0;s<e.length;s++)switch(e[s]){case"*":t=!0;break;case">":if(s!==e.length-1)throw new Error(`invalid key: ${r}`);t=!0;break}return t}function Gt(r){if(!Jn.test(r))throw new Error(`invalid bucket name: ${r}`)}var Re;(function(r){r.MsgIdHdr="Nats-Msg-Id",r.ExpectedStreamHdr="Nats-Expected-Stream",r.ExpectedLastSeqHdr="Nats-Expected-Last-Sequence",r.ExpectedLastMsgIdHdr="Nats-Expected-Last-Msg-Id",r.ExpectedLastSubjectSequenceHdr="Nats-Expected-Last-Subject-Sequence"})(Re||(Re={}));class xt{constructor(e,t,s){h(this,"js");h(this,"jsm");h(this,"stream");h(this,"bucket");h(this,"direct");h(this,"codec");h(this,"prefix");h(this,"editPrefix");h(this,"useJsPrefix");h(this,"_prefixLen");h(this,"validateKey",zn);h(this,"validateSearchKey",Gn);h(this,"hasWildcards",Kn);Gt(e),this.js=t,this.jsm=s,this.bucket=e,this.prefix=$r,this.editPrefix="",this.useJsPrefix=!1,this._prefixLen=0}static async create(e,t,s={}){Gt(t);const i=await e.jetstreamManager(),n=new xt(t,e,i);return await n.init(s),n}static async bind(e,t,s={}){const i=await e.jetstreamManager(),n={config:{allow_direct:s.allow_direct}};Gt(t);const o=new xt(t,e,i);return n.config.name=s.streamName??o.bucketName(),Object.assign(o,n),o.stream=n.config.name,o.codec=s.codec||Mr(),o.direct=n.config.allow_direct??!1,o.initializePrefixes(n),o}async init(e={}){const t=Object.assign(Bn(),e);this.codec=t.codec;const s={};this.stream=s.name=e.streamName??this.bucketName(),s.retention=bs.Limits,s.max_msgs_per_subject=t.history,t.maxBucketSize&&(t.max_bytes=t.maxBucketSize),t.max_bytes&&(s.max_bytes=t.max_bytes),s.max_msg_size=t.maxValueSize,s.storage=t.storage;const i=e.placementCluster??"";if(i&&(e.placement={},e.placement.cluster=i,e.placement.tags=[]),e.placement&&(s.placement=e.placement),e.republish&&(s.republish=e.republish),e.description&&(s.description=e.description),e.mirror){const y=Object.assign({},e.mirror);y.name.startsWith(ye)||(y.name=`${ye}${y.name}`),s.mirror=y,s.mirror_direct=!0}else if(e.sources){const y=e.sources.map(x=>{const P=Object.assign({},x),j=P.name.startsWith(ye)?P.name.substring(ye.length):P.name;return P.name.startsWith(ye)||(P.name=`${ye}${P.name}`),!x.external&&j!==this.bucket&&(P.subject_transforms=[{src:`$KV.${j}.>`,dest:`$KV.${this.bucket}.>`}]),P});s.sources=y,s.subjects=[this.subjectForBucket()]}else s.subjects=[this.subjectForBucket()];e.metadata&&(s.metadata=e.metadata),typeof e.compression=="boolean"&&(s.compression=e.compression?He.S2:He.None);const n=this.js.nc,o=n.getServerVersion(),a=o?ws(o,Ke("2.7.2"))>=0:!1;s.discard=a?pt.New:pt.Old;const{ok:d,min:p}=n.features.get(H.JS_ALLOW_DIRECT);if(!d&&e.allow_direct===!0){const y=o?`${o.major}.${o.minor}.${o.micro}`:"unknown";return Promise.reject(new Error(`allow_direct is not available on server version ${y} - requires ${p}`))}e.allow_direct=typeof e.allow_direct=="boolean"?e.allow_direct:d,s.allow_direct=e.allow_direct,this.direct=s.allow_direct,s.num_replicas=t.replicas,t.ttl&&(s.max_age=G(t.ttl)),s.allow_rollup_hdrs=!0;let _;try{_=await this.jsm.streams.info(s.name),!_.config.allow_direct&&this.direct===!0&&(this.direct=!1)}catch(y){if(y.message==="stream not found")_=await this.jsm.streams.add(s);else throw y}this.initializePrefixes(_)}initializePrefixes(e){this._prefixLen=0,this.prefix=`$KV.${this.bucket}`,this.useJsPrefix=this.js.apiPrefix!=="$JS.API";const{mirror:t}=e.config;if(t){let s=t.name;if(s.startsWith(ye)&&(s=s.substring(ye.length)),t.external&&t.external.api!==""){const i=t.name.substring(ye.length);this.useJsPrefix=!1,this.prefix=`$KV.${i}`,this.editPrefix=`${t.external.api}.$KV.${s}`}else this.editPrefix=this.prefix}}bucketName(){return this.stream??`${ye}${this.bucket}`}subjectForBucket(){return`${this.prefix}.${this.bucket}.>`}subjectForKey(e,t=!1){const s=[];return t?(this.useJsPrefix&&s.push(this.js.apiPrefix),this.editPrefix!==""?s.push(this.editPrefix):s.push(this.prefix)):this.prefix&&s.push(this.prefix),s.push(e),s.join(".")}fullKeyName(e){return this.prefix!==""?`${this.prefix}.${e}`:`${$r}.${this.bucket}.${e}`}get prefixLen(){return this._prefixLen===0&&(this._prefixLen=this.prefix.length+1),this._prefixLen}encodeKey(e){const t=[];for(const s of e.split("."))switch(s){case">":case"*":t.push(s);break;default:t.push(this.codec.key.encode(s));break}return t.join(".")}decodeKey(e){const t=[];for(const s of e.split("."))switch(s){case">":case"*":t.push(s);break;default:t.push(this.codec.key.decode(s));break}return t.join(".")}close(){return Promise.resolve()}dataLen(e,t){const s=t&&t.get(fe.MessageSizeHdr)||"";return s!==""?parseInt(s,10):e.length}smToEntry(e){return new co(this.bucket,this.prefixLen,e)}jmToEntry(e){const t=this.decodeKey(e.subject.substring(this.prefixLen));return new ho(this.bucket,t,e)}async create(e,t){var n;let s;try{const o=await this.put(e,t,{previousSeq:0});return Promise.resolve(o)}catch(o){if(s=o,((n=o==null?void 0:o.api_error)==null?void 0:n.err_code)!==10071)return Promise.reject(o)}let i=0;try{const o=await this.get(e);return(o==null?void 0:o.operation)==="DEL"||(o==null?void 0:o.operation)==="PURGE"?(i=o!==null?o.revision:0,this.update(e,t,i)):Promise.reject(s)}catch(o){return Promise.reject(o)}}update(e,t,s){if(s<=0)throw new Error("version must be greater than 0");return this.put(e,t,{previousSeq:s})}async put(e,t,s={}){var o,a;const i=this.encodeKey(e);this.validateKey(i);const n={};if(s.previousSeq!==void 0){const d=Ue();n.headers=d,d.set(Re.ExpectedLastSubjectSequenceHdr,`${s.previousSeq}`)}try{return(await this.js.publish(this.subjectForKey(i,!0),t,n)).seq}catch(d){const p=d;return p.isJetStreamError()?(p.message=(o=p.api_error)==null?void 0:o.description,p.code=`${(a=p.api_error)==null?void 0:a.code}`,Promise.reject(p)):Promise.reject(d)}}async get(e,t){const s=this.encodeKey(e);this.validateKey(s);let i={last_by_subj:this.subjectForKey(s)};t&&t.revision>0&&(i={seq:t.revision});let n;try{this.direct?n=await this.jsm.direct.getMessage(this.bucketName(),i):n=await this.jsm.streams.getMessage(this.bucketName(),i);const o=this.smToEntry(n);return o.key!==s?null:o}catch(o){if(o.code===k.JetStream404NoMessages)return null;throw o}}purge(e,t){return this._deleteOrPurge(e,"PURGE",t)}delete(e,t){return this._deleteOrPurge(e,"DEL",t)}async purgeDeletes(e=30*60*1e3){const t=z(),s=[],i=await this.watch({key:">",initializedFn:()=>{t.resolve()}});(async()=>{for await(const d of i)(d.operation==="DEL"||d.operation==="PURGE")&&s.push(d)})().then(),await t,i.stop();const n=Date.now()-e,o=s.map(d=>{const p=this.subjectForKey(d.key);return d.created.getTime()>=n?this.jsm.streams.purge(this.stream,{filter:p,keep:1}):this.jsm.streams.purge(this.stream,{filter:p,keep:0})}),a=await Promise.all(o);return a.unshift({success:!0,purged:0}),a.reduce((d,p)=>(d.purged+=p.purged,d))}async _deleteOrPurge(e,t,s){if(!this.hasWildcards(e))return this._doDeleteOrPurge(e,t,s);const i=await this.keys(e),n=[];for await(const o of i)n.push(this._doDeleteOrPurge(o,t)),n.length===100&&(await Promise.all(n),n.length=0);n.length>0&&await Promise.all(n)}async _doDeleteOrPurge(e,t,s){const i=this.encodeKey(e);this.validateKey(i);const n=Ue();n.set(zt,t),t==="PURGE"&&n.set(fe.RollupHdr,fe.RollupValueSubject),s!=null&&s.previousSeq&&n.set(Re.ExpectedLastSubjectSequenceHdr,`${s.previousSeq}`),await this.js.publish(this.subjectForKey(i,!0),be,{headers:n})}_buildCC(e,t,s={}){let n=(Array.isArray(e)?e:[e]).map(d=>{const p=this.encodeKey(d);return this.validateSearchKey(d),this.fullKeyName(p)}),o=Z.LastPerSubject;t===Oe.AllHistory&&(o=Z.All),t===Oe.UpdatesOnly&&(o=Z.New);let a;return n.length===1&&(a=n[0],n=void 0),Object.assign({deliver_policy:o,ack_policy:ie.None,filter_subjects:n,filter_subject:a,flow_control:!0,idle_heartbeat:G(5*1e3)},s)}remove(e){return this.purge(e)}async history(e={}){const t=e.key??">",s=new re,i={};i.headers_only=e.headers_only||!1;let n;n=()=>{s.stop()};let o=0;const a=this._buildCC(t,Oe.AllHistory,i),d=a.filter_subject,p=Je(a);p.bindStream(this.stream),p.orderedConsumer(),p.callback((y,x)=>{if(y){s.stop(y);return}if(x){const P=this.jmToEntry(x);s.push(P),s.received++,(n&&o>0&&s.received>=o||x.info.pending===0)&&(s.push(n),n=void 0)}});const _=await this.js.subscribe(d,p);if(n){const{info:{last:y}}=_,x=y.num_pending+y.delivered.consumer_seq;if(x===0||s.received>=x)try{n()}catch(P){s.stop(P)}finally{n=void 0}else o=x}return s._data=_,s.iterClosed.then(()=>{_.unsubscribe()}),_.closed.then(()=>{s.stop()}).catch(y=>{s.stop(y)}),s}canSetWatcherName(){const t=this.js.nc,{ok:s}=t.features.get(H.JS_NEW_CONSUMER_CREATE_API);return s}async watch(e={}){const t=e.key??">",s=new re,i={};i.headers_only=e.headers_only||!1;let n=Oe.LastValue;e.include===Oe.AllHistory?n=Oe.AllHistory:e.include===Oe.UpdatesOnly&&(n=Oe.UpdatesOnly);const o=e.ignoreDeletes===!0;let a=e.initializedFn,d=0;const p=this._buildCC(t,n,i),_=p.filter_subject,y=Je(p);this.canSetWatcherName()&&y.consumerName(Le.next()),y.bindStream(this.stream),e.resumeFromRevision&&e.resumeFromRevision>0&&y.startSequence(e.resumeFromRevision),y.orderedConsumer(),y.callback((P,j)=>{if(P){s.stop(P);return}if(j){const T=this.jmToEntry(j);if(o&&T.operation==="DEL")return;s.push(T),s.received++,a&&(d>0&&s.received>=d||j.info.pending===0)&&(s.push(a),a=void 0)}});const x=await this.js.subscribe(_,y);if(a){const{info:{last:P}}=x,j=P.num_pending+P.delivered.consumer_seq;if(j===0||s.received>=j)try{a()}catch(T){s.stop(T)}finally{a=void 0}else d=j}return s._data=x,s.iterClosed.then(()=>{x.unsubscribe()}),x.closed.then(()=>{s.stop()}).catch(P=>{s.stop(P)}),s}async keys(e=">"){const t=new re,s=this._buildCC(e,Oe.LastValue,{headers_only:!0}),i=Array.isArray(e)?">":s.filter_subject,n=Je(s);n.bindStream(this.stream),n.orderedConsumer();const o=await this.js.subscribe(i,n);return(async()=>{var d;for await(const p of o){const _=(d=p.headers)==null?void 0:d.get(zt);if(_!=="DEL"&&_!=="PURGE"){const y=this.decodeKey(p.subject.substring(this.prefixLen));t.push(y)}p.info.pending===0&&o.unsubscribe()}})().then(()=>{t.stop()}).catch(d=>{t.stop(d)}),o.info.last.num_pending===0&&o.unsubscribe(),t}purgeBucket(e){return this.jsm.streams.purge(this.bucketName(),e)}destroy(){return this.jsm.streams.delete(this.bucketName())}async status(){var n;const t=((n=this.js.nc.info)==null?void 0:n.cluster)??"",s=this.bucketName(),i=await this.jsm.streams.info(s);return new Ur(i,t)}}class Ur{constructor(e,t=""){h(this,"si");h(this,"cluster");this.si=e,this.cluster=t}get bucket(){return this.si.config.name.startsWith(ye)?this.si.config.name.substring(ye.length):this.si.config.name}get values(){return this.si.state.messages}get history(){return this.si.config.max_msgs_per_subject}get ttl(){return us(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(){var e;return((e=this.si.config.placement)==null?void 0:e.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!==He.None:!1}}const ks="OBJ_",qr="SHA-256=";function Vn(r){return Gt(r),`${ks}${r}`}function Wn(r){return r.startsWith(ks)?r.substring(4):r}class Os{constructor(e){h(this,"si");h(this,"backingStore");this.si=e,this.backingStore="JetStream"}get bucket(){return Wn(this.si.config.name)}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!==He.None:!1}}function Kt(r){if(r===void 0)return;const{domain:e}=r;if(e===void 0)return r;const t=Object.assign({},r);if(delete t.domain,e==="")return t;if(t.external)throw new Error("domain and external are both set");return t.external={api:`$JS.${e}.API`},t}var Ae;(function(r){r[r.Unset=-1]="Unset",r[r.Consume=0]="Consume",r[r.Fetch=1]="Fetch"})(Ae||(Ae={}));var Ne;(function(r){r.HeartbeatsMissed="heartbeats_missed",r.ConsumerNotFound="consumer_not_found",r.StreamNotFound="stream_not_found",r.ConsumerDeleted="consumer_deleted",r.OrderedConsumerRecreated="ordered_consumer_recreated",r.NoResponders="no_responders"})(Ne||(Ne={}));var nt;(function(r){r.DebugEvent="debug",r.Discard="discard",r.Reset="reset",r.Next="next"})(nt||(nt={}));const Lr=Uint8Array.of(43,65,67,75),Yn=Uint8Array.of(45,78,65,75),St=Uint8Array.of(43,87,80,73),Xn=Uint8Array.of(43,78,88,84),Zn=Uint8Array.of(43,84,69,82,77),Qn=Uint8Array.of(32);function vt(r,e=5e3){return new go(r,e)}class Cs extends re{constructor(t,s,i=!1){super();h(this,"consumer");h(this,"opts");h(this,"sub");h(this,"monitor");h(this,"pending");h(this,"inbox");h(this,"refilling");h(this,"pong");h(this,"callback");h(this,"timeout");h(this,"cleanupHandler");h(this,"listeners");h(this,"statusIterator");h(this,"forOrderedConsumer");h(this,"resetHandler");h(this,"abortOnMissingResource");h(this,"bind");h(this,"inBackOff");this.consumer=t;const n=s;this.opts=this.parseOptions(s,i),this.callback=n.callback||null,this.noIterator=typeof this.callback=="function",this.monitor=null,this.pong=null,this.pending={msgs:0,bytes:0,requests:0},this.refilling=i,this.timeout=null,this.inbox=$e(t.api.nc.options.inboxPrefix),this.listeners=[],this.forOrderedConsumer=!1,this.abortOnMissingResource=n.abort_on_missing_resource===!0,this.bind=n.bind===!0,this.inBackOff=!1,this.start()}start(){const{max_messages:t,max_bytes:s,idle_heartbeat:i,threshold_bytes:n,threshold_messages:o}=this.opts;this.closed().then(d=>{if(this.cleanupHandler)try{this.cleanupHandler(d)}catch{}});const{sub:a}=this;a&&a.unsubscribe(),this.sub=this.consumer.api.nc.subscribe(this.inbox,{callback:(d,p)=>{var y,x,P,j;if(d){this.stop(d);return}if((y=this.monitor)==null||y.work(),p.subject===this.inbox){if(ps(p))return;const T=(x=p.headers)==null?void 0:x.code,J=((j=(P=p.headers)==null?void 0:P.description)==null?void 0:j.toLowerCase())||"unknown",{msgsLeft:Q,bytesLeft:q}=this.parseDiscard(p.headers);if(Q>0||q>0)this.pending.msgs-=Q,this.pending.bytes-=q,this.pending.requests--,this.notify(nt.Discard,{msgsLeft:Q,bytesLeft:q});else if(T===400){this.stop(new N(J,`${T}`));return}else if(T===409&&J==="consumer deleted"){if(this.notify(Ne.ConsumerDeleted,`${T} ${J}`),!this.refilling||this.abortOnMissingResource){const X=new N(J,`${T}`);this.stop(X);return}}else if(T===503){if(this.notify(Ne.NoResponders,`${T} No Responders`),!this.refilling||this.abortOnMissingResource){const X=new N("no responders",`${T}`);this.stop(X);return}}else this.notify(nt.DebugEvent,`${T} ${J}`)}else this._push(vt(p,this.consumer.api.timeout)),this.received++,this.pending.msgs&&this.pending.msgs--,this.pending.bytes&&(this.pending.bytes-=p.size());if(this.pending.msgs===0&&this.pending.bytes===0&&(this.pending.requests=0),this.refilling){if(t&&this.pending.msgs<=o||s&&this.pending.bytes<=n){const T=this.pullOptions();this.pull(T)}}else this.pending.requests===0&&this._push(()=>{this.stop()})}}),this.sub.closed.then(()=>{this.sub.draining&&this._push(()=>{this.stop()})}),i&&(this.monitor=new ms(i,d=>(this.notify(Ne.HeartbeatsMissed,d),this.resetPending().then(()=>{}).catch(()=>{}),!1),{maxOut:2})),(async()=>{var p;const d=this.consumer.api.nc.status();this.statusIterator=d;for await(const _ of d)switch(_.type){case Se.Disconnect:(p=this.monitor)==null||p.cancel();break;case Se.Reconnect:this.resetPending().then(y=>{var x;y&&((x=this.monitor)==null||x.restart())}).catch(()=>{});break}})(),this.pull(this.pullOptions())}_push(t){if(!this.callback)super.push(t);else{const s=typeof t=="function"?t:null;try{s?s():this.callback(t)}catch(i){this.stop(i)}}}notify(t,s){this.listeners.length>0&&this.listeners.forEach(i=>{i.done||i.push({type:t,data:s})})}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 t=0,s=0;const i=hs([this.opts.expires]);let n=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,t=0,this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),!0}catch(o){if(o.message==="stream not found"){if(s++,this.notify(Ne.StreamNotFound,s),!this.refilling||this.abortOnMissingResource)return this.stop(o),!1}else if(o.message==="consumer not found"){if(t++,this.notify(Ne.ConsumerNotFound,t),this.resetHandler)try{this.resetHandler()}catch{}if(!this.refilling||this.abortOnMissingResource)return this.stop(o),!1;if(this.forOrderedConsumer)return!1}else t=0,s=0;this.inBackOff=!0;const a=i.backoff(n),d=Xe(a);await Promise.race([d,this.consumer.api.nc.closed()]),d.cancel(),n++}}}pull(t){this.pending.bytes+=t.max_bytes??0,this.pending.msgs+=t.batch??0,this.pending.requests++;const s=this.consumer.api.nc;this._push(()=>{s.publish(`${this.consumer.api.prefix}.CONSUMER.MSG.NEXT.${this.consumer.stream}.${this.consumer.name}`,this.consumer.api.jc.encode(t),{reply:this.inbox}),this.notify(nt.Next,t)})}pullOptions(){const t=this.opts.max_messages-this.pending.msgs,s=this.opts.max_bytes-this.pending.bytes,i=G(this.opts.idle_heartbeat),n=G(this.opts.expires);return{batch:t,max_bytes:s,idle_heartbeat:i,expires:n}}parseDiscard(t){const s={msgsLeft:0,bytesLeft:0},i=t==null?void 0:t.get(fe.PendingMessagesHdr);i&&(s.msgsLeft=parseInt(i));const n=t==null?void 0:t.get(fe.PendingBytesHdr);return n&&(s.bytesLeft=parseInt(n)),s}trackTimeout(t){this.timeout=t}close(){return this.stop(),this.iterClosed}closed(){return this.iterClosed}clearTimers(){var t,s;(t=this.monitor)==null||t.cancel(),this.monitor=null,(s=this.timeout)==null||s.cancel(),this.timeout=null}setCleanupHandler(t){this.cleanupHandler=t}stop(t){var s,i;this.done||((s=this.sub)==null||s.unsubscribe(),this.clearTimers(),(i=this.statusIterator)==null||i.stop(),this._push(()=>{super.stop(t),this.listeners.forEach(n=>{n.stop()})}))}parseOptions(t,s=!1){const i=t||{};if(i.max_messages=i.max_messages||0,i.max_bytes=i.max_bytes||0,i.max_messages!==0&&i.max_bytes!==0)throw new Error("only specify one of max_messages or max_bytes");if(i.max_messages===0&&(i.max_messages=100),i.expires=i.expires||3e4,i.expires<1e3)throw new Error("expires should be at least 1000ms");if(i.idle_heartbeat=i.idle_heartbeat||i.expires/2,i.idle_heartbeat=i.idle_heartbeat>3e4?3e4:i.idle_heartbeat,s){const n=Math.round(i.max_messages*.75)||1;i.threshold_messages=i.threshold_messages||n;const o=Math.round(i.max_bytes*.75)||1;i.threshold_bytes=i.threshold_bytes||o}return i}status(){const t=new re;return this.listeners.push(t),Promise.resolve(t)}}class eo extends re{constructor(){super();h(this,"src");h(this,"listeners");this.listeners=[]}setSource(t){this.src&&(this.src.resetHandler=void 0,this.src.setCleanupHandler(),this.src.stop()),this.src=t,this.src.setCleanupHandler(s=>{this.stop(s||void 0)}),(async()=>{const s=await this.src.status();for await(const i of s)this.notify(i.type,i.data)})().catch(()=>{})}notify(t,s){this.listeners.length>0&&this.listeners.forEach(i=>{i.done||i.push({type:t,data:s})})}stop(t){var s;this.done||((s=this.src)==null||s.stop(t),super.stop(t),this.listeners.forEach(i=>{i.stop()}))}close(){return this.stop(),this.iterClosed}closed(){return this.iterClosed}status(){const t=new re;return this.listeners.push(t),Promise.resolve(t)}}class js{constructor(e,t){h(this,"api");h(this,"_info");h(this,"stream");h(this,"name");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 Cs(this,e,!0))}fetch(e={max_messages:100,expires:3e4}){const t=new Cs(this,e,!1),s=Math.round(t.opts.expires*1.05),i=Ye(s);return t.closed().catch(()=>{}).finally(()=>{i.cancel()}),i.catch(()=>{t.close().catch()}),t.trackTimeout(i),Promise.resolve(t)}next(e={expires:3e4}){const t=z(),s=e;s.max_messages=1;const i=new Cs(this,s,!1),n=Math.round(i.opts.expires*1.05);n>=6e4&&(async()=>{for await(const a of await i.status())if(a.type===Ne.HeartbeatsMissed&&a.data>=2){t.reject(new Error("consumer missed heartbeats"));break}})().catch(),(async()=>{for await(const a of i){t.resolve(a);break}})().catch(()=>{});const o=Ye(n);return i.closed().then(a=>{a?t.reject(a):t.resolve(null)}).catch(a=>{t.reject(a)}).finally(()=>{o.cancel()}),o.catch(a=>{t.resolve(null),i.close().catch()}),i.trackTimeout(o),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:s}=this._info;return this.api.info(t,s).then(i=>(this._info=i,this._info))}}class to{constructor(e,t,s={}){h(this,"api");h(this,"consumerOpts");h(this,"consumer");h(this,"opts");h(this,"cursor");h(this,"stream");h(this,"namePrefix");h(this,"serial");h(this,"currentConsumer");h(this,"userCallback");h(this,"iter");h(this,"type");h(this,"startSeq");h(this,"maxInitialReset");this.api=e,this.stream=t,this.cursor={stream_seq:1,deliver_seq:0},this.namePrefix=Le.next(),typeof s.name_prefix=="string"&&($t("name_prefix",s.name_prefix),this.namePrefix=s.name_prefix+this.namePrefix),this.serial=0,this.currentConsumer=null,this.userCallback=null,this.iter=null,this.type=Ae.Unset,this.consumerOpts=s,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++;const t=`${this.namePrefix}_${this.serial}`;e=e===0?1:e;const s={name:t,deliver_policy:Z.StartSequence,opt_start_seq:e,ack_policy:ie.None,inactive_threshold:G(5*60*1e3),num_replicas:1};return this.consumerOpts.headers_only===!0&&(s.headers_only=!0),Array.isArray(this.consumerOpts.filterSubjects)&&(s.filter_subjects=this.consumerOpts.filterSubjects),typeof this.consumerOpts.filterSubjects=="string"&&(s.filter_subject=this.consumerOpts.filterSubjects),this.consumerOpts.replay_policy&&(s.replay_policy=this.consumerOpts.replay_policy),e===this.startSeq+1&&(s.deliver_policy=this.consumerOpts.deliver_policy||Z.StartSequence,(this.consumerOpts.deliver_policy===Z.LastPerSubject||this.consumerOpts.deliver_policy===Z.New||this.consumerOpts.deliver_policy===Z.Last)&&(delete s.opt_start_seq,s.deliver_policy=this.consumerOpts.deliver_policy),s.deliver_policy===Z.LastPerSubject&&typeof s.filter_subjects>"u"&&typeof s.filter_subject>"u"&&(s.filter_subject=">"),this.consumerOpts.opt_start_time&&(delete s.opt_start_seq,s.deliver_policy=Z.StartTime,s.opt_start_time=this.consumerOpts.opt_start_time),this.consumerOpts.inactive_threshold&&(s.inactive_threshold=G(this.consumerOpts.inactive_threshold))),s}async resetConsumer(e=0){var o,a,d,p,_;Le.next();const t=this.serial===0;(o=this.consumer)==null||o.delete().catch(()=>{}),e=e===0?1:e,this.cursor.deliver_seq=0;const s=this.getConsumerOpts(e);s.max_deliver=1,s.mem_storage=!0;const i=hs([((a=this.opts)==null?void 0:a.expires)||3e4]);let n;for(let y=0;;y++)try{n=await this.api.add(this.stream,s),(d=this.iter)==null||d.notify(Ne.OrderedConsumerRecreated,n.name);break}catch(x){if(x.message==="stream not found"&&((p=this.iter)==null||p.notify(Ne.StreamNotFound,y),this.type===Ae.Fetch||this.opts.abort_on_missing_resource===!0))return(_=this.iter)==null||_.stop(x),Promise.reject(x);if(t&&y>=this.maxInitialReset)throw x;await Xe(i.backoff(y+1))}return n}internalHandler(e){return t=>{var i;if(this.serial!==e)return;const s=t.info.deliverySequence;if(s!==this.cursor.deliver_seq+1){this.notifyOrderedResetAndReset();return}this.cursor.deliver_seq=s,this.cursor.stream_seq=t.info.streamSequence,this.userCallback?this.userCallback(t):(i=this.iter)==null||i.push(t)}}async reset(e={max_messages:100,expires:3e4},t){var d,p;t=t||{};const s=t.fromFetch||!1,i=t.orderedReset||!1;if(this.type===Ae.Fetch&&i){(d=this.iter)==null||d.src.stop(),await((p=this.iter)==null?void 0:p.closed()),this.currentConsumer=null;return}(this.currentConsumer===null||i)&&(this.currentConsumer=await this.resetConsumer(this.cursor.stream_seq+1)),(this.iter===null||s)&&(this.iter=new eo),this.consumer=new js(this.api,this.currentConsumer);const n=e;n.callback=this.internalHandler(this.serial);let o=null;this.type===Ae.Fetch&&s?o=await this.consumer.fetch(e):this.type===Ae.Consume&&(o=await this.consumer.consume(e));const a=o;a.forOrderedConsumer=!0,a.resetHandler=()=>{this.notifyOrderedResetAndReset()},this.iter.setSource(a)}notifyOrderedResetAndReset(){var e;(e=this.iter)==null||e.notify(nt.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===Ae.Fetch)return Promise.reject(new Error("ordered consumer initialized as fetch"));if(this.type===Ae.Consume)return Promise.reject(new Error("ordered consumer doesn't support concurrent consume"));const{callback:s}=e;return s&&(this.userCallback=s),this.type=Ae.Consume,this.opts=e,await this.reset(e),this.iter}async fetch(e={max_messages:100,expires:3e4}){var i;if(e.bind)return Promise.reject(new Error("bind is not supported"));if(this.type===Ae.Consume)return Promise.reject(new Error("ordered consumer already initialized as consume"));if(((i=this.iter)==null?void 0:i.done)===!1)return Promise.reject(new Error("ordered consumer doesn't support concurrent fetch"));const{callback:s}=e;return s&&(this.userCallback=s),this.type=Ae.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 s=z();return t.callback=n=>{this.userCallback=null,s.resolve(n)},(await this.fetch(t)).iterClosed.then(n=>{n&&s.reject(n),s.resolve(null)}).catch(n=>{s.reject(n)}),s}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 this.currentConsumer==null?(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 Is{constructor(e){h(this,"api");h(this,"notified");this.api=e,this.notified=!1}checkVersion(){const e=this.api.nc.features.get(H.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(e.config.deliver_subject!==void 0)throw new Error("push consumer not supported");return new js(this.api,e)}async get(e,t={}){return typeof t=="object"?this.ordered(e,t):(await this.checkVersion(),this.api.info(e,t).then(s=>s.config.deliver_subject!==void 0?Promise.reject(new Error("push consumer not supported")):new js(this.api,s)).catch(s=>Promise.reject(s)))}async ordered(e,t){await this.checkVersion();const s=this.api;return new Rs(s.nc,s.opts).info(e).then(n=>Promise.resolve(new to(this.api,e,t))).catch(n=>Promise.reject(n))}}class Vt{constructor(e,t){h(this,"api");h(this,"_info");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 Vt(this.api,e)}else return this}info(e=!1,t){return e?Promise.resolve(this._info):this.api.info(this.name,t).then(s=>(this._info=s,this._info))}getConsumerFromInfo(e){return new Is(new Lt(this.api.nc,this.api.opts)).getPullConsumerFor(e)}getConsumer(e){return new Is(new Lt(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 Rs extends bt{constructor(e,t){super(e,t)}checkStreamConfigVersions(e){const t=this.nc;if(e.metadata){const{min:i,ok:n}=t.features.get(H.JS_STREAM_CONSUMER_METADATA);if(!n)throw new Error(`stream 'metadata' requires server ${i}`)}if(e.first_seq){const{min:i,ok:n}=t.features.get(H.JS_STREAM_FIRST_SEQ);if(!n)throw new Error(`stream 'first_seq' requires server ${i}`)}if(e.subject_transform){const{min:i,ok:n}=t.features.get(H.JS_STREAM_SUBJECT_TRANSFORM);if(!n)throw new Error(`stream 'subject_transform' requires server ${i}`)}if(e.compression){const{min:i,ok:n}=t.features.get(H.JS_STREAM_COMPRESSION);if(!n)throw new Error(`stream 'compression' requires server ${i}`)}if(e.consumer_limits){const{min:i,ok:n}=t.features.get(H.JS_DEFAULT_CONSUMER_LIMITS);if(!n)throw new Error(`stream 'consumer_limits' requires server ${i}`)}function s(i,n){var a;if((((a=n==null?void 0:n.subject_transforms)==null?void 0:a.length)||0)>0){const{min:d,ok:p}=t.features.get(H.JS_STREAM_SOURCE_SUBJECT_TRANSFORM);if(!p)throw new Error(`${i} 'subject_transforms' requires server ${d}`)}}e.sources&&e.sources.forEach(i=>{s("stream sources",i)}),e.mirror&&s("stream mirror",e.mirror)}async add(e={}){var i;this.checkStreamConfigVersions(e),le(e.name),e.mirror=Kt(e.mirror),e.sources=(i=e.sources)==null?void 0:i.map(Kt);const s=await this._request(`${this.prefix}.STREAM.CREATE.${e.name}`,e);return this._fixInfo(s),s}async delete(e){return le(e),(await this._request(`${this.prefix}.STREAM.DELETE.${e}`)).success}async update(e,t={}){var a;if(typeof e=="object"){const d=e;e=d.name,t=d,console.trace("\x1B[33m >> streams.update(config: StreamConfig) api changed to streams.update(name: string, config: StreamUpdateConfig) - this shim will be removed - update your code. \x1B[0m")}this.checkStreamConfigVersions(t),le(e);const s=await this.info(e),i=Object.assign(s.config,t);i.mirror=Kt(i.mirror),i.sources=(a=i.sources)==null?void 0:a.map(Kt);const o=await this._request(`${this.prefix}.STREAM.UPDATE.${e}`,i);return this._fixInfo(o),o}async info(e,t){le(e);const s=`${this.prefix}.STREAM.INFO.${e}`;let n=await this._request(s,t),{total:o,limit:a}=n,d=n.state.subjects?Object.getOwnPropertyNames(n.state.subjects).length:1;if(o&&o>d){const p=[n],_=t||{};let y=0;for(;o>d;){y++,_.offset=a*y;const P=await this._request(s,_);o=P.total,p.push(P);const j=Object.getOwnPropertyNames(P.state.subjects).length;if(d+=j,j<a)break}let x={};for(let P=0;P<p.length;P++)n=p[P],n.state.subjects&&(x=Object.assign(x,n.state.subjects));n.offset=0,n.total=0,n.limit=0,n.state.subjects=x}return this._fixInfo(n),n}list(e=""){const t=e!=null&&e.length?{subject:e}:{},s=n=>{const o=n;return o.streams.forEach(a=>{this._fixInfo(a)}),o.streams},i=`${this.prefix}.STREAM.LIST`;return new gt(i,s,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:i,seq:n}=t;if(typeof i=="number"&&typeof n=="number")throw new Error("can specify one of keep or seq")}return le(e),await this._request(`${this.prefix}.STREAM.PURGE.${e}`,t)}async deleteMessage(e,t,s=!0){le(e);const i={seq:t};return s||(i.no_erase=!0),(await this._request(`${this.prefix}.STREAM.MSG.DELETE.${e}`,i)).success}async getMessage(e,t){le(e);const i=await this._request(`${this.prefix}.STREAM.MSG.GET.${e}`,t);return new Fr(i)}find(e){return this.findStream(e)}listKvs(){const e=s=>{var d;const n=s.streams.filter(p=>p.config.name.startsWith(ye));n.forEach(p=>{this._fixInfo(p)});let o="";return n.length&&(o=((d=this.nc.info)==null?void 0:d.cluster)??""),n.map(p=>new Ur(p,o))},t=`${this.prefix}.STREAM.LIST`;return new gt(t,e,this)}listObjectStores(){const e=s=>{const n=s.streams.filter(a=>a.config.name.startsWith(ks));return n.forEach(a=>{this._fixInfo(a)}),n.map(a=>new Os(a))},t=`${this.prefix}.STREAM.LIST`;return new gt(t,e,this)}names(e=""){const t=e!=null&&e.length?{subject:e}:{},s=n=>n.streams,i=`${this.prefix}.STREAM.NAMES`;return new gt(i,s,this,t)}async get(e){const t=await this.info(e);return Promise.resolve(new Vt(this,t))}}class so extends bt{constructor(e,t){super(e,t)}async getMessage(e,t){le(e);let s=t;const{last_by_subj:i}=s;i&&(s=null);const n=s?this.jc.encode(s):be,o=this.opts.apiPrefix||"$JS.API",a=i?`${o}.DIRECT.GET.${e}.${i}`:`${o}.DIRECT.GET.${e}`,d=await this.nc.request(a,n,{timeout:this.timeout}),p=Qe(d);if(p)return Promise.reject(p);const _=new Ns(d);return Promise.resolve(_)}async getBatch(e,t){le(e);const i=`${this.opts.apiPrefix||"$JS.API"}.DIRECT.GET.${e}`;if(!Array.isArray(t.multi_last)||t.multi_last.length===0)return Promise.reject("multi_last is required");const n=JSON.stringify(t,(d,p)=>d==="up_to_time"&&p instanceof Date?p.toISOString():p),o=new re,a=await this.nc.requestMany(i,n,{strategy:ke.SentinelMsg});return(async()=>{var y,x,P;let d=!1,p=!1,_;for await(const j of a){if(!d){d=!0;const T=((y=j.headers)==null?void 0:y.code)||0;if(T!==0&&T<200||T>299){_=(x=j.headers)==null?void 0:x.description.toLowerCase();break}if(((P=j.headers)==null?void 0:P.get("Nats-Num-Pending"))===""){p=!0;break}}if(j.data.length===0)break;o.push(new Ns(j))}o.push(()=>{if(p)throw new Error("batch direct get not supported by the server");if(_)throw new Error(`bad request: ${_}`);o.stop()})})(),Promise.resolve(o)}}class Ns{constructor(e){h(this,"data");h(this,"header");if(!e.headers)throw new Error("headers expected");this.data=e.data,this.header=e.headers}get subject(){return this.header.last(tt.Subject)}get seq(){const e=this.header.last(tt.Sequence);return typeof e=="string"?parseInt(e):0}get time(){return new Date(Date.parse(this.timestamp))}get timestamp(){return this.header.last(tt.TimeStamp)}get stream(){return this.header.last(tt.Stream)}json(e){return ve(e).decode(this.data)}string(){return ge.decode(this.data)}}h(Ns,"jc");class ro extends bt{constructor(t,s){super(t,s);h(this,"streams");h(this,"consumers");h(this,"direct");this.streams=new Rs(t,s),this.consumers=new Lt(t,s),this.direct=new so(t,s)}async getAccountInfo(){return await this._request(`${this.prefix}.INFO`)}jetstream(){return this.nc.jetstream(this.getOptions())}advisories(){const t=new re;return this.nc.subscribe("$JS.EVENT.ADVISORY.>",{callback:(s,i)=>{if(s)throw s;try{const n=this.parseJsResponse(i),o=n.type.split("."),a=o[o.length-1];t.push({kind:a,data:n})}catch(n){t.stop(n)}}}),t}}class Fr{constructor(e){h(this,"_header");h(this,"smr");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):be}get header(){if(!this._header)if(this.smr.message.hdrs){const e=this._parse(this.smr.message.hdrs);this._header=De.decode(e)}else this._header=Ue();return this._header}_parse(e){const t=atob(e),s=t.length,i=new Uint8Array(s);for(let n=0;n<s;n++)i[n]=t.charCodeAt(n);return i}json(e){return ve(e).decode(this.data)}string(){return ge.decode(this.data)}}h(Fr,"jc");class io{constructor(e){h(this,"api");this.api=e}get(e){return this.api.info(e).then(t=>new Vt(this.api,t))}}class Ts{constructor(e){h(this,"info");h(this,"hdrs");this.info=e}get name(){return this.info.name}get description(){return this.info.description??""}get headers(){return this.hdrs||(this.hdrs=De.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(){var e,t;return((e=this.info.options)==null?void 0:e.link)!==void 0&&((t=this.info.options)==null?void 0:t.link)!==null}}function Br(r){const e={name:r.name,description:r.description??"",options:r.options,metadata:r.metadata};if(r.headers){const t=r.headers;e.headers=t.toRecord()}return e}function no(){return new ReadableStream({pull(r){r.enqueue(new Uint8Array(0)),r.close()}})}class Et{constructor(e,t,s){h(this,"jsm");h(this,"js");h(this,"stream");h(this,"name");this.name=e,this.jsm=t,this.js=s}_checkNotEmpty(e){return!e||e.length===0?{name:e,error:new Error("name cannot be empty")}:{name:e}}async info(e){const t=await this.rawInfo(e);return t?new Ts(t):null}async list(){const e=[],t=await this.watch({ignoreDeletes:!0,includeHistory:!0});for await(const s of t){if(s===null)break;e.push(s)}return Promise.resolve(e)}async rawInfo(e){const{name:t,error:s}=this._checkNotEmpty(e);if(s)return Promise.reject(s);const i=this._metaSubject(t);try{const n=await this.jsm.streams.getMessage(this.stream,{last_by_subj:i}),a=ve().decode(n.data);return a.revision=n.seq,a}catch(n){return n.code==="404"?null:Promise.reject(n)}}async _si(e){try{return await this.jsm.streams.info(this.stream,e)}catch(t){return t.code==="404"?null:Promise.reject(t)}}async seal(){let e=await this._si();return e===null?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 Os(e)))}async status(e){const t=await this._si(e);return t===null?Promise.reject(new Error("object store not found")):Promise.resolve(new Os(t))}destroy(){return this.jsm.streams.delete(this.stream)}async _put(e,t,s){var pe;const i=this.js.getOptions();s=s||{timeout:i.timeout},s.timeout=s.timeout||i.timeout,s.previousRevision=s.previousRevision??void 0;const{timeout:n,previousRevision:o}=s,a=this.js.nc.info,d=(a==null?void 0:a.max_payload)||1024;e=e||{},e.options=e.options||{};let p=((pe=e.options)==null?void 0:pe.max_chunk_size)||128*1024;p=p>d?d:p,e.options.max_chunk_size=p;const _=await this.info(e.name),{name:y,error:x}=this._checkNotEmpty(e.name);if(x)return Promise.reject(x);const P=Le.next(),j=this._chunkSubject(P),T=this._metaSubject(y),J=Object.assign({bucket:this.name,nuid:P,size:0,chunks:0},Br(e)),Q=z(),q=[],X=new rt;try{const w=t?t.getReader():null,I=yr.create();for(;;){const{done:F,value:R}=w?await w.read():{done:!0,value:void 0};if(F){if(X.size()>0){const U=X.drain();I.update(U),J.chunks++,J.size+=U.length,q.push(this.js.publish(j,U,{timeout:n}))}await Promise.all(q),q.length=0,J.mtime=new Date().toISOString();const A=st.encode(I.digest());J.digest=`${qr}${A}`,J.deleted=!1;const $=Ue();typeof o=="number"&&$.set(Re.ExpectedLastSubjectSequenceHdr,`${o}`),$.set(fe.RollupHdr,fe.RollupValueSubject);const L=await this.js.publish(T,ve().encode(J),{headers:$,timeout:n});if(J.revision=L.seq,_)try{await this.jsm.streams.purge(this.stream,{filter:`$O.${this.name}.C.${_.nuid}`})}catch{}Q.resolve(new Ts(J));break}if(R)for(X.fill(R);X.size()>p;){J.chunks++,J.size+=p;const A=X.drain(e.options.max_chunk_size);I.update(A),q.push(this.js.publish(j,A,{timeout:n}))}}}catch(w){await this.jsm.streams.purge(this.stream,{filter:j}),Q.reject(w)}return Q}putBlob(e,t,s){function i(n){return new ReadableStream({pull(o){o.enqueue(n),o.close()}})}return t===null&&(t=new Uint8Array(0)),this.put(e,i(t),s)}put(e,t,s){var i;return(i=e==null?void 0:e.options)!=null&&i.link?Promise.reject(new Error("link cannot be set when putting the object in bucket")):this._put(e,t,s)}async getBlob(e){async function t(n){const o=new rt,a=n.getReader();for(;;){const{done:d,value:p}=await a.read();if(d)return o.drain();p&&p.length&&o.fill(p)}}const s=await this.get(e);if(s===null)return Promise.resolve(null);const i=await Promise.all([s.error,t(s.data)]);return i[0]?Promise.reject(i[0]):Promise.resolve(i[1])}async get(e){const t=await this.rawInfo(e);if(t===null||t.deleted)return Promise.resolve(null);if(t.options&&t.options.link){const y=t.options.link.name||"";if(y==="")throw new Error("link is a bucket");return(t.options.link.bucket!==this.name?await Et.create(this.js,t.options.link.bucket):this).get(y)}if(!t.digest.startsWith(qr))return Promise.reject(new Error(`unknown digest type: ${t.digest}`));const s=ys(t.digest.substring(8));if(s===null)return Promise.reject(new Error(`unable to parse digest: ${t.digest}`));const i=z(),n={info:new Ts(t),error:i};if(t.size===0)return n.data=no(),i.resolve(null),Promise.resolve(n);let o;const a=Je();a.orderedConsumer();const d=yr.create(),p=`$O.${this.name}.C.${t.nuid}`,_=await this.js.subscribe(p,a);return(async()=>{for await(const y of _)y.data.length>0&&(d.update(y.data),o.enqueue(y.data)),y.info.pending===0&&(Gi(s,d.digest())?o.close():o.error(new Error(`received a corrupt object, digests do not match received: ${t.digest} calculated ${s}`)),_.unsubscribe())})().then(()=>{i.resolve()}).catch(y=>{o.error(y),i.reject(y)}),n.data=new ReadableStream({start(y){o=y},cancel(){_.unsubscribe()}}),n}linkStore(e,t){if(!(t instanceof Et))return Promise.reject("bucket required");const s=t,{name:i,error:n}=this._checkNotEmpty(e);if(n)return Promise.reject(n);const o={name:i,options:{link:{bucket:s.name}}};return this._put(o,null)}async link(e,t){const{name:s,error:i}=this._checkNotEmpty(e);if(i)return Promise.reject(i);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 n=await this.rawInfo(e);if(n!==null&&!n.deleted)return Promise.reject(new Error("an object already exists with that name"));const o={bucket:t.bucket,name:t.name},a={name:s,bucket:t.bucket,options:{link:o}};await this.js.publish(this._metaSubject(e),JSON.stringify(a));const d=await this.info(e);return Promise.resolve(d)}async delete(e){const t=await this.rawInfo(e);if(t===null)return Promise.resolve({purged:0,success:!1});t.deleted=!0,t.size=0,t.chunks=0,t.digest="";const s=ve(),i=Ue();return i.set(fe.RollupHdr,fe.RollupValueSubject),await this.js.publish(this._metaSubject(t.name),s.encode(t),{headers:i}),this.jsm.streams.purge(this.stream,{filter:this._chunkSubject(t.nuid)})}async update(e,t={}){const s=await this.rawInfo(e);if(s===null)return Promise.reject(new Error("object not found"));if(s.deleted)return Promise.reject(new Error("cannot update meta for a deleted object"));t.name=t.name??s.name;const{name:i,error:n}=this._checkNotEmpty(t.name);if(n)return Promise.reject(n);if(e!==t.name){const d=await this.info(t.name);if(d&&!d.deleted)return Promise.reject(new Error("an object already exists with that name"))}t.name=i;const o=Object.assign({},s,Br(t)),a=await this.js.publish(this._metaSubject(o.name),JSON.stringify(o));return e!==t.name&&await this.jsm.streams.purge(this.stream,{filter:this._metaSubject(e)}),Promise.resolve(a)}async watch(e={}){e.includeHistory=e.includeHistory??!1,e.ignoreDeletes=e.ignoreDeletes??!1;let t=!1;const s=new re,i=this._metaSubjectAll();try{await this.jsm.streams.getMessage(this.stream,{last_by_subj:i})}catch(d){d.code==="404"?(s.push(null),t=!0):s.stop(d)}const n=ve(),o=Je();o.orderedConsumer(),e.includeHistory?o.deliverLastPerSubject():(t=!0,o.deliverNew()),o.callback((d,p)=>{var _;if(d){s.stop(d);return}if(p!==null){const y=n.decode(p.data);y.deleted&&e.ignoreDeletes===!0||s.push(y),((_=p.info)==null?void 0:_.pending)===0&&!t&&(t=!0,s.push(null))}});const a=await this.js.subscribe(i,o);return s._data=a,s.iterClosed.then(()=>{a.unsubscribe()}),a.closed.then(()=>{s.stop()}).catch(d=>{s.stop(d)}),s}_chunkSubject(e){return`$O.${this.name}.C.${e}`}_metaSubject(e){return`$O.${this.name}.M.${st.encode(e)}`}_metaSubjectAll(){return`$O.${this.name}.M.>`}async init(e={}){try{this.stream=Vn(this.name)}catch(i){return Promise.reject(i)}const t=(e==null?void 0:e.ttl)||0;delete e.ttl;const s=Object.assign({max_age:t},e);s.name=this.stream,s.num_replicas=e.replicas??1,s.allow_direct=!0,s.allow_rollup_hdrs=!0,s.discard=pt.New,s.subjects=[`$O.${this.name}.C.>`,`$O.${this.name}.M.>`],e.placement&&(s.placement=e.placement),e.metadata&&(s.metadata=e.metadata),typeof e.compression=="boolean"&&(s.compression=e.compression?He.S2:He.None);try{await this.jsm.streams.info(s.name)}catch(i){i.message==="stream not found"&&await this.jsm.streams.add(s)}}static async create(e,t,s={}){const i=await e.jetstreamManager(),n=new Et(t,i,e);return await n.init(s),Promise.resolve(n)}}class oo{constructor(e){h(this,"js");this.js=e}kv(e,t={}){const s=this.js,{ok:i,min:n}=s.nc.features.get(H.JS_KV);return i?t.bindOnly?xt.bind(this.js,e,t):xt.create(this.js,e,t):Promise.reject(new Error(`kv is only supported on servers ${n} or better`))}os(e,t={}){var o;if(typeof((o=crypto==null?void 0:crypto.subtle)==null?void 0:o.digest)!="function")return Promise.reject(new Error("objectstore: unable to calculate hashes - crypto.subtle.digest with sha256 support is required"));const s=this.js,{ok:i,min:n}=s.nc.features.get(H.JS_OBJECTSTORE);return i?Et.create(this.js,e,t):Promise.reject(new Error(`objectstore is only supported on servers ${n} or better`))}}class Ms extends bt{constructor(t,s){super(t,s);h(this,"consumers");h(this,"streams");h(this,"consumerAPI");h(this,"streamAPI");this.consumerAPI=new Lt(t,s),this.streamAPI=new Rs(t,s),this.consumers=new Is(this.consumerAPI),this.streams=new io(this.streamAPI)}jetstreamManager(t){t===void 0&&(t=this.opts.checkAPI);const s=Object.assign({},this.opts,{checkAPI:t});return this.nc.jetstreamManager(s)}get apiPrefix(){return this.prefix}get views(){return new oo(this)}async publish(t,s=be,i){i=i||{},i.expect=i.expect||{};const n=(i==null?void 0:i.headers)||Ue();i&&(i.msgID&&n.set(Re.MsgIdHdr,i.msgID),i.expect.lastMsgID&&n.set(Re.ExpectedLastMsgIdHdr,i.expect.lastMsgID),i.expect.streamName&&n.set(Re.ExpectedStreamHdr,i.expect.streamName),typeof i.expect.lastSequence=="number"&&n.set(Re.ExpectedLastSeqHdr,`${i.expect.lastSequence}`),typeof i.expect.lastSubjectSequence=="number"&&n.set(Re.ExpectedLastSubjectSequenceHdr,`${i.expect.lastSubjectSequence}`));const o=i.timeout||this.timeout,a={};o&&(a.timeout=o),i&&(a.headers=n);let{retries:d,retry_delay:p}=i;d=d||1,p=p||250;let _;for(let x=0;x<d;x++)try{_=await this.nc.request(t,s,a);break}catch(P){if(P.code==="503"&&x+1<d)await Xe(p);else throw P}const y=this.parseJsResponse(_);if(y.stream==="")throw N.errorForCode(k.JetStreamInvalidAck);return y.duplicate=y.duplicate?y.duplicate:!1,y}async pull(t,s,i=0){le(t),Ze(s);let n=this.timeout;i>n&&(n=i),i=i<0?0:G(i);const o={batch:1,no_wait:i===0,expires:i},a=await this.nc.request(`${this.prefix}.CONSUMER.MSG.NEXT.${t}.${s}`,this.jc.encode(o),{noMux:!0,timeout:n}),d=Qe(a);if(d)throw d;return vt(a,this.timeout)}fetch(t,s,i={}){le(t),Ze(s);let n=null;const o=(i.max_bytes??0)>0;let a=0;const d=o?i.max_bytes:0;let p=null;const _={};if(_.batch=i.batch||1,d){const q=this.nc.features.get(H.JS_PULL_MAX_BYTES);if(!q.ok)throw new Error(`max_bytes is only supported on servers ${q.min} or better`);_.max_bytes=d}_.no_wait=i.no_wait||!1,_.no_wait&&_.expires&&(_.expires=0);const y=i.expires||0;if(y&&(_.expires=G(y)),y===0&&_.no_wait===!1)throw new Error("expires or no_wait is required");const x=i.idle_heartbeat||0;x&&(_.idle_heartbeat=G(x),i.delay_heartbeat===!0&&(_.idle_heartbeat=G(x*4)));const P=new re,j=_.batch;let T=0;P.protocolFilterFn=(q,X=!1)=>ps(q.msg)?(p==null||p.work(),!1):!0,P.dispatchedFn=q=>{if(q){if(o&&(a+=q.data.length),T++,n&&q.info.pending===0)return;(P.getPending()===1&&q.info.pending===0||j===T||d>0&&a>=d)&&P.stop()}};const J=$e(this.nc.options.inboxPrefix),Q=this.nc.subscribe(J,{max:i.batch,callback:(q,X)=>{q===null&&(q=Qe(X)),q!==null?(n&&(n.cancel(),n=null),ki(q)?P.stop(Hr(q)===null?void 0:q):P.stop(q)):(p==null||p.work(),P.received++,P.push(vt(X,this.timeout)))}});return y&&(n=Ye(y),n.catch(()=>{Q.isClosed()||(Q.drain().catch(()=>{}),n=null),p&&p.cancel()})),(async()=>{try{x&&(p=new ms(x,q=>(P.push(()=>{P.err=new N(`${Ee.IdleHeartbeatMissed}: ${q}`,k.JetStreamIdleHeartBeat)}),!0)))}catch{}await Q.closed,n!==null&&(n.cancel(),n=null),p&&p.cancel(),P.stop()})().catch(),this.nc.publish(`${this.prefix}.CONSUMER.MSG.NEXT.${t}.${s}`,this.jc.encode(_),{reply:J}),P}async pullSubscribe(t,s=Je()){const i=await this._processOptions(t,s);if(i.ordered)throw new Error("pull subscribers cannot be be ordered");if(i.config.deliver_subject)throw new Error("consumer info specifies deliver_subject - pull consumers cannot have deliver_subject set");const n=i.config.ack_policy;if(n===ie.None||n===ie.All)throw new Error("ack policy for pull consumers must be explicit");const o=this._buildTypedSubscriptionOpts(i),a=new uo(this,i.deliver,o);a.info=i;try{await this._maybeCreateConsumer(i)}catch(d){throw a.unsubscribe(),d}return a}async subscribe(t,s=Je()){const i=await this._processOptions(t,s);if(!i.isBind&&!i.config.deliver_subject)throw new Error("push consumer requires deliver_subject");const n=this._buildTypedSubscriptionOpts(i),o=new Dr(this,i.deliver,n);o.info=i;try{await this._maybeCreateConsumer(i)}catch(a){throw o.unsubscribe(),a}return o._maybeSetupHbMonitoring(),o}async _processOptions(t,s=Je()){const i=mr(s)?s.getOpts():s;if(i.isBind=mr(s)?s.isBind:!1,i.flow_control={heartbeat_count:0,fc_count:0,consumer_restarts:0},i.ordered){if(i.ordered_consumer_sequence={stream_seq:0,delivery_seq:0},i.config.ack_policy!==ie.NotSet&&i.config.ack_policy!==ie.None)throw new N("ordered consumer: ack_policy can only be set to 'none'",k.ApiError);if(i.config.durable_name&&i.config.durable_name.length>0)throw new N("ordered consumer: durable_name cannot be set",k.ApiError);if(i.config.deliver_subject&&i.config.deliver_subject.length>0)throw new N("ordered consumer: deliver_subject cannot be set",k.ApiError);if(i.config.max_deliver!==void 0&&i.config.max_deliver>1)throw new N("ordered consumer: max_deliver cannot be set",k.ApiError);if(i.config.deliver_group&&i.config.deliver_group.length>0)throw new N("ordered consumer: deliver_group cannot be set",k.ApiError);i.config.deliver_subject=$e(this.nc.options.inboxPrefix),i.config.ack_policy=ie.None,i.config.max_deliver=1,i.config.flow_control=!0,i.config.idle_heartbeat=i.config.idle_heartbeat||G(5e3),i.config.ack_wait=G(22*60*60*1e3),i.config.mem_storage=!0,i.config.num_replicas=1}if(i.config.ack_policy===ie.NotSet&&(i.config.ack_policy=ie.All),i.api=this,i.config=i.config||{},i.stream=i.stream?i.stream:await this.findStream(t),i.attached=!1,i.config.durable_name)try{const n=await this.consumerAPI.info(i.stream,i.config.durable_name);if(n){if(n.config.filter_subject&&n.config.filter_subject!==t)throw new Error("subject does not match consumer");const o=i.config.deliver_group??"";if(o===""&&n.push_bound===!0)throw new Error("duplicate subscription");const a=n.config.deliver_group??"";if(o!==a)throw a===""?new Error("durable requires no queue group"):new Error(`durable requires queue group '${a}'`);i.last=n,i.config=n.config,i.attached=!0,i.config.durable_name||(i.name=n.name)}}catch(n){if(n.code!=="404")throw n}return!i.attached&&i.config.filter_subject===void 0&&i.config.filter_subjects===void 0&&(i.config.filter_subject=t),i.deliver=i.config.deliver_subject||$e(this.nc.options.inboxPrefix),i}_buildTypedSubscriptionOpts(t){const s={};return s.adapter=lo(t.callbackFn===void 0,this.timeout),s.ingestionFilterFn=Ms.ingestionFn(t.ordered),s.protocolFilterFn=(i,n=!1)=>{const o=i;return ds(o.msg)?(n||o.msg.respond(),!1):!0},!t.mack&&t.config.ack_policy!==ie.None&&(s.dispatchedFn=mo),t.callbackFn&&(s.callback=t.callbackFn),s.max=t.max||0,s.queue=t.queue,s}async _maybeCreateConsumer(t){if(t.attached)return;if(t.isBind)throw new Error(`unable to bind - durable consumer ${t.config.durable_name} doesn't exist in ${t.stream}`);t.config=Object.assign({deliver_policy:Z.All,ack_policy:ie.Explicit,ack_wait:G(30*1e3),replay_policy:et.Instant},t.config);const s=await this.consumerAPI.add(t.stream,t.config);if(Array.isArray(t.config.filter_subjects&&!Array.isArray(s.config.filter_subjects)))throw new Error("jetstream server doesn't support consumers with multiple filter subjects");t.name=s.name,t.config=s.config,t.last=s}static ingestionFn(t){return(s,i)=>{var d;const n=i;if(!s)return{ingest:!1,protocol:!1};const o=s;if(Qe(o.msg)||(d=n.monitor)==null||d.work(),ps(o.msg)){const p=t?n._checkHbOrderConsumer(o.msg):!0;return t||n.info.flow_control.heartbeat_count++,{ingest:p,protocol:!0}}else if(ds(o.msg))return n.info.flow_control.fc_count++,{ingest:!0,protocol:!0};return{ingest:t?n._checkOrderedConsumer(s):!0,protocol:!1}}}}class $s{constructor(e){h(this,"options");h(this,"protocol");h(this,"draining");h(this,"listeners");h(this,"_services");this.draining=!1,this.options=Cn(e),this.listeners=[]}static connect(e={}){return new Promise((t,s)=>{const i=new $s(e);Jt.connect(i.options,i).then(n=>{i.protocol=n,async function(){for await(const o of n.status())i.listeners.forEach(a=>{a.push(o)})}(),t(i)}).catch(n=>{s(n)})})}closed(){return this.protocol.closed}async close(){await this.protocol.close()}_check(e,t,s){if(this.isClosed())throw N.errorForCode(k.ConnectionClosed);if(t&&this.isDraining()||s&&this.protocol.noMorePublishing)throw N.errorForCode(k.ConnectionDraining);if(e=e||"",e.length===0)throw N.errorForCode(k.BadSubject)}publish(e,t,s){this._check(e,!1,!0),this.protocol.publish(e,t,s)}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):!1}subscribe(e,t={}){this._check(e,!0,!1);const s=new Nr(this.protocol,e,t);return this.protocol.subscribe(s),s}_resub(e,t,s){this._check(t,!0,!1);const i=e;i.max=s,s&&(i.max=s+i.received),this.protocol.resub(i,t)}requestMany(e,t=be,s={maxWait:1e3,maxMessages:-1}){const i=!this.protocol.options.noAsyncTraces;try{this._check(e,!0,!0)}catch(d){return Promise.reject(d)}if(s.strategy=s.strategy||ke.Timer,s.maxWait=s.maxWait||1e3,s.maxWait<1)return Promise.reject(new N("timeout",k.InvalidOption));const n=new re;function o(d){n.push(()=>{n.stop(d)})}function a(d,p){d||p===null?o(d===null?void 0:d):n.push(p)}if(s.noMux){const d=i?new Error().stack:null;let p=typeof s.maxMessages=="number"&&s.maxMessages>0?s.maxMessages:-1;const _=this.subscribe($e(this.options.inboxPrefix),{callback:(j,T)=>{var J,Q;if(((J=T==null?void 0:T.data)==null?void 0:J.length)===0&&((Q=T==null?void 0:T.headers)==null?void 0:Q.status)===k.NoResponders&&(j=N.errorForCode(k.NoResponders)),j){d&&(j.stack+=`
34
+
35
+ ${d}`),y(j);return}a(null,T),s.strategy===ke.Count&&(p--,p===0&&y()),s.strategy===ke.JitterTimer&&(P(),x=setTimeout(()=>{y()},300)),s.strategy===ke.SentinelMsg&&T&&T.data.length===0&&y()}});_.requestSubject=e,_.closed.then(()=>{o()}).catch(j=>{n.stop(j)});const y=j=>{j&&n.push(()=>{throw j}),P(),_.drain().then(()=>{o()}).catch(T=>{o()})};n.iterClosed.then(()=>{P(),_==null||_.unsubscribe()}).catch(j=>{P(),_==null||_.unsubscribe()});try{this.publish(e,t,{reply:_.getSubject()})}catch(j){y(j)}let x=setTimeout(()=>{y()},s.maxWait);const P=()=>{x&&clearTimeout(x)}}else{const d=s;d.callback=a,n.iterClosed.then(()=>{p.cancel()}).catch(_=>{p.cancel(_)});const p=new Ki(this.protocol.muxSubscriptions,e,d);this.protocol.request(p);try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${p.token}`,headers:s.headers})}catch(_){p.cancel(_)}}return Promise.resolve(n)}request(e,t,s={timeout:1e3,noMux:!1}){try{this._check(e,!0,!0)}catch(n){return Promise.reject(n)}const i=!this.protocol.options.noAsyncTraces;if(s.timeout=s.timeout||1e3,s.timeout<1)return Promise.reject(new N("timeout",k.InvalidOption));if(!s.noMux&&s.reply)return Promise.reject(new N("reply can only be used with noMux",k.InvalidOption));if(s.noMux){const n=s.reply?s.reply:$e(this.options.inboxPrefix),o=z(),a=i?new Error:null,d=this.subscribe(n,{max:1,timeout:s.timeout,callback:(p,_)=>{p?(a&&p.code!==k.Timeout&&(p.stack+=`
36
+
37
+ ${a.stack}`),d.unsubscribe(),o.reject(p)):(p=lr(_),p?(a&&(p.stack+=`
38
+
39
+ ${a.stack}`),o.reject(p)):o.resolve(_))}});return d.requestSubject=e,this.protocol.publish(e,t,{reply:n,headers:s.headers}),o}else{const n=new xr(this.protocol.muxSubscriptions,e,s,i);this.protocol.request(n);try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${n.token}`,headers:s.headers})}catch(a){n.cancel(a)}const o=Promise.race([n.timer,n.deferred]);return o.catch(()=>{n.cancel()}),o}}flush(){return this.isClosed()?Promise.reject(N.errorForCode(k.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(N.errorForCode(k.ConnectionClosed)):this.isDraining()?Promise.reject(N.errorForCode(k.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 re;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((t,s)=>t==="time"?new Date(Date.parse(s)):s)}stats(){return{inBytes:this.protocol.inBytes,outBytes:this.protocol.outBytes,inMsgs:this.protocol.inMsgs,outMsgs:this.protocol.outMsgs}}async jetstreamManager(e={}){const t=new ro(this,e);if(e.checkAPI!==!1)try{await t.getAccountInfo()}catch(s){const i=s;throw i.code===k.NoResponders&&(i.code=k.JetStreamNotEnabled),i}return t}jetstream(e={}){return new Ms(this,e)}getServerVersion(){const e=this.info;return e?Ke(e.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw N.errorForCode(k.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 ao(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(N.errorForCode(k.ConnectionClosed)):this.isDraining()?Promise.reject(N.errorForCode(k.ConnectionDraining)):this.protocol.reconnect()}}class ao{constructor(e){h(this,"nc");this.nc=e}add(e){try{return new wt(this.nc,e).start()}catch(t){return Promise.reject(t)}}client(e,t){return new Fn(this.nc,e,t)}}class co{constructor(e,t,s){h(this,"bucket");h(this,"sm");h(this,"prefixLen");this.bucket=e,this.prefixLen=t,this.sm=s}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(zt)||"PUT"}get length(){const e=this.sm.header.get(fe.MessageSizeHdr)||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class ho{constructor(e,t,s){h(this,"bucket");h(this,"key");h(this,"sm");this.bucket=e,this.key=t,this.sm=s}get value(){return this.sm.data}get created(){return new Date(us(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var e;return((e=this.sm.headers)==null?void 0:e.get(zt))||"PUT"}get delta(){return this.sm.info.pending}get length(){var t;const e=((t=this.sm.headers)==null?void 0:t.get(fe.MessageSizeHdr))||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Dr extends Xi{constructor(t,s,i){super(t.nc,s,i);h(this,"js");h(this,"monitor");this.js=t,this.monitor=null,this.sub.closed.then(()=>{this.monitor&&this.monitor.cancel()})}set info(t){this.sub.info=t}get info(){return this.sub.info}_resetOrderedConsumer(t){if(this.info===null||this.sub.isClosed())return;const s=$e(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,s);const n=this.info;n.config.name=Le.next(),n.ordered_consumer_sequence.delivery_seq=0,n.flow_control.heartbeat_count=0,n.flow_control.fc_count=0,n.flow_control.consumer_restarts++,n.deliver=s,n.config.deliver_subject=s,n.config.deliver_policy=Z.StartSequence,n.config.opt_start_seq=t;const o={};o.stream_name=this.info.stream,o.config=n.config;const a=`${n.api.prefix}.CONSUMER.CREATE.${n.stream}`;this.js._request(a,o,{retries:-1}).then(d=>{const p=d,_=this.sub.info;_.last=p,this.info.config=p.config,this.info.name=p.name}).catch(d=>{const p=new N(`unable to recreate ordered consumer ${n.stream} at seq ${t}`,k.RequestError,d);this.sub.callback(p,{})})}_maybeSetupHbMonitoring(){var s,i;const t=((i=(s=this.info)==null?void 0:s.config)==null?void 0:i.idle_heartbeat)||0;t&&this._setupHbMonitoring(us(t))}_setupHbMonitoring(t,s=0){const i={cancelAfter:0,maxOut:2};s&&(i.cancelAfter=s);const n=this.sub,o=a=>{var _,y,x,P;const d=Ii(409,`${Ee.IdleHeartbeatMissed}: ${a}`,this.sub.subject);if(!((_=this.info)==null?void 0:_.ordered))this.sub.callback(null,d);else{if(!this.js.nc.protocol.connected)return!1;const j=((x=(y=this.info)==null?void 0:y.ordered_consumer_sequence)==null?void 0:x.stream_seq)||0;return this._resetOrderedConsumer(j+1),(P=this.monitor)==null||P.restart(),!1}return!n.noIterator};this.monitor=new ms(t,o,i)}_checkHbOrderConsumer(t){const s=t.headers.get(fe.ConsumerStalledHdr);s!==""&&this.js.nc.publish(s);const i=parseInt(t.headers.get(fe.LastConsumerSeqHdr),10),n=this.info.ordered_consumer_sequence;return this.info.flow_control.heartbeat_count++,i!==n.delivery_seq&&this._resetOrderedConsumer(n.stream_seq+1),!1}_checkOrderedConsumer(t){const s=this.info.ordered_consumer_sequence,i=t.info.streamSequence,n=t.info.deliverySequence;return n!=s.delivery_seq+1?(this._resetOrderedConsumer(s.stream_seq+1),!1):(s.delivery_seq=n,s.stream_seq=i,!0)}async destroy(){this.isClosed()||await this.drain();const t=this.sub.info,s=t.config.durable_name||t.name,i=`${t.api.prefix}.CONSUMER.DELETE.${t.stream}.${s}`;await t.api._request(i)}async consumerInfo(){const t=this.sub.info,s=t.config.durable_name||t.name,i=`${t.api.prefix}.CONSUMER.INFO.${t.stream}.${s}`,n=await t.api._request(i);return t.last=n,n}}class uo extends Dr{constructor(e,t,s){super(e,t,s)}pull(e={batch:1}){const{stream:t,config:s,name:i}=this.sub.info,n=s.durable_name??i,o={};if(o.batch=e.batch||1,o.no_wait=e.no_wait||!1,(e.max_bytes??0)>0){const p=this.js.nc.features.get(H.JS_PULL_MAX_BYTES);if(!p.ok)throw new Error(`max_bytes is only supported on servers ${p.min} or better`);o.max_bytes=e.max_bytes}let a=0;e.expires&&e.expires>0&&(a=e.expires,o.expires=G(a));let d=0;if(e.idle_heartbeat&&e.idle_heartbeat>0&&(d=e.idle_heartbeat,o.idle_heartbeat=G(d)),d&&a===0)throw new Error("idle_heartbeat requires expires");if(d>a)throw new Error("expires must be greater than idle_heartbeat");if(this.info){this.monitor&&this.monitor.cancel(),a&&d&&(this.monitor?this.monitor._change(d,a):this._setupHbMonitoring(d,a));const p=this.info.api,_=`${p.prefix}.CONSUMER.MSG.NEXT.${t}.${n}`,y=this.sub.subject;p.nc.publish(_,p.jc.encode(o),{reply:y})}}}function lo(r,e){return r?po(e):fo(e)}function fo(r){return(e,t)=>e?[e,null]:(e=Qe(t),e?[e,null]:[null,vt(t,r)])}function po(r){return(e,t)=>{if(e)return[e,null];const s=Qe(t);return s!==null?[Hr(s),null]:[null,vt(t,r)]}}function Hr(r){if(r!==null)switch(r.code){case k.JetStream404NoMessages:case k.JetStream408RequestTimeout:return null;case k.JetStream409:return Ri(r)?r:null;default:return r}return null}function mo(r){r&&r.ack()}function bo(r){const e=r.split(".");if(e.length===9&&e.splice(2,0,"_",""),e.length<11||e[0]!=="$JS"||e[1]!=="ACK")throw new Error("not js message");const t={};return t.domain=e[2]==="_"?"":e[2],t.account_hash=e[3],t.stream=e[4],t.consumer=e[5],t.deliveryCount=parseInt(e[6],10),t.redeliveryCount=t.deliveryCount,t.redelivered=t.deliveryCount>1,t.streamSequence=parseInt(e[7],10),t.deliverySequence=parseInt(e[8],10),t.timestampNanos=parseInt(e[9],10),t.pending=parseInt(e[10],10),t}class go{constructor(e,t){h(this,"msg");h(this,"di");h(this,"didAck");h(this,"timeout");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=bo(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 e.length===4&&e[0]===St[0]&&e[1]===St[1]&&e[2]===St[2]&&e[3]===St[3]}async ackAck(e){var s;e=e||{},e.timeout=e.timeout||this.timeout;const t=z();if(this.didAck)t.resolve(!1);else if(this.didAck=!0,this.msg.reply){const n=this.msg.publisher,o=!((s=n.options)!=null&&s.noAsyncTraces),a=new xr(n.muxSubscriptions,this.msg.reply,{timeout:e.timeout},o);n.request(a);try{n.publish(this.msg.reply,Lr,{reply:`${n.muxSubscriptions.baseInbox}${a.token}`})}catch(d){a.cancel(d)}try{await Promise.race([a.timer,a.deferred]),t.resolve(!0)}catch(d){a.cancel(d),t.reject(d)}}else t.resolve(!1);return t}ack(){this.doAck(Lr)}nak(e){let t=Yn;e&&(t=ur().encode(`-NAK ${JSON.stringify({delay:G(e)})}`)),this.doAck(t)}working(){this.doAck(St)}next(e,t={batch:1}){const s={};s.batch=t.batch||1,s.no_wait=t.no_wait||!1,t.expires&&t.expires>0&&(s.expires=G(t.expires));const i=ve().encode(s),n=rt.concat(Xn,Qn,i),o=e?{reply:e}:void 0;this.msg.respond(n,o)}term(e=""){let t=Zn;(e==null?void 0:e.length)>0&&(t=ur().encode(`+TERM ${e}`)),this.doAck(t)}json(){return this.msg.json()}string(){return this.msg.string()}}const _o="1.30.3",yo="nats.ws";class wo{constructor(){h(this,"version");h(this,"lang");h(this,"closeError");h(this,"connected");h(this,"done");h(this,"socket");h(this,"options");h(this,"socketClosed");h(this,"encrypted");h(this,"peeked");h(this,"yields");h(this,"signal");h(this,"closedNotification");this.version=_o,this.lang=yo,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=z(),this.closedNotification=z()}async connect(e,t){const s=z();if(t.tls)return s.reject(new N("tls",k.InvalidOption)),s;this.options=t;const i=e.src;if(t.wsFactory){const{socket:n,encrypted:o}=await t.wsFactory(e.src,t);this.socket=n,this.encrypted=o}else this.encrypted=i.indexOf("wss://")===0,this.socket=new WebSocket(i);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{this.isDiscarded()},this.socket.onmessage=n=>{if(this.isDiscarded())return;if(this.yields.push(new Uint8Array(n.data)),this.peeked){this.signal.resolve();return}const o=rt.concat(...this.yields),a=rn(o);if(a!==""){const d=Rn.exec(a);if(!d){t.debug&&console.error("!!!",Mt(o)),s.reject(new Error("unexpected response from server"));return}try{const p=JSON.parse(d[1]);jn(p,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),s.resolve()}catch(p){s.reject(p);return}}},this.socket.onclose=n=>{if(this.isDiscarded())return;this.socketClosed=!0;let o;this.done||(n.wasClean||(o=new Error(n.reason)),this._closed(o))},this.socket.onerror=n=>{if(this.isDiscarded())return;const o=n,a=new N(o.message,k.Unknown,new Error(o.error));s.reject(a)},s}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 Xe(100);this.done=!0;try{this.socket.close(e?1002:1e3,e?e.message:void 0)}catch{}t&&this.closedNotification.resolve(e)}}get isClosed(){return this.done}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){for(;;){if(this.isDiscarded())return;this.yields.length===0&&await this.signal;const e=this.yields;this.yields=[];for(let t=0;t<e.length;t++)this.options.debug&&console.info(`> ${Mt(e[t])}`),yield e[t];if(this.done)break;this.yields.length===0&&(e.length=0,this.yields=e,this.signal=z())}}isEncrypted(){return this.connected&&this.encrypted}send(e){if(!this.isDiscarded())try{this.socket.send(e.buffer),this.options.debug&&console.info(`< ${Mt(e)}`);return}catch(t){this.options.debug&&console.error(`!!! ${Mt(e)}: ${t}`)}}close(e){return this._closed(e,!1)}closed(){return this.closedNotification}isDiscarded(){return this.done?(this.discard(),!0):!1}discard(){var e;this.done=!0;try{(e=this.socket)==null||e.close()}catch{}}}function xo(r,e){/^(.*:\/\/)(.*)/.test(r)||(typeof e=="boolean"?r=`${e===!0?"https":"http"}://${r}`:r=`https://${r}`);let s=new URL(r);const i=s.protocol.toLowerCase();i==="ws:"&&(e=!1),i==="wss:"&&(e=!0),i!=="https:"&&i!=="http"&&(r=r.replace(/^(.*:\/\/)(.*)/gm,"$2"),s=new URL(`http://${r}`));let n,o;const a=s.hostname,d=s.pathname,p=s.search||"";switch(i){case"http:":case"ws:":case"nats:":o=s.port||"80",n="ws:";break;case"https:":case"wss:":case"tls:":o=s.port||"443",n="wss:";break;default:o=s.port||e===!0?"443":"80",n=e===!0?"wss:":"ws:";break}return`${n}//${a}:${o}${d}${p}`}function So(r={}){return Zi({defaultPort:443,urlParseFn:xo,factory:()=>new wo}),$s.connect(r)}const ze=ve();class Jr{constructor(){h(this,"onStatusChange");h(this,"nc");h(this,"sessionId","");h(this,"userId","");h(this,"globalPrefix","");h(this,"resolveConnected",e=>{});h(this,"isConnected",new Promise(e=>this.resolveConnected=e))}async connect(e,t,s){var i;this.nc=await So({servers:e}),this.userId=t.userId,this.sessionId=t.sessionId,this.globalPrefix=s??"",this.resolveConnected(!0),(i=this.onStatusChange)==null||i.call(this,!0),console.log("[nats] connected.",this.globalPrefix?`(prefix: ${this.globalPrefix})`:""),(async()=>{var n,o;for await(const a of this.nc.status())switch(a.type!==Fe.PingTimer&&console.log("[nats] connection status:",a.type),a.type){case Se.Reconnect:(n=this.onStatusChange)==null||n.call(this,!0);break;case Se.Disconnect:case Se.Error:case Fe.Reconnecting:(o=this.onStatusChange)==null||o.call(this,!1);break}})()}async disconnect(){var e,t;await((e=this.nc)==null?void 0:e.drain()),await((t=this.nc)==null?void 0:t.close())}async publish(e,t){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");try{const s=this.buildSubject(e);console.debug("[nats]>>",s),this.nc.publish(s,ze.encode(t))}catch(s){throw console.error("[nats] publish failed:",s),s}}async call(e,t,s){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");try{const i=this.buildSubject(e);console.debug("[nats]>>",i);const n=await this.nc.request(i,ze.encode(t),{timeout:(s==null?void 0:s.timeoutInMs)??5e3}),o=ze.decode(n.data);if(!o.ok)throw new Error(o.message);return o.data}catch(i){throw console.error("[nats] request failed:",i),new Error("Api call failed.")}}async on(e,t){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");const i=(this.globalPrefix?`${this.globalPrefix}.`:"")+e+".>",n=this.nc.subscribe(i);return(async()=>{for await(const o of n)try{console.debug("[nats]<<",o.subject);const a=o.subject.split(".");if(this.globalPrefix&&a[0]!==this.globalPrefix){console.log("[nats]","Skipped - "+o.subject);continue}a[0]==="dev"&&a.shift();const d=a.slice(0,a.length-2).join("."),p=a[a.length-2],_=a[a.length-1],y=ze.decode(o.data);t(y,{subject:d,userId:p,sessionId:_})}catch(a){console.error("[nats] subscribe error",a)}})(),()=>n.unsubscribe()}async handler(e,t){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");const i=(this.globalPrefix?`${this.globalPrefix}.`:"")+e+".>",n=this.nc.subscribe(i);return(async()=>{for await(const o of n)try{console.debug("[nats]<<",o.subject);const a=o.subject.split(".");if(this.globalPrefix&&a[0]!==this.globalPrefix){console.log("[nats]","Skipped - "+o.subject);continue}a[0]==="dev"&&a.shift();const d=a.slice(0,a.length-2).join("."),p=a[a.length-2],_=a[a.length-1],y=ze.decode(o.data);t(y,{subject:d,userId:p,sessionId:_}).then(x=>{o.reply&&o.respond(ze.encode({ok:!0,data:x}))}).catch(x=>{console.error("[nats] handle",x),o.reply&&o.respond(ze.encode({ok:!1,message:x.message}))})}catch(a){console.error("[nats] handle",a),o.reply&&o.respond(ze.encode({ok:!1,message:a.message}))}})(),()=>n.unsubscribe()}buildSubject(e){return[this.globalPrefix,e,this.userId,this.sessionId].filter(t=>t).join(".")}}class vo{constructor(e){this.config=e}async getAudioBuffer(e,t){const s=await fetch(`${this.config.voicevoxUrl}/audio_query?text=${encodeURIComponent(e)}&speaker=${t||3}`,{method:"POST",headers:{Accept:"application/json"}});if(!s.ok)throw new Error(`Audio query failed: ${s.statusText}`);const i=await s.json(),n=await fetch(`${this.config.voicevoxUrl}/synthesis?speaker=${t}`,{method:"POST",headers:{Accept:"audio/wav","Content-Type":"application/json"},body:JSON.stringify(i)});if(!n.body)return null;const o=n.body.getReader(),a=[];for(;;){const{done:y,value:x}=await o.read();if(y)break;a.push(x)}const d=a.reduce((y,x)=>y+x.length,0),p=new Uint8Array(d);let _=0;for(const y of a)p.set(y,_),_+=y.length;return p.buffer}async getAudio(e,t){return this.getAudioBuffer(e,t).then(s=>s?tr(s):null)}async getVoices(){return(await fetch(`${this.config.voicevoxUrl}/speakers`).then(t=>t.json())).flatMap(t=>t.styles.map(s=>({id:s.id.toString(),locale:"ja-JP",description:`${t.name} - ${s.name}`})))}}const zr={debug:!1,authUrl:"https://auth.jok.io",voicevoxUrl:"https://voicevox.fly.dev"},Eo={setup(r){r.authUrl&&(this.auth=new Zs({authUrl:r.authUrl}))},auth:new Zs(zr),edgeTts:new gi,voicevoxTts:new vo(zr),nats:new Jr,crypto:new bi};me.NatsService=Jr,me.jok=Eo,Object.defineProperty(me,Symbol.toStringTag,{value:"Module"})});
@@ -0,0 +1,36 @@
1
+ export declare class NatsService<TApi> {
2
+ onStatusChange?: (isConnected: boolean) => void;
3
+ private nc?;
4
+ private sessionId;
5
+ private userId;
6
+ private globalPrefix;
7
+ private resolveConnected;
8
+ isConnected: Promise<unknown>;
9
+ connect(natsServerUrls: string[], user: IdentityUser, prefix?: string): Promise<void>;
10
+ disconnect(): Promise<void>;
11
+ publish<TSubject extends keyof TApi & string>(subject: TSubject, data: InferReturnType<TApi, TSubject>): Promise<void>;
12
+ call<TSubject extends keyof TApi & string>(subject: TSubject, data: InferProps<TApi, TSubject>, opts?: {
13
+ timeoutInMs?: number;
14
+ }): Promise<InferReturnType<TApi, TSubject>>;
15
+ on<TSubject extends keyof TApi & string>(subject: TSubject, cb: (data: InferReturnType<TApi, TSubject>, ctx: {
16
+ subject: string;
17
+ userId: string;
18
+ sessionId: string;
19
+ }) => void): Promise<() => void>;
20
+ handler<TSubject extends keyof TApi & string>(subject: TSubject, cb: (data: InferProps<TApi, TSubject>, ctx: {
21
+ subject: string;
22
+ userId: string;
23
+ sessionId: string;
24
+ }) => Promise<InferReturnType<TApi, TSubject>>): Promise<() => void>;
25
+ private buildSubject;
26
+ }
27
+ export declare const nats: NatsService<unknown>;
28
+ type IdentityUser = {
29
+ jwt: string;
30
+ seed: string;
31
+ userId: string;
32
+ sessionId: string;
33
+ };
34
+ type InferProps<TApi, TSubject extends keyof TApi> = TApi[TSubject] extends (args: infer TProps) => unknown ? TProps : {};
35
+ type InferReturnType<TApi, TSubject extends keyof TApi> = TApi[TSubject] extends (args: any) => infer TResult ? TResult : TApi[TSubject];
36
+ export {};
@@ -0,0 +1,11 @@
1
+ type Config = {
2
+ voicevoxUrl: string;
3
+ };
4
+ export declare class VoicevoxTtsService {
5
+ private config;
6
+ constructor(config: Config);
7
+ getAudioBuffer(text: string, voice: string): Promise<ArrayBuffer | null>;
8
+ getAudio(text: string, voice: string): Promise<HTMLAudioElement | null>;
9
+ getVoices(): Promise<any[]>;
10
+ }
11
+ export {};