!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},t=(new e.Error).stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e41584f4-0411-47a0-b5ee-7157ff8f7437",e._sentryDebugIdIdentifier="sentry-dbid-e41584f4-0411-47a0-b5ee-7157ff8f7437")}catch(e){}}();"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[1441],{52248:(e,t,s)=>{var r,i,n,o,a,c,h,l,u,d,f,p,m,b,g,_,y,w,x,S,v,E,P,A,k,C,O,j,I,M,N;let R,$;s.r(t),s.d(t,{AckPolicy:()=>m,AdvisoryKind:()=>y,Bench:()=>tD,ConsumerDebugEvents:()=>N,ConsumerEvents:()=>M,DebugEvents:()=>i,DeliverPolicy:()=>p,DirectMsgHeaders:()=>S,DiscardPolicy:()=>d,Empty:()=>T,ErrorCode:()=>n,Events:()=>r,JSONCodec:()=>em,JsHeaders:()=>w,KvWatchInclude:()=>x,Match:()=>o,Metric:()=>tB,MsgHdrsImpl:()=>ef,NatsError:()=>z,Nuid:()=>D,ReplayPolicy:()=>b,RepublishHeaders:()=>v,RequestStrategy:()=>a,RetentionPolicy:()=>u,ServiceError:()=>Y,ServiceErrorCodeHeader:()=>W,ServiceErrorHeader:()=>V,ServiceResponseType:()=>c,ServiceVerb:()=>h,StorageType:()=>f,StoreCompression:()=>g,StringCodec:()=>ep,backoff:()=>ea,buildAuthenticator:()=>tC,canonicalMIMEHeaderKey:()=>el,checkJsError:()=>eE,connect:()=>sO,consumerOpts:()=>eO,createInbox:()=>X,credsAuthenticator:()=>tk,deadline:()=>er,deferred:()=>ei,delay:()=>es,headers:()=>eu,isFlowControlMsg:()=>eS,isHeartbeatMsg:()=>ev,jwtAuthenticator:()=>tA,millis:()=>eh,nanos:()=>ec,nkeyAuthenticator:()=>tP,nkeys:()=>tS,nuid:()=>H,syncIterator:()=>G,tokenAuthenticator:()=>tE,usernamePasswordAuthenticator:()=>tv});let T=new Uint8Array(0),q=new TextEncoder,U=new TextDecoder;function L(...e){let t=[];for(let s=0;s=12;t--)this.buf[t]=B.charCodeAt(e%36),e=Math.floor(e/36)}next(){return this.inited||this.init(),this.seq+=this.inc,this.seq>0xcfd41b9100000&&(this.setPre(),this.initSeqAndInc()),this.fillSeq(),String.fromCharCode.apply(String,this.buf)}reset(){this.init()}}let H=new D;!function(e){e.Disconnect="disconnect",e.Reconnect="reconnect",e.Update="update",e.LDM="ldm",e.Error="error"}(r||(r={})),function(e){e.Reconnecting="reconnecting",e.PingTimer="pingTimer",e.StaleConnection="staleConnection",e.ClientInitiatedReconnect="client initiated reconnect"}(i||(i={})),function(e){e.ApiError="BAD API",e.BadAuthentication="BAD_AUTHENTICATION",e.BadCreds="BAD_CREDS",e.BadHeader="BAD_HEADER",e.BadJson="BAD_JSON",e.BadPayload="BAD_PAYLOAD",e.BadSubject="BAD_SUBJECT",e.Cancelled="CANCELLED",e.ConnectionClosed="CONNECTION_CLOSED",e.ConnectionDraining="CONNECTION_DRAINING",e.ConnectionRefused="CONNECTION_REFUSED",e.ConnectionTimeout="CONNECTION_TIMEOUT",e.Disconnect="DISCONNECT",e.InvalidOption="INVALID_OPTION",e.InvalidPayload="INVALID_PAYLOAD",e.MaxPayloadExceeded="MAX_PAYLOAD_EXCEEDED",e.NoResponders="503",e.NotFunction="NOT_FUNC",e.RequestError="REQUEST_ERROR",e.ServerOptionNotAvailable="SERVER_OPT_NA",e.SubClosed="SUB_CLOSED",e.SubDraining="SUB_DRAINING",e.Timeout="TIMEOUT",e.Tls="TLS",e.Unknown="UNKNOWN_ERROR",e.WssRequired="WSS_REQUIRED",e.JetStreamInvalidAck="JESTREAM_INVALID_ACK",e.JetStream404NoMessages="404",e.JetStream408RequestTimeout="408",e.JetStream409MaxAckPendingExceeded="409",e.JetStream409="409",e.JetStreamNotEnabled="503",e.JetStreamIdleHeartBeat="IDLE_HEARTBEAT",e.AuthorizationViolation="AUTHORIZATION_VIOLATION",e.AuthenticationExpired="AUTHENTICATION_EXPIRED",e.ProtocolError="NATS_PROTOCOL_ERR",e.PermissionsViolation="PERMISSIONS_VIOLATION",e.AuthenticationTimeout="AUTHENTICATION_TIMEOUT",e.AccountExpired="ACCOUNT_EXPIRED"}(n||(n={}));class J{messages;constructor(){this.messages=new Map,this.messages.set(n.InvalidPayload,"Invalid payload type - payloads can be 'binary', 'string', or 'json'"),this.messages.set(n.BadJson,"Bad JSON"),this.messages.set(n.WssRequired,"TLS is required, therefore a secure websocket connection is also required")}static getMessage(e){return K.getMessage(e)}getMessage(e){return this.messages.get(e)||e}}let K=new J;class z extends Error{name;message;code;permissionContext;chainedError;api_error;constructor(e,t,s){super(e),this.name="NatsError",this.message=e,this.code=t,this.chainedError=s}static errorForCode(e,t){return new z(J.getMessage(e),e,t)}isAuthError(){return this.code===n.AuthenticationExpired||this.code===n.AuthorizationViolation||this.code===n.AccountExpired}isAuthTimeout(){return this.code===n.AuthenticationTimeout}isPermissionError(){return this.code===n.PermissionsViolation}isProtocolError(){return this.code===n.ProtocolError}isJetStreamError(){return void 0!==this.api_error}jsError(){return this.api_error?this.api_error:null}}function G(e){let t=e[Symbol.asyncIterator]();return{async next(){let e=await t.next();return e.done?Promise.resolve(null):Promise.resolve(e.value)}}}!function(e){e[e.Exact=0]="Exact",e[e.CanonicalMIME=1]="CanonicalMIME",e[e.IgnoreCase=2]="IgnoreCase"}(o||(o={})),function(e){e.Timer="timer",e.Count="count",e.JitterTimer="jitterTimer",e.SentinelMsg="sentinelMsg"}(a||(a={})),function(e){e.STATS="io.nats.micro.v1.stats_response",e.INFO="io.nats.micro.v1.info_response",e.PING="io.nats.micro.v1.ping_response"}(c||(c={}));let V="Nats-Service-Error",W="Nats-Service-Error-Code";class Y extends Error{code;constructor(e,t){super(t),this.code=e}static isServiceError(e){return null!==Y.toServiceError(e)}static toServiceError(e){let t=e?.headers?.get(W)||"";if(""!==t){let s=parseInt(t)||400,r=e?.headers?.get(V)||"";return new Y(s,r.length?r:t)}return null}}function X(e=""){if("string"!=typeof(e=e||"_INBOX"))throw Error("prefix must be a string");return e.split(".").forEach(t=>{if("*"===t||">"===t)throw Error(`inbox prefixes cannot have wildcards '${e}'`)}),`${e}.${H.next()}`}let Q="127.0.0.1";function Z(e,...t){for(let s=0;s{s={cancel:()=>{r&&clearTimeout(r)}},r=setTimeout(()=>{null===i?o(z.errorForCode(n.Timeout)):o(i)},e)}),s)}function es(e=0){let t;return Object.assign(new Promise(s=>{let r=setTimeout(()=>{s()},e);t={cancel:()=>{r&&clearTimeout(r)}}}),t)}function er(e,t=1e3){let s=Error("deadline exceeded"),r=ei(),i=setTimeout(()=>r.reject(s),t);return Promise.race([e,r]).finally(()=>clearTimeout(i))}function ei(){let e={};return Object.assign(new Promise((t,s)=>{e={resolve:t,reject:s}}),e)}function en(e){for(let t=e.length-1;t>0;t--){let s=Math.floor(Math.random()*(t+1));[e[t],e[s]]=[e[s],e[t]]}return e}!function(e){e.PING="PING",e.STATS="STATS",e.INFO="INFO"}(h||(h={}));class eo{timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark(e){this.timers.set(e,performance.now())}measure(e,t,s){let r=this.timers.get(t);if(void 0===r)throw Error(`${t} is not defined`);let i=this.timers.get(s);if(void 0===i)throw Error(`${s} is not defined`);this.measures.set(e,i-r)}getEntries(){let e=[];return this.measures.forEach((t,s)=>{e.push({name:s,duration:t})}),e}}function ea(e=[0,250,250,500,500,3e3,5e3]){Array.isArray(e)||(e=[0,250,250,500,500,3e3,5e3]);let t=e.length-1;return{backoff:s=>{var r;return 0===(r=s>t?e[t]:e[s])?0:Math.floor(r/2+Math.random()*r)}}}function ec(e){return 1e6*e}function eh(e){return Math.floor(e/1e6)}function el(e){let t=!0,s=Array(e.length);for(let r=0;r126)throw new z(`'${e[r]}' is not a valid character for a header key`,n.BadHeader);t&&97<=i&&i<=122?i-=32:!t&&65<=i&&i<=90&&(i+=32),s[r]=i,t=45==i}return String.fromCharCode(...s)}function eu(e=0,t=""){if(0===e&&""!==t||e>0&&""===t)throw Error("setting status requires both code and description");return new ef(e,t)}let ed="NATS/1.0";class ef{_code;headers;_description;constructor(e=0,t=""){this._code=e,this._description=t,this.headers=new Map}[Symbol.iterator](){return this.headers.entries()}size(){return this.headers.size}equals(e){if(e&&this.headers.size===e.headers.size&&this._code===e._code){for(let[t,s]of this.headers){let r=e.values(t);if(s.length!==r.length)return!1;let i=[...s].sort(),n=[...r].sort();for(let e=0;e0){t._code=parseInt(e,10),isNaN(t._code)&&(t._code=0);let s=t._code.toString();t._description=(e=e.replace(s,"")).trim()}}return s.length>=1&&s.slice(1).map(e=>{if(e){let s=e.indexOf(":");if(s>-1){let r=e.slice(0,s),i=e.slice(s+1).trim();t.append(r,i)}}}),t}toString(){if(0===this.headers.size&&0===this._code)return"";let e=ed;for(let[t,s]of(this._code>0&&""!==this._description&&(e+=` ${this._code} ${this._description}`),this.headers))for(let r=0;rt===e);case o.CanonicalMIME:return e=el(e),s.filter(t=>t===e);default:{let t=e.toLowerCase();return s.filter(e=>t===e.toLowerCase())}}}get(e,t=o.Exact){let s=this.findKeys(e,t);if(s.length){let e=this.headers.get(s[0]);if(e)return Array.isArray(e)?e[0]:e}return""}last(e,t=o.Exact){let s=this.findKeys(e,t);if(s.length){let e=this.headers.get(s[0]);if(e)return Array.isArray(e)?e[e.length-1]:e}return""}has(e,t=o.Exact){return this.findKeys(e,t).length>0}set(e,t,s=o.Exact){this.delete(e,s),this.append(e,t,s)}append(e,t,s=o.Exact){let r=el(e);s===o.CanonicalMIME&&(e=r);let i=this.findKeys(e,s);e=i.length>0?i[0]:e;let n=ef.validHeaderValue(t),a=this.headers.get(e);a||(a=[],this.headers.set(e,a)),a.push(n)}values(e,t=o.Exact){let s=[];return this.findKeys(e,t).forEach(e=>{let t=this.headers.get(e);t&&s.push(...t)}),s}delete(e,t=o.Exact){this.findKeys(e,t).forEach(e=>{this.headers.delete(e)})}get hasError(){return this._code>=300}get status(){return`${this._code} ${this._description}`.trim()}toRecord(){let 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){let t=new ef;for(let s in e)t.headers.set(s,e[s]);return t}}function ep(){return{encode:e=>q.encode(e),decode:e=>U.decode(e)}}function em(e){return{encode(e){try{return void 0===e&&(e=null),q.encode(JSON.stringify(e))}catch(e){throw z.errorForCode(n.BadJson,e)}},decode(t){try{return JSON.parse(U.decode(t),e)}catch(e){throw z.errorForCode(n.BadJson,e)}}}}function eb(e){return e&&0===e.data.length&&e.headers?.code===503?z.errorForCode(n.NoResponders):null}class eg{_headers;_msg;_rdata;_reply;_subject;publisher;static jc;constructor(e,t,s){this._msg=e,this._rdata=t,this.publisher=s}get subject(){return this._subject||(this._subject=U.decode(this._msg.subject)),this._subject}get reply(){return this._reply||(this._reply=U.decode(this._msg.reply)),this._reply}get sid(){return this._msg.sid}get headers(){if(this._msg.hdr>-1&&!this._headers){let e=this._rdata.subarray(0,this._msg.hdr);this._headers=ef.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=T,t){return!!this.reply&&(this.publisher.publish(this.reply,e,t),!0)}size(){let e=this._msg.subject.length;return e+(this._msg.reply?.length||0)+(-1===this._msg.size?0:this._msg.size)}json(e){return em(e).decode(this.data)}string(){return U.decode(this.data)}requestInfo(){let e=this.headers?.get("Nats-Request-Info");return e?JSON.parse(e,function(e,t){return("start"===e||"stop"===e)&&""!==t?new Date(Date.parse(t)):t}):null}}function e_(e){return ew("durable",e)}function ey(e){return ew("stream",e)}function ew(e,t=""){if(""===t)throw Error(`${e} name required`);return[".","*",">","/","\\"," "," ","\n","\r"].forEach(s=>{if(-1!==t.indexOf(s)){switch(s){case"\n":s="\\n";break;case"\r":s="\\r";break;case" ":s="\\t"}throw Error(`invalid ${e} name - ${e} name cannot contain '${s}'`)}}),""}function ex(e,t=""){if(""===t)throw Error(`${e} name required`);let s=function(e=""){if(""===e)throw Error("name required");let t=/^[-\w]+$/g;if(null===e.match(t)){for(let s of e.split(""))if(null===s.match(t))return`cannot contain '${s}'`}return""}(t);if(s.length)throw Error(`invalid ${e} name - ${e} name ${s}`)}function eS(e){if(e.data.length>0)return!1;let t=e.headers;return!!t&&t.code>=100&&t.code<200}function ev(e){return eS(e)&&e.headers?.description==="Idle Heartbeat"}function eE(e){if(0!==e.data.length)return null;let t=e.headers;return t?eP(t.code,t.description):null}function eP(e,t=""){if(e<300)return null;switch(t=t.toLowerCase(),e){case 404:return new z(t,n.JetStream404NoMessages);case 408:return new z(t,n.JetStream408RequestTimeout);case 409:{let e=t.startsWith(l.IdleHeartbeatMissed)?n.JetStreamIdleHeartBeat:n.JetStream409;return new z(t,e)}case 503:return z.errorForCode(n.JetStreamNotEnabled,Error(t));default:return""===t&&(t=n.Unknown),new z(t,`${e}`)}}!function(e){e.MaxBatchExceeded="exceeded maxrequestbatch of",e.MaxExpiresExceeded="exceeded maxrequestexpires of",e.MaxBytesExceeded="exceeded maxrequestmaxbytes of",e.MaxMessageSizeExceeded="message size exceeds maxbytes",e.PushConsumer="consumer is push based",e.MaxWaitingExceeded="exceeded maxwaiting",e.IdleHeartbeatMissed="idle heartbeats missed",e.ConsumerDeleted="consumer deleted"}(l||(l={}));class eA{inflight;processed;received;noIterator;iterClosed;done;signal;yields;filtered;pendingFiltered;ingestionFilterFn;protocolFilterFn;dispatchedFn;ctx;_data;err;time;yielding;constructor(){this.inflight=0,this.filtered=0,this.pendingFiltered=0,this.processed=0,this.received=0,this.noIterator=!1,this.done=!1,this.signal=ei(),this.yields=[],this.iterClosed=ei(),this.time=0,this.yielding=!1}[Symbol.asyncIterator](){return this.iterate()}push(e){if(this.done)return;if("function"==typeof e){this.yields.push(e),this.signal.resolve();return}let{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 z("unsupported iterator",n.ApiError);if(this.yielding)throw new z("already yielding",n.ApiError);this.yielding=!0;try{for(;;){if(0===this.yields.length&&await this.signal,this.err)throw this.err;let e=this.yields;this.inflight=e.length,this.yields=[];for(let t=0;t0&&(this.autoCancelTimer=setTimeout(()=>{this.cancel()},this.cancelAfter)),this.timer=setInterval(()=>{if(this.count++,Date.now()-this.last>this.interval&&this.missed++,this.missed>=this.maxOut)try{!0===this.callback(this.missed)&&this.cancel()}catch(e){console.log(e)}},this.interval)}}!function(e){e.Limits="limits",e.Interest="interest",e.Workqueue="workqueue"}(u||(u={})),function(e){e.Old="old",e.New="new"}(d||(d={})),function(e){e.File="file",e.Memory="memory"}(f||(f={})),function(e){e.All="all",e.Last="last",e.New="new",e.StartSequence="by_start_sequence",e.StartTime="by_start_time",e.LastPerSubject="last_per_subject"}(p||(p={})),function(e){e.None="none",e.All="all",e.Explicit="explicit",e.NotSet=""}(m||(m={})),function(e){e.Instant="instant",e.Original="original"}(b||(b={})),function(e){e.None="none",e.S2="s2"}(g||(g={})),function(e){e.CreateOrUpdate="",e.Update="update",e.Create="create"}(_||(_={})),!function(e){e.API="api_audit",e.StreamAction="stream_action",e.ConsumerAction="consumer_action",e.SnapshotCreate="snapshot_create",e.SnapshotComplete="snapshot_complete",e.RestoreCreate="restore_create",e.RestoreComplete="restore_complete",e.MaxDeliver="max_deliver",e.Terminated="terminated",e.Ack="consumer_ack",e.StreamLeaderElected="stream_leader_elected",e.StreamQuorumLost="stream_quorum_lost",e.ConsumerLeaderElected="consumer_leader_elected",e.ConsumerQuorumLost="consumer_quorum_lost"}(y||(y={})),function(e){e.StreamSourceHdr="Nats-Stream-Source",e.LastConsumerSeqHdr="Nats-Last-Consumer",e.LastStreamSeqHdr="Nats-Last-Stream",e.ConsumerStalledHdr="Nats-Consumer-Stalled",e.MessageSizeHdr="Nats-Msg-Size",e.RollupHdr="Nats-Rollup",e.RollupValueSubject="sub",e.RollupValueAll="all",e.PendingMessagesHdr="Nats-Pending-Messages",e.PendingBytesHdr="Nats-Pending-Bytes"}(w||(w={})),function(e){e.LastValue="",e.AllHistory="history",e.UpdatesOnly="updates"}(x||(x={})),function(e){e.Stream="Nats-Stream",e.Sequence="Nats-Sequence",e.TimeStamp="Nats-Time-Stamp",e.Subject="Nats-Subject"}(S||(S={})),function(e){e.Stream="Nats-Stream",e.Subject="Nats-Subject",e.Sequence="Nats-Sequence",e.LastSequence="Nats-Last-Sequence",e.Size="Nats-Msg-Size"}(v||(v={}));class eC{config;ordered;mack;stream;callbackFn;max;qname;isBind;filters;constructor(e){this.stream="",this.mack=!1,this.ordered=!1,this.config=function(e,t={}){return Object.assign({name:"",deliver_policy:p.All,ack_policy:m.Explicit,ack_wait:ec(3e4),replay_policy:b.Instant},t)}(0,e||{})}getOpts(){let e={};if(e.config=Object.assign({},this.config),e.config.filter_subject&&(this.filterSubject(e.config.filter_subject),e.config.filter_subject=void 0),e.config.filter_subjects&&(e.config.filter_subjects?.forEach(e=>{this.filterSubject(e)}),e.config.filter_subjects=void 0),e.mack=this.mack,e.stream=this.stream,e.callbackFn=this.callbackFn,e.max=this.max,e.queue=this.qname,e.ordered=this.ordered,e.config.ack_policy=e.ordered?m.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 e_(e),this.config.durable_name=e,this}startSequence(e){if(e<=0)throw Error("sequence must be greater than 0");return this.config.deliver_policy=p.StartSequence,this.config.opt_start_seq=e,this}startTime(e){return this.config.deliver_policy=p.StartTime,this.config.opt_start_time=e.toISOString(),this}deliverAll(){return this.config.deliver_policy=p.All,this}deliverLastPerSubject(){return this.config.deliver_policy=p.LastPerSubject,this}deliverLast(){return this.config.deliver_policy=p.Last,this}deliverNew(){return this.config.deliver_policy=p.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=m.None,this}ackAll(){return this.config.ack_policy=m.All,this}ackExplicit(){return this.config.ack_policy=m.Explicit,this}ackWait(e){return this.config.ack_wait=ec(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=b.Instant,this}replayOriginal(){return this.config.replay_policy=b.Original,this}sample(e){if((e=Math.trunc(e))<0||e>100)throw 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=ec(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=ec(e),this}maxPullBatch(e){return this.config.max_batch=e,this}maxPullRequestExpires(e){return this.config.max_expires=ec(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 eO(e){return new eC(e)}function ej(e){return"function"==typeof e.getOpts}class eI{static encode(e){return"string"==typeof e?btoa(e):btoa(String.fromCharCode(...Array.from(e)))}static decode(e,t=!1){let s=atob(e);return t?Uint8Array.from(s,e=>e.charCodeAt(0)):s}}class eM{static encode(e){return eM.toB64URLEncoding(eI.encode(e))}static decode(e,t=!1){return eM.decode(eM.fromB64URLEncoding(e),t)}static toB64URLEncoding(e){return e.replace(/\+/g,"-").replace(/\//g,"_")}static fromB64URLEncoding(e){return e.replace(/_/g,"/").replace(/-/g,"+")}}class eN{buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...e){let t=0;for(let s=0;s1){let e=new Uint8Array(this.byteLength),t=0;for(let s=0;ss)&&(e=s);let r=t.subarray(0,e);return s>e&&this.buffers.push(t.subarray(e)),this.byteLength=s-e,r}}return new Uint8Array(0)}fill(e,...t){e&&(this.buffers.push(e),this.byteLength+=e.length);for(let e=0;er.apply(null,eR(e)),toUint8Array(e){let s,i,[n,o]=eR(e),a=new Uint8Array(r(n,o)),c=o?n-4:n,h=0;for(i=0;i>16&255,a[h++]=s>>8&255,a[h++]=255&s;return 2===o?(s=t[e.charCodeAt(i)]<<2|t[e.charCodeAt(i+1)]>>4,a[h++]=255&s):1===o&&(s=t[e.charCodeAt(i)]<<10|t[e.charCodeAt(i+1)]<<4|t[e.charCodeAt(i+2)]>>2,a[h++]=s>>8&255,a[h++]=255&s),a},fromUint8Array(t){let r,i,n=t.length,o=n%3,a=n-o,c=Array(Math.ceil(a/16383)+ +!!o),h=0;for(let s=0;s>18&63]+e[n>>12&63]+e[n>>6&63]+e[63&n]}return i.join("")}(t,s,r>a?a:r);return 1===o?(i=t[a],c[h]=e[i>>2]+e[i<<4&63],s||(c[h]+="==")):2===o&&(i=t[a]<<8|255&t[a+1],c[h]=e[i>>10]+e[i>>4&63]+e[i<<2&63],s||(c[h]+="=")),c.join("")}}}(e$,eT,!0),eB=new TextDecoder,eD=new TextEncoder;class eH{hashSize=32;_buf;_bufIdx;_count;_K;_H;_finalized;constructor(){this._buf=new Uint8Array(64),this._K=new Uint32Array([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0xfc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x6ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]),this.init()}init(){return this._H=new Uint32Array([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),this._bufIdx=0,this._count=new Uint32Array(2),this._buf.fill(0),this._finalized=!1,this}update(e,t){if(null===e)throw TypeError("msg must be a string or Uint8Array.");"string"==typeof e&&(e=function(e,t="utf8"){if(/^utf-?8$/i.test(t))return eD.encode(e);if(/^base64$/i.test(t))return eL(e);if(/^hex(?:adecimal)?$/i.test(t)){var s=e;let t=s.length;if(t%2||!/^[0-9a-fA-F]+$/.test(s))throw TypeError("Invalid hex string.");s=s.toLowerCase();let r=new Uint8Array(Math.floor(t/2)),i=t/2;for(let e=0;e>>29,this}digest(e){if(this._finalized)throw Error("digest has already been called.");this._finalized=!0;let t=this._buf,s=this._bufIdx;for(t[s++]=128;56!==s;)64===s&&(this._transform(),s=0),t[s++]=0;let r=this._count;t[56]=r[1]>>>24&255,t[57]=r[1]>>>16&255,t[58]=r[1]>>>8&255,t[59]=r[1]>>>0&255,t[60]=r[0]>>>24&255,t[61]=r[0]>>>16&255,t[62]=r[0]>>>8&255,t[63]=r[0]>>>0&255,this._transform();let i=new Uint8Array(32);for(let e=0;e<8;e++)i[(e<<2)+0]=this._H[e]>>>24&255,i[(e<<2)+1]=this._H[e]>>>16&255,i[(e<<2)+2]=this._H[e]>>>8&255,i[(e<<2)+3]=this._H[e]>>>0&255;return this.init(),e?function(e,t="utf8"){if(/^utf-?8$/i.test(t))return eB.decode(e);if(/^base64$/i.test(t))return eF(e);if(/^hex(?:adecimal)?$/i.test(t))return e.reduce((e,t)=>`${e}${t<16?"0":""}${t.toString(16)}`,"");throw TypeError("Unsupported string encoding.")}(i,e):i}_transform(){let e,t=this._H,s=t[0],r=t[1],i=t[2],n=t[3],o=t[4],a=t[5],c=t[6],h=t[7],l=new Uint32Array(16);for(e=0;e<16;e++)l[e]=this._buf[(e<<2)+3]|this._buf[(e<<2)+2]<<8|this._buf[(e<<2)+1]<<16|this._buf[e<<2]<<24;for(e=0;e<64;e++){let t;if(e<16)t=l[e];else{let s=l[e+1&15],r=l[e+14&15];t=l[15&e]=(s>>>7^s>>>18^s>>>3^s<<25^s<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+l[15&e]+l[e+9&15]|0}t=t+h+(o>>>6^o>>>11^o>>>25^o<<26^o<<21^o<<7)+(c^o&(a^c))+this._K[e]|0,h=c,c=a,a=o,o=n+t,n=i,i=r,s=t+((r=s)&i^n&(r^i))+(r>>>2^r>>>13^r>>>22^r<<30^r<<19^r<<10)|0}t[0]=t[0]+s|0,t[1]=t[1]+r|0,t[2]=t[2]+i|0,t[3]=t[3]+n|0,t[4]=t[4]+o|0,t[5]=t[5]+a|0,t[6]=t[6]+c|0,t[7]=t[7]+h|0}}class eJ{token;received;ctx;requestSubject;mux;constructor(e,t,s=!0){this.mux=e,this.requestSubject=t,this.received=0,this.token=H.next(),s&&(this.ctx=Error())}}class eK extends eJ{callback;done;timer;max;opts;constructor(e,t,s={maxWait:1e3}){if(super(e,t),this.opts=s,"function"!=typeof this.opts.callback)throw Error("callback is required");this.callback=this.opts.callback,this.max="number"==typeof s.maxMessages&&s.maxMessages>0?s.maxMessages:-1,this.done=ei(),this.done.then(()=>{this.callback(null,null)}),this.timer=setTimeout(()=>{this.cancel()},s.maxWait)}cancel(e){e&&this.callback(e,null),clearTimeout(this.timer),this.mux.cancel(this),this.done.resolve()}resolver(e,t){e?(this.ctx&&(e.stack+=` ${this.ctx.stack}`),this.cancel(e)):(this.callback(null,t),this.opts.strategy===a.Count&&(this.max--,0===this.max&&this.cancel()),this.opts.strategy===a.JitterTimer&&(clearTimeout(this.timer),this.timer=setTimeout(()=>{this.cancel()},this.opts.jitter||300)),this.opts.strategy===a.SentinelMsg&&t&&0===t.data.length&&this.cancel())}}class ez extends eJ{deferred;timer;constructor(e,t,s={timeout:1e3},r=!0){super(e,t,r),this.deferred=ei(),this.timer=et(s.timeout,r)}resolver(e,t){this.timer&&this.timer.cancel(),e?(this.ctx&&(e.stack+=` ${this.ctx.stack}`),this.deferred.reject(e)):this.deferred.resolve(t),this.cancel()}cancel(e){this.timer&&this.timer.cancel(),this.mux.cancel(this),this.deferred.reject(e||z.errorForCode(n.Cancelled))}}class eG{nc;opts;prefix;timeout;jc;constructor(e,t){this.nc=e,this.opts=function(e){return(e=e||{}).domain&&(e.apiPrefix=`$JS.${e.domain}.API`,delete e.domain),Z({apiPrefix:"$JS.API",timeout:5e3},e)}(t),this._parseOpts(),this.prefix=this.opts.apiPrefix,this.timeout=this.opts.timeout,this.jc=em()}getOptions(){return Object.assign({},this.opts)}_parseOpts(){let e=this.opts.apiPrefix;if(!e||0===e.length)throw 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||{}).timeout=this.timeout;let r=T;t&&(r=this.jc.encode(t));let{retries:i}=s;i=-1===(i=i||1)?Number.MAX_SAFE_INTEGER:i;let o=ea();for(let t=0;t=this.pageInfo.total)return[];let e={offset:this.offset};this.payload&&Object.assign(e,this.payload);try{let t=await this.jsm._request(this.subject,e,{timeout:this.jsm.timeout});this.pageInfo=t;let s=this.countResponse(t);if(0===s)return[];return this.offset+=s,this.filter(t)}catch(e){throw this.err=e,e}}countResponse(e){switch(e?.type){case"io.nats.jetstream.api.v1.stream_names_response":case"io.nats.jetstream.api.v1.stream_list_response":return e.streams?.length||0;case"io.nats.jetstream.api.v1.consumer_list_response":return e.consumers?.length||0;default:return console.error(`jslister.ts: unknown API response for paged output: ${e?.type}`),e.streams?.length||0}}async *[Symbol.asyncIterator](){let e=await this.next();for(;e.length>0;){for(let t of e)yield t;e=await this.next()}}}function eW(e=""){let t=e.match(/(\d+).(\d+).(\d+)/);if(t)return{major:parseInt(t[1]),minor:parseInt(t[2]),micro:parseInt(t[3])};throw Error(`'${e}' is not a semver value`)}function eY(e,t){return e.majort.major?1:e.minort.minor?1:e.microt.micro)}!function(e){e.JS_KV="js_kv",e.JS_OBJECTSTORE="js_objectstore",e.JS_PULL_MAX_BYTES="js_pull_max_bytes",e.JS_NEW_CONSUMER_CREATE_API="js_new_consumer_create",e.JS_ALLOW_DIRECT="js_allow_direct",e.JS_MULTIPLE_CONSUMER_FILTER="js_multiple_consumer_filter",e.JS_SIMPLIFICATION="js_simplification",e.JS_STREAM_CONSUMER_METADATA="js_stream_consumer_metadata",e.JS_CONSUMER_FILTER_SUBJECTS="js_consumer_filter_subjects",e.JS_STREAM_FIRST_SEQ="js_stream_first_seq",e.JS_STREAM_SUBJECT_TRANSFORM="js_stream_subject_transform",e.JS_STREAM_SOURCE_SUBJECT_TRANSFORM="js_stream_source_subject_transform",e.JS_STREAM_COMPRESSION="js_stream_compression",e.JS_DEFAULT_CONSUMER_LIMITS="js_default_consumer_limits",e.JS_BATCH_DIRECT_GET="js_batch_direct_get"}(E||(E={}));class eX{server;features;disabled;constructor(e){this.features=new Map,this.disabled=[],this.update(e)}resetDisabled(){this.disabled.length=0,this.update(this.server)}disable(e){this.disabled.push(e),this.update(this.server)}isDisabled(e){return -1!==this.disabled.indexOf(e)}update(e){"string"==typeof e&&(e=eW(e)),this.server=e,this.set(E.JS_KV,"2.6.2"),this.set(E.JS_OBJECTSTORE,"2.6.3"),this.set(E.JS_PULL_MAX_BYTES,"2.8.3"),this.set(E.JS_NEW_CONSUMER_CREATE_API,"2.9.0"),this.set(E.JS_ALLOW_DIRECT,"2.9.0"),this.set(E.JS_MULTIPLE_CONSUMER_FILTER,"2.10.0"),this.set(E.JS_SIMPLIFICATION,"2.9.4"),this.set(E.JS_STREAM_CONSUMER_METADATA,"2.10.0"),this.set(E.JS_CONSUMER_FILTER_SUBJECTS,"2.10.0"),this.set(E.JS_STREAM_FIRST_SEQ,"2.10.0"),this.set(E.JS_STREAM_SUBJECT_TRANSFORM,"2.10.0"),this.set(E.JS_STREAM_SOURCE_SUBJECT_TRANSFORM,"2.10.0"),this.set(E.JS_STREAM_COMPRESSION,"2.10.0"),this.set(E.JS_DEFAULT_CONSUMER_LIMITS,"2.10.0"),this.set(E.JS_BATCH_DIRECT_GET,"2.11.0"),this.disabled.forEach(e=>{this.features.delete(e)})}set(e,t){this.features.set(e,{min:t,ok:eY(this.server,eW(t))>=0})}get(e){return this.features.get(e)||{min:"unknown",ok:!1}}supports(e){return this.get(e)?.ok||!1}require(e){return"string"==typeof e&&(e=eW(e)),eY(this.server,e)>=0}}class eQ extends eG{constructor(e,t){super(e,t)}async add(e,t,s=_.Create){let r;if(ey(e),t.deliver_group&&t.flow_control)throw Error("jetstream flow control is not supported with queue groups");if(t.deliver_group&&t.idle_heartbeat)throw Error("jetstream idle heartbeat is not supported with queue groups");let i={};i.config=t,i.stream_name=e,i.action=s,i.config.durable_name&&e_(i.config.durable_name);let n=this.nc,{min:o,ok:a}=n.features.get(E.JS_NEW_CONSUMER_CREATE_API),c=""===t.name?void 0:t.name;if(c&&!a)throw Error(`consumer 'name' requires server ${o}`);if(c)try{ew("name",c)}catch(s){let e=s.message,t=e.indexOf("cannot contain");if(-1!==t)throw Error(`consumer 'name' ${e.substring(t)}`);throw s}let h="";if(Array.isArray(t.filter_subjects)){let{min:e,ok:t}=n.features.get(E.JS_MULTIPLE_CONSUMER_FILTER);if(!t)throw Error(`consumer 'filter_subjects' requires server ${e}`);a=!1}if(t.metadata){let{min:e,ok:t}=n.features.get(E.JS_STREAM_CONSUMER_METADATA);if(!t)throw Error(`consumer 'metadata' requires server ${e}`)}if(a&&(h=t.name??t.durable_name??""),""!==h){let s=t.filter_subject??void 0;">"===s&&(s=void 0),r=void 0!==s?`${this.prefix}.CONSUMER.CREATE.${e}.${h}.${s}`:`${this.prefix}.CONSUMER.CREATE.${e}.${h}`}else r=t.durable_name?`${this.prefix}.CONSUMER.DURABLE.CREATE.${e}.${t.durable_name}`:`${this.prefix}.CONSUMER.CREATE.${e}`;return await this._request(r,i)}async update(e,t,s){let r=await this.info(e,t);return this.add(e,Object.assign(r.config,s),_.Update)}async info(e,t){return ey(e),e_(t),await this._request(`${this.prefix}.CONSUMER.INFO.${e}.${t}`)}async delete(e,t){return ey(e),e_(t),(await this._request(`${this.prefix}.CONSUMER.DELETE.${e}.${t}`)).success}list(e){return ey(e),new eV(`${this.prefix}.CONSUMER.LIST.${e}`,e=>e.consumers,this)}pause(e,t,s){let r=`${this.prefix}.CONSUMER.PAUSE.${e}.${t}`,i={pause_until:s.toISOString()};return this._request(r,i)}resume(e,t){return this.pause(e,t,new Date(0))}}function eZ(e,t,s=!1){if(!0===s&&!e||e&&"function"!=typeof e)throw z.errorForCode(n.ApiError,Error(`${t} is not a function`))}class e0 extends eA{sub;adapter;subIterDone;constructor(e,t,s){super(),eZ(s.adapter,"adapter",!0),this.adapter=s.adapter,s.callback&&eZ(s.callback,"callback"),this.noIterator="function"==typeof s.callback,s.ingestionFilterFn&&(eZ(s.ingestionFilterFn,"ingestionFilterFn"),this.ingestionFilterFn=s.ingestionFilterFn),s.protocolFilterFn&&(eZ(s.protocolFilterFn,"protocolFilterFn"),this.protocolFilterFn=s.protocolFilterFn),s.dispatchedFn&&(eZ(s.dispatchedFn,"dispatchedFn"),this.dispatchedFn=s.dispatchedFn),s.cleanupFn&&eZ(s.cleanupFn,"cleanupFn");let r=(e,t)=>{this.callback(e,t)};if(s.callback){let e=s.callback;r=(t,s)=>{let[r,i]=this.adapter(t,s);if(r)return void e(r,null);let{ingest:n}=this.ingestionFilterFn?this.ingestionFilterFn(i,this):{ingest:!0};n&&(!this.protocolFilterFn||this.protocolFilterFn(i))&&(e(r,i),this.dispatchedFn&&i&&this.dispatchedFn(i))}}let{max:i,queue:n,timeout:o}=s,a={queue:n,timeout:o,callback:r};i&&i>0&&(a.max=i),this.sub=e.subscribe(t,a),s.cleanupFn&&(this.sub.cleanupFn=s.cleanupFn),this.noIterator||this.iterClosed.then(()=>{this.unsubscribe()}),this.subIterDone=ei(),Promise.all([this.sub.closed,this.iterClosed]).then(()=>{this.subIterDone.resolve()}).catch(()=>{this.subIterDone.resolve()}),(async e=>{await e.closed,this.stop()})(this.sub).then().catch()}unsubscribe(e){this.sub.unsubscribe(e)}drain(){return this.sub.drain()}isDraining(){return this.sub.isDraining()}isClosed(){return this.sub.isClosed()}callback(e,t){this.sub.cancelTimeout();let[s,r]=this.adapter(e,t);s&&this.stop(s),r&&this.push(r)}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}}function e1(){return void 0!==R&&void 0!==R.defaultPort?R.defaultPort:4222}function e2(){return void 0!==R&&R.urlParseFn?R.urlParseFn:void 0}function e3(){return void 0!==R&&R.dnsResolveFn?R.dnsResolveFn:void 0}let e4=eN.fromAscii("\r\n"),e5=new Uint8Array(e4)[0],e6=new Uint8Array(e4)[1];function e8(e){return void 0!==function(e){for(let t=0;t=2&&":"===e[0]&&":"===e[1]&&(s=0,0===(e=e.substring(2)).length))return t;let r=0;for(;r<16;){let{n:i,c:n,ok:o}=function(e){let t=0,s=0;for(s=0;s=e.charCodeAt(s))t*=16,t+=e.charCodeAt(s)-48;else if(97<=e.charCodeAt(s)&&102>=e.charCodeAt(s))t*=16,t+=e.charCodeAt(s)-97+10;else if(65<=e.charCodeAt(s)&&70>=e.charCodeAt(s))t*=16,t+=e.charCodeAt(s)-65+10;else break;if(t>=0xffffff)return{n:0,c:s,ok:!1}}return 0===s?{n:0,c:s,ok:!1}:{n:t,c:s,ok:!0}}(e);if(!o||i>65535)return;if(n16)return;let i=e7(e);if(void 0===i)return;t[r]=i[12],t[r+1]=i[13],t[r+2]=i[14],t[r+3]=i[15],e="",r+=4;break}if(t[r]=i>>8,t[r+1]=i,r+=2,0===(e=e.substring(n)).length)break;if(":"!==e[0]||1==e.length)return;if(":"===(e=e.substring(1))[0]){if(s>=0)return;if(s=r,0===(e=e.substring(1)).length)break}}if(0===e.length){if(r<16){if(s<0)return;let e=16-r;for(let i=r-1;i>=s;i--)t[i+e]=t[i];for(let r=s+e-1;r>=s;r--)t[r]=0}else if(s>=0)return;return t}}(e)}}(e)}function e7(e){let t=new Uint8Array(4);for(let s=0;s<4;s++){if(0===e.length)return;if(s>0){if("."!==e[0])return;e=e.substring(1)}let{n:r,c:i,ok:n}=function(e){let t=0,s=0;for(t=0;t=e.charCodeAt(t);t++)if((s=10*s+(e.charCodeAt(t)-48))>=0xffffff)return{n:0xffffff,c:t,ok:!1};return 0===t?{n:0,c:0,ok:!1}:{n:s,c:t,ok:!0}}(e);if(!n||r>255)return;e=e.substring(i),t[s]=r}return function(e,t,s,r){let i=new Uint8Array(16);return[0,0,0,0,0,0,0,0,0,0,255,255].forEach((e,t)=>{i[t]=e}),i[12]=e,i[13]=t,i[14]=s,i[15]=r,i}(t[0],t[1],t[2],t[3])}function e9(e){return!(-1===e.indexOf("[")&&-1===e.indexOf("::")&&(-1!==e.indexOf(".")||e.split(":").length<=2))}class te{src;listen;hostname;port;didConnect;reconnects;lastConnect;gossiped;tlsName;resolves;constructor(e,t=!1){this.src=e,this.tlsName="";let s=function(e){(e=e.trim()).match(/^(.*:\/\/)(.*)/m)&&(e=e.replace(/^(.*:\/\/)(.*)/gm,"$2")),e9(e=function(e){let t="::FFFF:",s=e.toUpperCase().indexOf(t);if(-1!==s&&-1!==e.indexOf(".")){let r=e.substring(s+t.length);return(r=r.replace("[","")).replace("]","")}return e}(e))&&-1===e.indexOf("[")&&(e=`[${e}]`);let t=e9(e)?e.match(/(]:)(\d+)/):e.match(/(:)(\d+)/),s=t&&3===t.length&&t[1]&&t[2]?parseInt(t[2]):4222,r=new URL(`${80===s?"https":"http"}://${e}`);r.port=`${s}`;let i=r.hostname;return"["===i.charAt(0)&&(i=i.substring(1,i.length-1)),{listen:r.host,hostname:i,port:s}}(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||!1===e.resolve)return[this];let t=[];if(e8(this.hostname))return[this];{let s=await e.fn(this.hostname);for(let r of(e.debug&&console.log(`resolve ${this.hostname} = ${s.join(",")}`),s)){let e=80===this.port?"https":"http",s=new URL(`${e}://${e9(r)?"["+r+"]":r}`);s.port=`${this.port}`;let i=new te(s.host,!1);i.tlsName=this.hostname,t.push(i)}}return e.randomize&&en(t),this.resolves=t,t}}class tt{firstSelect;servers;currentServer;tlsName;randomize;constructor(e=[],t={}){this.firstSelect=!0,this.servers=[],this.tlsName="",this.randomize=t.randomize||!1;let s=e2();e&&(e.forEach(e=>{e=s?s(e):e,this.servers.push(new te(e))}),this.randomize&&(this.servers=en(this.servers))),0===this.servers.length&&this.addServer(`${Q}:${e1()}`,!1),this.currentServer=this.servers[0]}clear(){this.servers.length=0}updateTLSName(){let e=this.getCurrentServer();e8(e.hostname)||(this.tlsName=e.hostname,this.servers.forEach(e=>{e.gossiped&&(e.tlsName=this.tlsName)}))}getCurrentServer(){return this.currentServer}addServer(e,t=!1){let s=e2(),r=new te(e=s?s(e):e,t);e8(r.hostname)&&(r.tlsName=this.tlsName),this.servers.push(r)}selectServer(){if(this.firstSelect)return this.firstSelect=!1,this.currentServer;let e=this.servers.shift();return e&&(this.servers.push(e),this.currentServer=e),e}removeCurrentServer(){this.removeServer(this.currentServer)}removeServer(e){if(e){let 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){let s=[],r=[],i=e2(),n=new Map;e.connect_urls&&e.connect_urls.length>0&&e.connect_urls.forEach(e=>{let s=new te(e=i?i(e,t):e,!0);n.set(e,s)});let o=[];return this.servers.forEach((e,t)=>{let s=e.listen;e.gossiped&&this.currentServer.listen!==s&&void 0===n.get(s)&&o.push(t),n.delete(s)}),o.reverse(),o.forEach(e=>{let t=this.servers.splice(e,1);r=r.concat(t[0].listen)}),n.forEach((e,t)=>{this.servers.push(e),s.push(t)}),{added:s,deleted:r}}}class ts{baseInbox;reqs;constructor(){this.reqs=new Map}size(){return this.reqs.size}init(e){return this.baseInbox=`${X(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){let t=e.subject||"";return 0===t.indexOf(this.baseInbox)?t.substring(this.baseInbox.length):null}all(){return Array.from(this.reqs.values())}handleError(e,t){if(t&&t.permissionContext){if(e)return this.all().forEach(e=>{e.resolver(t,{})}),!0;let s=t.permissionContext;if("publish"===s.operation){let e=this.all().find(e=>e.requestSubject===s.subject);if(e)return e.resolver(t,{}),!0}}return!1}dispatcher(){return(e,t)=>{let s=this.getToken(t);if(s){let r=this.get(s);r&&(null===e&&t.headers&&(e=eb(t)),r.resolver(e,t))}}}close(){let e=z.errorForCode(n.Timeout);this.reqs.forEach(t=>{t.resolver(e,{})})}}class tr{ph;interval;maxOut;timer;pendings;constructor(e,t,s){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:i.PingTimer,data:`${this.pendings.length+1}`}),this.pendings.length===this.maxOut)return void this.cancel(!0);let e=ei();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 ti extends Error{constructor(e){super(e),this.name="AssertionError"}}let tn=0x100000000-2;function to(e,t,s=0){let r=t.byteLength-s;return e.byteLength>r&&(e=e.subarray(0,r)),t.set(e,s),e.byteLength}class ta{_buf;_off;constructor(e){if(this._off=0,null==e){this._buf=new Uint8Array(0);return}this._buf=new Uint8Array(e)}bytes(e={copy:!0}){return!1===e.copy?this._buf.subarray(this._off):this._buf.slice(this._off)}empty(){return this._buf.byteLength<=this._off}get length(){return this._buf.byteLength-this._off}get capacity(){return this._buf.buffer.byteLength}truncate(e){if(0===e)return void this.reset();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){let t=this._buf.byteLength;return e<=this.capacity-t?(this._reslice(t+e),t):-1}_reslice(e){!function(e,t="Assertion failed."){if(!e)throw new ti(t)}(e<=this._buf.buffer.byteLength),this._buf=new Uint8Array(this._buf.buffer,0,e)}readByte(){let e=new Uint8Array(1);return this.read(e)?e[0]:null}read(e){if(this.empty())return(this.reset(),0===e.byteLength)?0:null;let t=to(this._buf.subarray(this._off),e);return this._off+=t,t}writeByte(e){return this.write(Uint8Array.of(e))}writeString(e){return this.write(q.encode(e))}write(e){let t=this._grow(e.byteLength);return to(e,this._buf,t)}_grow(e){let t=this.length;0===t&&0!==this._off&&this.reset();let s=this._tryGrowByReslice(e);if(s>=0)return s;let r=this.capacity;if(e<=Math.floor(r/2)-t)to(this._buf.subarray(this._off),this._buf);else if(r+e>tn)throw Error("The buffer cannot be grown beyond the maximum size.");else{let t=new Uint8Array(Math.min(2*r+e,tn));to(this._buf.subarray(this._off),t),this._buf=t}return this._off=0,this._reslice(Math.min(t+e,tn)),t}grow(e){if(e<0)throw Error("Buffer._grow: negative count");let t=this._grow(e);this._reslice(t)}readFrom(e){let t=0,s=new Uint8Array(32768);for(;;){let r=this.capacity-this.length<32768,i=r?s:new Uint8Array(this._buf.buffer,this.length),n=e.read(i);if(null===n)return t;r?this.write(i.subarray(0,n)):this._reslice(this.length+n),t+=n}}}function tc(){let e={};return e.sid=-1,e.hdr=-1,e.size=-1,e}!function(e){e[e.OK=0]="OK",e[e.ERR=1]="ERR",e[e.MSG=2]="MSG",e[e.INFO=3]="INFO",e[e.PING=4]="PING",e[e.PONG=5]="PONG"}(P||(P={}));class th{dispatcher;state;as;drop;hdr;ma;argBuf;msgBuf;constructor(e){this.dispatcher=e,this.state=A.OP_START,this.as=0,this.drop=0,this.hdr=0}parse(e){let t;for(t=0;t=this.ma.size){let e=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:P.MSG,msg:this.ma,data:e}),this.argBuf=void 0,this.msgBuf=void 0,this.state=A.MSG_END}else{let r=this.ma.size-this.msgBuf.length,i=e.length-t;i0?(this.msgBuf.write(e.subarray(t,t+r)),t=t+r-1):this.msgBuf.writeByte(s)}else t-this.as>=this.ma.size&&(this.dispatcher.push({kind:P.MSG,msg:this.ma,data:e.subarray(this.as,t)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=A.MSG_END);break;case A.MSG_END:if(s!==k.NL)continue;this.drop=0,this.as=t+1,this.state=A.OP_START;break;case A.OP_PLUS:switch(s){case k.O:case k.o:this.state=A.OP_PLUS_O;break;default:throw this.fail(e.subarray(t))}break;case A.OP_PLUS_O:switch(s){case k.K:case k.k:this.state=A.OP_PLUS_OK;break;default:throw this.fail(e.subarray(t))}break;case A.OP_PLUS_OK:s===k.NL&&(this.dispatcher.push({kind:P.OK}),this.drop=0,this.state=A.OP_START);break;case A.OP_MINUS:switch(s){case k.E:case k.e:this.state=A.OP_MINUS_E;break;default:throw this.fail(e.subarray(t))}break;case A.OP_MINUS_E:switch(s){case k.R:case k.r:this.state=A.OP_MINUS_ER;break;default:throw this.fail(e.subarray(t))}break;case A.OP_MINUS_ER:switch(s){case k.R:case k.r:this.state=A.OP_MINUS_ERR;break;default:throw this.fail(e.subarray(t))}break;case A.OP_MINUS_ERR:switch(s){case k.SPACE:case k.TAB:this.state=A.OP_MINUS_ERR_SPC;break;default:throw this.fail(e.subarray(t))}break;case A.OP_MINUS_ERR_SPC:switch(s){case k.SPACE:case k.TAB:continue;default:this.state=A.MINUS_ERR_ARG,this.as=t}break;case A.MINUS_ERR_ARG:switch(s){case k.CR:this.drop=1;break;case k.NL:{let s;this.argBuf?(s=this.argBuf.bytes(),this.argBuf=void 0):s=e.subarray(this.as,t-this.drop),this.dispatcher.push({kind:P.ERR,data:s}),this.drop=0,this.as=t+1,this.state=A.OP_START;break}default:this.argBuf&&this.argBuf.write(Uint8Array.of(s))}break;case A.OP_P:switch(s){case k.I:case k.i:this.state=A.OP_PI;break;case k.O:case k.o:this.state=A.OP_PO;break;default:throw this.fail(e.subarray(t))}break;case A.OP_PO:switch(s){case k.N:case k.n:this.state=A.OP_PON;break;default:throw this.fail(e.subarray(t))}break;case A.OP_PON:switch(s){case k.G:case k.g:this.state=A.OP_PONG;break;default:throw this.fail(e.subarray(t))}break;case A.OP_PONG:s===k.NL&&(this.dispatcher.push({kind:P.PONG}),this.drop=0,this.state=A.OP_START);break;case A.OP_PI:switch(s){case k.N:case k.n:this.state=A.OP_PIN;break;default:throw this.fail(e.subarray(t))}break;case A.OP_PIN:switch(s){case k.G:case k.g:this.state=A.OP_PING;break;default:throw this.fail(e.subarray(t))}break;case A.OP_PING:s===k.NL&&(this.dispatcher.push({kind:P.PING}),this.drop=0,this.state=A.OP_START);break;case A.OP_I:switch(s){case k.N:case k.n:this.state=A.OP_IN;break;default:throw this.fail(e.subarray(t))}break;case A.OP_IN:switch(s){case k.F:case k.f:this.state=A.OP_INF;break;default:throw this.fail(e.subarray(t))}break;case A.OP_INF:switch(s){case k.O:case k.o:this.state=A.OP_INFO;break;default:throw this.fail(e.subarray(t))}break;case A.OP_INFO:switch(s){case k.SPACE:case k.TAB:this.state=A.OP_INFO_SPC;break;default:throw this.fail(e.subarray(t))}break;case A.OP_INFO_SPC:switch(s){case k.SPACE:case k.TAB:continue;default:this.state=A.INFO_ARG,this.as=t}break;case A.INFO_ARG:switch(s){case k.CR:this.drop=1;break;case k.NL:{let s;this.argBuf?(s=this.argBuf.bytes(),this.argBuf=void 0):s=e.subarray(this.as,t-this.drop),this.dispatcher.push({kind:P.INFO,data:s}),this.drop=0,this.as=t+1,this.state=A.OP_START;break}default:this.argBuf&&this.argBuf.writeByte(s)}break;default:throw this.fail(e.subarray(t))}}this.state!==A.MSG_ARG&&this.state!==A.MINUS_ERR_ARG&&this.state!==A.INFO_ARG||this.argBuf||(this.argBuf=new ta(e.subarray(this.as,t-this.drop))),this.state!==A.MSG_PAYLOAD||this.msgBuf||(this.argBuf||this.cloneMsgArg(),this.msgBuf=new ta(e.subarray(this.as)))}cloneMsgArg(){let e=this.ma.subject.length,t=new Uint8Array(e+(this.ma.reply?this.ma.reply.length:0));t.set(this.ma.subject),this.ma.reply&&t.set(this.ma.reply,e),this.argBuf=new ta(t),this.ma.subject=t.subarray(0,e),this.ma.reply&&(this.ma.reply=t.subarray(e))}processMsgArgs(e){if(this.hdr>=0)return this.processHeaderMsgArgs(e);let t=[],s=-1;for(let r=0;r=0&&(t.push(e.subarray(s,r)),s=-1);break;default:s<0&&(s=r)}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}]`:`parse error [${this.state}]`,Error(`${t}: ${U.decode(e)}`)}processHeaderMsgArgs(e){let t=[],s=-1;for(let r=0;r=0&&(t.push(e.subarray(s,r)),s=-1);break;default:s<0&&(s=r)}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(0===e.length)return -1;let t=0;for(let s=0;s57)return -1;t=10*t+(e[s]-48)}return t}}!function(e){e[e.OP_START=0]="OP_START",e[e.OP_PLUS=1]="OP_PLUS",e[e.OP_PLUS_O=2]="OP_PLUS_O",e[e.OP_PLUS_OK=3]="OP_PLUS_OK",e[e.OP_MINUS=4]="OP_MINUS",e[e.OP_MINUS_E=5]="OP_MINUS_E",e[e.OP_MINUS_ER=6]="OP_MINUS_ER",e[e.OP_MINUS_ERR=7]="OP_MINUS_ERR",e[e.OP_MINUS_ERR_SPC=8]="OP_MINUS_ERR_SPC",e[e.MINUS_ERR_ARG=9]="MINUS_ERR_ARG",e[e.OP_M=10]="OP_M",e[e.OP_MS=11]="OP_MS",e[e.OP_MSG=12]="OP_MSG",e[e.OP_MSG_SPC=13]="OP_MSG_SPC",e[e.MSG_ARG=14]="MSG_ARG",e[e.MSG_PAYLOAD=15]="MSG_PAYLOAD",e[e.MSG_END=16]="MSG_END",e[e.OP_H=17]="OP_H",e[e.OP_P=18]="OP_P",e[e.OP_PI=19]="OP_PI",e[e.OP_PIN=20]="OP_PIN",e[e.OP_PING=21]="OP_PING",e[e.OP_PO=22]="OP_PO",e[e.OP_PON=23]="OP_PON",e[e.OP_PONG=24]="OP_PONG",e[e.OP_I=25]="OP_I",e[e.OP_IN=26]="OP_IN",e[e.OP_INF=27]="OP_INF",e[e.OP_INFO=28]="OP_INFO",e[e.OP_INFO_SPC=29]="OP_INFO_SPC",e[e.INFO_ARG=30]="INFO_ARG"}(A||(A={})),function(e){e[e.CR=13]="CR",e[e.E=69]="E",e[e.e=101]="e",e[e.F=70]="F",e[e.f=102]="f",e[e.G=71]="G",e[e.g=103]="g",e[e.H=72]="H",e[e.h=104]="h",e[e.I=73]="I",e[e.i=105]="i",e[e.K=75]="K",e[e.k=107]="k",e[e.M=77]="M",e[e.m=109]="m",e[e.MINUS=45]="MINUS",e[e.N=78]="N",e[e.n=110]="n",e[e.NL=10]="NL",e[e.O=79]="O",e[e.o=111]="o",e[e.P=80]="P",e[e.p=112]="p",e[e.PLUS=43]="PLUS",e[e.R=82]="R",e[e.r=114]="r",e[e.S=83]="S",e[e.s=115]="s",e[e.SPACE=32]="SPACE",e[e.TAB=9]="TAB"}(k||(k={})),function(e){"use strict";var t,s=function(e,t){this.hi=0|e,this.lo=0|t},r=function(e){var t,s=new Float64Array(16);if(e)for(t=0;t>>32-t}function b(e,t){var s=255&e[t+3];return(s=(s=s<<8|255&e[t+2])<<8|255&e[t+1])<<8|255&e[t+0]}function g(e,t){return new s(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],e[t+4]<<24|e[t+5]<<16|e[t+6]<<8|e[t+7])}function _(e,t,s){var r;for(r=0;r<4;r++)e[t+r]=255&s,s>>>=8}function y(e,t,s){e[t]=s.hi>>24&255,e[t+1]=s.hi>>16&255,e[t+2]=s.hi>>8&255,e[t+3]=255&s.hi,e[t+4]=s.lo>>24&255,e[t+5]=s.lo>>16&255,e[t+6]=s.lo>>8&255,e[t+7]=255&s.lo}function w(e,t,s,r,i){var n,o=0;for(n=0;n>>8)-1}function x(e,t,s,r){return w(e,t,s,r,16)}function S(e,t,s,r){return w(e,t,s,r,32)}function v(e,t,s,r,i){var n,o,a,c=new Uint32Array(16),h=new Uint32Array(16),l=new Uint32Array(16),u=new Uint32Array(4);for(n=0;n<4;n++)h[5*n]=b(r,4*n),h[1+n]=b(s,4*n),h[6+n]=b(t,4*n),h[11+n]=b(s,16+4*n);for(n=0;n<16;n++)l[n]=h[n];for(n=0;n<20;n++){for(o=0;o<4;o++){for(a=0;a<4;a++)u[a]=h[(5*o+4*a)%16];for(u[1]^=m(u[0]+u[3]|0,7),u[2]^=m(u[1]+u[0]|0,9),u[3]^=m(u[2]+u[1]|0,13),u[0]^=m(u[3]+u[2]|0,18),a=0;a<4;a++)c[4*o+(o+a)%4]=u[a]}for(a=0;a<16;a++)h[a]=c[a]}if(i){for(n=0;n<16;n++)h[n]=h[n]+l[n]|0;for(n=0;n<4;n++)h[5*n]=h[5*n]-b(r,4*n)|0,h[6+n]=h[6+n]-b(t,4*n)|0;for(n=0;n<4;n++)_(e,4*n,h[5*n]),_(e,16+4*n,h[6+n])}else for(n=0;n<16;n++)_(e,4*n,h[n]+l[n]|0)}function E(e,t,s,r){return v(e,t,s,r,!0),0}var P=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function A(e,t,s,r,i,n,o){var a,c,h=new Uint8Array(16),l=new Uint8Array(64);if(!i)return 0;for(c=0;c<16;c++)h[c]=0;for(c=0;c<8;c++)h[c]=n[c];for(;i>=64;){for(v(l,h,o,P,!1),c=0;c<64;c++)e[t+c]=(s?s[r+c]:0)^l[c];for(c=8,a=1;c<16;c++)a=a+(255&h[c])|0,h[c]=255&a,a>>>=8;i-=64,t+=64,s&&(r+=64)}if(i>0)for(v(l,h,o,P,!1),c=0;c>>=8}var I=new Uint32Array([5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252]);function M(e,t,s,r,i,n){var o,a,c,h,l=new Uint32Array(17),u=new Uint32Array(17),d=new Uint32Array(17),f=new Uint32Array(17),p=new Uint32Array(17);for(c=0;c<17;c++)u[c]=d[c]=0;for(c=0;c<16;c++)u[c]=n[c];for(u[3]&=15,u[4]&=252,u[7]&=15,u[8]&=252,u[11]&=15,u[12]&=252,u[15]&=15;i>0;){for(c=0;c<17;c++)f[c]=0;for(c=0;c<16&&c>>=8;for(c=0,h=h+d[16]|0,d[16]=3&h,h=5*(h>>>2)|0;c<16;c++)h=h+d[c]|0,d[c]=255&h,h>>>=8;h=h+d[16]|0,d[16]=h}for(c=0;c<17;c++)p[c]=d[c];for(j(d,I),o=0|-(d[16]>>>7),c=0;c<17;c++)d[c]^=o&(p[c]^d[c]);for(c=0;c<16;c++)f[c]=n[c+16];for(f[16]=0,j(d,f),c=0;c<16;c++)e[t+c]=d[c];return 0}function N(e,t,s,r,i,n){var o=new Uint8Array(16);return M(o,0,s,r,i,n),x(e,t,o,0)}function R(e,t,s,r,i){var n;if(s<32)return -1;for(O(e,0,t,0,s,r,i),M(e,16,e,32,s-32,e),n=0;n<16;n++)e[n]=0;return 0}function $(e,t,s,r,i){var n,o=new Uint8Array(32);if(s<32||(C(o,0,32,r,i),0!==N(t,16,t,32,s-32,o)))return -1;for(O(e,0,t,0,s,r,i),n=0;n<32;n++)e[n]=0;return 0}function T(e,t){var s;for(s=0;s<16;s++)e[s]=0|t[s]}function q(e){var t,s;for(s=0;s<16;s++)e[s]+=65536,t=Math.floor(e[s]/65536),e[(s<15)*(s+1)]+=t-1+37*(t-1)*(15===s),e[s]-=65536*t}function U(e,t,s){for(var r,i=~(s-1),n=0;n<16;n++)r=i&(e[n]^t[n]),e[n]^=r,t[n]^=r}function L(e,t){var s,i,n,o=r(),a=r();for(s=0;s<16;s++)a[s]=t[s];for(q(a),q(a),q(a),i=0;i<2;i++){for(s=1,o[0]=a[0]-65517;s<15;s++)o[s]=a[s]-65535-(o[s-1]>>16&1),o[s-1]&=65535;o[15]=a[15]-32767-(o[14]>>16&1),n=o[15]>>16&1,o[14]&=65535,U(a,o,1-n)}for(s=0;s<16;s++)e[2*s]=255&a[s],e[2*s+1]=a[s]>>8}function F(e,t){var s=new Uint8Array(32),r=new Uint8Array(32);return L(s,e),L(r,t),S(s,0,r,0)}function B(e){var t=new Uint8Array(32);return L(t,e),1&t[0]}function D(e,t){var s;for(s=0;s<16;s++)e[s]=t[2*s]+(t[2*s+1]<<8);e[15]&=32767}function H(e,t,s){var r;for(r=0;r<16;r++)e[r]=t[r]+s[r]|0}function J(e,t,s){var r;for(r=0;r<16;r++)e[r]=t[r]-s[r]|0}function K(e,t,s){var r,i,n=new Float64Array(31);for(r=0;r<31;r++)n[r]=0;for(r=0;r<16;r++)for(i=0;i<16;i++)n[r+i]+=t[r]*s[i];for(r=0;r<15;r++)n[r]+=38*n[r+16];for(r=0;r<16;r++)e[r]=n[r];q(e),q(e)}function z(e,t){K(e,t,t)}function G(e,t){var s,i=r();for(s=0;s<16;s++)i[s]=t[s];for(s=253;s>=0;s--)z(i,i),2!==s&&4!==s&&K(i,i,t);for(s=0;s<16;s++)e[s]=i[s]}function V(e,t){var s,i=r();for(s=0;s<16;s++)i[s]=t[s];for(s=250;s>=0;s--)z(i,i),1!==s&&K(i,i,t);for(s=0;s<16;s++)e[s]=i[s]}function W(e,t,s){var i,n,o=new Uint8Array(32),a=new Float64Array(80),c=r(),l=r(),u=r(),d=r(),f=r(),p=r();for(n=0;n<31;n++)o[n]=t[n];for(o[31]=127&t[31]|64,o[0]&=248,D(a,s),n=0;n<16;n++)l[n]=a[n],d[n]=c[n]=u[n]=0;for(n=254,c[0]=d[0]=1;n>=0;--n)U(c,l,i=o[n>>>3]>>>(7&n)&1),U(u,d,i),H(f,c,u),J(c,c,u),H(u,l,d),J(l,l,d),z(d,f),z(p,c),K(c,u,c),K(u,l,f),H(f,c,u),J(c,c,u),z(l,c),J(u,d,p),K(c,u,h),H(c,c,d),K(u,u,c),K(c,d,p),K(d,l,a),z(l,f),U(c,l,i),U(u,d,i);for(n=0;n<16;n++)a[n+16]=c[n],a[n+32]=u[n],a[n+48]=l[n],a[n+64]=d[n];var m=a.subarray(32),b=a.subarray(16);return G(m,m),K(b,b,m),L(e,b),0}function Y(e,t){return W(e,t,o)}function X(e,t){return i(t,32),Y(e,t)}function Q(e,t,s){var r=new Uint8Array(32);return W(r,s,t),E(e,n,r,P)}function Z(){var e,t,r,i=0,n=0,o=0,a=0;for(r=0;r>>16,o+=65535&t,a+=t>>>16;return n+=i>>>16,o+=n>>>16,a+=o>>>16,new s(65535&o|a<<16,65535&i|n<<16)}function ee(e,t){return new s(e.hi>>>t,e.lo>>>t|e.hi<<32-t)}function et(){var e,t=0,r=0;for(e=0;e>>t|e.lo<>>t|e.hi<>>t|e.hi<>>t|e.lo<=128;){for(m=0;m<16;m++)S[m]=g(t,8*m+v);for(m=0;m<80;m++){for(b=0;b<8;b++)w[b]=x[b];for(b=0,p=Z(x[7],et(es(i=x[4],14),es(i,18),es(i,41)),(n=x[4],o=x[5],a=x[6],new s(n.hi&o.hi^~n.hi&a.hi,n.lo&o.lo^~n.lo&a.lo)),er[m],S[m%16]),w[7]=Z(p,et(es(c=x[0],28),es(c,34),es(c,39)),(h=x[0],l=x[1],u=x[2],new s(h.hi&l.hi^h.hi&u.hi^l.hi&u.hi,h.lo&l.lo^h.lo&u.lo^l.lo&u.lo))),w[3]=Z(w[3],p);b<8;b++)x[(b+1)%8]=w[b];if(m%16==15)for(b=0;b<16;b++)S[b]=Z(S[b],S[(b+9)%16],et(es(d=S[(b+1)%16],1),es(d,8),ee(d,7)),et(es(f=S[(b+14)%16],19),es(f,61),ee(f,6)))}for(m=0;m<8;m++)x[m]=Z(x[m],_[m]),_[m]=x[m];v+=128,r-=128}for(m=0;m<8;m++)y(e,8*m,_[m]);return r}var en=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 eo(e,t,r){var i,n=new Uint8Array(64),o=new Uint8Array(256),a=r;for(i=0;i<64;i++)n[i]=en[i];for(ei(n,t,r),r%=128,i=0;i<256;i++)o[i]=0;for(i=0;i=0;--i)ec(e,t,r=s[i/8|0]>>(7&i)&1),ea(t,e),ea(e,e),ec(e,t,r)}function eu(e,t){var s=[r(),r(),r(),r()];T(s[0],d),T(s[1],f),T(s[2],c),K(s[3],d,f),el(e,s,t)}function ed(e,t,s){var n,o=new Uint8Array(64),a=[r(),r(),r(),r()];for(s||i(t,32),eo(o,t,32),o[0]&=248,o[31]&=127,o[31]|=64,eu(a,o),eh(e,a),n=0;n<32;n++)t[n+32]=e[n];return 0}var ef=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 ep(e,t){var s,r,i,n;for(r=63;r>=32;--r){for(s=0,i=r-32,n=r-12;i>4)*ef[i],s=t[i]>>8,t[i]&=255;for(i=0;i<32;i++)t[i]-=s*ef[i];for(r=0;r<32;r++)t[r+1]+=t[r]>>8,e[r]=255&t[r]}function em(e){var t,s=new Float64Array(64);for(t=0;t<64;t++)s[t]=e[t];for(t=0;t<64;t++)e[t]=0;ep(e,s)}function eb(e,t,s,i){var n,o,a=new Uint8Array(64),c=new Uint8Array(64),h=new Uint8Array(64),l=new Float64Array(64),u=[r(),r(),r(),r()];for(eo(a,i,32),a[0]&=248,a[31]&=127,a[31]|=64,n=0;n>7&&J(w[0],a,w[0]),K(w[3],w[0],w[1]),0)))return -1;for(b=0;b=0},e.sign.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(64);return ed(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(ey(e),64!==e.length)throw Error("bad secret key size");for(var t=new Uint8Array(32),s=0;s>8^e[s])&255];return t}static validate(e,t){return tf.checksum(e)==t}}let tp="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";class tm{static encode(e){let t=0,s=0,r=new Uint8Array(e),i=new Uint8Array(2*e.byteLength),n=0;for(let e=0;e=5;){let e=s>>>t-5&31;i[n++]=tp.charAt(e).charCodeAt(0),t-=5}if(t>0){let e=s<<5-t&31;i[n++]=tp.charAt(e).charCodeAt(0)}return i.slice(0,n)}static decode(e){let t=0,s=0,r=0,i=new Uint8Array(e),n=new Uint8Array(5*i.byteLength/8|0);for(let e=0;e=8&&(n[r++]=s>>>t-8&255,t-=8)}return n.slice(0,r)}}class tb extends Error{name;code;chainedError;constructor(e,t){super(e),this.name="NKeysError",this.code=e,this.chainedError=t}}!function(e){e.InvalidPrefixByte="nkeys: invalid prefix byte",e.InvalidKey="nkeys: invalid key",e.InvalidPublicKey="nkeys: invalid public key",e.InvalidSeedLen="nkeys: invalid seed length",e.InvalidSeed="nkeys: invalid seed",e.InvalidEncoding="nkeys: invalid encoded key",e.InvalidSignature="nkeys: signature verification failed",e.CannotSign="nkeys: cannot sign, no private key available",e.PublicKeyOnly="nkeys: no seed or private key available",e.InvalidChecksum="nkeys: invalid checksum",e.SerializationError="nkeys: serialization error",e.ApiError="nkeys: api error",e.ClearedPair="nkeys: pair is cleared"}(C||(C={})),function(e){e[e.Seed=144]="Seed",e[e.Private=120]="Private",e[e.Operator=112]="Operator",e[e.Server=104]="Server",e[e.Cluster=16]="Cluster",e[e.Account=0]="Account",e[e.User=160]="User"}(O||(O={}));class tg{static isValidPublicPrefix(e){return e==O.Server||e==O.Operator||e==O.Cluster||e==O.Account||e==O.User}static startsWithValidPrefix(e){let t=e[0];return"S"==t||"P"==t||"O"==t||"N"==t||"C"==t||"A"==t||"U"==t}static isValidPrefix(e){return -1!=this.parsePrefix(e)}static parsePrefix(e){switch(e){case O.Seed:return O.Seed;case O.Private:return O.Private;case O.Operator:return O.Operator;case O.Server:return O.Server;case O.Cluster:return O.Cluster;case O.Account:return O.Account;case O.User:return O.User;default:return -1}}}class t_{static encode(e,t){if(!t||!(t instanceof Uint8Array))throw new tb(C.SerializationError);if(!tg.isValidPrefix(e))throw new tb(C.InvalidPrefixByte);return t_._encode(!1,e,t)}static encodeSeed(e,t){if(!t)throw new tb(C.ApiError);if(!tg.isValidPublicPrefix(e))throw new tb(C.InvalidPrefixByte);if(32!==t.byteLength)throw new tb(C.InvalidSeedLen);return t_._encode(!0,e,t)}static decode(e,t){if(!tg.isValidPrefix(e))throw new tb(C.InvalidPrefixByte);let s=t_._decode(t);if(s[0]!==e)throw new tb(C.InvalidPrefixByte);return s.slice(1)}static decodeSeed(e){let t=t_._decode(e),s=t_._decodePrefix(t);if(s[0]!=O.Seed)throw new tb(C.InvalidSeed);if(!tg.isValidPublicPrefix(s[1]))throw new tb(C.InvalidPrefixByte);return{buf:t.slice(2),prefix:s[1]}}static _encode(e,t,s){let r=e?2:1,i=s.byteLength,n=r+i,o=new Uint8Array(r+i+2);if(e){let e=t_._encodePrefix(O.Seed,t);o.set(e)}else o[0]=t;o.set(s,r);let a=tf.checksum(o.slice(0,n));return new DataView(o.buffer).setUint16(n,a,!0),tm.encode(o)}static _decode(e){let t;if(e.byteLength<4)throw new tb(C.InvalidEncoding);try{t=tm.decode(e)}catch(e){throw new tb(C.InvalidEncoding,e)}let s=t.byteLength-2,r=new DataView(t.buffer).getUint16(s,!0),i=t.slice(0,s);if(!tf.validate(i,r))throw new tb(C.InvalidChecksum);return i}static _encodePrefix(e,t){return new Uint8Array([e|t>>5,(31&t)<<3])}static _decodePrefix(e){return new Uint8Array([248&e[0],(7&e[0])<<5|(248&e[1])>>3])}}class ty{seed;constructor(e){this.seed=e}getRawSeed(){if(!this.seed)throw new tb(C.ClearedPair);return t_.decodeSeed(this.seed).buf}getSeed(){if(!this.seed)throw new tb(C.ClearedPair);return this.seed}getPublicKey(){if(!this.seed)throw new tb(C.ClearedPair);let e=t_.decodeSeed(this.seed),t=$.fromSeed(this.getRawSeed()),s=t_.encode(e.prefix,t.publicKey);return new TextDecoder().decode(s)}getPrivateKey(){if(!this.seed)throw new tb(C.ClearedPair);let e=$.fromSeed(this.getRawSeed());return t_.encode(O.Private,e.secretKey)}sign(e){if(!this.seed)throw new tb(C.ClearedPair);let t=$.fromSeed(this.getRawSeed());return $.sign(e,t.secretKey)}verify(e,t){if(!this.seed)throw new tb(C.ClearedPair);let s=$.fromSeed(this.getRawSeed());return $.verify(e,t,s.publicKey)}clear(){this.seed&&(this.seed.fill(0),this.seed=void 0)}}function tw(e){let t=$.randomBytes(32);return new ty(t_.encodeSeed(e,new Uint8Array(t)))}class tx{publicKey;constructor(e){this.publicKey=e}getPublicKey(){if(!this.publicKey)throw new tb(C.ClearedPair);return new TextDecoder().decode(this.publicKey)}getPrivateKey(){if(!this.publicKey)throw new tb(C.ClearedPair);throw new tb(C.PublicKeyOnly)}getSeed(){if(!this.publicKey)throw new tb(C.ClearedPair);throw new tb(C.PublicKeyOnly)}sign(e){if(!this.publicKey)throw new tb(C.ClearedPair);throw new tb(C.CannotSign)}verify(e,t){if(!this.publicKey)throw new tb(C.ClearedPair);let s=t_._decode(this.publicKey);return $.verify(e,t,s.slice(1))}clear(){this.publicKey&&(this.publicKey.fill(0),this.publicKey=void 0)}}$=tu;let tS={createAccount:function(){return tw(O.Account)},createOperator:function(){return tw(O.Operator)},createPair:tw,createUser:function(){return tw(O.User)},fromPublic:function(e){let t=new TextEncoder().encode(e),s=t_._decode(t),r=tg.parsePrefix(s[0]);if(tg.isValidPublicPrefix(r))return new tx(t);throw new tb(C.InvalidPublicKey)},fromSeed:function(e){return t_.decodeSeed(e),new ty(e)},NKeysError:tb,NKeysErrorCode:C,Prefix:O,decode:function(e){let t=atob(e),s=new Uint8Array(t.length);for(let e=0;e({user:"function"==typeof e?e():e,pass:"function"==typeof t?t():t})}function tE(e){return()=>({auth_token:"function"==typeof e?e():e})}function tP(e){return t=>{let s="function"==typeof e?e():e,r=s?tS.fromSeed(s):void 0,i=r?r.getPublicKey():"",n=q.encode(t||""),o=void 0!==r&&t?r.sign(n):void 0;return{nkey:i,sig:o?tS.encode(o):""}}}function tA(e,t){return s=>{let r="function"==typeof e?e():e,{nkey:i,sig:n}=tP(t)(s);return{jwt:r,nkey:i,sig:n}}}function tk(e){let t="function"!=typeof e?()=>e:e,s=()=>{let e=/\s*(?:(?:[-]{3,}[^\n]*[-]{3,}\n)(.+)(?:\n\s*[-]{3,}[^\n]*[-]{3,}\n))/ig,s=U.decode(t()),r=e.exec(s);if(!r)throw z.errorForCode(n.BadCreds);let i=r[1].trim();if(!(r=e.exec(s))||!r)throw z.errorForCode(n.BadCreds);return{jwt:i,seed:q.encode(r[1].trim())}};return tA(()=>{let{jwt:e}=s();return e},()=>{let{seed:e}=s();return e})}function tC(e){let t=[];return"function"==typeof e.authenticator&&t.push(e.authenticator),Array.isArray(e.authenticator)&&t.push(...e.authenticator),e.token&&t.push(tE(e.token)),e.user&&t.push(tv(e.user,e.pass)),0===t.length?()=>{}:e=>{let s={};return t.forEach(t=>{let r=t(e)||{};s=Object.assign(s,r)}),s}}let tO=/^INFO\s+([^\r\n]+)\r\n/i,tj=L("PONG\r\n"),tI=L("PING\r\n");class tM{echo;no_responders;protocol;verbose;pedantic;jwt;nkey;sig;user;pass;auth_token;tls_required;name;lang;version;headers;constructor(e,t,s){this.protocol=1,this.version=e.version,this.lang=e.lang,this.echo=!t.noEcho&&void 0,this.verbose=t.verbose,this.pedantic=t.pedantic,this.tls_required=!!t.tls||void 0,this.name=t.name,Z(this,(t&&"function"==typeof t.authenticator?t.authenticator(s):{})||{})}}class tN extends eA{sid;queue;draining;max;subject;drained;protocol;timer;info;cleanupFn;closed;requestSubject;constructor(e,t,s={}){super(),Z(this,s),this.protocol=e,this.subject=t,this.draining=!1,this.noIterator="function"==typeof s.callback,this.closed=ei();let r=!e.options?.noAsyncTraces;s.timeout&&(this.timer=et(s.timeout,r),this.timer.then(()=>{this.timer=void 0}).catch(e=>{this.stop(e),this.noIterator&&this.callback(e,{})})),this.noIterator||this.iterClosed.then(()=>{this.closed.resolve(),this.unsubscribe()})}setPrePostHandlers(e){if(this.noIterator){let t=this.callback,s=e.ingestionFilterFn?e.ingestionFilterFn:()=>({ingest:!0,protocol:!1}),r=e.protocolFilterFn?e.protocolFilterFn:()=>!0,i=e.dispatchedFn?e.dispatchedFn:()=>{};this.callback=(e,n)=>{let{ingest:o}=s(n);o&&r(n)&&(t(e,n),i(n))}}else this.protocolFilterFn=e.protocolFilterFn,this.dispatchedFn=e.dispatchedFn}callback(e,t){this.cancelTimeout(),e?this.stop(e):this.push(t)}close(){if(!this.isClosed()){this.cancelTimeout();let e=()=>{if(this.stop(),this.cleanupFn)try{this.cleanupFn(this,this.info)}catch(e){}this.closed.resolve()};this.noIterator?e():this.push(e)}}unsubscribe(e){this.protocol.unsubscribe(this,e)}cancelTimeout(){this.timer&&(this.timer.cancel(),this.timer=void 0)}drain(){return this.protocol.isClosed()?Promise.reject(z.errorForCode(n.ConnectionClosed)):this.isClosed()?Promise.reject(z.errorForCode(n.SubClosed)):(this.drained||(this.draining=!0,this.protocol.unsub(this),this.drained=this.protocol.flush(ei()).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 tR{mux;subs;sidCounter;constructor(){this.sidCounter=0,this.mux=null,this.subs=new Map}size(){return this.subs.size}add(e){return this.sidCounter++,e.sid=this.sidCounter,this.subs.set(e.sid,e),e}setMux(e){return this.mux=e,e}getMux(){return this.mux}get(e){return this.subs.get(e)}resub(e){return this.sidCounter++,this.subs.delete(e.sid),e.sid=this.sidCounter,this.subs.set(e.sid,e),e}all(){return Array.from(this.subs.values())}cancel(e){e&&(e.close(),this.subs.delete(e.sid))}handleError(e){if(e&&e.permissionContext){let t,s=e.permissionContext,r=this.all();if("subscription"===s.operation&&(t=r.find(e=>e.subject===s.subject&&e.queue===s.queue)),"publish"===s.operation&&(t=r.find(e=>e.requestSubject===s.subject)),t)return t.callback(e,{}),t.close(),this.subs.delete(t.sid),t!==this.mux}return!1}close(){this.subs.forEach(e=>{e.close()})}}class t${connected;connectedOnce;infoReceived;info;muxSubscriptions;options;outbound;pongs;subscriptions;transport;noMorePublishing;connectError;publisher;_closed;closed;listeners;heartbeats;parser;outMsgs;inMsgs;outBytes;inBytes;pendingLimit;lastError;abortReconnect;whyClosed;servers;server;features;connectPromise;constructor(e,t){this._closed=!1,this.connected=!1,this.connectedOnce=!1,this.infoReceived=!1,this.noMorePublishing=!1,this.abortReconnect=!1,this.listeners=[],this.pendingLimit=32768,this.outMsgs=0,this.inMsgs=0,this.outBytes=0,this.inBytes=0,this.options=e,this.publisher=t,this.subscriptions=new tR,this.muxSubscriptions=new ts,this.outbound=new eN,this.pongs=[],this.whyClosed="",this.pendingLimit=e.pendingLimit||this.pendingLimit,this.features=new eX({major:0,minor:0,micro:0}),this.connectPromise=null;let s="string"==typeof e.servers?[e.servers]:e.servers;this.servers=new tt(s,{randomize:!e.noRandomize}),this.closed=ei(),this.parser=new th(this),this.heartbeats=new tr(this,this.options.pingInterval||12e4,this.options.maxPingOut||2)}resetOutbound(){this.outbound.reset();let e=this.pongs;this.pongs=[];let t=z.errorForCode(n.Disconnect);t.stack="",e.forEach(e=>{e.reject(t)}),this.parser=new th(this),this.infoReceived=!1}dispatchStatus(e){this.listeners.forEach(t=>{t.push(e)})}status(){let e=new eA;return this.listeners.push(e),e}prepare(){this.transport&&this.transport.discard(),this.info=void 0,this.resetOutbound();let e=ei();return e.catch(()=>{}),this.pongs.unshift(e),this.connectError=t=>{e.reject(t)},this.transport=function(){if(!R||"function"!=typeof R.factory)throw Error("transport fn is not set");return R.factory()}(),this.transport.closed().then(async e=>{if(this.connected=!1,!this.isClosed())return void await this.disconnected(this.transport.closeError||this.lastError)}),e}disconnect(){this.dispatchStatus({type:i.StaleConnection,data:""}),this.transport.disconnect()}reconnect(){return this.connected&&(this.dispatchStatus({type:i.ClientInitiatedReconnect,data:""}),this.transport.disconnect()),Promise.resolve()}async disconnected(e){this.dispatchStatus({type:r.Disconnect,data:this.servers.getCurrentServer().toString()}),this.options.reconnect?await this.dialLoop().then(()=>{this.dispatchStatus({type:r.Reconnect,data:this.servers.getCurrentServer().toString()}),this.lastError?.code===n.AuthenticationExpired&&(this.lastError=void 0)}).catch(e=>{this._close(e)}):await this._close(e)}async dial(e){let t,s=this.prepare();try{t=et(this.options.timeout||2e4);let s=this.transport.connect(e,this.options);await Promise.race([s,t]),(async()=>{try{for await(let e of this.transport)this.parser.parse(e)}catch(e){console.log("reader closed",e)}})().then()}catch(e){s.reject(e)}try{await Promise.race([t,s]),t&&t.cancel(),this.connected=!0,this.connectError=void 0,this.sendSubscriptions(),this.connectedOnce=!0,this.server.didConnect=!0,this.server.reconnects=0,this.flushPending(),this.heartbeats.start()}catch(e){throw t&&t.cancel(),await this.transport.close(e),e}}async _doDial(e){let{resolve:t}=this.options,s=await e.resolve({fn:e3(),debug:this.options.debug,randomize:!this.options.noRandomize,resolve:t}),r=null;for(let e of s)try{r=null,this.dispatchStatus({type:i.Reconnecting,data:e.toString()}),await this.dial(e);return}catch(e){r=e}throw r}dialLoop(){return null===this.connectPromise&&(this.connectPromise=this.dodialLoop(),this.connectPromise.then(()=>{}).catch(()=>{}).finally(()=>{this.connectPromise=null})),this.connectPromise}async dodialLoop(){let e;for(;;){this._closed&&this.servers.clear();let t=this.options.reconnectDelayHandler?this.options.reconnectDelayHandler():2e3,s=t,r=this.selectServer();if(!r||this.abortReconnect)if(e)throw e;else if(this.lastError)throw this.lastError;else throw z.errorForCode(n.ConnectionRefused);let i=Date.now();if(0===r.lastConnect||r.lastConnect+t<=i){r.lastConnect=Date.now();try{await this._doDial(r);break}catch(s){if(e=s,!this.connectedOnce){if(this.options.waitOnFirstConnect)continue;this.servers.removeCurrentServer()}r.reconnects++;let t=this.options.maxReconnectAttempts||0;-1!==t&&r.reconnects>=t&&this.servers.removeCurrentServer()}}else s=Math.min(s,r.lastConnect+t-i),await es(s)}}static async connect(e,t){let s=new t$(e,t);return await s.dialLoop(),s}static toError(e){let t=e?e.toLowerCase():"";if(-1!==t.indexOf("permissions violation")){let t=new z(e,n.PermissionsViolation),s=e.match(/(Publish|Subscription) to "(\S+)"/);if(s){t.permissionContext={operation:s[1].toLowerCase(),subject:s[2],queue:void 0};let r=e.match(/using queue "(\S+)"/);r&&(t.permissionContext.queue=r[1])}return t}if(-1!==t.indexOf("authorization violation"))return new z(e,n.AuthorizationViolation);if(-1!==t.indexOf("user authentication expired"))return new z(e,n.AuthenticationExpired);if(-1!=t.indexOf("account authentication expired"))return new z(e,n.AccountExpired);if(-1!==t.indexOf("authentication timeout"))return new z(e,n.AuthenticationTimeout);else return new z(e,n.ProtocolError)}processMsg(e,t){if(this.inMsgs++,this.inBytes+=t.length,!this.subscriptions.sidCounter)return;let s=this.subscriptions.get(e.sid);s&&(s.received+=1,s.callback&&s.callback(null,new eg(e,t,this)),void 0!==s.max&&s.received>=s.max&&s.unsubscribe())}processError(e){let t=F(e),s=t$.toError(t),i={type:r.Error,data:s.code};if(s.isPermissionError()){let e=!1;if(s.permissionContext){i.permissionContext=s.permissionContext;let t=this.subscriptions.getMux();e=t?.subject===s.permissionContext.subject}this.subscriptions.handleError(s),this.muxSubscriptions.handleError(e,s),e&&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&&!1===this.options.ignoreAuthErrorAbort&&(this.abortReconnect=!0),this.connectError?this.connectError(e):this.disconnect()}processPing(){this.transport.send(tj)}processPong(){let e=this.pongs.shift();e&&e.resolve()}processInfo(e){let t=JSON.parse(F(e));this.info=t;let s=this.options&&this.options.ignoreClusterUpdates?void 0:this.servers.update(t,this.transport.isEncrypted());if(!this.infoReceived){this.features.update(eW(t.version)),this.infoReceived=!0,this.transport.isEncrypted()&&this.servers.updateTLSName();let{version:e,lang:s}=this.transport;try{let r=new tM({version:e,lang:s},this.options,t.nonce);t.headers&&(r.headers=!0,r.no_responders=!0);let i=JSON.stringify(r);this.transport.send(L(`CONNECT ${i}\r `)),this.transport.send(tI)}catch(e){this._close(e)}}s&&this.dispatchStatus({type:r.Update,data:s}),void 0!==t.ldm&&t.ldm&&this.dispatchStatus({type:r.LDM,data:this.servers.getCurrentServer().toString()})}push(e){switch(e.kind){case P.MSG:{let{msg:t,data:s}=e;this.processMsg(t,s);break}case P.OK:break;case P.ERR:this.processError(e.data);break;case P.PING:this.processPing();break;case P.PONG:this.processPong();break;case P.INFO:this.processInfo(e.data)}}sendCommand(e,...t){let s,r=this.outbound.length();s="string"==typeof e?L(e):e,this.outbound.fill(s,...t),0===r?queueMicrotask(()=>{this.flushPending()}):this.outbound.size()>=this.pendingLimit&&this.flushPending()}publish(e,t=T,s){let r,i;if(t instanceof Uint8Array)r=t;else if("string"==typeof t)r=q.encode(t);else throw z.errorForCode(n.BadPayload);let o=r.length;(s=s||{}).reply=s.reply||"";let a=T,c=0;if(s.headers){if(this.info&&!this.info.headers)throw new z("headers",n.ServerOptionNotAvailable);c=(a=s.headers.encode()).length,o=r.length+c}if(this.info&&o>this.info.max_payload)throw z.errorForCode(n.MaxPayloadExceeded);this.outBytes+=o,this.outMsgs++,s.headers?(i=s.reply?`HPUB ${e} ${s.reply} ${c} ${o}\r `:`HPUB ${e} ${c} ${o}\r `,this.sendCommand(i,a,r,e4)):(i=s.reply?`PUB ${e} ${s.reply} ${o}\r `:`PUB ${e} ${o}\r `,this.sendCommand(i,r,e4))}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 `):this.sendCommand(`SUB ${e.subject} ${e.sid}\r `)}_subunsub(e){return this._sub(e),e.max&&this.unsubscribe(e,e.max),e}unsubscribe(e,t){this.unsub(e,t),(void 0===e.max||e.received>=e.max)&&this.subscriptions.cancel(e)}unsub(e,t){!e||this.isClosed()||(t?this.sendCommand(`UNSUB ${e.sid} ${t}\r `):this.sendCommand(`UNSUB ${e.sid}\r `),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=ei()),this.pongs.push(e),this.outbound.fill(tI),this.flushPending(),e}sendSubscriptions(){let e=[];this.subscriptions.all().forEach(t=>{t.queue?e.push(`SUB ${t.subject} ${t.queue} ${t.sid}\r `):e.push(`SUB ${t.subject} ${t.sid}\r `)}),e.length&&this.transport.send(L(e.join("")))}async _close(e){this._closed||(this.whyClosed=Error("close trace").stack||"",this.heartbeats.cancel(),this.connectError&&(this.connectError(e),this.connectError=void 0),this.muxSubscriptions.close(),this.subscriptions.close(),this.listeners.forEach(e=>{e.stop()}),this._closed=!0,await this.transport.close(e),await this.closed.resolve(e))}close(){return this._close()}isClosed(){return this._closed}drain(){let e=this.subscriptions.all(),t=[];return e.forEach(e=>{t.push(e.drain())}),Promise.all(t).then(async()=>(this.noMorePublishing=!0,await this.flush(),this.close())).catch(()=>{})}flushPending(){if(this.infoReceived&&this.connected&&this.outbound.size()){let e=this.outbound.drain();this.transport.send(e)}}initMux(){if(!this.subscriptions.getMux()){let e=this.muxSubscriptions.init(this.options.inboxPrefix),t=new tN(this,`${e}*`);t.callback=this.muxSubscriptions.dispatcher(),this.subscriptions.setMux(t),this.subscribe(t)}}selectServer(){let e=this.servers.selectServer();if(void 0!==e)return this.server=e,this.server}getServer(){return this.server}}class tT{msg;constructor(e){this.msg=e}get data(){return this.msg.data}get sid(){return this.msg.sid}get subject(){return this.msg.subject}get reply(){return this.msg.reply||""}get headers(){return this.msg.headers}respond(e,t){return this.msg.respond(e,t)}respondError(e,t,s,r){return(r=r||{}).headers=r.headers||eu(),r.headers?.set(W,`${e}`),r.headers?.set(V,t),this.msg.respond(s,r)}json(e){return this.msg.json(e)}string(){return this.msg.string()}}class tq{subject;queue;srv;constructor(e,t="",s=""){""!==t&&function(e,t){if(-1!==t.indexOf(" "))throw Error(`${e} cannot contain spaces: '${t}'`);t.split(".").forEach(s=>{if(">"===s)throw Error(`${e} name cannot contain internal '>': '${t}'`)})}("service group",t);let r="";if(e instanceof tU)this.srv=e,r="";else if(e instanceof tq)this.srv=e.srv,""===s&&""!==e.queue&&(s=e.queue),r=e.subject;else throw Error("unknown ServiceGroup type");this.subject=this.calcSubject(r,t),this.queue=s}calcSubject(e,t=""){return""===t?e:""!==e?`${e}.${t}`:t}addEndpoint(e="",t){let s="function"==typeof(t=t||{subject:e})?{handler:t,subject:e}:t;ex("endpoint",e);let{subject:r,handler:i,metadata:n,queue:o}=s;r=r||e,o=o||this.queue,function(e,t){if(""===t)throw Error(`${e} cannot be empty`);if(-1!==t.indexOf(" "))throw Error(`${e} cannot contain spaces: '${t}'`);let s=t.split(".");s.forEach((r,i)=>{if(">"===r&&i!==s.length-1)throw Error(`${e} cannot have internal '>': '${t}'`)})}("endpoint subject",r);let a={name:e,subject:r=this.calcSubject(this.subject,r),queue:o,handler:i,metadata:n};return this.srv._addEndpoint(a)}addGroup(e="",t=""){return new tq(this,e,t)}}class tU{nc;_id;config;handlers;internal;_stopped;_done;started;static controlSubject(e,t="",s="",r){let i=r??"$SRV";return""===t&&""===s?`${i}.${e}`:(ex("control subject name",t),""!==s)?(ex("control subject id",s),`${i}.${e}.${t}.${s}`):`${i}.${e}.${t}`}constructor(e,t={name:"",version:""}){this.nc=e,this.config=Object.assign({},t),this.config.queue||(this.config.queue="q"),ex("name",this.config.name),ex("queue",this.config.queue),eW(this.config.version),this._id=H.next(),this.internal=[],this._done=ei(),this._stopped=!1,this.handlers=[],this.started=new Date().toISOString(),this.reset(),this.nc.closed().then(()=>{this.close().catch()}).catch(e=>{this.close(e).catch()})}get subjects(){return this.handlers.filter(e=>!1===e.internal).map(e=>e.subject)}get id(){return this._id}get name(){return this.config.name}get description(){return this.config.description??""}get version(){return this.config.version}get metadata(){return this.config.metadata}errorToHeader(e){let t=eu();return e instanceof Y?(t.set(V,e.message),t.set(W,`${e.code}`)):(t.set(V,e.message),t.set(W,"500")),t}setupHandler(e,t=!1){let s=t?"":e.queue?e.queue:this.config.queue,{name:r,subject:i,handler:n}=e;e.internal=t,t&&this.internal.push(e),e.stats=new tL(r,i,s),e.queue=s;let o=n?(t,s)=>{if(t)return void this.close(t);let r=Date.now();try{n(t,new tT(s))}catch(t){e.stats.countError(t),s?.respond(T,{headers:this.errorToHeader(t)})}finally{e.stats.countLatency(r)}}:void 0;return e.sub=this.nc.subscribe(i,{callback:o,queue:s}),e.sub.closed.then(()=>{this._stopped||this.close(Error(`required subscription ${e.subject} stopped`)).catch()}).catch(t=>{if(!this._stopped){let s=Error(`required subscription ${e.subject} errored: ${t.message}`);s.stack=t.stack,this.close(s).catch()}}),e}info(){return{type:c.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=>{let{subject:t,metadata:s,name:r,queue:i}=e;return{subject:t,metadata:s,name:r,queue_group:i}})}async stats(){let e=[];for(let t of this.handlers){if("function"==typeof this.config.statsHandler)try{t.stats.data=await this.config.statsHandler(t)}catch(e){t.stats.countError(e)}e.push(t.stats.stats(t.qi))}return{type:c.STATS,name:this.name,id:this.id,version:this.version,started:this.started,metadata:this.metadata,endpoints:e}}addInternalHandler(e,t){let 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,r="",i=""){let n={};n.name=e,n.subject=tU.controlSubject(t,r,i),n.handler=s,this.setupHandler(n,!0)}start(){let e=em(),t=e.encode(this.ping());return this.addInternalHandler(h.PING,(e,s)=>e?(this.close(e).then().catch(),Promise.reject(e)):(s.respond(t),Promise.resolve())),this.addInternalHandler(h.STATS,(t,s)=>t?(this.close(t),Promise.reject(t)):this.stats().then(t=>(s?.respond(e.encode(t)),Promise.resolve()))),this.addInternalHandler(h.INFO,(t,s)=>t?(this.close(t),Promise.reject(t)):(s?.respond(e.encode(this.info())),Promise.resolve())),this.handlers.forEach(e=>{let{subject:t}=e;"string"==typeof t&&null!==e.handler&&this.setupHandler(e)}),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(e=>e.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:c.PING,name:this.name,id:this.id,version:this.version,metadata:this.metadata}}reset(){if(this.started=new Date().toISOString(),this.handlers)for(let e of this.handlers)e.stats.reset(e.qi)}addGroup(e,t){return new tq(this,e,t)}addEndpoint(e,t){return new tq(this).addEndpoint(e,t)}_addEndpoint(e){let t=new eA;t.noIterator="function"==typeof e.handler,t.noIterator||(e.handler=(e,s)=>{e?this.stop(e).catch():t.push(new tT(s))},t.iterClosed.then(()=>{this.close().catch()}));let s=this.setupHandler(e,!1);return s.qi=t,this.handlers.push(s),t}}class tL{name;subject;average_processing_time;num_requests;processing_time;num_errors;last_error;data;metadata;queue;constructor(e,t,s=""){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,e&&(e.time=0,e.processed=0)}countLatency(e){this.num_requests++,this.processing_time+=ec(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(){let{name:e,subject:t,average_processing_time:s,num_errors:r,num_requests:i,processing_time:n,last_error:o,data:a,queue:c}=this;return{name:e,subject:t,average_processing_time:s,num_errors:r,num_requests:i,processing_time:n,last_error:o,data:a,queue_group:c}}stats(e){return e?.noIterator===!1&&(this.processing_time=e.time,this.num_requests=e.processed,this.average_processing_time=this.processing_time>0&&this.num_requests>0?this.processing_time/this.num_requests:0),this._stats()}}class tF{nc;prefix;opts;constructor(e,t={strategy:a.JitterTimer,maxWait:2e3},s){this.nc=e,this.prefix=s,this.opts=t}ping(e="",t=""){return this.q(h.PING,e,t)}stats(e="",t=""){return this.q(h.STATS,e,t)}info(e="",t=""){return this.q(h.INFO,e,t)}async q(e,t="",s=""){let r=new eA,i=em(),n=tU.controlSubject(e,t,s,this.prefix),o=await this.nc.requestMany(n,T,this.opts);return(async()=>{for await(let e of o)try{let t=i.decode(e.data);r.push(t)}catch(e){r.push(()=>{r.stop(e)})}r.push(()=>{r.stop()})})().catch(e=>{r.stop(e)}),r}}class tB{name;duration;date;payload;msgs;lang;version;bytes;asyncRequests;min;max;constructor(e,t){this.name=e,this.duration=t,this.date=Date.now(),this.payload=0,this.msgs=0,this.bytes=0}toString(){var e,t;let s=this.duration/1e3,r=Math.round(this.msgs/s),i=this.asyncRequests?"asyncRequests":"",n="";return this.max&&(n=`${this.min}/${this.max}`),`${this.name}${i?" [asyncRequests]":""} ${r.toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")} msgs/sec - [${s.toFixed(2)} secs] ~ ${e=this.bytes,t=s,`${function(e,t=!1){let s=t?1e3:1024,r=t?"iB":"B";if(e{if(e)throw new z(`bench closed with an error: ${e.message}`,n.Unknown,e)}),this.callbacks?await this.runCallbacks():await this.runAsync(),this.processMetrics()}processMetrics(){let{lang:e,version:t}=this.nc.protocol.transport;this.pub&&this.sub&&this.perf.measure("pubsub","pubStart","subStop"),this.req&&this.rep&&this.perf.measure("reqrep","reqStart","reqStop");let s=this.perf.getEntries(),r=s.find(e=>"pubsub"===e.name),i=s.find(e=>"reqrep"===e.name),n=s.find(e=>"req"===e.name),o=s.find(e=>"rep"===e.name),a=s.find(e=>"pub"===e.name),c=s.find(e=>"sub"===e.name),h=this.nc.stats(),l=[];if(r){let{name:s,duration:i}=r,n=new tB(s,i);n.msgs=2*this.msgs,n.bytes=h.inBytes+h.outBytes,n.lang=e,n.version=t,n.payload=this.payload.length,l.push(n)}if(i){let{name:s,duration:r}=i,n=new tB(s,r);n.msgs=2*this.msgs,n.bytes=h.inBytes+h.outBytes,n.lang=e,n.version=t,n.payload=this.payload.length,l.push(n)}if(a){let{name:s,duration:r}=a,i=new tB(s,r);i.msgs=this.msgs,i.bytes=h.outBytes,i.lang=e,i.version=t,i.payload=this.payload.length,l.push(i)}if(c){let{name:s,duration:r}=c,i=new tB(s,r);i.msgs=this.msgs,i.bytes=h.inBytes,i.lang=e,i.version=t,i.payload=this.payload.length,l.push(i)}if(o){let{name:s,duration:r}=o,i=new tB(s,r);i.msgs=this.msgs,i.bytes=h.inBytes+h.outBytes,i.lang=e,i.version=t,i.payload=this.payload.length,l.push(i)}if(n){let{name:s,duration:r}=n,i=new tB(s,r);i.msgs=this.msgs,i.bytes=h.inBytes+h.outBytes,i.lang=e,i.version=t,i.payload=this.payload.length,l.push(i)}return l}async runCallbacks(){let e=[];if(this.sub){let t=ei();e.push(t);let s=0;this.nc.subscribe(this.subject,{max:this.msgs,callback:()=>{1==++s&&this.perf.mark("subStart"),s===this.msgs&&(this.perf.mark("subStop"),this.perf.measure("sub","subStart","subStop"),t.resolve())}})}if(this.rep){let t=ei();e.push(t);let s=0;this.nc.subscribe(this.subject,{max:this.msgs,callback:(e,r)=>{r.respond(this.payload),1==++s&&this.perf.mark("repStart"),s===this.msgs&&(this.perf.mark("repStop"),this.perf.measure("rep","repStart","repStop"),t.resolve())}})}if(this.pub){let t=(async()=>{this.perf.mark("pubStart");for(let e=0;e{if(this.asyncRequests){this.perf.mark("reqStart");let e=[];for(let t=0;t{for await(let e of s)t||(this.perf.mark("repStart"),t=!0),e.respond(this.payload);await this.nc.flush(),this.perf.mark("repStop"),this.perf.measure("rep","repStart","repStop")})();e.push(r)}if(this.sub){let t=!1,s=this.nc.subscribe(this.subject,{max:this.msgs}),r=(async()=>{for await(let e of s)t||(this.perf.mark("subStart"),t=!0);this.perf.mark("subStop"),this.perf.measure("sub","subStart","subStop")})();e.push(r)}if(this.pub){let t=(async()=>{this.perf.mark("pubStart");for(let e=0;e{if(this.asyncRequests){this.perf.mark("reqStart");let e=[];for(let t=0;te,decode:e=>e},value:{encode:e=>e,decode:e=>e}}}let tJ="KV-Operation",tK=/^[-/=.\w]+$/,tz=/^[-/=.>*\w]+$/,tG=/^[-\w]+$/;function tV(e){if(e.startsWith(".")||e.endsWith(".")||!tK.test(e))throw Error(`invalid key: ${e}`)}function tW(e){if(e.startsWith(".")||e.endsWith(".")||!tz.test(e))throw Error(`invalid key: ${e}`)}function tY(e){if(e.startsWith(".")||e.endsWith("."))throw Error(`invalid key: ${e}`);let t=e.split("."),s=!1;for(let r=0;r":if(r!==t.length-1)throw Error(`invalid key: ${e}`);s=!0}return s}function tX(e){if(!tG.test(e))throw Error(`invalid bucket name: ${e}`)}!function(e){e.MsgIdHdr="Nats-Msg-Id",e.ExpectedStreamHdr="Nats-Expected-Stream",e.ExpectedLastSeqHdr="Nats-Expected-Last-Sequence",e.ExpectedLastMsgIdHdr="Nats-Expected-Last-Msg-Id",e.ExpectedLastSubjectSequenceHdr="Nats-Expected-Last-Subject-Sequence"}(j||(j={}));class tQ{js;jsm;stream;bucket;direct;codec;prefix;editPrefix;useJsPrefix;_prefixLen;constructor(e,t,s){tX(e),this.js=t,this.jsm=s,this.bucket=e,this.prefix="$KV",this.editPrefix="",this.useJsPrefix=!1,this._prefixLen=0}static async create(e,t,s={}){tX(t);let r=await e.jetstreamManager(),i=new tQ(t,e,r);return await i.init(s),i}static async bind(e,t,s={}){let r=await e.jetstreamManager(),i={config:{allow_direct:s.allow_direct}};tX(t);let n=new tQ(t,e,r);return i.config.name=s.streamName??n.bucketName(),Object.assign(n,i),n.stream=i.config.name,n.codec=s.codec||tH(),n.direct=i.config.allow_direct??!1,n.initializePrefixes(i),n}async init(e={}){let t,s=Object.assign({replicas:1,history:1,timeout:2e3,max_bytes:-1,maxValueSize:-1,codec:tH(),storage:f.File},e);this.codec=s.codec;let r={};this.stream=r.name=e.streamName??this.bucketName(),r.retention=u.Limits,r.max_msgs_per_subject=s.history,s.maxBucketSize&&(s.max_bytes=s.maxBucketSize),s.max_bytes&&(r.max_bytes=s.max_bytes),r.max_msg_size=s.maxValueSize,r.storage=s.storage;let i=e.placementCluster??"";if(i&&(e.placement={},e.placement.cluster=i,e.placement.tags=[]),e.placement&&(r.placement=e.placement),e.republish&&(r.republish=e.republish),e.description&&(r.description=e.description),e.mirror){let t=Object.assign({},e.mirror);t.name.startsWith("KV_")||(t.name=`KV_${t.name}`),r.mirror=t,r.mirror_direct=!0}else e.sources?r.sources=e.sources.map(e=>{let t=Object.assign({},e);t.name.startsWith("KV_")||(t.name=`KV_${t.name}`)}):r.subjects=[this.subjectForBucket()];e.metadata&&(r.metadata=e.metadata),"boolean"==typeof e.compression&&(r.compression=e.compression?g.S2:g.None);let n=this.js.nc,o=n.getServerVersion();r.discard=o&&eY(o,eW("2.7.2"))>=0?d.New:d.Old;let{ok:a,min:c}=n.features.get(E.JS_ALLOW_DIRECT);if(!a&&!0===e.allow_direct){let e=o?`${o.major}.${o.minor}.${o.micro}`:"unknown";return Promise.reject(Error(`allow_direct is not available on server version ${e} - requires ${c}`))}e.allow_direct="boolean"==typeof e.allow_direct?e.allow_direct:a,r.allow_direct=e.allow_direct,this.direct=r.allow_direct,r.num_replicas=s.replicas,s.ttl&&(r.max_age=ec(s.ttl)),r.allow_rollup_hdrs=!0;try{(t=await this.jsm.streams.info(r.name)).config.allow_direct||!0!==this.direct||(this.direct=!1)}catch(e){if("stream not found"===e.message)t=await this.jsm.streams.add(r);else throw e}this.initializePrefixes(t)}initializePrefixes(e){this._prefixLen=0,this.prefix=`$KV.${this.bucket}`,this.useJsPrefix="$JS.API"!==this.js.apiPrefix;let{mirror:t}=e.config;if(t){let e=t.name;if(e.startsWith("KV_")&&(e=e.substring(3)),t.external&&""!==t.external.api){let s=t.name.substring(3);this.useJsPrefix=!1,this.prefix=`$KV.${s}`,this.editPrefix=`${t.external.api}.$KV.${e}`}else this.editPrefix=this.prefix}}bucketName(){return this.stream??`KV_${this.bucket}`}subjectForBucket(){return`${this.prefix}.${this.bucket}.>`}subjectForKey(e,t=!1){let 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}`:`$KV.${this.bucket}.${e}`}get prefixLen(){return 0===this._prefixLen&&(this._prefixLen=this.prefix.length+1),this._prefixLen}encodeKey(e){let t=[];for(let s of e.split("."))switch(s){case">":case"*":t.push(s);break;default:t.push(this.codec.key.encode(s))}return t.join(".")}decodeKey(e){let t=[];for(let s of e.split("."))switch(s){case">":case"*":t.push(s);break;default:t.push(this.codec.key.decode(s))}return t.join(".")}validateKey=tV;validateSearchKey=tW;hasWildcards=tY;close(){return Promise.resolve()}dataLen(e,t){let s=t&&t.get(w.MessageSizeHdr)||"";return""!==s?parseInt(s,10):e.length}smToEntry(e){return new sw(this.bucket,this.prefixLen,e)}jmToEntry(e){let t=this.decodeKey(e.subject.substring(this.prefixLen));return new sx(this.bucket,t,e)}async create(e,t){let s;try{let s=await this.put(e,t,{previousSeq:0});return Promise.resolve(s)}catch(e){if(s=e,e?.api_error?.err_code!==10071)return Promise.reject(e)}let r=0;try{let i=await this.get(e);if(i?.operation==="DEL"||i?.operation==="PURGE")return r=null!==i?i.revision:0,this.update(e,t,r);return Promise.reject(s)}catch(e){return Promise.reject(e)}}update(e,t,s){if(s<=0)throw Error("version must be greater than 0");return this.put(e,t,{previousSeq:s})}async put(e,t,s={}){let r=this.encodeKey(e);this.validateKey(r);let i={};if(void 0!==s.previousSeq){let e=eu();i.headers=e,e.set(j.ExpectedLastSubjectSequenceHdr,`${s.previousSeq}`)}try{return(await this.js.publish(this.subjectForKey(r,!0),t,i)).seq}catch(e){if(e.isJetStreamError())return e.message=e.api_error?.description,e.code=`${e.api_error?.code}`,Promise.reject(e);return Promise.reject(e)}}async get(e,t){let s,r=this.encodeKey(e);this.validateKey(r);let i={last_by_subj:this.subjectForKey(r)};t&&t.revision>0&&(i={seq:t.revision});try{if(this.direct){let e=this.jsm.direct;s=await e.getMessage(this.bucketName(),i)}else s=await this.jsm.streams.getMessage(this.bucketName(),i);let e=this.smToEntry(s);if(e.key!==r)return null;return e}catch(e){if(e.code===n.JetStream404NoMessages)return null;throw e}}purge(e,t){return this._deleteOrPurge(e,"PURGE",t)}delete(e,t){return this._deleteOrPurge(e,"DEL",t)}async purgeDeletes(e=18e5){let t=ei(),s=[],r=await this.watch({key:">",initializedFn:()=>{t.resolve()}});(async()=>{for await(let e of r)("DEL"===e.operation||"PURGE"===e.operation)&&s.push(e)})().then(),await t,r.stop();let i=Date.now()-e,n=s.map(e=>{let t=this.subjectForKey(e.key);return e.created.getTime()>=i?this.jsm.streams.purge(this.stream,{filter:t,keep:1}):this.jsm.streams.purge(this.stream,{filter:t,keep:0})}),o=await Promise.all(n);return o.unshift({success:!0,purged:0}),o.reduce((e,t)=>(e.purged+=t.purged,e))}async _deleteOrPurge(e,t,s){if(!this.hasWildcards(e))return this._doDeleteOrPurge(e,t,s);let r=await this.keys(e),i=[];for await(let e of r)i.push(this._doDeleteOrPurge(e,t)),100===i.length&&(await Promise.all(i),i.length=0);i.length>0&&await Promise.all(i)}async _doDeleteOrPurge(e,t,s){let r=this.encodeKey(e);this.validateKey(r);let i=eu();i.set(tJ,t),"PURGE"===t&&i.set(w.RollupHdr,w.RollupValueSubject),s?.previousSeq&&i.set(j.ExpectedLastSubjectSequenceHdr,`${s.previousSeq}`),await this.js.publish(this.subjectForKey(r,!0),T,{headers:i})}_buildCC(e,t,s={}){let r,i=(Array.isArray(e)?e:[e]).map(e=>{let t=this.encodeKey(e);return this.validateSearchKey(e),this.fullKeyName(t)}),n=p.LastPerSubject;return t===x.AllHistory&&(n=p.All),t===x.UpdatesOnly&&(n=p.New),1===i.length&&(r=i[0],i=void 0),Object.assign({deliver_policy:n,ack_policy:m.None,filter_subjects:i,filter_subject:r,flow_control:!0,idle_heartbeat:ec(5e3)},s)}remove(e){return this.purge(e)}async history(e={}){let t,s=e.key??">",r=new eA,i={};i.headers_only=e.headers_only||!1,t=()=>{r.stop()};let n=0,o=this._buildCC(s,x.AllHistory,i),a=o.filter_subject,c=eO(o);c.bindStream(this.stream),c.orderedConsumer(),c.callback((e,s)=>{if(e)return void r.stop(e);if(s){let e=this.jmToEntry(s);r.push(e),r.received++,(t&&n>0&&r.received>=n||0===s.info.pending)&&(r.push(t),t=void 0)}});let h=await this.js.subscribe(a,c);if(t){let{info:{last:e}}=h,s=e.num_pending+e.delivered.consumer_seq;if(0===s||r.received>=s)try{t()}catch(e){r.stop(e)}finally{t=void 0}else n=s}return r._data=h,r.iterClosed.then(()=>{h.unsubscribe()}),h.closed.then(()=>{r.stop()}).catch(e=>{r.stop(e)}),r}canSetWatcherName(){let{ok:e}=this.js.nc.features.get(E.JS_NEW_CONSUMER_CREATE_API);return e}async watch(e={}){let t=e.key??">",s=new eA,r={};r.headers_only=e.headers_only||!1;let i=x.LastValue;e.include===x.AllHistory?i=x.AllHistory:e.include===x.UpdatesOnly&&(i=x.UpdatesOnly);let n=!0===e.ignoreDeletes,o=e.initializedFn,a=0,c=this._buildCC(t,i,r),h=c.filter_subject,l=eO(c);this.canSetWatcherName()&&l.consumerName(H.next()),l.bindStream(this.stream),e.resumeFromRevision&&e.resumeFromRevision>0&&l.startSequence(e.resumeFromRevision),l.orderedConsumer(),l.callback((e,t)=>{if(e)return void s.stop(e);if(t){let e=this.jmToEntry(t);if(n&&"DEL"===e.operation)return;s.push(e),s.received++,o&&(a>0&&s.received>=a||0===t.info.pending)&&(s.push(o),o=void 0)}});let u=await this.js.subscribe(h,l);if(o){let{info:{last:e}}=u,t=e.num_pending+e.delivered.consumer_seq;if(0===t||s.received>=t)try{o()}catch(e){s.stop(e)}finally{o=void 0}else a=t}return s._data=u,s.iterClosed.then(()=>{u.unsubscribe()}),u.closed.then(()=>{s.stop()}).catch(e=>{s.stop(e)}),s}async keys(e=">"){let t=new eA,s=this._buildCC(e,x.LastValue,{headers_only:!0}),r=Array.isArray(e)?">":s.filter_subject,i=eO(s);i.bindStream(this.stream),i.orderedConsumer();let n=await this.js.subscribe(r,i);return(async()=>{for await(let e of n){let s=e.headers?.get(tJ);if("DEL"!==s&&"PURGE"!==s){let s=this.decodeKey(e.subject.substring(this.prefixLen));t.push(s)}0===e.info.pending&&n.unsubscribe()}})().then(()=>{t.stop()}).catch(e=>{t.stop(e)}),0===n.info.last.num_pending&&n.unsubscribe(),t}purgeBucket(e){return this.jsm.streams.purge(this.bucketName(),e)}destroy(){return this.jsm.streams.delete(this.bucketName())}async status(){let e=this.js.nc,t=e.info?.cluster??"",s=this.bucketName();return new tZ(await this.jsm.streams.info(s),t)}}class tZ{si;cluster;constructor(e,t=""){this.si=e,this.cluster=t}get bucket(){return this.si.config.name.startsWith("KV_")?this.si.config.name.substring(3):this.si.config.name}get values(){return this.si.state.messages}get history(){return this.si.config.max_msgs_per_subject}get ttl(){return eh(this.si.config.max_age)}get bucket_location(){return this.cluster}get backingStore(){return this.si.config.storage}get storage(){return this.si.config.storage}get replicas(){return this.si.config.num_replicas}get description(){return this.si.config.description??""}get maxBucketSize(){return this.si.config.max_bytes}get maxValueSize(){return this.si.config.max_msg_size}get max_bytes(){return this.si.config.max_bytes}get placement(){return this.si.config.placement||{cluster:"",tags:[]}}get placementCluster(){return this.si.config.placement?.cluster??""}get republish(){return this.si.config.republish??{src:"",dest:""}}get streamInfo(){return this.si}get size(){return this.si.state.bytes}get metadata(){return this.si.config.metadata??{}}get compression(){return!!this.si.config.compression&&this.si.config.compression!==g.None}}let t0="OBJ_",t1="SHA-256=";class t2{si;backingStore;constructor(e){this.si=e,this.backingStore="JetStream"}get bucket(){var e;return(e=this.si.config.name).startsWith(t0)?e.substring(4):e}get description(){return this.si.config.description??""}get ttl(){return this.si.config.max_age}get storage(){return this.si.config.storage}get replicas(){return this.si.config.num_replicas}get sealed(){return this.si.config.sealed}get size(){return this.si.state.bytes}get streamInfo(){return this.si}get metadata(){return this.si.config.metadata}get compression(){return!!this.si.config.compression&&this.si.config.compression!==g.None}}function t3(e){if(void 0===e)return;let{domain:t}=e;if(void 0===t)return e;let s=Object.assign({},e);if(delete s.domain,""===t)return s;if(s.external)throw Error("domain and external are both set");return s.external={api:`$JS.${t}.API`},s}!function(e){e[e.Unset=-1]="Unset",e[e.Consume=0]="Consume",e[e.Fetch=1]="Fetch"}(I||(I={})),function(e){e.HeartbeatsMissed="heartbeats_missed",e.ConsumerNotFound="consumer_not_found",e.StreamNotFound="stream_not_found",e.ConsumerDeleted="consumer_deleted",e.OrderedConsumerRecreated="ordered_consumer_recreated"}(M||(M={})),function(e){e.DebugEvent="debug",e.Discard="discard",e.Reset="reset",e.Next="next"}(N||(N={}));let t4=Uint8Array.of(43,65,67,75),t5=Uint8Array.of(45,78,65,75),t6=Uint8Array.of(43,87,80,73),t8=Uint8Array.of(43,78,88,84),t7=Uint8Array.of(43,84,69,82,77),t9=Uint8Array.of(32);function se(e,t=5e3){return new sA(e,t)}class st extends eA{consumer;opts;sub;monitor;pending;inbox;refilling;pong;callback;timeout;cleanupHandler;listeners;statusIterator;forOrderedConsumer;resetHandler;abortOnMissingResource;bind;constructor(e,t,s=!1){super(),this.consumer=e,this.opts=this.parseOptions(t,s),this.callback=t.callback||null,this.noIterator="function"==typeof this.callback,this.monitor=null,this.pong=null,this.pending={msgs:0,bytes:0,requests:0},this.refilling=s,this.timeout=null,this.inbox=X(e.api.nc.options.inboxPrefix),this.listeners=[],this.forOrderedConsumer=!1,this.abortOnMissingResource=!0===t.abort_on_missing_resource,this.bind=!0===t.bind,this.start()}start(){let{max_messages:e,max_bytes:t,idle_heartbeat:s,threshold_bytes:i,threshold_messages:n}=this.opts;this.closed().then(e=>{if(this.cleanupHandler)try{this.cleanupHandler(e)}catch(e){}});let{sub:o}=this;o&&o.unsubscribe(),this.sub=this.consumer.api.nc.subscribe(this.inbox,{callback:(s,r)=>{if(s)return void this.stop(s);if(this.monitor?.work(),r.subject===this.inbox){if(ev(r))return;let e=r.headers?.code,t=r.headers?.description?.toLowerCase()||"unknown",{msgsLeft:s,bytesLeft:i}=this.parseDiscard(r.headers);if(s>0||i>0)this.pending.msgs-=s,this.pending.bytes-=i,this.pending.requests--,this.notify(N.Discard,{msgsLeft:s,bytesLeft:i});else if(400===e)return void this.stop(new z(t,`${e}`));else if(409===e&&"consumer deleted"===t){if(this.notify(M.ConsumerDeleted,`${e} ${t}`),!this.refilling||this.abortOnMissingResource){let s=new z(t,`${e}`);this.stop(s);return}}else this.notify(N.DebugEvent,`${e} ${t}`)}else this._push(se(r,this.consumer.api.timeout)),this.received++,this.pending.msgs&&this.pending.msgs--,this.pending.bytes&&(this.pending.bytes-=r.size());if(0===this.pending.msgs&&0===this.pending.bytes&&(this.pending.requests=0),this.refilling){if(e&&this.pending.msgs<=n||t&&this.pending.bytes<=i){let e=this.pullOptions();this.pull(e)}}else 0===this.pending.requests&&this._push(()=>{this.stop()})}}),this.sub.closed.then(()=>{this.sub.draining&&this._push(()=>{this.stop()})}),s&&(this.monitor=new ek(s,e=>(this.notify(M.HeartbeatsMissed,e),this.resetPending().then(()=>{}).catch(()=>{}),!1),{maxOut:2})),(async()=>{let e=this.consumer.api.nc.status();for await(let t of(this.statusIterator=e,e))switch(t.type){case r.Disconnect:this.monitor?.cancel();break;case r.Reconnect:this.resetPending().then(e=>{e&&this.monitor?.restart()}).catch(()=>{})}})(),this.pull(this.pullOptions())}_push(e){if(this.callback){let t="function"==typeof e?e:null;try{t?t():this.callback(e)}catch(e){this.stop(e)}}else super.push(e)}notify(e,t){this.listeners.length>0&&this.listeners.forEach(s=>{s.done||s.push({type:e,data:t})})}resetPending(){return this.bind?this.resetPendingNoInfo():this.resetPendingWithInfo()}resetPendingNoInfo(){return this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),Promise.resolve(!0)}async resetPendingWithInfo(){let e=0,t=0,s=ea(),r=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(),e=0,this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),!0}catch(n){if("stream not found"===n.message){if(t++,this.notify(M.StreamNotFound,t),!this.refilling||this.abortOnMissingResource)return this.stop(n),!1}else if("consumer not found"===n.message){if(e++,this.notify(M.ConsumerNotFound,e),this.resetHandler)try{this.resetHandler()}catch(e){}if(!this.refilling||this.abortOnMissingResource)return this.stop(n),!1;if(this.forOrderedConsumer)return!1}else e=0,t=0;let i=es(s.backoff(r));await Promise.race([i,this.consumer.api.nc.closed()]),i.cancel(),r++}}}pull(e){this.pending.bytes+=e.max_bytes??0,this.pending.msgs+=e.batch??0,this.pending.requests++;let t=this.consumer.api.nc;this._push(()=>{t.publish(`${this.consumer.api.prefix}.CONSUMER.MSG.NEXT.${this.consumer.stream}.${this.consumer.name}`,this.consumer.api.jc.encode(e),{reply:this.inbox}),this.notify(N.Next,e)})}pullOptions(){let e=this.opts.max_messages-this.pending.msgs,t=this.opts.max_bytes-this.pending.bytes;return{batch:e,max_bytes:t,idle_heartbeat:ec(this.opts.idle_heartbeat),expires:ec(this.opts.expires)}}parseDiscard(e){let t={msgsLeft:0,bytesLeft:0},s=e?.get(w.PendingMessagesHdr);s&&(t.msgsLeft=parseInt(s));let r=e?.get(w.PendingBytesHdr);return r&&(t.bytesLeft=parseInt(r)),t}trackTimeout(e){this.timeout=e}close(){return this.stop(),this.iterClosed}closed(){return this.iterClosed}clearTimers(){this.monitor?.cancel(),this.monitor=null,this.timeout?.cancel(),this.timeout=null}setCleanupHandler(e){this.cleanupHandler=e}stop(e){this.done||(this.sub?.unsubscribe(),this.clearTimers(),this.statusIterator?.stop(),this._push(()=>{super.stop(e),this.listeners.forEach(e=>{e.stop()})}))}parseOptions(e,t=!1){let s=e||{};if(s.max_messages=s.max_messages||0,s.max_bytes=s.max_bytes||0,0!==s.max_messages&&0!==s.max_bytes)throw Error("only specify one of max_messages or max_bytes");if(0===s.max_messages&&(s.max_messages=100),s.expires=s.expires||3e4,s.expires<1e3)throw Error("expires should be at least 1000ms");if(s.idle_heartbeat=s.idle_heartbeat||s.expires/2,s.idle_heartbeat=s.idle_heartbeat>3e4?3e4:s.idle_heartbeat,t){let e=Math.round(.75*s.max_messages)||1;s.threshold_messages=s.threshold_messages||e;let t=Math.round(.75*s.max_bytes)||1;s.threshold_bytes=s.threshold_bytes||t}return s}status(){let e=new eA;return this.listeners.push(e),Promise.resolve(e)}}class ss extends eA{src;listeners;constructor(){super(),this.listeners=[]}setSource(e){this.src&&(this.src.resetHandler=void 0,this.src.setCleanupHandler(),this.src.stop()),this.src=e,this.src.setCleanupHandler(e=>{this.stop(e||void 0)}),(async()=>{for await(let e of(await this.src.status()))this.notify(e.type,e.data)})().catch(()=>{})}notify(e,t){this.listeners.length>0&&this.listeners.forEach(s=>{s.done||s.push({type:e,data:t})})}stop(e){this.done||(this.src?.stop(e),super.stop(e),this.listeners.forEach(e=>{e.stop()}))}close(){return this.stop(),this.iterClosed}closed(){return this.iterClosed}status(){let e=new eA;return this.listeners.push(e),Promise.resolve(e)}}class sr{api;_info;stream;name;constructor(e,t){this.api=e,this._info=t,this.stream=t.stream_name,this.name=t.name}consume(e={max_messages:100,expires:3e4}){return Promise.resolve(new st(this,e,!0))}fetch(e={max_messages:100,expires:3e4}){let t=new st(this,e,!1),s=et(Math.round(1.05*t.opts.expires));return t.closed().catch(()=>{}).finally(()=>{s.cancel()}),s.catch(()=>{t.close().catch()}),t.trackTimeout(s),Promise.resolve(t)}next(e={expires:3e4}){let t=ei();e.max_messages=1;let s=new st(this,e,!1),r=Math.round(1.05*s.opts.expires);r>=6e4&&(async()=>{for await(let e of(await s.status()))if(e.type===M.HeartbeatsMissed&&e.data>=2){t.reject(Error("consumer missed heartbeats"));break}})().catch(),(async()=>{for await(let e of s){t.resolve(e);break}})().catch(()=>{});let i=et(r);return s.closed().then(e=>{e?t.reject(e):t.resolve(null)}).catch(e=>{t.reject(e)}).finally(()=>{i.cancel()}),i.catch(e=>{t.resolve(null),s.close().catch()}),s.trackTimeout(i),t}delete(){let{stream_name:e,name:t}=this._info;return this.api.delete(e,t)}info(e=!1){if(e)return Promise.resolve(this._info);let{stream_name:t,name:s}=this._info;return this.api.info(t,s).then(e=>(this._info=e,this._info))}}class si{api;consumerOpts;consumer;opts;cursor;stream;namePrefix;serial;currentConsumer;userCallback;iter;type;startSeq;constructor(e,t,s={}){this.api=e,this.stream=t,this.cursor={stream_seq:1,deliver_seq:0},this.namePrefix=H.next(),"string"==typeof s.name_prefix&&(ew("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=I.Unset,this.consumerOpts=s,this.startSeq=this.consumerOpts.opt_start_seq||0,this.cursor.stream_seq=this.startSeq>0?this.startSeq-1:0}getConsumerOpts(e){this.serial++;let t=`${this.namePrefix}_${this.serial}`;e=0===e?1:e;let s={name:t,deliver_policy:p.StartSequence,opt_start_seq:e,ack_policy:m.None,inactive_threshold:ec(3e5),num_replicas:1};return!0===this.consumerOpts.headers_only&&(s.headers_only=!0),Array.isArray(this.consumerOpts.filterSubjects)&&(s.filter_subjects=this.consumerOpts.filterSubjects),"string"==typeof this.consumerOpts.filterSubjects&&(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||p.StartSequence,(this.consumerOpts.deliver_policy===p.LastPerSubject||this.consumerOpts.deliver_policy===p.New||this.consumerOpts.deliver_policy===p.Last)&&(delete s.opt_start_seq,s.deliver_policy=this.consumerOpts.deliver_policy),s.deliver_policy===p.LastPerSubject&&void 0===s.filter_subjects&&void 0===s.filter_subject&&(s.filter_subject=">"),this.consumerOpts.opt_start_time&&(delete s.opt_start_seq,s.deliver_policy=p.StartTime,s.opt_start_time=this.consumerOpts.opt_start_time),this.consumerOpts.inactive_threshold&&(s.inactive_threshold=ec(this.consumerOpts.inactive_threshold))),s}async resetConsumer(e=0){let t;this.consumer?.delete().catch(()=>{}),e=0===e?1:e,this.cursor.deliver_seq=0;let s=this.getConsumerOpts(e);s.max_deliver=1,s.mem_storage=!0;let r=ea();for(let i=0;;i++)try{t=await this.api.add(this.stream,s),this.iter?.notify(M.OrderedConsumerRecreated,t.name);break}catch(t){if("stream not found"===t.message&&(this.iter?.notify(M.StreamNotFound,i),this.type===I.Fetch||!0===this.opts.abort_on_missing_resource))return this.iter?.stop(t),Promise.reject(t);if(0===e&&i>=30)throw t;await es(r.backoff(i+1))}return t}internalHandler(e){return t=>{if(this.serial!==e)return;let s=t.info.deliverySequence;if(s!==this.cursor.deliver_seq+1)return void this.notifyOrderedResetAndReset();this.cursor.deliver_seq=s,this.cursor.stream_seq=t.info.streamSequence,this.userCallback?this.userCallback(t):this.iter?.push(t)}}async reset(e={max_messages:100,expires:3e4},t){let s=(t=t||{}).fromFetch||!1,r=t.orderedReset||!1;if(this.type===I.Fetch&&r){this.iter?.src.stop(),await this.iter?.closed(),this.currentConsumer=null;return}(null===this.currentConsumer||r)&&(this.currentConsumer=await this.resetConsumer(this.cursor.stream_seq+1)),(null===this.iter||s)&&(this.iter=new ss),this.consumer=new sr(this.api,this.currentConsumer),e.callback=this.internalHandler(this.serial);let i=null;this.type===I.Fetch&&s?i=await this.consumer.fetch(e):this.type===I.Consume&&(i=await this.consumer.consume(e));let n=i;n.forOrderedConsumer=!0,n.resetHandler=()=>{this.notifyOrderedResetAndReset()},this.iter.setSource(n)}notifyOrderedResetAndReset(){this.iter?.notify(N.Reset,""),this.reset(this.opts,{orderedReset:!0})}async consume(e={max_messages:100,expires:3e4}){if(e.bind)return Promise.reject(Error("bind is not supported"));if(this.type===I.Fetch)return Promise.reject(Error("ordered consumer initialized as fetch"));if(this.type===I.Consume)return Promise.reject(Error("ordered consumer doesn't support concurrent consume"));let{callback:t}=e;return t&&(this.userCallback=t),this.type=I.Consume,this.opts=e,await this.reset(e),this.iter}async fetch(e={max_messages:100,expires:3e4}){if(e.bind)return Promise.reject(Error("bind is not supported"));if(this.type===I.Consume)return Promise.reject(Error("ordered consumer already initialized as consume"));if(this.iter?.done===!1)return Promise.reject(Error("ordered consumer doesn't support concurrent fetch"));let{callback:t}=e;return t&&(this.userCallback=t),this.type=I.Fetch,this.opts=e,await this.reset(e,{fromFetch:!0}),this.iter}async next(e={expires:3e4}){if(e.bind)return Promise.reject(Error("bind is not supported"));e.max_messages=1;let t=ei();return e.callback=e=>{this.userCallback=null,t.resolve(e)},(await this.fetch(e)).iterClosed.then(e=>{e&&t.reject(e),t.resolve(null)}).catch(e=>{t.reject(e)}),t}delete(){return this.currentConsumer?this.api.delete(this.stream,this.currentConsumer.name).then(e=>Promise.resolve(e)).catch(e=>Promise.reject(e)).finally(()=>{this.currentConsumer=null}):Promise.resolve(!1)}async info(e){return null==this.currentConsumer?(this.currentConsumer=await this.resetConsumer(this.serial),Promise.resolve(this.currentConsumer)):e&&this.currentConsumer?Promise.resolve(this.currentConsumer):this.api.info(this.stream,this.currentConsumer.name)}}class sn{api;notified;constructor(e){this.api=e,this.notified=!1}checkVersion(){let e=this.api.nc.features.get(E.JS_SIMPLIFICATION);return e.ok?Promise.resolve():Promise.reject(Error(`consumers framework is only supported on servers ${e.min} or better`))}async get(e,t={}){return"object"==typeof t?this.ordered(e,t):(await this.checkVersion(),this.api.info(e,t).then(e=>void 0!==e.config.deliver_subject?Promise.reject(Error("push consumer not supported")):new sr(this.api,e)).catch(e=>Promise.reject(e)))}async ordered(e,t){await this.checkVersion();let s=this.api;return new sa(s.nc,s.opts).info(e).then(s=>Promise.resolve(new si(this.api,e,t))).catch(e=>Promise.reject(e))}}class so{api;_info;constructor(e,t){this.api=e,this._info=t}get name(){return this._info.config.name}alternates(){return this.info().then(e=>e.alternates?e.alternates:[])}async best(){if(await this.info(),!this._info.alternates)return this;{let e=await this.api.info(this._info.alternates[0].name);return new so(this.api,e)}}info(e=!1,t){return e?Promise.resolve(this._info):this.api.info(this.name,t).then(e=>(this._info=e,this._info))}getConsumer(e){return new sn(new eQ(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 sa extends eG{constructor(e,t){super(e,t)}checkStreamConfigVersions(e){let t=this.nc;if(e.metadata){let{min:e,ok:s}=t.features.get(E.JS_STREAM_CONSUMER_METADATA);if(!s)throw Error(`stream 'metadata' requires server ${e}`)}if(e.first_seq){let{min:e,ok:s}=t.features.get(E.JS_STREAM_FIRST_SEQ);if(!s)throw Error(`stream 'first_seq' requires server ${e}`)}if(e.subject_transform){let{min:e,ok:s}=t.features.get(E.JS_STREAM_SUBJECT_TRANSFORM);if(!s)throw Error(`stream 'subject_transform' requires server ${e}`)}if(e.compression){let{min:e,ok:s}=t.features.get(E.JS_STREAM_COMPRESSION);if(!s)throw Error(`stream 'compression' requires server ${e}`)}if(e.consumer_limits){let{min:e,ok:s}=t.features.get(E.JS_DEFAULT_CONSUMER_LIMITS);if(!s)throw Error(`stream 'consumer_limits' requires server ${e}`)}function s(e,s){if((s.subject_transforms?.length||0)>0){let{min:s,ok:r}=t.features.get(E.JS_STREAM_SOURCE_SUBJECT_TRANSFORM);if(!r)throw Error(`${e} 'subject_transforms' requires server ${s}`)}}e.sources&&e.sources.forEach(e=>{s("stream sources",e)}),e.mirror&&s("stream mirror",e.mirror)}async add(e={}){this.checkStreamConfigVersions(e),ey(e.name),e.mirror=t3(e.mirror),e.sources=e.sources?.map(t3);let t=await this._request(`${this.prefix}.STREAM.CREATE.${e.name}`,e);return this._fixInfo(t),t}async delete(e){return ey(e),(await this._request(`${this.prefix}.STREAM.DELETE.${e}`)).success}async update(e,t={}){if("object"==typeof e){let s=e;e=s.name,t=s,console.trace(`\u001B[33m >> streams.update(config: StreamConfig) api changed to streams.update(name: string, config: StreamUpdateConfig) - this shim will be removed - update your code. \u001B[0m`)}this.checkStreamConfigVersions(t),ey(e);let s=Object.assign((await this.info(e)).config,t);s.mirror=t3(s.mirror),s.sources=s.sources?.map(t3);let r=await this._request(`${this.prefix}.STREAM.UPDATE.${e}`,s);return this._fixInfo(r),r}async info(e,t){ey(e);let s=`${this.prefix}.STREAM.INFO.${e}`,r=await this._request(s,t),{total:i,limit:n}=r,o=r.state.subjects?Object.getOwnPropertyNames(r.state.subjects).length:1;if(i&&i>o){let e=[r],a=t||{},c=0;for(;i>o;){a.offset=n*++c;let t=await this._request(s,a);i=t.total,e.push(t);let r=Object.getOwnPropertyNames(t.state.subjects).length;if(o+=r,r(e.streams.forEach(e=>{this._fixInfo(e)}),e.streams),this,t)}_fixInfo(e){e.config.sealed=e.config.sealed||!1,e.config.deny_delete=e.config.deny_delete||!1,e.config.deny_purge=e.config.deny_purge||!1,e.config.allow_rollup_hdrs=e.config.allow_rollup_hdrs||!1}async purge(e,t){if(t){let{keep:e,seq:s}=t;if("number"==typeof e&&"number"==typeof s)throw Error("can specify one of keep or seq")}return ey(e),await this._request(`${this.prefix}.STREAM.PURGE.${e}`,t)}async deleteMessage(e,t,s=!0){ey(e);let r={seq:t};return s||(r.no_erase=!0),(await this._request(`${this.prefix}.STREAM.MSG.DELETE.${e}`,r)).success}async getMessage(e,t){return ey(e),new su(await this._request(`${this.prefix}.STREAM.MSG.GET.${e}`,t))}find(e){return this.findStream(e)}listKvs(){return new eV(`${this.prefix}.STREAM.LIST`,e=>{let t=e.streams.filter(e=>e.config.name.startsWith("KV_"));t.forEach(e=>{this._fixInfo(e)});let s="";return t.length&&(s=this.nc.info?.cluster??""),t.map(e=>new tZ(e,s))},this)}listObjectStores(){return new eV(`${this.prefix}.STREAM.LIST`,e=>{let t=e.streams.filter(e=>e.config.name.startsWith(t0));return t.forEach(e=>{this._fixInfo(e)}),t.map(e=>new t2(e))},this)}names(e=""){let t=e?.length?{subject:e}:{};return new eV(`${this.prefix}.STREAM.NAMES`,e=>e.streams,this,t)}async get(e){return Promise.resolve(new so(this,await this.info(e)))}}class sc extends eG{constructor(e,t){super(e,t)}async getMessage(e,t){ey(e);let s=t,{last_by_subj:r}=s;r&&(s=null);let i=s?this.jc.encode(s):T,n=this.opts.apiPrefix||"$JS.API",o=r?`${n}.DIRECT.GET.${e}.${r}`:`${n}.DIRECT.GET.${e}`,a=await this.nc.request(o,i),c=eE(a);return c?Promise.reject(c):Promise.resolve(new sh(a))}async getBatch(e,t){ey(e);let s=this.opts.apiPrefix||"$JS.API",r=`${s}.DIRECT.GET.${e}`;if(!Array.isArray(t.multi_last)||0===t.multi_last.length)return Promise.reject("multi_last is required");let i=JSON.stringify(t,(e,t)=>"up_to_time"===e&&t instanceof Date?t.toISOString():t),n=new eA,o=await this.nc.requestMany(r,i,{strategy:a.SentinelMsg});return(async()=>{let e,t=!1,s=!1;for await(let r of o){if(!t){t=!0;let i=r.headers?.code||0;if(0!==i&&i<200||i>299){e=r.headers?.description.toLowerCase();break}if(""===r.headers?.get("Nats-Num-Pending")){s=!0;break}}if(0===r.data.length)break;n.push(new sh(r))}n.push(()=>{if(s)throw Error("batch direct get not supported by the server");if(e)throw Error(`bad request: ${e}`);n.stop()})})(),Promise.resolve(n)}}class sh{data;header;static jc;constructor(e){if(!e.headers)throw Error("headers expected");this.data=e.data,this.header=e.headers}get subject(){return this.header.last(S.Subject)}get seq(){let e=this.header.last(S.Sequence);return"string"==typeof e?parseInt(e):0}get time(){return new Date(Date.parse(this.timestamp))}get timestamp(){return this.header.last(S.TimeStamp)}get stream(){return this.header.last(S.Stream)}json(e){return em(e).decode(this.data)}string(){return U.decode(this.data)}}class sl extends eG{streams;consumers;direct;constructor(e,t){super(e,t),this.streams=new sa(e,t),this.consumers=new eQ(e,t),this.direct=new sc(e,t)}async getAccountInfo(){return await this._request(`${this.prefix}.INFO`)}jetstream(){return this.nc.jetstream(this.getOptions())}advisories(){let e=new eA;return this.nc.subscribe("$JS.EVENT.ADVISORY.>",{callback:(t,s)=>{if(t)throw t;try{let t=this.parseJsResponse(s),r=t.type.split("."),i=r[r.length-1];e.push({kind:i,data:t})}catch(t){e.stop(t)}}}),e}}class su{_header;smr;static jc;constructor(e){this.smr=e}get subject(){return this.smr.message.subject}get seq(){return this.smr.message.seq}get timestamp(){return this.smr.message.time}get time(){return new Date(Date.parse(this.timestamp))}get data(){return this.smr.message.data?this._parse(this.smr.message.data):T}get header(){if(!this._header)if(this.smr.message.hdrs){let e=this._parse(this.smr.message.hdrs);this._header=ef.decode(e)}else this._header=eu();return this._header}_parse(e){let t=atob(e),s=t.length,r=new Uint8Array(s);for(let e=0;enew so(this.api,e))}}class sf{info;hdrs;constructor(e){this.info=e}get name(){return this.info.name}get description(){return this.info.description??""}get headers(){return this.hdrs||(this.hdrs=ef.fromRecord(this.info.headers||{})),this.hdrs}get options(){return this.info.options}get bucket(){return this.info.bucket}get chunks(){return this.info.chunks}get deleted(){return this.info.deleted??!1}get digest(){return this.info.digest}get mtime(){return this.info.mtime}get nuid(){return this.info.nuid}get size(){return this.info.size}get revision(){return this.info.revision}get metadata(){return this.info.metadata||{}}isLink(){return this.info.options?.link!==void 0&&this.info.options?.link!==null}}function sp(e){let t={name:e.name,description:e.description??"",options:e.options,metadata:e.metadata};return e.headers&&(t.headers=e.headers.toRecord()),t}class sm{jsm;js;stream;name;constructor(e,t,s){this.name=e,this.jsm=t,this.js=s}_checkNotEmpty(e){return e&&0!==e.length?{name:e}:{name:e,error:Error("name cannot be empty")}}async info(e){let t=await this.rawInfo(e);return t?new sf(t):null}async list(){let e=[];for await(let t of(await this.watch({ignoreDeletes:!0,includeHistory:!0}))){if(null===t)break;e.push(t)}return Promise.resolve(e)}async rawInfo(e){let{name:t,error:s}=this._checkNotEmpty(e);if(s)return Promise.reject(s);let r=this._metaSubject(t);try{let e=await this.jsm.streams.getMessage(this.stream,{last_by_subj:r}),t=em().decode(e.data);return t.revision=e.seq,t}catch(e){if("404"===e.code)return null;return Promise.reject(e)}}async _si(e){try{return await this.jsm.streams.info(this.stream,e)}catch(e){if("404"===e.code)return null;return Promise.reject(e)}}async seal(){let e=await this._si();return null===e?Promise.reject(Error("object store not found")):(e.config.sealed=!0,Promise.resolve(new t2(e=await this.jsm.streams.update(this.stream,e.config))))}async status(e){let t=await this._si(e);return null===t?Promise.reject(Error("object store not found")):Promise.resolve(new t2(t))}destroy(){return this.jsm.streams.delete(this.stream)}async _put(e,t,s){let r=this.js.getOptions();(s=s||{timeout:r.timeout}).timeout=s.timeout||r.timeout,s.previousRevision=s.previousRevision??void 0;let{timeout:i,previousRevision:n}=s,o=this.js.nc.info,a=o?.max_payload||1024;(e=e||{}).options=e.options||{};let c=e.options?.max_chunk_size||131072;c=c>a?a:c,e.options.max_chunk_size=c;let h=await this.info(e.name),{name:l,error:u}=this._checkNotEmpty(e.name);if(u)return Promise.reject(u);let d=H.next(),f=this._chunkSubject(d),p=this._metaSubject(l),m=Object.assign({bucket:this.name,nuid:d,size:0,chunks:0},sp(e)),b=ei(),g=[],_=new eN;try{let s=t?t.getReader():null,r=new eH;for(;;){let{done:t,value:o}=s?await s.read():{done:!0,value:void 0};if(t){if(_.size()>0){let e=_.drain();r.update(e),m.chunks++,m.size+=e.length,g.push(this.js.publish(f,e,{timeout:i}))}await Promise.all(g),g.length=0,m.mtime=new Date().toISOString();let e=r.digest("base64"),t=e.length%3,s=t>0?"=".repeat(t):"";m.digest=`${t1}${e}${s}`,m.deleted=!1;let o=eu();"number"==typeof n&&o.set(j.ExpectedLastSubjectSequenceHdr,`${n}`),o.set(w.RollupHdr,w.RollupValueSubject);let a=await this.js.publish(p,em().encode(m),{headers:o,timeout:i});if(m.revision=a.seq,h)try{await this.jsm.streams.purge(this.stream,{filter:`$O.${this.name}.C.${h.nuid}`})}catch(e){}b.resolve(new sf(m));break}if(o)for(_.fill(o);_.size()>c;){m.chunks++,m.size+=c;let t=_.drain(e.options.max_chunk_size);r.update(t),g.push(this.js.publish(f,t,{timeout:i}))}}}catch(e){await this.jsm.streams.purge(this.stream,{filter:f}),b.reject(e)}return b}putBlob(e,t,s){var r;return null===t&&(t=new Uint8Array(0)),this.put(e,(r=t,new ReadableStream({pull(e){e.enqueue(r),e.close()}})),s)}put(e,t,s){return e?.options?.link?Promise.reject(Error("link cannot be set when putting the object in bucket")):this._put(e,t,s)}async getBlob(e){async function t(e){let t=new eN,s=e.getReader();for(;;){let{done:e,value:r}=await s.read();if(e)return t.drain();r&&r.length&&t.fill(r)}}let s=await this.get(e);if(null===s)return Promise.resolve(null);let r=await Promise.all([s.error,t(s.data)]);return r[0]?Promise.reject(r[0]):Promise.resolve(r[1])}async get(e){let t,s=await this.rawInfo(e);if(null===s||s.deleted)return Promise.resolve(null);if(s.options&&s.options.link){let e=s.options.link.name||"";if(""===e)throw Error("link is a bucket");return(s.options.link.bucket!==this.name?await sm.create(this.js,s.options.link.bucket):this).get(e)}let r=ei(),i={info:new sf(s),error:r};if(0===s.size)return i.data=new ReadableStream({pull(e){e.enqueue(new Uint8Array(0)),e.close()}}),r.resolve(null),Promise.resolve(i);let n=eO();n.orderedConsumer();let o=new eH,a=`$O.${this.name}.C.${s.nuid}`,c=await this.js.subscribe(a,n);return(async()=>{for await(let e of c)if(e.data.length>0&&(o.update(e.data),t.enqueue(e.data)),0===e.info.pending){let e=o.digest("base64"),r=e.length%3,i=r>0?"=".repeat(r):"",n=`${t1}${e}${i}`;n!==s.digest?t.error(Error(`received a corrupt object, digests do not match received: ${s.digest} calculated ${n}`)):t.close(),c.unsubscribe()}})().then(()=>{r.resolve()}).catch(e=>{t.error(e),r.reject(e)}),i.data=new ReadableStream({start(e){t=e},cancel(){c.unsubscribe()}}),i}linkStore(e,t){if(!(t instanceof sm))return Promise.reject("bucket required");let{name:s,error:r}=this._checkNotEmpty(e);if(r)return Promise.reject(r);let i={name:s,options:{link:{bucket:t.name}}};return this._put(i,null)}async link(e,t){let{name:s,error:r}=this._checkNotEmpty(e);if(r)return Promise.reject(r);if(t.deleted)return Promise.reject(Error("src object is deleted"));if(t.isLink())return Promise.reject(Error("src object is a link"));let i=await this.rawInfo(e);if(null!==i&&!i.deleted)return Promise.reject(Error("an object already exists with that name"));let n={bucket:t.bucket,name:t.name},o={name:s,bucket:t.bucket,options:{link:n}};return await this.js.publish(this._metaSubject(e),JSON.stringify(o)),Promise.resolve(await this.info(e))}async delete(e){let t=await this.rawInfo(e);if(null===t)return Promise.resolve({purged:0,success:!1});t.deleted=!0,t.size=0,t.chunks=0,t.digest="";let s=em(),r=eu();return r.set(w.RollupHdr,w.RollupValueSubject),await this.js.publish(this._metaSubject(t.name),s.encode(t),{headers:r}),this.jsm.streams.purge(this.stream,{filter:this._chunkSubject(t.nuid)})}async update(e,t={}){let s=await this.rawInfo(e);if(null===s)return Promise.reject(Error("object not found"));if(s.deleted)return Promise.reject(Error("cannot update meta for a deleted object"));t.name=t.name??s.name;let{name:r,error:i}=this._checkNotEmpty(t.name);if(i)return Promise.reject(i);if(e!==t.name){let e=await this.info(t.name);if(e&&!e.deleted)return Promise.reject(Error("an object already exists with that name"))}t.name=r;let n=Object.assign({},s,sp(t)),o=await this.js.publish(this._metaSubject(n.name),JSON.stringify(n));return e!==t.name&&await this.jsm.streams.purge(this.stream,{filter:this._metaSubject(e)}),Promise.resolve(o)}async watch(e={}){e.includeHistory=e.includeHistory??!1,e.ignoreDeletes=e.ignoreDeletes??!1;let t=!1,s=new eA,r=this._metaSubjectAll();try{await this.jsm.streams.getMessage(this.stream,{last_by_subj:r})}catch(e){"404"===e.code?(s.push(null),t=!0):s.stop(e)}let i=em(),n=eO();n.orderedConsumer(),e.includeHistory?n.deliverLastPerSubject():(t=!0,n.deliverNew()),n.callback((r,n)=>{if(r)return void s.stop(r);if(null!==n){let r=i.decode(n.data);r.deleted&&!0===e.ignoreDeletes||s.push(r),n.info?.pending!==0||t||(t=!0,s.push(null))}});let o=await this.js.subscribe(r,n);return s._data=o,s.iterClosed.then(()=>{o.unsubscribe()}),o.closed.then(()=>{s.stop()}).catch(e=>{s.stop(e)}),s}_chunkSubject(e){return`$O.${this.name}.C.${e}`}_metaSubject(e){return`$O.${this.name}.M.${eM.encode(e)}`}_metaSubjectAll(){return`$O.${this.name}.M.>`}async init(e={}){try{var t;this.stream=(t=this.name,tX(t),`${t0}${t}`)}catch(e){return Promise.reject(e)}let s=e?.ttl||0;delete e.ttl;let r=Object.assign({max_age:s},e);r.name=this.stream,r.num_replicas=e.replicas??1,r.allow_direct=!0,r.allow_rollup_hdrs=!0,r.discard=d.New,r.subjects=[`$O.${this.name}.C.>`,`$O.${this.name}.M.>`],e.placement&&(r.placement=e.placement),e.metadata&&(r.metadata=e.metadata),"boolean"==typeof e.compression&&(r.compression=e.compression?g.S2:g.None);try{await this.jsm.streams.info(r.name)}catch(e){"stream not found"===e.message&&await this.jsm.streams.add(r)}}static async create(e,t,s={}){let r=new sm(t,await e.jetstreamManager(),e);return await r.init(s),Promise.resolve(r)}}class sb{js;constructor(e){this.js=e}kv(e,t={}){let{ok:s,min:r}=this.js.nc.features.get(E.JS_KV);return s?t.bindOnly?tQ.bind(this.js,e,t):tQ.create(this.js,e,t):Promise.reject(Error(`kv is only supported on servers ${r} or better`))}os(e,t={}){if("function"!=typeof crypto?.subtle?.digest)return Promise.reject(Error("objectstore: unable to calculate hashes - crypto.subtle.digest with sha256 support is required"));let{ok:s,min:r}=this.js.nc.features.get(E.JS_OBJECTSTORE);return s?sm.create(this.js,e,t):Promise.reject(Error(`objectstore is only supported on servers ${r} or better`))}}class sg extends eG{consumers;streams;consumerAPI;streamAPI;constructor(e,t){super(e,t),this.consumerAPI=new eQ(e,t),this.streamAPI=new sa(e,t),this.consumers=new sn(this.consumerAPI),this.streams=new sd(this.streamAPI)}jetstreamManager(e){void 0===e&&(e=this.opts.checkAPI);let t=Object.assign({},this.opts,{checkAPI:e});return this.nc.jetstreamManager(t)}get apiPrefix(){return this.prefix}get views(){return new sb(this)}async publish(e,t=T,s){let r;(s=s||{}).expect=s.expect||{};let i=s?.headers||eu();s&&(s.msgID&&i.set(j.MsgIdHdr,s.msgID),s.expect.lastMsgID&&i.set(j.ExpectedLastMsgIdHdr,s.expect.lastMsgID),s.expect.streamName&&i.set(j.ExpectedStreamHdr,s.expect.streamName),"number"==typeof s.expect.lastSequence&&i.set(j.ExpectedLastSeqHdr,`${s.expect.lastSequence}`),"number"==typeof s.expect.lastSubjectSequence&&i.set(j.ExpectedLastSubjectSequenceHdr,`${s.expect.lastSubjectSequence}`));let o=s.timeout||this.timeout,a={};o&&(a.timeout=o),s&&(a.headers=i);let{retries:c,retry_delay:h}=s;c=c||1,h=h||250;for(let s=0;sr&&(r=s);let i={batch:1,no_wait:0===(s=s<0?0:ec(s)),expires:s},n=await this.nc.request(`${this.prefix}.CONSUMER.MSG.NEXT.${e}.${t}`,this.jc.encode(i),{noMux:!0,timeout:r}),o=eE(n);if(o)throw o;return se(n,this.timeout)}fetch(e,t,s={}){ey(e),e_(t);let r=null,i=(s.max_bytes??0)>0,o=0,a=i?s.max_bytes:0,c=null,h={};if(h.batch=s.batch||1,a){let e=this.nc.features.get(E.JS_PULL_MAX_BYTES);if(!e.ok)throw Error(`max_bytes is only supported on servers ${e.min} or better`);h.max_bytes=a}h.no_wait=s.no_wait||!1,h.no_wait&&h.expires&&(h.expires=0);let u=s.expires||0;if(u&&(h.expires=ec(u)),0===u&&!1===h.no_wait)throw Error("expires or no_wait is required");let d=s.idle_heartbeat||0;d&&(h.idle_heartbeat=ec(d),!0===s.delay_heartbeat&&(h.idle_heartbeat=ec(4*d)));let f=new eA,p=h.batch,m=0;f.protocolFilterFn=(e,t=!1)=>!ev(e.msg)||(c?.work(),!1),f.dispatchedFn=e=>{e&&(i&&(o+=e.data.length),m++,(!r||0!==e.info.pending)&&(1===f.getPending()&&0===e.info.pending||p===m||a>0&&o>=a)&&f.stop())};let b=X(this.nc.options.inboxPrefix),g=this.nc.subscribe(b,{max:s.batch,callback:(e,t)=>{(null===e&&(e=eE(t)),null!==e)?(r&&(r.cancel(),r=null),"string"==typeof e.code)?f.stop(null===sE(e)?void 0:e):f.stop(e):(c?.work(),f.received++,f.push(se(t,this.timeout)))}});return u&&(r=et(u)).catch(()=>{g.isClosed()||(g.drain().catch(()=>{}),r=null),c&&c.cancel()}),(async()=>{try{d&&(c=new ek(d,e=>(f.push(()=>{f.err=new z(`${l.IdleHeartbeatMissed}: ${e}`,n.JetStreamIdleHeartBeat)}),!0)))}catch(e){}await g.closed,null!==r&&(r.cancel(),r=null),c&&c.cancel(),f.stop()})().catch(),this.nc.publish(`${this.prefix}.CONSUMER.MSG.NEXT.${e}.${t}`,this.jc.encode(h),{reply:b}),f}async pullSubscribe(e,t=eO()){let s=await this._processOptions(e,t);if(s.ordered)throw Error("pull subscribers cannot be be ordered");if(s.config.deliver_subject)throw Error("consumer info specifies deliver_subject - pull consumers cannot have deliver_subject set");let r=s.config.ack_policy;if(r===m.None||r===m.All)throw Error("ack policy for pull consumers must be explicit");let i=this._buildTypedSubscriptionOpts(s),n=new sv(this,s.deliver,i);n.info=s;try{await this._maybeCreateConsumer(s)}catch(e){throw n.unsubscribe(),e}return n}async subscribe(e,t=eO()){let s=await this._processOptions(e,t);if(!s.isBind&&!s.config.deliver_subject)throw Error("push consumer requires deliver_subject");let r=this._buildTypedSubscriptionOpts(s),i=new sS(this,s.deliver,r);i.info=s;try{await this._maybeCreateConsumer(s)}catch(e){throw i.unsubscribe(),e}return i._maybeSetupHbMonitoring(),i}async _processOptions(e,t=eO()){let s=ej(t)?t.getOpts():t;if(s.isBind=!!ej(t)&&t.isBind,s.flow_control={heartbeat_count:0,fc_count:0,consumer_restarts:0},s.ordered){if(s.ordered_consumer_sequence={stream_seq:0,delivery_seq:0},s.config.ack_policy!==m.NotSet&&s.config.ack_policy!==m.None)throw new z("ordered consumer: ack_policy can only be set to 'none'",n.ApiError);if(s.config.durable_name&&s.config.durable_name.length>0)throw new z("ordered consumer: durable_name cannot be set",n.ApiError);if(s.config.deliver_subject&&s.config.deliver_subject.length>0)throw new z("ordered consumer: deliver_subject cannot be set",n.ApiError);if(void 0!==s.config.max_deliver&&s.config.max_deliver>1)throw new z("ordered consumer: max_deliver cannot be set",n.ApiError);if(s.config.deliver_group&&s.config.deliver_group.length>0)throw new z("ordered consumer: deliver_group cannot be set",n.ApiError);s.config.deliver_subject=X(this.nc.options.inboxPrefix),s.config.ack_policy=m.None,s.config.max_deliver=1,s.config.flow_control=!0,s.config.idle_heartbeat=s.config.idle_heartbeat||ec(5e3),s.config.ack_wait=ec(792e5),s.config.mem_storage=!0,s.config.num_replicas=1}if(s.config.ack_policy===m.NotSet&&(s.config.ack_policy=m.All),s.api=this,s.config=s.config||{},s.stream=s.stream?s.stream:await this.findStream(e),s.attached=!1,s.config.durable_name)try{let t=await this.consumerAPI.info(s.stream,s.config.durable_name);if(t){if(t.config.filter_subject&&t.config.filter_subject!==e)throw Error("subject does not match consumer");let r=s.config.deliver_group??"";if(""===r&&!0===t.push_bound)throw Error("duplicate subscription");let i=t.config.deliver_group??"";if(r!==i)if(""===i)throw Error("durable requires no queue group");else throw Error(`durable requires queue group '${i}'`);s.last=t,s.config=t.config,s.attached=!0,s.config.durable_name||(s.name=t.name)}}catch(e){if("404"!==e.code)throw e}return s.attached||void 0!==s.config.filter_subject||void 0!==s.config.filter_subjects||(s.config.filter_subject=e),s.deliver=s.config.deliver_subject||X(this.nc.options.inboxPrefix),s}_buildTypedSubscriptionOpts(e){var t,s,r,i;let n={};return t=void 0===e.callbackFn,s=this.timeout,n.adapter=t?(r=s,(e,t)=>{if(e)return[e,null];let s=eE(t);return null!==s?[sE(s),null]:[null,se(t,r)]}):(i=s,(e,t)=>e||(e=eE(t))?[e,null]:[null,se(t,i)]),n.ingestionFilterFn=sg.ingestionFn(e.ordered),n.protocolFilterFn=(e,t=!1)=>!eS(e.msg)||(t||e.msg.respond(),!1),e.mack||e.config.ack_policy===m.None||(n.dispatchedFn=sP),e.callbackFn&&(n.callback=e.callbackFn),n.max=e.max||0,n.queue=e.queue,n}async _maybeCreateConsumer(e){if(e.attached)return;if(e.isBind)throw Error(`unable to bind - durable consumer ${e.config.durable_name} doesn't exist in ${e.stream}`);e.config=Object.assign({deliver_policy:p.All,ack_policy:m.Explicit,ack_wait:ec(3e4),replay_policy:b.Instant},e.config);let t=await this.consumerAPI.add(e.stream,e.config);if(Array.isArray(e.config.filter_subjects&&!Array.isArray(t.config.filter_subjects)))throw Error("jetstream server doesn't support consumers with multiple filter subjects");e.name=t.name,e.config=t.config,e.last=t}static ingestionFn(e){return(t,s)=>{if(!t)return{ingest:!1,protocol:!1};if(eE(t.msg)||s.monitor?.work(),ev(t.msg)){let r=!e||s._checkHbOrderConsumer(t.msg);return!e&&s.info.flow_control.heartbeat_count++,{ingest:r,protocol:!0}}return eS(t.msg)?(s.info.flow_control.fc_count++,{ingest:!0,protocol:!0}):{ingest:!e||s._checkOrderedConsumer(t),protocol:!1}}}}class s_{options;protocol;draining;listeners;_services;constructor(e){this.draining=!1,this.options=function(e){let t=`${Q}:${e1()}`;if((e=e||{servers:[t]}).servers=e.servers||[],"string"==typeof e.servers&&(e.servers=[e.servers]),e.servers.length>0&&e.port)throw new z("port and servers options are mutually exclusive",n.InvalidOption);0===e.servers.length&&e.port&&(e.servers=[`${Q}:${e.port}`]),e.servers&&0===e.servers.length&&(e.servers=[t]);let s=Z({maxPingOut:2,maxReconnectAttempts:10,noRandomize:!1,pedantic:!1,pingInterval:12e4,reconnect:!0,reconnectJitter:100,reconnectJitterTLS:1e3,reconnectTimeWait:2e3,tls:void 0,verbose:!1,waitOnFirstConnect:!1,ignoreAuthErrorAbort:!1},e);if(s.authenticator=tC(s),["reconnectDelayHandler","authenticator"].forEach(e=>{if(s[e]&&"function"!=typeof s[e])throw new z(`${e} option should be a function`,n.NotFunction)}),s.reconnectDelayHandler||(s.reconnectDelayHandler=()=>{let e=s.tls?s.reconnectJitterTLS:s.reconnectJitter;return e&&(e=Math.floor(Math.random()*++e)),s.reconnectTimeWait+e}),s.inboxPrefix)try{X(s.inboxPrefix)}catch(e){throw new z(e.message,n.ApiError)}if(void 0===s.resolve&&(s.resolve="function"==typeof e3()),s.resolve&&"function"!=typeof e3())throw new z("'resolve' is not supported on this client",n.InvalidOption);return s}(e),this.listeners=[]}static connect(e={}){return new Promise((t,s)=>{let r=new s_(e);t$.connect(r.options,r).then(e=>{r.protocol=e,async function(){for await(let t of e.status())r.listeners.forEach(e=>{e.push(t)})}(),t(r)}).catch(e=>{s(e)})})}closed(){return this.protocol.closed}async close(){await this.protocol.close()}_check(e,t,s){if(this.isClosed())throw z.errorForCode(n.ConnectionClosed);if(t&&this.isDraining()||s&&this.protocol.noMorePublishing)throw z.errorForCode(n.ConnectionDraining);if(0===(e=e||"").length)throw z.errorForCode(n.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)}subscribe(e,t={}){this._check(e,!0,!1);let s=new tN(this.protocol,e,t);return this.protocol.subscribe(s),s}_resub(e,t,s){this._check(t,!0,!1),e.max=s,s&&(e.max=s+e.received),this.protocol.resub(e,t)}requestMany(e,t=T,s={maxWait:1e3,maxMessages:-1}){let r=!this.protocol.options.noAsyncTraces;try{this._check(e,!0,!0)}catch(e){return Promise.reject(e)}if(s.strategy=s.strategy||a.Timer,s.maxWait=s.maxWait||1e3,s.maxWait<1)return Promise.reject(new z("timeout",n.InvalidOption));let i=new eA;function o(e){i.push(()=>{i.stop(e)})}function c(e,t){e||null===t?o(null===e?void 0:e):i.push(t)}if(s.noMux){let h=r?Error().stack:null,l="number"==typeof s.maxMessages&&s.maxMessages>0?s.maxMessages:-1,u=this.subscribe(X(this.options.inboxPrefix),{callback:(e,t)=>{if(t?.data?.length===0&&t?.headers?.status===n.NoResponders&&(e=z.errorForCode(n.NoResponders)),e){h&&(e.stack+=` ${h}`),d(e);return}c(null,t),s.strategy===a.Count&&0==--l&&d(),s.strategy===a.JitterTimer&&(p(),f=setTimeout(()=>{d()},300)),s.strategy===a.SentinelMsg&&t&&0===t.data.length&&d()}});u.requestSubject=e,u.closed.then(()=>{o()}).catch(e=>{i.stop(e)});let d=e=>{e&&i.push(()=>{throw e}),p(),u.drain().then(()=>{o()}).catch(e=>{o()})};i.iterClosed.then(()=>{p(),u?.unsubscribe()}).catch(e=>{p(),u?.unsubscribe()});try{this.publish(e,t,{reply:u.getSubject()})}catch(e){d(e)}let f=setTimeout(()=>{d()},s.maxWait),p=()=>{f&&clearTimeout(f)}}else{s.callback=c,i.iterClosed.then(()=>{r.cancel()}).catch(e=>{r.cancel(e)});let r=new eK(this.protocol.muxSubscriptions,e,s);this.protocol.request(r);try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${r.token}`,headers:s.headers})}catch(e){r.cancel(e)}}return Promise.resolve(i)}request(e,t,s={timeout:1e3,noMux:!1}){try{this._check(e,!0,!0)}catch(e){return Promise.reject(e)}let r=!this.protocol.options.noAsyncTraces;if(s.timeout=s.timeout||1e3,s.timeout<1)return Promise.reject(new z("timeout",n.InvalidOption));if(!s.noMux&&s.reply)return Promise.reject(new z("reply can only be used with noMux",n.InvalidOption));if(s.noMux){let i=s.reply?s.reply:X(this.options.inboxPrefix),o=ei(),a=r?Error():null,c=this.subscribe(i,{max:1,timeout:s.timeout,callback:(e,t)=>{e?(a&&e.code!==n.Timeout&&(e.stack+=` ${a.stack}`),c.unsubscribe(),o.reject(e)):(e=eb(t))?(a&&(e.stack+=` ${a.stack}`),o.reject(e)):o.resolve(t)}});return c.requestSubject=e,this.protocol.publish(e,t,{reply:i,headers:s.headers}),o}{let i=new ez(this.protocol.muxSubscriptions,e,s,r);this.protocol.request(i);try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${i.token}`,headers:s.headers})}catch(e){i.cancel(e)}let n=Promise.race([i.timer,i.deferred]);return n.catch(()=>{i.cancel()}),n}}flush(){return this.isClosed()?Promise.reject(z.errorForCode(n.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(z.errorForCode(n.ConnectionClosed)):this.isDraining()?Promise.reject(z.errorForCode(n.ConnectionDraining)):(this.draining=!0,this.protocol.drain())}isClosed(){return this.protocol.isClosed()}isDraining(){return this.draining}getServer(){let e=this.protocol.getServer();return e?e.listen:""}status(){let e=new eA;return e.iterClosed.then(()=>{let t=this.listeners.indexOf(e);this.listeners.splice(t,1)}),this.listeners.push(e),e}get info(){return this.protocol.isClosed()?void 0:this.protocol.info}async context(){return(await this.request("$SYS.REQ.USER.INFO")).json((e,t)=>"time"===e?new Date(Date.parse(t)):t)}stats(){return{inBytes:this.protocol.inBytes,outBytes:this.protocol.outBytes,inMsgs:this.protocol.inMsgs,outMsgs:this.protocol.outMsgs}}async jetstreamManager(e={}){let t=new sl(this,e);if(!1!==e.checkAPI)try{await t.getAccountInfo()}catch(e){throw e.code===n.NoResponders&&(e.code=n.JetStreamNotEnabled),e}return t}jetstream(e={}){return new sg(this,e)}getServerVersion(){let e=this.info;return e?eW(e.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw z.errorForCode(n.Disconnect);let e=Date.now();return await this.flush(),Date.now()-e}get features(){return this.protocol.features}get services(){return this._services||(this._services=new sy(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(z.errorForCode(n.ConnectionClosed)):this.isDraining()?Promise.reject(z.errorForCode(n.ConnectionDraining)):this.protocol.reconnect()}}class sy{nc;constructor(e){this.nc=e}add(e){try{return new tU(this.nc,e).start()}catch(e){return Promise.reject(e)}}client(e,t){return new tF(this.nc,e,t)}}class sw{bucket;sm;prefixLen;constructor(e,t,s){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(tJ)||"PUT"}get length(){let e=this.sm.header.get(w.MessageSizeHdr)||"";return""!==e?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class sx{bucket;key;sm;constructor(e,t,s){this.bucket=e,this.key=t,this.sm=s}get value(){return this.sm.data}get created(){return new Date(eh(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){return this.sm.headers?.get(tJ)||"PUT"}get delta(){return this.sm.info.pending}get length(){let e=this.sm.headers?.get(w.MessageSizeHdr)||"";return""!==e?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class sS extends e0{js;monitor;constructor(e,t,s){super(e.nc,t,s),this.js=e,this.monitor=null,this.sub.closed.then(()=>{this.monitor&&this.monitor.cancel()})}set info(e){this.sub.info=e}get info(){return this.sub.info}_resetOrderedConsumer(e){if(null===this.info||this.sub.isClosed())return;let t=X(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,t);let s=this.info;s.config.name=H.next(),s.ordered_consumer_sequence.delivery_seq=0,s.flow_control.heartbeat_count=0,s.flow_control.fc_count=0,s.flow_control.consumer_restarts++,s.deliver=t,s.config.deliver_subject=t,s.config.deliver_policy=p.StartSequence,s.config.opt_start_seq=e;let r={};r.stream_name=this.info.stream,r.config=s.config;let i=`${s.api.prefix}.CONSUMER.CREATE.${s.stream}`;this.js._request(i,r,{retries:-1}).then(e=>{this.sub.info.last=e,this.info.config=e.config,this.info.name=e.name}).catch(t=>{let r=new z(`unable to recreate ordered consumer ${s.stream} at seq ${e}`,n.RequestError,t);this.sub.callback(r,{})})}_maybeSetupHbMonitoring(){let e=this.info?.config?.idle_heartbeat||0;e&&this._setupHbMonitoring(eh(e))}_setupHbMonitoring(e,t=0){let s={cancelAfter:0,maxOut:2};t&&(s.cancelAfter=t);let r=this.sub;this.monitor=new ek(e,e=>{let t=function(e,t,s){let r=eu(409,t),i=new eg({hdr:1,sid:0,size:0},T,{});return i._headers=r,i._subject=s,i}(0,`${l.IdleHeartbeatMissed}: ${e}`,this.sub.subject);if(this.info?.ordered){if(!this.js.nc.protocol.connected)return!1;let e=this.info?.ordered_consumer_sequence?.stream_seq||0;return this._resetOrderedConsumer(e+1),this.monitor?.restart(),!1}return this.sub.callback(null,t),!r.noIterator},s)}_checkHbOrderConsumer(e){let t=e.headers.get(w.ConsumerStalledHdr);""!==t&&this.js.nc.publish(t);let s=parseInt(e.headers.get(w.LastConsumerSeqHdr),10),r=this.info.ordered_consumer_sequence;return this.info.flow_control.heartbeat_count++,s!==r.delivery_seq&&this._resetOrderedConsumer(r.stream_seq+1),!1}_checkOrderedConsumer(e){let t=this.info.ordered_consumer_sequence,s=e.info.streamSequence,r=e.info.deliverySequence;return r!=t.delivery_seq+1?(this._resetOrderedConsumer(t.stream_seq+1),!1):(t.delivery_seq=r,t.stream_seq=s,!0)}async destroy(){this.isClosed()||await this.drain();let e=this.sub.info,t=e.config.durable_name||e.name,s=`${e.api.prefix}.CONSUMER.DELETE.${e.stream}.${t}`;await e.api._request(s)}async consumerInfo(){let e=this.sub.info,t=e.config.durable_name||e.name,s=`${e.api.prefix}.CONSUMER.INFO.${e.stream}.${t}`,r=await e.api._request(s);return e.last=r,r}}class sv extends sS{constructor(e,t,s){super(e,t,s)}pull(e={batch:1}){let{stream:t,config:s,name:r}=this.sub.info,i=s.durable_name??r,n={};if(n.batch=e.batch||1,n.no_wait=e.no_wait||!1,(e.max_bytes??0)>0){let t=this.js.nc.features.get(E.JS_PULL_MAX_BYTES);if(!t.ok)throw Error(`max_bytes is only supported on servers ${t.min} or better`);n.max_bytes=e.max_bytes}let o=0;e.expires&&e.expires>0&&(n.expires=ec(o=e.expires));let a=0;if(e.idle_heartbeat&&e.idle_heartbeat>0&&(n.idle_heartbeat=ec(a=e.idle_heartbeat)),a&&0===o)throw Error("idle_heartbeat requires expires");if(a>o)throw Error("expires must be greater than idle_heartbeat");if(this.info){this.monitor&&this.monitor.cancel(),o&&a&&(this.monitor?this.monitor._change(a,o):this._setupHbMonitoring(a,o));let e=this.info.api,s=`${e.prefix}.CONSUMER.MSG.NEXT.${t}.${i}`,r=this.sub.subject;e.nc.publish(s,e.jc.encode(n),{reply:r})}}}function sE(e){if(null!==e)switch(e.code){case n.JetStream404NoMessages:case n.JetStream408RequestTimeout:break;case n.JetStream409:var t;if((t=e).code===n.JetStream409&&void 0!==[l.MaxBatchExceeded,l.MaxExpiresExceeded,l.MaxBytesExceeded,l.MaxMessageSizeExceeded,l.PushConsumer,l.IdleHeartbeatMissed,l.ConsumerDeleted].find(e=>-1!==t.message.indexOf(e)))return e;break;default:return e}return null}function sP(e){e&&e.ack()}class sA{msg;di;didAck;timeout;constructor(e,t){this.msg=e,this.didAck=!1,this.timeout=t}get subject(){return this.msg.subject}get sid(){return this.msg.sid}get data(){return this.msg.data}get headers(){return this.msg.headers}get info(){return this.di||(this.di=function(e){let t=e.split(".");if(9===t.length&&t.splice(2,0,"_",""),t.length<11||"$JS"!==t[0]||"ACK"!==t[1])throw Error("not js message");let s={};return s.domain="_"===t[2]?"":t[2],s.account_hash=t[3],s.stream=t[4],s.consumer=t[5],s.redeliveryCount=parseInt(t[6],10),s.redelivered=s.redeliveryCount>1,s.streamSequence=parseInt(t[7],10),s.deliverySequence=parseInt(t[8],10),s.timestampNanos=parseInt(t[9],10),s.pending=parseInt(t[10],10),s}(this.reply)),this.di}get redelivered(){return this.info.redeliveryCount>1}get reply(){return this.msg.reply||""}get seq(){return this.info.streamSequence}doAck(e){this.didAck||(this.didAck=!this.isWIP(e),this.msg.respond(e))}isWIP(e){return 4===e.length&&e[0]===t6[0]&&e[1]===t6[1]&&e[2]===t6[2]&&e[3]===t6[3]}async ackAck(e){(e=e||{}).timeout=e.timeout||this.timeout;let t=ei();if(this.didAck)t.resolve(!1);else if(this.didAck=!0,this.msg.reply){let s=this.msg.publisher,r=!s.options?.noAsyncTraces,i=new ez(s.muxSubscriptions,this.msg.reply,{timeout:e.timeout},r);s.request(i);try{s.publish(this.msg.reply,t4,{reply:`${s.muxSubscriptions.baseInbox}${i.token}`})}catch(e){i.cancel(e)}try{await Promise.race([i.timer,i.deferred]),t.resolve(!0)}catch(e){i.cancel(e),t.reject(e)}}else t.resolve(!1);return t}ack(){this.doAck(t4)}nak(e){let t=t5;e&&(t=ep().encode(`-NAK ${JSON.stringify({delay:ec(e)})}`)),this.doAck(t)}working(){this.doAck(t6)}next(e,t={batch:1}){let s={};s.batch=t.batch||1,s.no_wait=t.no_wait||!1,t.expires&&t.expires>0&&(s.expires=ec(t.expires));let r=em().encode(s),i=eN.concat(t8,t9,r);this.msg.respond(i,e?{reply:e}:void 0)}term(e=""){let t=t7;e?.length>0&&(t=ep().encode(`+TERM ${e}`)),this.doAck(t)}json(){return this.msg.json()}string(){return this.msg.string()}}class sk{version;lang;closeError;connected;done;socket;options;socketClosed;encrypted;peeked;yields;signal;closedNotification;constructor(){this.version="1.29.1",this.lang="nats.ws",this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=ei(),this.closedNotification=ei()}async connect(e,t){let s=ei();if(t.tls)return s.reject(new z("tls",n.InvalidOption)),s;this.options=t;let r=e.src;if(t.wsFactory){let{socket:s,encrypted:r}=await t.wsFactory(e.src,t);this.socket=s,this.encrypted=r}else this.encrypted=0===r.indexOf("wss://"),this.socket=new WebSocket(r);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{if(this.isDiscarded())return},this.socket.onmessage=e=>{if(this.isDiscarded())return;if(this.yields.push(new Uint8Array(e.data)),this.peeked)return void this.signal.resolve();let r=eN.concat(...this.yields),i=function(e){let t=function(e){for(let t=0;ts&&e[t]===e5&&e[s]===e6)return s+1}return 0}(e);if(t>0){let s=new Uint8Array(e).slice(0,t);return U.decode(s)}return""}(r);if(""!==i){let e=tO.exec(i);if(!e){t.debug&&console.error("!!!",ee(r)),s.reject(Error("unexpected response from server"));return}try{var o=JSON.parse(e[1]),a=this.options;let{proto:t,tls_required:r,tls_available:i}=o;if((void 0===t||t<1)&&a.noEcho)throw new z("noEcho",n.ServerOptionNotAvailable);if(a.tls&&!(r||i))throw new z("tls",n.ServerOptionNotAvailable);this.peeked=!0,this.connected=!0,this.signal.resolve(),s.resolve()}catch(e){s.reject(e);return}}},this.socket.onclose=e=>{let t;!this.isDiscarded()&&(this.socketClosed=!0,this.done||(e.wasClean||(t=Error(e.reason)),this._closed(t)))},this.socket.onerror=e=>{if(this.isDiscarded())return;let t=new z(e.message,n.Unknown,Error(e.error));s.reject(t)},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 es(100);this.done=!0;try{this.socket.close(e?1002:1e3,e?e.message:void 0)}catch(e){}t&&this.closedNotification.resolve(e)}}get isClosed(){return this.done}[Symbol.asyncIterator](){return this.iterate()}async *iterate(){for(;;){if(this.isDiscarded())return;0===this.yields.length&&await this.signal;let e=this.yields;this.yields=[];for(let t=0;t ${ee(e[t])}`),yield e[t];if(this.done)break;0===this.yields.length&&(e.length=0,this.yields=e,this.signal=ei())}}isEncrypted(){return this.connected&&this.encrypted}send(e){if(!this.isDiscarded())try{this.socket.send(e.buffer),this.options.debug&&console.info(`< ${ee(e)}`);return}catch(t){this.options.debug&&console.error(`!!! ${ee(e)}: ${t}`)}}close(e){return this._closed(e,!1)}closed(){return this.closedNotification}isDiscarded(){return!!this.done&&(this.discard(),!0)}discard(){this.done=!0;try{this.socket?.close()}catch(e){}}}function sC(e,t){let s,r;/^(.*:\/\/)(.*)/.test(e)||(e="boolean"==typeof t?`${!0===t?"https":"http"}://${e}`:`https://${e}`);let i=new URL(e),n=i.protocol.toLowerCase();"ws:"===n&&(t=!1),"wss:"===n&&(t=!0),"https:"!==n&&"http"!==n&&(e=e.replace(/^(.*:\/\/)(.*)/gm,"$2"),i=new URL(`http://${e}`));let o=i.hostname,a=i.pathname,c=i.search||"";switch(n){case"http:":case"ws:":case"nats:":r=i.port||"80",s="ws:";break;case"https:":case"wss:":case"tls:":r=i.port||"443",s="wss:";break;default:r=i.port||!0===t?"443":"80",s=!0===t?"wss:":"ws:"}return`${s}//${o}:${r}${a}${c}`}function sO(e={}){return R={defaultPort:443,urlParseFn:sC,factory:()=>new sk},s_.connect(e)}}}]);