@jokio/sdk
Version:
pure js/ts sdk for building decentralised localfirst web apps. Provides tts ai model integrations, realtime p2p communication & crypto encryptions.
12 lines (10 loc) • 206 kB
JavaScript
(function(ye,Q){typeof exports=="object"&&typeof module<"u"?Q(exports):typeof define=="function"&&define.amd?define(["exports"],Q):(ye=typeof globalThis<"u"?globalThis:ye||self,Q(ye["@jokio/sdk"]={}))})(this,function(ye){"use strict";var ma=Object.defineProperty;var ba=(ye,Q,qe)=>Q in ye?ma(ye,Q,{enumerable:!0,configurable:!0,writable:!0,value:qe}):ye[Q]=qe;var h=(ye,Q,qe)=>ba(ye,typeof Q!="symbol"?Q+"":Q,qe);function Q(r){const e=new Uint8Array(r);let t="";for(const i of e)t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function qe(r){const e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,s=e.padEnd(e.length+t,"="),i=atob(s),n=new ArrayBuffer(i.length),o=new Uint8Array(n);for(let a=0;a<i.length;a++)o[a]=i.charCodeAt(a);return n}function ps(){return xi.stubThis((globalThis==null?void 0:globalThis.PublicKeyCredential)!==void 0&&typeof globalThis.PublicKeyCredential=="function")}const xi={stubThis:r=>r};function ar(r){const{id:e}=r;return{...r,id:qe(e),transports:r.transports}}function cr(r){return r==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(r)}class le extends Error{constructor({message:e,code:t,cause:s,name:i}){super(e,{cause:s}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i??s.name,this.code=t}}function Si({error:r,options:e}){var s,i,n;const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new le({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else if(r.name==="ConstraintError"){if(((s=t.authenticatorSelection)==null?void 0:s.requireResidentKey)===!0)return new le({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:r});if(e.mediation==="conditional"&&((i=t.authenticatorSelection)==null?void 0:i.userVerification)==="required")return new le({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:r});if(((n=t.authenticatorSelection)==null?void 0:n.userVerification)==="required")return new le({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:r})}else{if(r.name==="InvalidStateError")return new le({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:r});if(r.name==="NotAllowedError")return new le({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="NotSupportedError")return t.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new le({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:r}):new le({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:r});if(r.name==="SecurityError"){const o=globalThis.location.hostname;if(cr(o)){if(t.rp.id!==o)return new le({message:`The RP ID "${t.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new le({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="TypeError"){if(t.user.id.byteLength<1||t.user.id.byteLength>64)return new le({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:r})}else if(r.name==="UnknownError")return new le({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return r}class vi{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){const t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const hr=new vi,Ei=["cross-platform","platform"];function ur(r){if(r&&!(Ei.indexOf(r)<0))return r}async function Ai(r){var I;!r.optionsJSON&&r.challenge&&(console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),r={optionsJSON:r});const{optionsJSON:e,useAutoRegister:t=!1}=r;if(!ps())throw new Error("WebAuthn is not supported in this browser");const s={...e,challenge:qe(e.challenge),user:{...e.user,id:qe(e.user.id)},excludeCredentials:(I=e.excludeCredentials)==null?void 0:I.map(ar)},i={};t&&(i.mediation="conditional"),i.publicKey=s,i.signal=hr.createNewAbortSignal();let n;try{n=await navigator.credentials.create(i)}catch(T){throw Si({error:T,options:i})}if(!n)throw new Error("Registration was not completed");const{id:o,rawId:a,response:f,type:p}=n;let g;typeof f.getTransports=="function"&&(g=f.getTransports());let y;if(typeof f.getPublicKeyAlgorithm=="function")try{y=f.getPublicKeyAlgorithm()}catch(T){ms("getPublicKeyAlgorithm()",T)}let x;if(typeof f.getPublicKey=="function")try{const T=f.getPublicKey();T!==null&&(x=Q(T))}catch(T){ms("getPublicKey()",T)}let A;if(typeof f.getAuthenticatorData=="function")try{A=Q(f.getAuthenticatorData())}catch(T){ms("getAuthenticatorData()",T)}return{id:o,rawId:Q(a),response:{attestationObject:Q(f.attestationObject),clientDataJSON:Q(f.clientDataJSON),transports:g,publicKeyAlgorithm:y,publicKey:x,authenticatorData:A},type:p,clientExtensionResults:n.getClientExtensionResults(),authenticatorAttachment:ur(n.authenticatorAttachment)}}function ms(r,e){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${r}. You should report this error to them.
`,e)}function Pi(){if(!ps())return bs.stubThis(new Promise(e=>e(!1)));const r=globalThis.PublicKeyCredential;return(r==null?void 0:r.isConditionalMediationAvailable)===void 0?bs.stubThis(new Promise(e=>e(!1))):bs.stubThis(r.isConditionalMediationAvailable())}const bs={stubThis:r=>r};function ki({error:r,options:e}){const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new le({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new le({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){const s=globalThis.location.hostname;if(cr(s)){if(t.rpId!==s)return new le({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new le({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new le({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return r}async function Oi(r){var A,I;!r.optionsJSON&&r.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),r={optionsJSON:r});const{optionsJSON:e,useBrowserAutofill:t=!1,verifyBrowserAutofillInput:s=!0}=r;if(!ps())throw new Error("WebAuthn is not supported in this browser");let i;((A=e.allowCredentials)==null?void 0:A.length)!==0&&(i=(I=e.allowCredentials)==null?void 0:I.map(ar));const n={...e,challenge:qe(e.challenge),allowCredentials:i},o={};if(t){if(!await Pi())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&s)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');o.mediation="conditional",n.allowCredentials=[]}o.publicKey=n,o.signal=hr.createNewAbortSignal();let a;try{a=await navigator.credentials.get(o)}catch(T){throw ki({error:T,options:o})}if(!a)throw new Error("Authentication was not completed");const{id:f,rawId:p,response:g,type:y}=a;let x;return g.userHandle&&(x=Q(g.userHandle)),{id:f,rawId:Q(p),response:{authenticatorData:Q(g.authenticatorData),clientDataJSON:Q(g.clientDataJSON),signature:Q(g.signature),userHandle:x},type:y,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:ur(a.authenticatorAttachment)}}const bt="ACCESS_TOKEN",lr="SESSION_SEED",gt="LAST_AUTH_DATA";class fr{constructor(e){h(this,"onUserDataUpdate");this.options=e}get url(){return this.options.authUrl}async me(){return await fetch(this.options.authUrl+"/me",{headers:await this.getAuthHeader()}).then(t=>t.json())}async requestEmailLogin(e,t=location.href){return await fetch(this.options.authUrl+`/email-verification-request/${e}?returnUrl=${t}`,{headers:await this.getAuthHeader()}).then(_t)}async completeEmailLogin(e,t){var i;const s=await fetch(this.options.authUrl+`/email-verification-complete/${e}/${t}`,{headers:await this.getAuthHeader()}).then(_t);return await this.options.storage.setItem(bt,s.accessToken),await this.options.storage.setItem(gt,s.jwtData),(i=this.onUserDataUpdate)==null||i.call(this,s.jwtData),s.jwtData}async requestPasskeyLogin(e={}){var f,p;const{displayName:t="",isRegistration:s=!1,addAsAdditionalDevice:i=!1}=e,n=await fetch(this.options.authUrl+`/webauth-challenge-request?registration=${s?"true":""}&displayName=${t}`,{headers:await this.getAuthHeader()}).then(_t);let o;try{(f=n.user)!=null&&f.id?o=await Ai({optionsJSON:n}):o=await Oi({optionsJSON:n})}catch(g){throw g.name==="InvalidStateError"?alert("Error: Authenticator was probably already registered by user"):alert(g.message),g}const a=await fetch(this.options.authUrl+`/webauth-challenge-complete?displayName=${t}&addAsAdditionalDevice=${i?"true":""}`,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json",...await this.getAuthHeader()}}).then(_t);return await this.options.storage.setItem(bt,a.accessToken),await this.options.storage.setItem(gt,a.jwtData),(p=this.onUserDataUpdate)==null||p.call(this,a.jwtData),a.jwtData}async guestLogin(){var t;const e=await fetch(this.options.authUrl+"/guest-session").then(_t);return await this.options.storage.setItem(bt,e.accessToken),await this.options.storage.setItem(lr,e.sessionSeed),await this.options.storage.setItem(gt,e.jwtData),(t=this.onUserDataUpdate)==null||t.call(this,e.jwtData),e.jwtData}signOut(){var e;this.options.storage.removeItem(bt),this.options.storage.removeItem(gt),(e=this.onUserDataUpdate)==null||e.call(this,null)}getLastLoginData(){return this.options.storage.getItem(gt)}getAccessToken(){return this.options.storage.getItem(bt)}getSessionSeed(){return this.options.storage.getItem(lr)}async getAuthHeader(){const e=await this.getAccessToken();if(e)return{authorization:"bearer "+e}}}const _t=async r=>{const e=await r.json();if(!r.ok)throw new Error(e.message);return e},gs=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),dr=r=>new Uint8Array(r.match(/.{1,2}/g).map(e=>parseInt(e,16))),pr=r=>btoa(String.fromCharCode(...new Uint8Array(r))),Ci=r=>Uint8Array.from(atob(r),e=>e.charCodeAt(0)).buffer,Ii=async r=>await crypto.subtle.digest("SHA-256",r),ji=new TextEncoder;class Ri{async createSessionKeyPair(){return await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey","deriveBits"])}async exportPublicKey(e){const t=await crypto.subtle.exportKey("spki",e);return pr(t)}async deriveAESKey(e,t){const s=Ci(t),i=await crypto.subtle.importKey("spki",s,{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveKey({name:"ECDH",public:i},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async exportRawKey(e){const t=await crypto.subtle.exportKey("raw",e);return gs(new Uint8Array(t))}async encrypt(e,t){const s=crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},t,i);return`${gs(new Uint8Array(n))}_${gs(s)}`}async decrypt(e,t){const s=e.split("_"),i=dr(s[0]).buffer,n=dr(s[1]),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},t,i);return new TextDecoder().decode(o)}async hashString(e){const t=await Ii(ji.encode(e).buffer);return pr(t)}}const we=new Uint8Array(0),He=new TextEncoder,xe=new TextDecoder;function Ni(...r){let e=0;for(let i=0;i<r.length;i++)e+=r[i].length;const t=new Uint8Array(e);let s=0;for(let i=0;i<r.length;i++)t.set(r[i],s),s+=r[i].length;return t}function yt(...r){const e=[];for(let t=0;t<r.length;t++)e.push(He.encode(r[t]));return e.length===0?we:e.length===1?e[0]:Ni(...e)}function mr(r){return!r||r.length===0?"":xe.decode(r)}const br="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",gr=36,Ti=0xcfd41b9100000,_r=33,Mi=333,yr=22;function Ui(r){for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*255)}function $i(r){var e;(e=globalThis==null?void 0:globalThis.crypto)!=null&&e.getRandomValues?globalThis.crypto.getRandomValues(r):Ui(r)}class Li{constructor(){h(this,"buf");h(this,"seq");h(this,"inc");h(this,"inited");this.buf=new Uint8Array(yr),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){this.seq=Math.floor(Math.random()*Ti),this.inc=Math.floor(Math.random()*(Mi-_r)+_r)}setPre(){const e=new Uint8Array(12);$i(e);for(let t=0;t<12;t++){const s=e[t]%36;this.buf[t]=br.charCodeAt(s)}}fillSeq(){let e=this.seq;for(let t=yr-1;t>=12;t--)this.buf[t]=br.charCodeAt(e%gr),e=Math.floor(e/gr)}next(){return this.inited||this.init(),this.seq+=this.inc,this.seq>0xcfd41b9100000&&(this.setPre(),this.initSeqAndInc()),this.fillSeq(),String.fromCharCode.apply(String,this.buf)}reset(){this.init()}}const Je=new Li;var Pe;(function(r){r.Disconnect="disconnect",r.Reconnect="reconnect",r.Update="update",r.LDM="ldm",r.Error="error"})(Pe||(Pe={}));var Ke;(function(r){r.Reconnecting="reconnecting",r.PingTimer="pingTimer",r.StaleConnection="staleConnection",r.ClientInitiatedReconnect="client initiated reconnect"})(Ke||(Ke={}));var k;(function(r){r.ApiError="BAD API",r.BadAuthentication="BAD_AUTHENTICATION",r.BadCreds="BAD_CREDS",r.BadHeader="BAD_HEADER",r.BadJson="BAD_JSON",r.BadPayload="BAD_PAYLOAD",r.BadSubject="BAD_SUBJECT",r.Cancelled="CANCELLED",r.ConnectionClosed="CONNECTION_CLOSED",r.ConnectionDraining="CONNECTION_DRAINING",r.ConnectionRefused="CONNECTION_REFUSED",r.ConnectionTimeout="CONNECTION_TIMEOUT",r.Disconnect="DISCONNECT",r.InvalidOption="INVALID_OPTION",r.InvalidPayload="INVALID_PAYLOAD",r.MaxPayloadExceeded="MAX_PAYLOAD_EXCEEDED",r.NoResponders="503",r.NotFunction="NOT_FUNC",r.RequestError="REQUEST_ERROR",r.ServerOptionNotAvailable="SERVER_OPT_NA",r.SubClosed="SUB_CLOSED",r.SubDraining="SUB_DRAINING",r.Timeout="TIMEOUT",r.Tls="TLS",r.Unknown="UNKNOWN_ERROR",r.WssRequired="WSS_REQUIRED",r.JetStreamInvalidAck="JESTREAM_INVALID_ACK",r.JetStream404NoMessages="404",r.JetStream408RequestTimeout="408",r.JetStream409MaxAckPendingExceeded="409",r.JetStream409="409",r.JetStreamNotEnabled="503",r.JetStreamIdleHeartBeat="IDLE_HEARTBEAT",r.AuthorizationViolation="AUTHORIZATION_VIOLATION",r.AuthenticationExpired="AUTHENTICATION_EXPIRED",r.ProtocolError="NATS_PROTOCOL_ERR",r.PermissionsViolation="PERMISSIONS_VIOLATION",r.AuthenticationTimeout="AUTHENTICATION_TIMEOUT",r.AccountExpired="ACCOUNT_EXPIRED"})(k||(k={}));function qi(r){return typeof r.code=="string"}class wr{constructor(){h(this,"messages");this.messages=new Map,this.messages.set(k.InvalidPayload,"Invalid payload type - payloads can be 'binary', 'string', or 'json'"),this.messages.set(k.BadJson,"Bad JSON"),this.messages.set(k.WssRequired,"TLS is required, therefore a secure websocket connection is also required")}static getMessage(e){return Fi.getMessage(e)}getMessage(e){return this.messages.get(e)||e}}const Fi=new wr;class N extends Error{constructor(t,s,i){super(t);h(this,"name");h(this,"message");h(this,"code");h(this,"permissionContext");h(this,"chainedError");h(this,"api_error");this.name="NatsError",this.message=t,this.code=s,this.chainedError=i}static errorForCode(t,s){const i=wr.getMessage(t);return new N(i,t,s)}isAuthError(){return this.code===k.AuthenticationExpired||this.code===k.AuthorizationViolation||this.code===k.AccountExpired}isAuthTimeout(){return this.code===k.AuthenticationTimeout}isPermissionError(){return this.code===k.PermissionsViolation}isProtocolError(){return this.code===k.ProtocolError}isJetStreamError(){return this.api_error!==void 0}jsError(){return this.api_error?this.api_error:null}}var Se;(function(r){r[r.Exact=0]="Exact",r[r.CanonicalMIME=1]="CanonicalMIME",r[r.IgnoreCase=2]="IgnoreCase"})(Se||(Se={}));var je;(function(r){r.Timer="timer",r.Count="count",r.JitterTimer="jitterTimer",r.SentinelMsg="sentinelMsg"})(je||(je={}));var wt;(function(r){r.STATS="io.nats.micro.v1.stats_response",r.INFO="io.nats.micro.v1.info_response",r.PING="io.nats.micro.v1.ping_response"})(wt||(wt={}));const Lt="Nats-Service-Error",qt="Nats-Service-Error-Code";class Ft extends Error{constructor(t,s){super(s);h(this,"code");this.code=t}static isServiceError(t){return Ft.toServiceError(t)!==null}static toServiceError(t){var i,n;const s=((i=t==null?void 0:t.headers)==null?void 0:i.get(qt))||"";if(s!==""){const o=parseInt(s)||400,a=((n=t==null?void 0:t.headers)==null?void 0:n.get(Lt))||"";return new Ft(o,a.length?a:s)}return null}}function Fe(r=""){if(r=r||"_INBOX",typeof r!="string")throw new Error("prefix must be a string");return r.split(".").forEach(e=>{if(e==="*"||e===">")throw new Error(`inbox prefixes cannot have wildcards '${r}'`)}),`${r}.${Je.next()}`}const _s="127.0.0.1";var ze;(function(r){r.PING="PING",r.STATS="STATS",r.INFO="INFO"})(ze||(ze={}));function Bt(r,...e){for(let t=0;t<e.length;t++){const s=e[t];Object.keys(s).forEach(function(i){r[i]=s[i]})}return r}function Dt(r){return xe.decode(r).replace(/\n/g,"␊").replace(/\r/g,"␍")}function tt(r,e=!0){const t=e?N.errorForCode(k.Timeout):null;let s,i;const n=new Promise((o,a)=>{s={cancel:()=>{i&&clearTimeout(i)}},i=setTimeout(()=>{a(t===null?N.errorForCode(k.Timeout):t)},r)});return Object.assign(n,s)}function st(r=0){let e;const t=new Promise(s=>{const i=setTimeout(()=>{s()},r);e={cancel:()=>{i&&clearTimeout(i)}}});return Object.assign(t,e)}function V(){let r={};const e=new Promise((t,s)=>{r={resolve:t,reject:s}});return Object.assign(e,r)}function xr(r){for(let e=r.length-1;e>0;e--){const t=Math.floor(Math.random()*(e+1));[r[e],r[t]]=[r[t],r[e]]}return r}function Bi(r){return r===0?0:Math.floor(r/2+Math.random()*r)}function ys(r=[0,250,250,500,500,3e3,5e3]){Array.isArray(r)||(r=[0,250,250,500,500,3e3,5e3]);const e=r.length-1;return{backoff(t){return Bi(t>e?r[e]:r[t])}}}function W(r){return r*1e6}function ws(r){return Math.floor(r/1e6)}function Sr(r){let s=!0;const i=new Array(r.length);for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);if(o===58||o<33||o>126)throw new N(`'${r[n]}' is not a valid character for a header key`,k.BadHeader);s&&97<=o&&o<=122?o-=32:!s&&65<=o&&o<=90&&(o+=32),i[n]=o,s=o==45}return String.fromCharCode(...i)}function Be(r=0,e=""){if(r===0&&e!==""||r>0&&e==="")throw new Error("setting status requires both code and description");return new Ge(r,e)}const xs="NATS/1.0";class Ge{constructor(e=0,t=""){h(this,"_code");h(this,"headers");h(this,"_description");this._code=e,this._description=t,this.headers=new Map}[Symbol.iterator](){return this.headers.entries()}size(){return this.headers.size}equals(e){if(e&&this.headers.size===e.headers.size&&this._code===e._code){for(const[t,s]of this.headers){const i=e.values(t);if(s.length!==i.length)return!1;const n=[...s].sort(),o=[...i].sort();for(let a=0;a<n.length;a++)if(n[a]!==o[a])return!1}return!0}return!1}static decode(e){const t=new Ge,i=xe.decode(e).split(`\r
`),n=i[0];if(n!==xs){let o=n.replace(xs,"").trim();if(o.length>0){t._code=parseInt(o,10),isNaN(t._code)&&(t._code=0);const a=t._code.toString();o=o.replace(a,""),t._description=o.trim()}}return i.length>=1&&i.slice(1).map(o=>{if(o){const a=o.indexOf(":");if(a>-1){const f=o.slice(0,a),p=o.slice(a+1).trim();t.append(f,p)}}}),t}toString(){if(this.headers.size===0&&this._code===0)return"";let e=xs;this._code>0&&this._description!==""&&(e+=` ${this._code} ${this._description}`);for(const[t,s]of this.headers)for(let i=0;i<s.length;i++)e=`${e}\r
${t}: ${s[i]}`;return`${e}\r
\r
`}encode(){return He.encode(this.toString())}static validHeaderValue(e){if(/[\r\n]/.test(e))throw new N("invalid header value - \\r and \\n are not allowed.",k.BadHeader);return e.trim()}keys(){const e=[];for(const t of this.headers.keys())e.push(t);return e}findKeys(e,t=Se.Exact){const s=this.keys();switch(t){case Se.Exact:return s.filter(i=>i===e);case Se.CanonicalMIME:return e=Sr(e),s.filter(i=>i===e);default:{const i=e.toLowerCase();return s.filter(n=>i===n.toLowerCase())}}}get(e,t=Se.Exact){const s=this.findKeys(e,t);if(s.length){const i=this.headers.get(s[0]);if(i)return Array.isArray(i)?i[0]:i}return""}last(e,t=Se.Exact){const s=this.findKeys(e,t);if(s.length){const i=this.headers.get(s[0]);if(i)return Array.isArray(i)?i[i.length-1]:i}return""}has(e,t=Se.Exact){return this.findKeys(e,t).length>0}set(e,t,s=Se.Exact){this.delete(e,s),this.append(e,t,s)}append(e,t,s=Se.Exact){const i=Sr(e);s===Se.CanonicalMIME&&(e=i);const n=this.findKeys(e,s);e=n.length>0?n[0]:e;const o=Ge.validHeaderValue(t);let a=this.headers.get(e);a||(a=[],this.headers.set(e,a)),a.push(o)}values(e,t=Se.Exact){const s=[];return this.findKeys(e,t).forEach(n=>{const o=this.headers.get(n);o&&s.push(...o)}),s}delete(e,t=Se.Exact){this.findKeys(e,t).forEach(i=>{this.headers.delete(i)})}get hasError(){return this._code>=300}get status(){return`${this._code} ${this._description}`.trim()}toRecord(){const e={};return this.keys().forEach(t=>{e[t]=this.values(t)}),e}get code(){return this._code}get description(){return this._description}static fromRecord(e){const t=new Ge;for(const s in e)t.headers.set(s,e[s]);return t}}function Ss(){return{encode(r){return He.encode(r)},decode(r){return xe.decode(r)}}}function ke(r){return{encode(e){try{return e===void 0&&(e=null),He.encode(JSON.stringify(e))}catch(t){throw N.errorForCode(k.BadJson,t)}},decode(e){try{return JSON.parse(xe.decode(e),r)}catch(t){throw N.errorForCode(k.BadJson,t)}}}}function vr(r){var e;return r&&r.data.length===0&&((e=r.headers)==null?void 0:e.code)===503?N.errorForCode(k.NoResponders):null}class vs{constructor(e,t,s){h(this,"_headers");h(this,"_msg");h(this,"_rdata");h(this,"_reply");h(this,"_subject");h(this,"publisher");this._msg=e,this._rdata=t,this.publisher=s}get subject(){return this._subject?this._subject:(this._subject=xe.decode(this._msg.subject),this._subject)}get reply(){return this._reply?this._reply:(this._reply=xe.decode(this._msg.reply),this._reply)}get sid(){return this._msg.sid}get headers(){if(this._msg.hdr>-1&&!this._headers){const e=this._rdata.subarray(0,this._msg.hdr);this._headers=Ge.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=we,t){return this.reply?(this.publisher.publish(this.reply,e,t),!0):!1}size(){var i;const e=this._msg.subject.length,t=((i=this._msg.reply)==null?void 0:i.length)||0,s=this._msg.size===-1?0:this._msg.size;return e+t+s}json(e){return ke(e).decode(this.data)}string(){return xe.decode(this.data)}requestInfo(){var t;const e=(t=this.headers)==null?void 0:t.get("Nats-Request-Info");return e?JSON.parse(e,function(s,i){return(s==="start"||s==="stop")&&i!==""?new Date(Date.parse(i)):i}):null}}h(vs,"jc");function rt(r){return Ht("durable",r)}function pe(r){return Ht("stream",r)}function Ht(r,e=""){if(e==="")throw Error(`${r} name required`);return[".","*",">","/","\\"," "," ",`
`,"\r"].forEach(s=>{if(e.indexOf(s)!==-1){switch(s){case`
`:s="\\n";break;case"\r":s="\\r";break;case" ":s="\\t";break}throw Error(`invalid ${r} name - ${r} name cannot contain '${s}'`)}}),""}function xt(r,e=""){if(e==="")throw Error(`${r} name required`);const t=Di(e);if(t.length)throw new Error(`invalid ${r} name - ${r} name ${t}`)}function Di(r=""){if(r==="")throw Error("name required");const e=/^[-\w]+$/g;if(r.match(e)===null){for(const s of r.split(""))if(s.match(e)===null)return`cannot contain '${s}'`}return""}function Es(r){if(r.data.length>0)return!1;const e=r.headers;return e?e.code>=100&&e.code<200:!1}function As(r){var e;return Es(r)&&((e=r.headers)==null?void 0:e.description)==="Idle Heartbeat"}function Hi(r,e,t){const s=Be(r,e),i={hdr:1,sid:0,size:0},n=new vs(i,we,{});return n._headers=s,n._subject=t,n}function it(r){if(r.data.length!==0)return null;const e=r.headers;return e?Er(e.code,e.description):null}var Oe;(function(r){r.MaxBatchExceeded="exceeded maxrequestbatch of",r.MaxExpiresExceeded="exceeded maxrequestexpires of",r.MaxBytesExceeded="exceeded maxrequestmaxbytes of",r.MaxMessageSizeExceeded="message size exceeds maxbytes",r.PushConsumer="consumer is push based",r.MaxWaitingExceeded="exceeded maxwaiting",r.IdleHeartbeatMissed="idle heartbeats missed",r.ConsumerDeleted="consumer deleted"})(Oe||(Oe={}));function Ji(r){return r.code!==k.JetStream409?!1:[Oe.MaxBatchExceeded,Oe.MaxExpiresExceeded,Oe.MaxBytesExceeded,Oe.MaxMessageSizeExceeded,Oe.PushConsumer,Oe.IdleHeartbeatMissed,Oe.ConsumerDeleted].find(t=>r.message.indexOf(t)!==-1)!==void 0}function Er(r,e=""){if(r<300)return null;switch(e=e.toLowerCase(),r){case 404:return new N(e,k.JetStream404NoMessages);case 408:return new N(e,k.JetStream408RequestTimeout);case 409:{const t=e.startsWith(Oe.IdleHeartbeatMissed)?k.JetStreamIdleHeartBeat:k.JetStream409;return new N(e,t)}case 503:return N.errorForCode(k.JetStreamNotEnabled,new Error(e));default:return e===""&&(e=k.Unknown),new N(e,`${r}`)}}class oe{constructor(){h(this,"inflight");h(this,"processed");h(this,"received");h(this,"noIterator");h(this,"iterClosed");h(this,"done");h(this,"signal");h(this,"yields");h(this,"filtered");h(this,"pendingFiltered");h(this,"ingestionFilterFn");h(this,"protocolFilterFn");h(this,"dispatchedFn");h(this,"ctx");h(this,"_data");h(this,"err");h(this,"time");h(this,"yielding");this.inflight=0,this.filtered=0,this.pendingFiltered=0,this.processed=0,this.received=0,this.noIterator=!1,this.done=!1,this.signal=V(),this.yields=[],this.iterClosed=V(),this.time=0,this.yielding=!1}[Symbol.asyncIterator](){return this.iterate()}push(e){if(this.done)return;if(typeof e=="function"){this.yields.push(e),this.signal.resolve();return}const{ingest:t,protocol:s}=this.ingestionFilterFn?this.ingestionFilterFn(e,this.ctx||this):{ingest:!0,protocol:!1};t&&(s&&(this.filtered++,this.pendingFiltered++),this.yields.push(e),this.signal.resolve())}async*iterate(){if(this.noIterator)throw new N("unsupported iterator",k.ApiError);if(this.yielding)throw new N("already yielding",k.ApiError);this.yielding=!0;try{for(;;){if(this.yields.length===0&&await this.signal,this.err)throw this.err;const e=this.yields;this.inflight=e.length,this.yields=[];for(let t=0;t<e.length;t++){if(typeof e[t]=="function"){const i=e[t];try{i()}catch(n){throw n}if(this.err)throw this.err;continue}if(this.protocolFilterFn?this.protocolFilterFn(e[t]):!0){this.processed++;const i=Date.now();yield e[t],this.time=Date.now()-i,this.dispatchedFn&&e[t]&&this.dispatchedFn(e[t])}else this.pendingFiltered--;this.inflight--}if(this.done)break;this.yields.length===0&&(e.length=0,this.yields=e,this.signal=V())}}finally{this.stop()}}stop(e){this.done||(this.err=e,this.done=!0,this.signal.resolve(),this.iterClosed.resolve(e))}getProcessed(){return this.noIterator?this.received:this.processed}getPending(){return this.yields.length+this.inflight-this.pendingFiltered}getReceived(){return this.received-this.filtered}}class Ps{constructor(e,t,s={maxOut:2}){h(this,"interval");h(this,"maxOut");h(this,"cancelAfter");h(this,"timer");h(this,"autoCancelTimer");h(this,"last");h(this,"missed");h(this,"count");h(this,"callback");this.interval=e,this.maxOut=(s==null?void 0:s.maxOut)||2,this.cancelAfter=(s==null?void 0:s.cancelAfter)||0,this.last=Date.now(),this.missed=0,this.count=0,this.callback=t,this._schedule()}cancel(){this.autoCancelTimer&&clearTimeout(this.autoCancelTimer),this.timer&&clearInterval(this.timer),this.timer=0,this.autoCancelTimer=0,this.missed=0}work(){this.last=Date.now(),this.missed=0}_change(e,t=0,s=2){this.interval=e,this.maxOut=s,this.cancelAfter=t,this.restart()}restart(){this.cancel(),this._schedule()}_schedule(){this.cancelAfter>0&&(this.autoCancelTimer=setTimeout(()=>{this.cancel()},this.cancelAfter)),this.timer=setInterval(()=>{if(this.count++,Date.now()-this.last>this.interval&&this.missed++,this.missed>=this.maxOut)try{this.callback(this.missed)===!0&&this.cancel()}catch(e){console.log(e)}},this.interval)}}var ks;(function(r){r.Limits="limits",r.Interest="interest",r.Workqueue="workqueue"})(ks||(ks={}));var St;(function(r){r.Old="old",r.New="new"})(St||(St={}));var Os;(function(r){r.File="file",r.Memory="memory"})(Os||(Os={}));var te;(function(r){r.All="all",r.Last="last",r.New="new",r.StartSequence="by_start_sequence",r.StartTime="by_start_time",r.LastPerSubject="last_per_subject"})(te||(te={}));var ae;(function(r){r.None="none",r.All="all",r.Explicit="explicit",r.NotSet=""})(ae||(ae={}));var nt;(function(r){r.Instant="instant",r.Original="original"})(nt||(nt={}));var Ve;(function(r){r.None="none",r.S2="s2"})(Ve||(Ve={}));var Jt;(function(r){r.CreateOrUpdate="",r.Update="update",r.Create="create"})(Jt||(Jt={}));function Ki(r,e={}){return Object.assign({name:r,deliver_policy:te.All,ack_policy:ae.Explicit,ack_wait:W(30*1e3),replay_policy:nt.Instant},e)}var Ar;(function(r){r.API="api_audit",r.StreamAction="stream_action",r.ConsumerAction="consumer_action",r.SnapshotCreate="snapshot_create",r.SnapshotComplete="snapshot_complete",r.RestoreCreate="restore_create",r.RestoreComplete="restore_complete",r.MaxDeliver="max_deliver",r.Terminated="terminated",r.Ack="consumer_ack",r.StreamLeaderElected="stream_leader_elected",r.StreamQuorumLost="stream_quorum_lost",r.ConsumerLeaderElected="consumer_leader_elected",r.ConsumerQuorumLost="consumer_quorum_lost"})(Ar||(Ar={}));var me;(function(r){r.StreamSourceHdr="Nats-Stream-Source",r.LastConsumerSeqHdr="Nats-Last-Consumer",r.LastStreamSeqHdr="Nats-Last-Stream",r.ConsumerStalledHdr="Nats-Consumer-Stalled",r.MessageSizeHdr="Nats-Msg-Size",r.RollupHdr="Nats-Rollup",r.RollupValueSubject="sub",r.RollupValueAll="all",r.PendingMessagesHdr="Nats-Pending-Messages",r.PendingBytesHdr="Nats-Pending-Bytes"})(me||(me={}));var Re;(function(r){r.LastValue="",r.AllHistory="history",r.UpdatesOnly="updates"})(Re||(Re={}));var ot;(function(r){r.Stream="Nats-Stream",r.Sequence="Nats-Sequence",r.TimeStamp="Nats-Time-Stamp",r.Subject="Nats-Subject"})(ot||(ot={}));var Pr;(function(r){r.Stream="Nats-Stream",r.Subject="Nats-Subject",r.Sequence="Nats-Sequence",r.LastSequence="Nats-Last-Sequence",r.Size="Nats-Msg-Size"})(Pr||(Pr={}));const ve="KV_";class zi{constructor(e){h(this,"config");h(this,"ordered");h(this,"mack");h(this,"stream");h(this,"callbackFn");h(this,"max");h(this,"qname");h(this,"isBind");h(this,"filters");this.stream="",this.mack=!1,this.ordered=!1,this.config=Ki("",e||{})}getOpts(){var t;const e={};if(e.config=Object.assign({},this.config),e.config.filter_subject&&(this.filterSubject(e.config.filter_subject),e.config.filter_subject=void 0),e.config.filter_subjects&&((t=e.config.filter_subjects)==null||t.forEach(s=>{this.filterSubject(s)}),e.config.filter_subjects=void 0),e.mack=this.mack,e.stream=this.stream,e.callbackFn=this.callbackFn,e.max=this.max,e.queue=this.qname,e.ordered=this.ordered,e.config.ack_policy=e.ordered?ae.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 rt(e),this.config.durable_name=e,this}startSequence(e){if(e<=0)throw new Error("sequence must be greater than 0");return this.config.deliver_policy=te.StartSequence,this.config.opt_start_seq=e,this}startTime(e){return this.config.deliver_policy=te.StartTime,this.config.opt_start_time=e.toISOString(),this}deliverAll(){return this.config.deliver_policy=te.All,this}deliverLastPerSubject(){return this.config.deliver_policy=te.LastPerSubject,this}deliverLast(){return this.config.deliver_policy=te.Last,this}deliverNew(){return this.config.deliver_policy=te.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=ae.None,this}ackAll(){return this.config.ack_policy=ae.All,this}ackExplicit(){return this.config.ack_policy=ae.Explicit,this}ackWait(e){return this.config.ack_wait=W(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=nt.Instant,this}replayOriginal(){return this.config.replay_policy=nt.Original,this}sample(e){if(e=Math.trunc(e),e<0||e>100)throw new Error("value must be between 0-100");return this.config.sample_freq=`${e}%`,this}limit(e){return this.config.rate_limit_bps=e,this}maxWaiting(e){return this.config.max_waiting=e,this}maxAckPending(e){return this.config.max_ack_pending=e,this}idleHeartbeat(e){return this.config.idle_heartbeat=W(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=W(e),this}maxPullBatch(e){return this.config.max_batch=e,this}maxPullRequestExpires(e){return this.config.max_expires=W(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 We(r){return new zi(r)}function kr(r){return typeof r.getOpts=="function"}class Gi{static encode(e){if(typeof e=="string")return btoa(e);const t=Array.from(e);return btoa(String.fromCharCode(...t))}static decode(e,t=!1){const s=atob(e);return t?Uint8Array.from(s,i=>i.charCodeAt(0)):s}}class at{static encode(e){return at.toB64URLEncoding(Gi.encode(e))}static decode(e,t=!1){return at.decode(at.fromB64URLEncoding(e),t)}static toB64URLEncoding(e){return e.replace(/\+/g,"-").replace(/\//g,"_")}static fromB64URLEncoding(e){return e.replace(/_/g,"/").replace(/-/g,"+")}}class ct{constructor(){h(this,"buffers");h(this,"byteLength");this.buffers=[],this.byteLength=0}static concat(...e){let t=0;for(let n=0;n<e.length;n++)t+=e[n].length;const s=new Uint8Array(t);let i=0;for(let n=0;n<e.length;n++)s.set(e[n],i),i+=e[n].length;return s}static fromAscii(e){return e||(e=""),He.encode(e)}static toAscii(e){return xe.decode(e)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){const e=new Uint8Array(this.byteLength);let t=0;for(let s=0;s<this.buffers.length;s++)e.set(this.buffers[s],t),t+=this.buffers[s].length;this.buffers.length=0,this.buffers.push(e)}}shift(){if(this.buffers.length){const e=this.buffers.shift();if(e)return this.byteLength-=e.length,e}return new Uint8Array(0)}drain(e){if(this.buffers.length){this.pack();const t=this.buffers.pop();if(t){const s=this.byteLength;(e===void 0||e>s)&&(e=s);const i=t.subarray(0,e);return s>e&&this.buffers.push(t.subarray(e)),this.byteLength=s-e,i}}return new Uint8Array(0)}fill(e,...t){e&&(this.buffers.push(e),this.byteLength+=e.length);for(let s=0;s<t.length;s++)t[s]&&t[s].length&&(this.buffers.push(t[s]),this.byteLength+=t[s].length)}peek(){return this.buffers.length?(this.pack(),this.buffers[0]):new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}function Vi(r,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(s){if(s!=="default"&&!(s in r)){var i=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(r,s,i.get?i:{enumerable:!0,get:function(){return t[s]}})}})}),Object.freeze(r)}var Wi=typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{},vt=Wi.performance||{};vt.now||vt.mozNow||vt.msNow||vt.oNow||vt.webkitNow;var Or={versions:{}},Yi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Xi(r){if(r.__esModule)return r;var e=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(r).forEach(function(t){var s=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:function(){return r[t]}})}),e}var Cs,Kt={exports:{}},Cr={},Ir=Xi(Vi({__proto__:null,default:Cr},[Cr]));Cs=Kt,function(){var r="input is invalid type",e=typeof window=="object",t=e?window:{};t.JS_SHA256_NO_WINDOW&&(e=!1);var s=!e&&typeof self=="object",i=!t.JS_SHA256_NO_NODE_JS&&Or.versions&&Or.versions.node;i?t=Yi:s&&(t=self);var n=!t.JS_SHA256_NO_COMMON_JS&&Cs.exports,o=!t.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",a="0123456789abcdef".split(""),f=[-2147483648,8388608,32768,128],p=[24,16,8,0],g=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],y=["hex","array","digest","arrayBuffer"],x=[];!t.JS_SHA256_NO_NODE_JS&&Array.isArray||(Array.isArray=function(w){return Object.prototype.toString.call(w)==="[object Array]"}),!o||!t.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(w){return typeof w=="object"&&w.buffer&&w.buffer.constructor===ArrayBuffer});var A=function(w,j){return function(F){return new L(j,!0).update(F)[w]()}},I=function(w){var j=A("hex",w);i&&(j=T(j,w)),j.create=function(){return new L(w)},j.update=function(P){return j.create().update(P)};for(var F=0;F<y.length;++F){var R=y[F];j[R]=A(R,w)}return j},T=function(w,j){var F,R=Ir,P=Ir.Buffer,U=j?"sha224":"sha256";return F=P.from&&!t.JS_SHA256_NO_BUFFER_FROM?P.from:function(q){return new P(q)},function(q){if(typeof q=="string")return R.createHash(U).update(q,"utf8").digest("hex");if(q==null)throw new Error(r);return q.constructor===ArrayBuffer&&(q=new Uint8Array(q)),Array.isArray(q)||ArrayBuffer.isView(q)||q.constructor===P?R.createHash(U).update(F(q)).digest("hex"):w(q)}},J=function(w,j){return function(F,R){return new ee(F,j,!0).update(R)[w]()}},se=function(w){var j=J("hex",w);j.create=function(P){return new ee(P,w)},j.update=function(P,U){return j.create(P).update(U)};for(var F=0;F<y.length;++F){var R=y[F];j[R]=J(R,w)}return j};function L(w,j){j?(x[0]=x[16]=x[1]=x[2]=x[3]=x[4]=x[5]=x[6]=x[7]=x[8]=x[9]=x[10]=x[11]=x[12]=x[13]=x[14]=x[15]=0,this.blocks=x):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],w?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=w}function ee(w,j,F){var R,P=typeof w;if(P==="string"){var U,q=[],$=w.length,Y=0;for(R=0;R<$;++R)(U=w.charCodeAt(R))<128?q[Y++]=U:U<2048?(q[Y++]=192|U>>>6,q[Y++]=128|63&U):U<55296||U>=57344?(q[Y++]=224|U>>>12,q[Y++]=128|U>>>6&63,q[Y++]=128|63&U):(U=65536+((1023&U)<<10|1023&w.charCodeAt(++R)),q[Y++]=240|U>>>18,q[Y++]=128|U>>>12&63,q[Y++]=128|U>>>6&63,q[Y++]=128|63&U);w=q}else{if(P!=="object")throw new Error(r);if(w===null)throw new Error(r);if(o&&w.constructor===ArrayBuffer)w=new Uint8Array(w);else if(!(Array.isArray(w)||o&&ArrayBuffer.isView(w)))throw new Error(r)}w.length>64&&(w=new L(j,!0).update(w).array());var ie=[],ce=[];for(R=0;R<64;++R){var ne=w[R]||0;ie[R]=92^ne,ce[R]=54^ne}L.call(this,j,F),this.update(ce),this.oKeyPad=ie,this.inner=!0,this.sharedMemory=F}L.prototype.update=function(w){if(!this.finalized){var j,F=typeof w;if(F!=="string"){if(F!=="object")throw new Error(r);if(w===null)throw new Error(r);if(o&&w.constructor===ArrayBuffer)w=new Uint8Array(w);else if(!(Array.isArray(w)||o&&ArrayBuffer.isView(w)))throw new Error(r);j=!0}for(var R,P,U=0,q=w.length,$=this.blocks;U<q;){if(this.hashed&&(this.hashed=!1,$[0]=this.block,this.block=$[16]=$[1]=$[2]=$[3]=$[4]=$[5]=$[6]=$[7]=$[8]=$[9]=$[10]=$[11]=$[12]=$[13]=$[14]=$[15]=0),j)for(P=this.start;U<q&&P<64;++U)$[P>>>2]|=w[U]<<p[3&P++];else for(P=this.start;U<q&&P<64;++U)(R=w.charCodeAt(U))<128?$[P>>>2]|=R<<p[3&P++]:R<2048?($[P>>>2]|=(192|R>>>6)<<p[3&P++],$[P>>>2]|=(128|63&R)<<p[3&P++]):R<55296||R>=57344?($[P>>>2]|=(224|R>>>12)<<p[3&P++],$[P>>>2]|=(128|R>>>6&63)<<p[3&P++],$[P>>>2]|=(128|63&R)<<p[3&P++]):(R=65536+((1023&R)<<10|1023&w.charCodeAt(++U)),$[P>>>2]|=(240|R>>>18)<<p[3&P++],$[P>>>2]|=(128|R>>>12&63)<<p[3&P++],$[P>>>2]|=(128|R>>>6&63)<<p[3&P++],$[P>>>2]|=(128|63&R)<<p[3&P++]);this.lastByteIndex=P,this.bytes+=P-this.start,P>=64?(this.block=$[16],this.start=P-64,this.hash(),this.hashed=!0):this.start=P}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this}},L.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var w=this.blocks,j=this.lastByteIndex;w[16]=this.block,w[j>>>2]|=f[3&j],this.block=w[16],j>=56&&(this.hashed||this.hash(),w[0]=this.block,w[16]=w[1]=w[2]=w[3]=w[4]=w[5]=w[6]=w[7]=w[8]=w[9]=w[10]=w[11]=w[12]=w[13]=w[14]=w[15]=0),w[14]=this.hBytes<<3|this.bytes>>>29,w[15]=this.bytes<<3,this.hash()}},L.prototype.hash=function(){var w,j,F,R,P,U,q,$,Y,ie=this.h0,ce=this.h1,ne=this.h2,he=this.h3,fe=this.h4,de=this.h5,X=this.h6,re=this.h7,ue=this.blocks;for(w=16;w<64;++w)j=((P=ue[w-15])>>>7|P<<25)^(P>>>18|P<<14)^P>>>3,F=((P=ue[w-2])>>>17|P<<15)^(P>>>19|P<<13)^P>>>10,ue[w]=ue[w-16]+j+ue[w-7]+F|0;for(Y=ce&ne,w=0;w<64;w+=4)this.first?(this.is224?(U=300032,re=(P=ue[0]-1413257819)-150054599|0,he=P+24177077|0):(U=704751109,re=(P=ue[0]-210244248)-1521486534|0,he=P+143694565|0),this.first=!1):(j=(ie>>>2|ie<<30)^(ie>>>13|ie<<19)^(ie>>>22|ie<<10),R=(U=ie&ce)^ie&ne^Y,re=he+(P=re+(F=(fe>>>6|fe<<26)^(fe>>>11|fe<<21)^(fe>>>25|fe<<7))+(fe&de^~fe&X)+g[w]+ue[w])|0,he=P+(j+R)|0),j=(he>>>2|he<<30)^(he>>>13|he<<19)^(he>>>22|he<<10),R=(q=he&ie)^he&ce^U,X=ne+(P=X+(F=(re>>>6|re<<26)^(re>>>11|re<<21)^(re>>>25|re<<7))+(re&fe^~re&de)+g[w+1]+ue[w+1])|0,j=((ne=P+(j+R)|0)>>>2|ne<<30)^(ne>>>13|ne<<19)^(ne>>>22|ne<<10),R=($=ne&he)^ne&ie^q,de=ce+(P=de+(F=(X>>>6|X<<26)^(X>>>11|X<<21)^(X>>>25|X<<7))+(X&re^~X&fe)+g[w+2]+ue[w+2])|0,j=((ce=P+(j+R)|0)>>>2|ce<<30)^(ce>>>13|ce<<19)^(ce>>>22|ce<<10),R=(Y=ce&ne)^ce&he^$,fe=ie+(P=fe+(F=(de>>>6|de<<26)^(de>>>11|de<<21)^(de>>>25|de<<7))+(de&X^~de&re)+g[w+3]+ue[w+3])|0,ie=P+(j+R)|0,this.chromeBugWorkAround=!0;this.h0=this.h0+ie|0,this.h1=this.h1+ce|0,this.h2=this.h2+ne|0,this.h3=this.h3+he|0,this.h4=this.h4+fe|0,this.h5=this.h5+de|0,this.h6=this.h6+X|0,this.h7=this.h7+re|0},L.prototype.hex=function(){this.finalize();var w=this.h0,j=this.h1,F=this.h2,R=this.h3,P=this.h4,U=this.h5,q=this.h6,$=this.h7,Y=a[w>>>28&15]+a[w>>>24&15]+a[w>>>20&15]+a[w>>>16&15]+a[w>>>12&15]+a[w>>>8&15]+a[w>>>4&15]+a[15&w]+a[j>>>28&15]+a[j>>>24&15]+a[j>>>20&15]+a[j>>>16&15]+a[j>>>12&15]+a[j>>>8&15]+a[j>>>4&15]+a[15&j]+a[F>>>28&15]+a[F>>>24&15]+a[F>>>20&15]+a[F>>>16&15]+a[F>>>12&15]+a[F>>>8&15]+a[F>>>4&15]+a[15&F]+a[R>>>28&15]+a[R>>>24&15]+a[R>>>20&15]+a[R>>>16&15]+a[R>>>12&15]+a[R>>>8&15]+a[R>>>4&15]+a[15&R]+a[P>>>28&15]+a[P>>>24&15]+a[P>>>20&15]+a[P>>>16&15]+a[P>>>12&15]+a[P>>>8&15]+a[P>>>4&15]+a[15&P]+a[U>>>28&15]+a[U>>>24&15]+a[U>>>20&15]+a[U>>>16&15]+a[U>>>12&15]+a[U>>>8&15]+a[U>>>4&15]+a[15&U]+a[q>>>28&15]+a[q>>>24&15]+a[q>>>20&15]+a[q>>>16&15]+a[q>>>12&15]+a[q>>>8&15]+a[q>>>4&15]+a[15&q];return this.is224||(Y+=a[$>>>28&15]+a[$>>>24&15]+a[$>>>20&15]+a[$>>>16&15]+a[$>>>12&15]+a[$>>>8&15]+a[$>>>4&15]+a[15&$]),Y},L.prototype.toString=L.prototype.hex,L.prototype.digest=function(){this.finalize();var w=this.h0,j=this.h1,F=this.h2,R=this.h3,P=this.h4,U=this.h5,q=this.h6,$=this.h7,Y=[w>>>24&255,w>>>16&255,w>>>8&255,255&w,j>>>24&255,j>>>16&255,j>>>8&255,255&j,F>>>24&255,F>>>16&255,F>>>8&255,255&F,R>>>24&255,R>>>16&255,R>>>8&255,255&R,P>>>24&255,P>>>16&255,P>>>8&255,255&P,U>>>24&255,U>>>16&255,U>>>8&255,255&U,q>>>24&255,q>>>16&255,q>>>8&255,255&q];return this.is224||Y.push($>>>24&255,$>>>16&255,$>>>8&255,255&$),Y},L.prototype.array=L.prototype.digest,L.prototype.arrayBuffer=function(){this.finalize();var w=new ArrayBuffer(this.is224?28:32),j=new DataView(w);return j.setUint32(0,this.h0),j.setUint32(4,this.h1),j.setUint32(8,this.h2),j.setUint32(12,this.h3),j.setUint32(16,this.h4),j.setUint32(20,this.h5),j.setUint32(24,this.h6),this.is224||j.setUint32(28,this.h7),w},ee.prototype=new L,ee.prototype.finalize=function(){if(L.prototype.finalize.call(this),this.inner){this.inner=!1;var w=this.array();L.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(w),L.prototype.finalize.call(this)}};var _e=I();_e.sha256=_e,_e.sha224=I(!0),_e.sha256.hmac=se(),_e.sha224.hmac=se(!0),n?Cs.exports=_e:(t.sha256=_e.sha256,t.sha224=_e.sha224)}(),Kt.exports,Kt.exports.sha224;var jr=Kt.exports.sha256;function Is(r){return rn(r)}function Zi(r){if(!/^[0-9A-Fa-f]+$/.test(r))return!1;const t=/^[0-9A-F]+$/.test(r),s=/^[0-9a-f]+$/.test(r);return t||s?r.length%2===0:!1}function Qi(r){return/^[A-Za-z0-9\-_]*(={0,2})?$/.test(r)||/^[A-Za-z0-9+/]*(={0,2})?$/.test(r)}function en(r){return Zi(r)?"hex":Qi(r)?"b64":""}function tn(r){if(r.length%2!==0)throw new Error("hex string must have an even length");const e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.substring(t,t+2),16);return e}function sn(r){r=r.replace(/-/g,"+"),r=r.replace(/_/g,"/");const e=atob(r);return Uint8Array.from(e,t=>t.charCodeAt(0))}function rn(r){switch(en(r)){case"hex":return tn(r);case"b64":return sn(r)}return null}function nn(r,e){const t=typeof r=="string"?Is(r):r,s=typeof e=="string"?Is(e):e;if(t===null||s===null||t.length!==s.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==s[i])return!1;return!0}class Rr{constructor(e,t,s=!0){h(this,"token");h(this,"received");h(this,"ctx");h(this,"requestSubject");h(this,"mux");this.mux=e,this.requestSubject=t,this.received=0,this.token=Je.next(),s&&(this.ctx=new Error)}}class on extends Rr{constructor(t,s,i={maxWait:1e3}){super(t,s);h(this,"callback");h(this,"done");h(this,"timer");h(this,"max");h(this,"opts");if(this.opts=i,typeof this.opts.callback!="function")throw new Error("callback is required");this.callback=this.opts.callback,this.max=typeof i.maxMessages=="number"&&i.maxMessages>0?i.maxMessages:-1,this.done=V(),this.done.then(()=>{this.callback(null,null)}),this.timer=setTimeout(()=>{this.cancel()},i.maxWait)}cancel(t){t&&this.callback(t,null),clearTimeout(this.timer),this.mux.cancel(this),this.done.resolve()}resolver(t,s){t?(this.ctx&&(t.stack+=`
${this.ctx.stack}`),this.cancel(t)):(this.callback(null,s),this.opts.strategy===je.Count&&(this.max--,this.max===0&&this.cancel()),this.opts.strategy===je.JitterTimer&&(clearTimeout(this.timer),this.timer=setTimeout(()=>{this.cancel()},this.opts.jitter||300)),this.opts.strategy===je.SentinelMsg&&s&&s.data.length===0&&this.cancel())}}class Nr extends Rr{constructor(t,s,i={timeout:1e3},n=!0){super(t,s,n);h(this,"deferred");h(this,"timer");this.deferred=V(),this.timer=tt(i.timeout,n)}resolver(t,s){this.timer&&this.timer.cancel(),t?(this.ctx&&(t.stack+=`
${this.ctx.stack}`),this.deferred.reject(t)):this.deferred.resolve(s),this.cancel()}cancel(t){this.timer&&this.timer.cancel(),this.mux.cancel(this),this.deferred.reject(t||N.errorForCode(k.Cancelled))}}const an="$JS.API";function cn(r){return r=r||{},r.domain&&(r.apiPrefix=`$JS.${r.domain}.API`,delete r.domain),Bt({apiPrefix:an,timeout:5e3},r)}class Et{constructor(e,t){h(this,"nc");h(this,"opts");h(this,"prefix");h(this,"timeout");h(this,"jc");this.nc=e,this.opts=cn(t),this._parseOpts(),this.prefix=this.opts.apiPrefix,this.timeout=this.opts.timeout,this.jc=ke()}getOptions(){return Object.assign({},this.opts)}_parseOpts(){let e=this.opts.apiPrefix;if(!e||e.length===0)throw new Error("invalid empty prefix");e[e.length-1]==="."&&(e=e.substr(0,e.length-1)),this.opts.apiPrefix=e}async _request(e,t=null,s){s=s||{},s.timeout=this.timeout;let i=we;t&&(i=this.jc.encode(t));let{retries:n}=s;n=n||1