UNPKG

@jokio/sdk

Version:

pure js/ts sdk for building decentralised localfirst web apps. Provides tts ai model integrations, realtime p2p communication & crypto encryptions.

1,648 lines 281 kB
var Mi = Object.defineProperty; var Ui = (r, e, t) => e in r ? Mi(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t; var h = (r, e, t) => Ui(r, typeof e != "symbol" ? e + "" : e, t); function Me(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 Zt(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 Ys() { return $i.stubThis((globalThis == null ? void 0 : globalThis.PublicKeyCredential) !== void 0 && typeof globalThis.PublicKeyCredential == "function"); } const $i = { stubThis: (r) => r }; function Gr(r) { const { id: e } = r; return { ...r, id: Zt(e), /** * `descriptor.transports` is an array of our `AuthenticatorTransportFuture` that includes newer * transports that TypeScript's DOM lib is ignorant of. Convince TS that our list of transports * are fine to pass to WebAuthn since browsers will recognize the new value. */ transports: r.transports }; } function Vr(r) { return ( // Consider localhost valid as well since it's okay wrt Secure Contexts r === "localhost" || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(r) ); } class fe 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 Li({ 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 fe({ 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 fe({ message: "Discoverable credentials were required but no available authenticator supported it", code: "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT", cause: r }); if ( // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024 e.mediation === "conditional" && ((i = t.authenticatorSelection) == null ? void 0 : i.userVerification) === "required" ) return new fe({ 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 fe({ 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 fe({ message: "The authenticator was previously registered", code: "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED", cause: r }); if (r.name === "NotAllowedError") return new fe({ 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 fe({ message: 'No entry in pubKeyCredParams was of type "public-key"', code: "ERROR_MALFORMED_PUBKEYCREDPARAMS", cause: r }) : new fe({ 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 (Vr(o)) { if (t.rp.id !== o) return new fe({ message: `The RP ID "${t.rp.id}" is invalid for this domain`, code: "ERROR_INVALID_RP_ID", cause: r }); } else return new fe({ 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 fe({ 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 fe({ 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 qi { 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 Wr = new qi(), Fi = ["cross-platform", "platform"]; function Yr(r) { if (r && !(Fi.indexOf(r) < 0)) return r; } async function Bi(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 (!Ys()) throw new Error("WebAuthn is not supported in this browser"); const s = { ...e, challenge: Zt(e.challenge), user: { ...e.user, id: Zt(e.user.id) }, excludeCredentials: (I = e.excludeCredentials) == null ? void 0 : I.map(Gr) }, i = {}; t && (i.mediation = "conditional"), i.publicKey = s, i.signal = Wr.createNewAbortSignal(); let n; try { n = await navigator.credentials.create(i); } catch (N) { throw Li({ error: N, 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 (N) { Es("getPublicKeyAlgorithm()", N); } let x; if (typeof f.getPublicKey == "function") try { const N = f.getPublicKey(); N !== null && (x = Me(N)); } catch (N) { Es("getPublicKey()", N); } let A; if (typeof f.getAuthenticatorData == "function") try { A = Me(f.getAuthenticatorData()); } catch (N) { Es("getAuthenticatorData()", N); } return { id: o, rawId: Me(a), response: { attestationObject: Me(f.attestationObject), clientDataJSON: Me(f.clientDataJSON), transports: g, publicKeyAlgorithm: y, publicKey: x, authenticatorData: A }, type: p, clientExtensionResults: n.getClientExtensionResults(), authenticatorAttachment: Yr(n.authenticatorAttachment) }; } function Es(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 Di() { if (!Ys()) return As.stubThis(new Promise((e) => e(!1))); const r = globalThis.PublicKeyCredential; return (r == null ? void 0 : r.isConditionalMediationAvailable) === void 0 ? As.stubThis(new Promise((e) => e(!1))) : As.stubThis(r.isConditionalMediationAvailable()); } const As = { stubThis: (r) => r }; function Hi({ 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 fe({ message: "Authentication ceremony was sent an abort signal", code: "ERROR_CEREMONY_ABORTED", cause: r }); } else { if (r.name === "NotAllowedError") return new fe({ message: r.message, code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", cause: r }); if (r.name === "SecurityError") { const s = globalThis.location.hostname; if (Vr(s)) { if (t.rpId !== s) return new fe({ message: `The RP ID "${t.rpId}" is invalid for this domain`, code: "ERROR_INVALID_RP_ID", cause: r }); } else return new fe({ message: `${globalThis.location.hostname} is an invalid domain`, code: "ERROR_INVALID_DOMAIN", cause: r }); } else if (r.name === "UnknownError") return new fe({ 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 Ji(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 (!Ys()) 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(Gr)); const n = { ...e, challenge: Zt(e.challenge), allowCredentials: i }, o = {}; if (t) { if (!await Di()) 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 = Wr.createNewAbortSignal(); let a; try { a = await navigator.credentials.get(o); } catch (N) { throw Hi({ error: N, 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 = Me(g.userHandle)), { id: f, rawId: Me(p), response: { authenticatorData: Me(g.authenticatorData), clientDataJSON: Me(g.clientDataJSON), signature: Me(g.signature), userHandle: x }, type: y, clientExtensionResults: a.getClientExtensionResults(), authenticatorAttachment: Yr(a.authenticatorAttachment) }; } const yt = "ACCESS_TOKEN", _r = "SESSION_SEED", wt = "LAST_AUTH_DATA"; class Xr { 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(xt); } async completeEmailLogin(e, t) { var i; const s = await fetch( this.options.authUrl + `/email-verification-complete/${e}/${t}`, { headers: await this.getAuthHeader() } ).then(xt); return await this.options.storage.setItem( yt, s.accessToken ), await this.options.storage.setItem(wt, 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(xt); let o; try { (f = n.user) != null && f.id ? o = await Bi({ optionsJSON: n }) : o = await Ji({ 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(xt); return await this.options.storage.setItem( yt, a.accessToken ), await this.options.storage.setItem(wt, 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(xt); return await this.options.storage.setItem( yt, e.accessToken ), await this.options.storage.setItem( _r, e.sessionSeed ), await this.options.storage.setItem(wt, e.jwtData), (t = this.onUserDataUpdate) == null || t.call(this, e.jwtData), e.jwtData; } signOut() { var e; this.options.storage.removeItem(yt), this.options.storage.removeItem(wt), (e = this.onUserDataUpdate) == null || e.call(this, null); } getLastLoginData() { return this.options.storage.getItem( wt ); } getAccessToken() { return this.options.storage.getItem(yt); } getSessionSeed() { return this.options.storage.getItem(_r); } async getAuthHeader() { const e = await this.getAccessToken(); if (e) return { authorization: "bearer " + e }; } } const xt = async (r) => { const e = await r.json(); if (!r.ok) throw new Error(e.message); return e; }, Ps = (r) => [...r].map((e) => e.toString(16).padStart(2, "0")).join(""), yr = (r) => new Uint8Array( r.match(/.{1,2}/g).map((e) => parseInt(e, 16)) ), wr = (r) => btoa(String.fromCharCode(...new Uint8Array(r))), Ki = (r) => Uint8Array.from(atob(r), (e) => e.charCodeAt(0)).buffer, zi = async (r) => await crypto.subtle.digest("SHA-256", r), Gi = new TextEncoder(); class Vi { async createSessionKeyPair() { return await crypto.subtle.generateKey( { name: "ECDH", namedCurve: "P-256" }, !1, // non-extractable private key ["deriveKey", "deriveBits"] ); } async exportPublicKey(e) { const t = await crypto.subtle.exportKey("spki", e); return wr(t); } async deriveAESKey(e, t) { const s = Ki(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 Ps(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 `${Ps(new Uint8Array(n))}_${Ps(s)}`; } async decrypt(e, t) { const s = e.split("_"), i = yr(s[0]).buffer, n = yr(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 zi(Gi.encode(e).buffer); return wr(t); } } const ve = new Uint8Array(0), We = new TextEncoder(), xe = new TextDecoder(); function Wi(...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 Pt(...r) { const e = []; for (let t = 0; t < r.length; t++) e.push(We.encode(r[t])); return e.length === 0 ? ve : e.length === 1 ? e[0] : Wi(...e); } function xr(r) { return !r || r.length === 0 ? "" : xe.decode(r); } const Sr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", vr = 36, Yi = 3656158440062976, Er = 33, Xi = 333, Ar = 22; function Zi(r) { for (let e = 0; e < r.length; e++) r[e] = Math.floor(Math.random() * 255); } function Qi(r) { var e; (e = globalThis == null ? void 0 : globalThis.crypto) != null && e.getRandomValues ? globalThis.crypto.getRandomValues(r) : Zi(r); } class en { constructor() { h(this, "buf"); h(this, "seq"); h(this, "inc"); h(this, "inited"); this.buf = new Uint8Array(Ar), this.inited = !1; } init() { this.inited = !0, this.setPre(), this.initSeqAndInc(), this.fillSeq(); } initSeqAndInc() { this.seq = Math.floor(Math.random() * Yi), this.inc = Math.floor(Math.random() * (Xi - Er) + Er); } setPre() { const e = new Uint8Array(12); Qi(e); for (let t = 0; t < 12; t++) { const s = e[t] % 36; this.buf[t] = Sr.charCodeAt(s); } } fillSeq() { let e = this.seq; for (let t = Ar - 1; t >= 12; t--) this.buf[t] = Sr.charCodeAt(e % vr), e = Math.floor(e / vr); } next() { return this.inited || this.init(), this.seq += this.inc, this.seq > 3656158440062976 && (this.setPre(), this.initSeqAndInc()), this.fillSeq(), String.fromCharCode.apply(String, this.buf); } reset() { this.init(); } } const Ge = new en(); var ke; (function(r) { r.Disconnect = "disconnect", r.Reconnect = "reconnect", r.Update = "update", r.LDM = "ldm", r.Error = "error"; })(ke || (ke = {})); var He; (function(r) { r.Reconnecting = "reconnecting", r.PingTimer = "pingTimer", r.StaleConnection = "staleConnection", r.ClientInitiatedReconnect = "client initiated reconnect"; })(He || (He = {})); 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 tn(r) { return typeof r.code == "string"; } class Zr { constructor() { h(this, "messages"); this.messages = /* @__PURE__ */ 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 sn.getMessage(e); } getMessage(e) { return this.messages.get(e) || e; } } const sn = new Zr(); class T 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 = Zr.getMessage(t); return new T(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 ye; (function(r) { r[r.Exact = 0] = "Exact", r[r.CanonicalMIME = 1] = "CanonicalMIME", r[r.IgnoreCase = 2] = "IgnoreCase"; })(ye || (ye = {})); var Ne; (function(r) { r.Timer = "timer", r.Count = "count", r.JitterTimer = "jitterTimer", r.SentinelMsg = "sentinelMsg"; })(Ne || (Ne = {})); var kt; (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"; })(kt || (kt = {})); const Qt = "Nats-Service-Error", es = "Nats-Service-Error-Code"; class ts extends Error { constructor(t, s) { super(s); h(this, "code"); this.code = t; } static isServiceError(t) { return ts.toServiceError(t) !== null; } static toServiceError(t) { var i, n; const s = ((i = t == null ? void 0 : t.headers) == null ? void 0 : i.get(es)) || ""; if (s !== "") { const o = parseInt(s) || 400, a = ((n = t == null ? void 0 : t.headers) == null ? void 0 : n.get(Qt)) || ""; return new ts(o, a.length ? a : s); } return null; } } function qe(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}.${Ge.next()}`; } const Ms = "127.0.0.1"; var Je; (function(r) { r.PING = "PING", r.STATS = "STATS", r.INFO = "INFO"; })(Je || (Je = {})); function cs(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 Kt(r) { return xe.decode(r).replace(/\n/g, "␊").replace(/\r/g, "␍"); } function ut(r, e = !0) { const t = e ? T.errorForCode(k.Timeout) : null; let s, i; const n = new Promise((o, a) => { s = { cancel: () => { i && clearTimeout(i); } }, i = setTimeout(() => { a(t === null ? T.errorForCode(k.Timeout) : t); }, r); }); return Object.assign(n, s); } function dt(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 Y() { let r = {}; const e = new Promise((t, s) => { r = { resolve: t, reject: s }; }); return Object.assign(e, r); } function Qr(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 rn(r) { return r === 0 ? 0 : Math.floor(r / 2 + Math.random() * r); } function Xs(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 rn(t > e ? r[e] : r[t]); } }; } function W(r) { return r * 1e6; } function Zs(r) { return Math.floor(r / 1e6); } function Pr(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 T(`'${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 Fe(r = 0, e = "") { if (r === 0 && e !== "" || r > 0 && e === "") throw new Error("setting status requires both code and description"); return new Ke(r, e); } const ks = "NATS/1.0"; class Ke { constructor(e = 0, t = "") { h(this, "_code"); h(this, "headers"); h(this, "_description"); this._code = e, this._description = t, this.headers = /* @__PURE__ */ 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 Ke(), i = xe.decode(e).split(`\r `), n = i[0]; if (n !== ks) { let o = n.replace(ks, "").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 = ks; 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 We.encode(this.toString()); } static validHeaderValue(e) { if (/[\r\n]/.test(e)) throw new T("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 = ye.Exact) { const s = this.keys(); switch (t) { case ye.Exact: return s.filter((i) => i === e); case ye.CanonicalMIME: return e = Pr(e), s.filter((i) => i === e); default: { const i = e.toLowerCase(); return s.filter((n) => i === n.toLowerCase()); } } } get(e, t = ye.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 = ye.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 = ye.Exact) { return this.findKeys(e, t).length > 0; } set(e, t, s = ye.Exact) { this.delete(e, s), this.append(e, t, s); } append(e, t, s = ye.Exact) { const i = Pr(e); s === ye.CanonicalMIME && (e = i); const n = this.findKeys(e, s); e = n.length > 0 ? n[0] : e; const o = Ke.validHeaderValue(t); let a = this.headers.get(e); a || (a = [], this.headers.set(e, a)), a.push(o); } values(e, t = ye.Exact) { const s = []; return this.findKeys(e, t).forEach((n) => { const o = this.headers.get(n); o && s.push(...o); }), s; } delete(e, t = ye.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 Ke(); for (const s in e) t.headers.set(s, e[s]); return t; } } function Us() { return { encode(r) { return We.encode(r); }, decode(r) { return xe.decode(r); } }; } function Oe(r) { return { encode(e) { try { return e === void 0 && (e = null), We.encode(JSON.stringify(e)); } catch (t) { throw T.errorForCode(k.BadJson, t); } }, decode(e) { try { return JSON.parse(xe.decode(e), r); } catch (t) { throw T.errorForCode(k.BadJson, t); } } }; } function ei(r) { var e; return r && r.data.length === 0 && ((e = r.headers) == null ? void 0 : e.code) === 503 ? T.errorForCode(k.NoResponders) : null; } class Qs { 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 = Ke.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 = ve, 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 Oe(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(Qs, "jc"); function ot(r) { return hs("durable", r); } function pe(r) { return hs("stream", r); } function hs(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 Et(r, e = "") { if (e === "") throw Error(`${r} name required`); const t = nn(e); if (t.length) throw new Error(`invalid ${r} name - ${r} name ${t}`); } function nn(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 $s(r) { if (r.data.length > 0) return !1; const e = r.headers; return e ? e.code >= 100 && e.code < 200 : !1; } function Ls(r) { var e; return $s(r) && ((e = r.headers) == null ? void 0 : e.description) === "Idle Heartbeat"; } function on(r, e, t) { const s = Fe(r, e), i = { hdr: 1, sid: 0, size: 0 }, n = new Qs(i, ve, {}); return n._headers = s, n._subject = t, n; } function at(r) { if (r.data.length !== 0) return null; const e = r.headers; return e ? ti(e.code, e.description) : null; } var Pe; (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"; })(Pe || (Pe = {})); function an(r) { return r.code !== k.JetStream409 ? !1 : [ Pe.MaxBatchExceeded, Pe.MaxExpiresExceeded, Pe.MaxBytesExceeded, Pe.MaxMessageSizeExceeded, Pe.PushConsumer, Pe.IdleHeartbeatMissed, Pe.ConsumerDeleted ].find((t) => r.message.indexOf(t) !== -1) !== void 0; } function ti(r, e = "") { if (r < 300) return null; switch (e = e.toLowerCase(), r) { case 404: return new T(e, k.JetStream404NoMessages); case 408: return new T(e, k.JetStream408RequestTimeout); case 409: { const t = e.startsWith(Pe.IdleHeartbeatMissed) ? k.JetStreamIdleHeartBeat : k.JetStream409; return new T(e, t); } case 503: return T.errorForCode(k.JetStreamNotEnabled, new Error(e)); default: return e === "" && (e = k.Unknown), new T(e, `${r}`); } } class he { 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 = Y(), this.yields = [], this.iterClosed = Y(), 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 T("unsupported iterator", k.ApiError); if (this.yielding) throw new T("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 = Y()); } } 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 er { 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 qs; (function(r) { r.Limits = "limits", r.Interest = "interest", r.Workqueue = "workqueue"; })(qs || (qs = {})); var It; (function(r) { r.Old = "old", r.New = "new"; })(It || (It = {})); var Fs; (function(r) { r.File = "file", r.Memory = "memory"; })(Fs || (Fs = {})); var se; (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"; })(se || (se = {})); var ce; (function(r) { r.None = "none", r.All = "all", r.Explicit = "explicit", r.NotSet = ""; })(ce || (ce = {})); var lt; (function(r) { r.Instant = "instant", r.Original = "original"; })(lt || (lt = {})); var Ve; (function(r) { r.None = "none", r.S2 = "s2"; })(Ve || (Ve = {})); var ss; (function(r) { r.CreateOrUpdate = "", r.Update = "update", r.Create = "create"; })(ss || (ss = {})); function cn(r, e = {}) { return Object.assign({ name: r, deliver_policy: se.All, ack_policy: ce.Explicit, ack_wait: W(30 * 1e3), replay_policy: lt.Instant }, e); } var kr; (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"; })(kr || (kr = {})); var ge; (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"; })(ge || (ge = {})); var Re; (function(r) { r.LastValue = "", r.AllHistory = "history", r.UpdatesOnly = "updates"; })(Re || (Re = {})); var it; (function(r) { r.Stream = "Nats-Stream", r.Sequence = "Nats-Sequence", r.TimeStamp = "Nats-Time-Stamp", r.Subject = "Nats-Subject"; })(it || (it = {})); var Or; (function(r) { r.Stream = "Nats-Stream", r.Subject = "Nats-Subject", r.Sequence = "Nats-Sequence", r.LastSequence = "Nats-Last-Sequence", r.Size = "Nats-Msg-Size"; })(Or || (Or = {})); const we = "KV_"; class hn { 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 = cn("", 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 ? ce.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 ot(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 = se.StartSequence, this.config.opt_start_seq = e, this; } startTime(e) { return this.config.deliver_policy = se.StartTime, this.config.opt_start_time = e.toISOString(), this; } deliverAll() { return this.config.deliver_policy = se.All, this; } deliverLastPerSubject() { return this.config.deliver_policy = se.LastPerSubject, this; } deliverLast() { return this.config.deliver_policy = se.Last, this; } deliverNew() { return this.config.deliver_policy = se.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 = ce.None, this; } ackAll() { return this.config.ack_policy = ce.All, this; } ackExplicit() { return this.config.ack_policy = ce.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 = lt.Instant, this; } replayOriginal() { return this.config.replay_policy = lt.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 ze(r) { return new hn(r); } function Cr(r) { return typeof r.getOpts == "function"; } class un { 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 ct { static encode(e) { return ct.toB64URLEncoding(un.encode(e)); } static decode(e, t = !1) { return ct.decode(ct.fromB64URLEncoding(e), t); } static toB64URLEncoding(e) { return e.replace(/\+/g, "-").replace(/\//g, "_"); } static fromB64URLEncoding(e) { return e.replace(/_/g, "/").replace(/-/g, "+"); } } class ft { 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 = ""), We.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 ln(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 fn = typeof global < "u" ? global : typeof self < "u" ? self : typeof window < "u" ? window : {}, St = fn.performance || {}; St.now || St.mozNow || St.msNow || St.oNow || St.webkitNow; var Ir = { versions: {} }, dn = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}; function pn(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 Os, us = { exports: {} }, jr = {}, Rr = pn(ln({ __proto__: null, default: jr }, [ jr ])); Os = us, 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 && Ir.versions && Ir.versions.node; i ? t = dn : s && (t = self); var n = !t.JS_SHA256_NO_COMMON_JS && Os.exports, o = !t.JS_SHA256_NO_ARRAY_BUFFER && typeof ArrayB