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,654 lines 271 kB
var Si = Object.defineProperty; var vi = (r, e, t) => e in r ? Si(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t; var h = (r, e, t) => vi(r, typeof e != "symbol" ? e + "" : e, t); function je(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 qs() { return Ei.stubThis((globalThis == null ? void 0 : globalThis.PublicKeyCredential) !== void 0 && typeof globalThis.PublicKeyCredential == "function"); } const Ei = { stubThis: (r) => r }; function Ur(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 $r(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 he 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 Ai({ 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 he({ 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 he({ 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 he({ 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 he({ 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 he({ message: "The authenticator was previously registered", code: "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED", cause: r }); if (r.name === "NotAllowedError") return new he({ 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 he({ message: 'No entry in pubKeyCredParams was of type "public-key"', code: "ERROR_MALFORMED_PUBKEYCREDPARAMS", cause: r }) : new he({ 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 ($r(o)) { if (t.rp.id !== o) return new he({ message: `The RP ID "${t.rp.id}" is invalid for this domain`, code: "ERROR_INVALID_RP_ID", cause: r }); } else return new he({ 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 he({ 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 he({ 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 Pi { 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 Lr = new Pi(), Oi = ["cross-platform", "platform"]; function qr(r) { if (r && !(Oi.indexOf(r) < 0)) return r; } async function ki(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 (!qs()) 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(Ur) }, i = {}; t && (i.mediation = "conditional"), i.publicKey = s, i.signal = Lr.createNewAbortSignal(); let n; try { n = await navigator.credentials.create(i); } catch (T) { throw Ai({ error: T, options: i }); } if (!n) throw new Error("Registration was not completed"); const { id: o, rawId: a, response: d, type: p } = n; let g; typeof d.getTransports == "function" && (g = d.getTransports()); let y; if (typeof d.getPublicKeyAlgorithm == "function") try { y = d.getPublicKeyAlgorithm(); } catch (T) { ms("getPublicKeyAlgorithm()", T); } let x; if (typeof d.getPublicKey == "function") try { const T = d.getPublicKey(); T !== null && (x = je(T)); } catch (T) { ms("getPublicKey()", T); } let P; if (typeof d.getAuthenticatorData == "function") try { P = je(d.getAuthenticatorData()); } catch (T) { ms("getAuthenticatorData()", T); } return { id: o, rawId: je(a), response: { attestationObject: je(d.attestationObject), clientDataJSON: je(d.clientDataJSON), transports: g, publicKeyAlgorithm: y, publicKey: x, authenticatorData: P }, type: p, clientExtensionResults: n.getClientExtensionResults(), authenticatorAttachment: qr(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 Ci() { if (!qs()) 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 Ii({ 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 he({ message: "Authentication ceremony was sent an abort signal", code: "ERROR_CEREMONY_ABORTED", cause: r }); } else { if (r.name === "NotAllowedError") return new he({ message: r.message, code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", cause: r }); if (r.name === "SecurityError") { const s = globalThis.location.hostname; if ($r(s)) { if (t.rpId !== s) return new he({ message: `The RP ID "${t.rpId}" is invalid for this domain`, code: "ERROR_INVALID_RP_ID", cause: r }); } else return new he({ message: `${globalThis.location.hostname} is an invalid domain`, code: "ERROR_INVALID_DOMAIN", cause: r }); } else if (r.name === "UnknownError") return new he({ 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 P, 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 (!qs()) throw new Error("WebAuthn is not supported in this browser"); let i; ((P = e.allowCredentials) == null ? void 0 : P.length) !== 0 && (i = (I = e.allowCredentials) == null ? void 0 : I.map(Ur)); const n = { ...e, challenge: zt(e.challenge), allowCredentials: i }, o = {}; if (t) { if (!await Ci()) 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 = Lr.createNewAbortSignal(); let a; try { a = await navigator.credentials.get(o); } catch (T) { throw Ii({ error: T, options: o }); } if (!a) throw new Error("Authentication was not completed"); const { id: d, rawId: p, response: g, type: y } = a; let x; return g.userHandle && (x = je(g.userHandle)), { id: d, rawId: je(p), response: { authenticatorData: je(g.authenticatorData), clientDataJSON: je(g.clientDataJSON), signature: je(g.signature), userHandle: x }, type: y, clientExtensionResults: a.getClientExtensionResults(), authenticatorAttachment: qr(a.authenticatorAttachment) }; } const Ze = "LAST_AUTH_DATA"; class Fr { constructor(e) { h(this, "onUserDataUpdate"); h(this, "isAuthenticated"); h(this, "isAuthenticatedResolver", () => { }); this.options = e, this.isAuthenticated = new Promise( (t) => this.isAuthenticatedResolver = t ); } get url() { return this.options.authUrl; } async init() { var t, s; const e = localStorage.getItem(Ze); if (e) try { const i = JSON.parse(e); (t = this.onUserDataUpdate) == null || t.call(this, i), this.isAuthenticatedResolver(); } catch { } else { const i = await this.me(); await this.options.storage.setItem(Ze, i), (s = this.onUserDataUpdate) == null || s.call(this, i), this.isAuthenticatedResolver(); } } async me() { return await fetch(this.options.authUrl + "/me", { credentials: "include" }).then((t) => t.json()); } async requestEmailLogin(e, t = location.href) { return await fetch( this.options.authUrl + `/email-verification-request/${e}?returnUrl=${t}`, { credentials: "include" } ).then(pt); } async completeEmailLogin(e, t) { var i; const s = await fetch( this.options.authUrl + `/email-verification-complete/${e}/${t}`, { credentials: "include" } ).then(pt); return await this.options.storage.setItem(Ze, s), (i = this.onUserDataUpdate) == null || i.call(this, s), s; } async requestPasskeyLogin(e = {}) { var d, 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}`, { credentials: "include" } ).then(pt); let o; try { (d = n.user) != null && d.id ? o = await ki({ 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" }, credentials: "include" } ).then(pt); return await this.options.storage.setItem(Ze, a), (p = this.onUserDataUpdate) == null || p.call(this, a), a; } async guestLogin() { var t; const e = await fetch(this.options.authUrl + "/sign-out", { credentials: "include" }).then(pt); return await this.options.storage.setItem(Ze, e), (t = this.onUserDataUpdate) == null || t.call(this, e), e; } getLastLoginData() { return this.options.storage.getItem( Ze ); } } const pt = 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(""), ar = (r) => new Uint8Array( r.match(/.{1,2}/g).map((e) => parseInt(e, 16)) ), cr = (r) => btoa(String.fromCharCode(...new Uint8Array(r))), Ri = (r) => Uint8Array.from(atob(r), (e) => e.charCodeAt(0)).buffer, Ni = async (r) => await crypto.subtle.digest("SHA-256", r), Ti = new TextEncoder(); class Mi { 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 cr(t); } async deriveAESKey(e, t) { const s = Ri(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 = ar(s[0]).buffer, n = ar(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 Ni(Ti.encode(e).buffer); return cr(t); } } const ye = new Uint8Array(0), Ke = new TextEncoder(), ge = new TextDecoder(); function Ui(...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(Ke.encode(r[t])); return e.length === 0 ? ye : e.length === 1 ? e[0] : Ui(...e); } function hr(r) { return !r || r.length === 0 ? "" : ge.decode(r); } const ur = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", lr = 36, $i = 3656158440062976, fr = 33, Li = 333, dr = 22; function qi(r) { for (let e = 0; e < r.length; e++) r[e] = Math.floor(Math.random() * 255); } function Fi(r) { var e; (e = globalThis == null ? void 0 : globalThis.crypto) != null && e.getRandomValues ? globalThis.crypto.getRandomValues(r) : qi(r); } class Bi { constructor() { h(this, "buf"); h(this, "seq"); h(this, "inc"); h(this, "inited"); this.buf = new Uint8Array(dr), this.inited = !1; } init() { this.inited = !0, this.setPre(), this.initSeqAndInc(), this.fillSeq(); } initSeqAndInc() { this.seq = Math.floor(Math.random() * $i), this.inc = Math.floor(Math.random() * (Li - fr) + fr); } setPre() { const e = new Uint8Array(12); Fi(e); for (let t = 0; t < 12; t++) { const s = e[t] % 36; this.buf[t] = ur.charCodeAt(s); } } fillSeq() { let e = this.seq; for (let t = dr - 1; t >= 12; t--) this.buf[t] = ur.charCodeAt(e % lr), e = Math.floor(e / lr); } 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 De = new Bi(); var ve; (function(r) { r.Disconnect = "disconnect", r.Reconnect = "reconnect", r.Update = "update", r.LDM = "ldm", r.Error = "error"; })(ve || (ve = {})); var Le; (function(r) { r.Reconnecting = "reconnecting", r.PingTimer = "pingTimer", r.StaleConnection = "staleConnection", r.ClientInitiatedReconnect = "client initiated reconnect"; })(Le || (Le = {})); var O; (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"; })(O || (O = {})); function Di(r) { return typeof r.code == "string"; } class Br { constructor() { h(this, "messages"); this.messages = /* @__PURE__ */ new Map(), this.messages.set(O.InvalidPayload, "Invalid payload type - payloads can be 'binary', 'string', or 'json'"), this.messages.set(O.BadJson, "Bad JSON"), this.messages.set(O.WssRequired, "TLS is required, therefore a secure websocket connection is also required"); } static getMessage(e) { return Hi.getMessage(e); } getMessage(e) { return this.messages.get(e) || e; } } const Hi = new Br(); 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 = Br.getMessage(t); return new N(i, t, s); } isAuthError() { return this.code === O.AuthenticationExpired || this.code === O.AuthorizationViolation || this.code === O.AccountExpired; } isAuthTimeout() { return this.code === O.AuthenticationTimeout; } isPermissionError() { return this.code === O.PermissionsViolation; } isProtocolError() { return this.code === O.ProtocolError; } isJetStreamError() { return this.api_error !== void 0; } jsError() { return this.api_error ? this.api_error : null; } } var me; (function(r) { r[r.Exact = 0] = "Exact", r[r.CanonicalMIME = 1] = "CanonicalMIME", r[r.IgnoreCase = 2] = "IgnoreCase"; })(me || (me = {})); var Ce; (function(r) { r.Timer = "timer", r.Count = "count", r.JitterTimer = "jitterTimer", r.SentinelMsg = "sentinelMsg"; })(Ce || (Ce = {})); 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 Gt = "Nats-Service-Error", Kt = "Nats-Service-Error-Code"; class Vt extends Error { constructor(t, s) { super(s); h(this, "code"); this.code = t; } static isServiceError(t) { return Vt.toServiceError(t) !== null; } static toServiceError(t) { var i, n; const s = ((i = t == null ? void 0 : t.headers) == null ? void 0 : i.get(Kt)) || ""; if (s !== "") { const o = parseInt(s) || 400, a = ((n = t == null ? void 0 : t.headers) == null ? void 0 : n.get(Gt)) || ""; return new Vt(o, a.length ? a : s); } return null; } } function Me(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}.${De.next()}`; } const As = "127.0.0.1"; var qe; (function(r) { r.PING = "PING", r.STATS = "STATS", r.INFO = "INFO"; })(qe || (qe = {})); function es(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 Lt(r) { return ge.decode(r).replace(/\n/g, "␊").replace(/\r/g, "␍"); } function nt(r, e = !0) { const t = e ? N.errorForCode(O.Timeout) : null; let s, i; const n = new Promise((o, a) => { s = { cancel: () => { i && clearTimeout(i); } }, i = setTimeout(() => { a(t === null ? N.errorForCode(O.Timeout) : t); }, r); }); return Object.assign(n, s); } function ct(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 K() { let r = {}; const e = new Promise((t, s) => { r = { resolve: t, reject: s }; }); return Object.assign(e, r); } function Dr(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 Ji(r) { return r === 0 ? 0 : Math.floor(r / 2 + Math.random() * r); } function Fs(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 Ji(t > e ? r[e] : r[t]); } }; } function G(r) { return r * 1e6; } function Bs(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 N(`'${r[n]}' is not a valid character for a header key`, O.BadHeader); s && 97 <= o && o <= 122 ? o -= 32 : !s && 65 <= o && o <= 90 && (o += 32), i[n] = o, s = o == 45; } return String.fromCharCode(...i); } function Ue(r = 0, e = "") { if (r === 0 && e !== "" || r > 0 && e === "") throw new Error("setting status requires both code and description"); return new Fe(r, e); } const _s = "NATS/1.0"; class Fe { 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 Fe(), i = ge.decode(e).split(`\r `), n = i[0]; if (n !== _s) { let o = n.replace(_s, "").trim(); if (o.length > 0) { t._code = parseInt(o, 10), isNaN(t._code) && (t._code = 0); const a = t._code.toString(); o = o.replace(a, ""), t._description = o.trim(); } } return i.length >= 1 && i.slice(1).map((o) => { if (o) { const a = o.indexOf(":"); if (a > -1) { const d = o.slice(0, a), p = o.slice(a + 1).trim(); t.append(d, p); } } }), t; } toString() { if (this.headers.size === 0 && this._code === 0) return ""; let e = _s; 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 Ke.encode(this.toString()); } static validHeaderValue(e) { if (/[\r\n]/.test(e)) throw new N("invalid header value - \\r and \\n are not allowed.", O.BadHeader); return e.trim(); } keys() { const e = []; for (const t of this.headers.keys()) e.push(t); return e; } findKeys(e, t = me.Exact) { const s = this.keys(); switch (t) { case me.Exact: return s.filter((i) => i === e); case me.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 = me.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 = me.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 = me.Exact) { return this.findKeys(e, t).length > 0; } set(e, t, s = me.Exact) { this.delete(e, s), this.append(e, t, s); } append(e, t, s = me.Exact) { const i = pr(e); s === me.CanonicalMIME && (e = i); const n = this.findKeys(e, s); e = n.length > 0 ? n[0] : e; const o = Fe.validHeaderValue(t); let a = this.headers.get(e); a || (a = [], this.headers.set(e, a)), a.push(o); } values(e, t = me.Exact) { const s = []; return this.findKeys(e, t).forEach((n) => { const o = this.headers.get(n); o && s.push(...o); }), s; } delete(e, t = me.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 Fe(); for (const s in e) t.headers.set(s, e[s]); return t; } } function mr() { return { encode(r) { return Ke.encode(r); }, decode(r) { return ge.decode(r); } }; } function Ee(r) { return { encode(e) { try { return e === void 0 && (e = null), Ke.encode(JSON.stringify(e)); } catch (t) { throw N.errorForCode(O.BadJson, t); } }, decode(e) { try { return JSON.parse(ge.decode(e), r); } catch (t) { throw N.errorForCode(O.BadJson, t); } } }; } function Hr(r) { var e; return r && r.data.length === 0 && ((e = r.headers) == null ? void 0 : e.code) === 503 ? N.errorForCode(O.NoResponders) : null; } class Ds { constructor(e, t, s) { h(this, "_headers"); h(this, "_msg"); h(this, "_rdata"); h(this, "_reply"); h(this, "_subject"); h(this, "publisher"); this._msg = e, this._rdata = t, this.publisher = s; } get subject() { return this._subject ? this._subject : (this._subject = ge.decode(this._msg.subject), this._subject); } get reply() { return this._reply ? this._reply : (this._reply = ge.decode(this._msg.reply), this._reply); } get sid() { return this._msg.sid; } get headers() { if (this._msg.hdr > -1 && !this._headers) { const e = this._rdata.subarray(0, this._msg.hdr); this._headers = Fe.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 = ye, 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 Ee(e).decode(this.data); } string() { return ge.decode(this.data); } requestInfo() { var t; const e = (t = this.headers) == null ? void 0 : t.get("Nats-Request-Info"); return e ? JSON.parse(e, function(s, i) { return (s === "start" || s === "stop") && i !== "" ? new Date(Date.parse(i)) : i; }) : null; } } h(Ds, "jc"); function tt(r) { return ts("durable", r); } function le(r) { return ts("stream", r); } function ts(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 gt(r, e = "") { if (e === "") throw Error(`${r} name required`); const t = zi(e); if (t.length) throw new Error(`invalid ${r} name - ${r} name ${t}`); } function zi(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 Ps(r) { if (r.data.length > 0) return !1; const e = r.headers; return e ? e.code >= 100 && e.code < 200 : !1; } function Os(r) { var e; return Ps(r) && ((e = r.headers) == null ? void 0 : e.description) === "Idle Heartbeat"; } function Gi(r, e, t) { const s = Ue(r, e), i = { hdr: 1, sid: 0, size: 0 }, n = new Ds(i, ye, {}); return n._headers = s, n._subject = t, n; } function st(r) { if (r.data.length !== 0) return null; const e = r.headers; return e ? Jr(e.code, e.description) : null; } var Se; (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"; })(Se || (Se = {})); function Ki(r) { return r.code !== O.JetStream409 ? !1 : [ Se.MaxBatchExceeded, Se.MaxExpiresExceeded, Se.MaxBytesExceeded, Se.MaxMessageSizeExceeded, Se.PushConsumer, Se.IdleHeartbeatMissed, Se.ConsumerDeleted ].find((t) => r.message.indexOf(t) !== -1) !== void 0; } function Jr(r, e = "") { if (r < 300) return null; switch (e = e.toLowerCase(), r) { case 404: return new N(e, O.JetStream404NoMessages); case 408: return new N(e, O.JetStream408RequestTimeout); case 409: { const t = e.startsWith(Se.IdleHeartbeatMissed) ? O.JetStreamIdleHeartBeat : O.JetStream409; return new N(e, t); } case 503: return N.errorForCode(O.JetStreamNotEnabled, new Error(e)); default: return e === "" && (e = O.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 = K(), this.yields = [], this.iterClosed = K(), 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", O.ApiError); if (this.yielding) throw new N("already yielding", O.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 = K()); } } 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 Hs { 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 vt; (function(r) { r.Old = "old", r.New = "new"; })(vt || (vt = {})); var Cs; (function(r) { r.File = "file", r.Memory = "memory"; })(Cs || (Cs = {})); var Q; (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"; })(Q || (Q = {})); var ne; (function(r) { r.None = "none", r.All = "all", r.Explicit = "explicit", r.NotSet = ""; })(ne || (ne = {})); var ot; (function(r) { r.Instant = "instant", r.Original = "original"; })(ot || (ot = {})); var He; (function(r) { r.None = "none", r.S2 = "s2"; })(He || (He = {})); var Wt; (function(r) { r.CreateOrUpdate = "", r.Update = "update", r.Create = "create"; })(Wt || (Wt = {})); function Vi(r, e = {}) { return Object.assign({ name: r, deliver_policy: Q.All, ack_policy: ne.Explicit, ack_wait: G(30 * 1e3), replay_policy: ot.Instant }, e); } var br; (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"; })(br || (br = {})); var de; (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"; })(de || (de = {})); var ke; (function(r) { r.LastValue = "", r.AllHistory = "history", r.UpdatesOnly = "updates"; })(ke || (ke = {})); var et; (function(r) { r.Stream = "Nats-Stream", r.Sequence = "Nats-Sequence", r.TimeStamp = "Nats-Time-Stamp", r.Subject = "Nats-Subject"; })(et || (et = {})); var gr; (function(r) { r.Stream = "Nats-Stream", r.Subject = "Nats-Subject", r.Sequence = "Nats-Sequence", r.LastSequence = "Nats-Last-Sequence", r.Size = "Nats-Msg-Size"; })(gr || (gr = {})); const be = "KV_"; class Wi { 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 = Vi("", 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 ? ne.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 tt(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 = Q.StartSequence, this.config.opt_start_seq = e, this; } startTime(e) { return this.config.deliver_policy = Q.StartTime, this.config.opt_start_time = e.toISOString(), this; } deliverAll() { return this.config.deliver_policy = Q.All, this; } deliverLastPerSubject() { return this.config.deliver_policy = Q.LastPerSubject, this; } deliverLast() { return this.config.deliver_policy = Q.Last, this; } deliverNew() { return this.config.deliver_policy = Q.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 = ne.None, this; } ackAll() { return this.config.ack_policy = ne.All, this; } ackExplicit() { return this.config.ack_policy = ne.Explicit, this; } ackWait(e) { return this.config.ack_wait = G(e), this; } maxDeliver(e) { return this.config.max_deliver = e, this; } filterSubject(e) { return this.filters = this.filters || [], this.filters.push(e), this; } replayInstantly() { return this.config.replay_policy = ot.Instant, this; } replayOriginal() { return this.config.replay_policy = ot.Original, this; } sample(e) { if (e = Math.trunc(e), e < 0 || e > 100) throw new Error("value must be between 0-100"); return this.config.sample_freq = `${e}%`, this; } limit(e) { return this.config.rate_limit_bps = e, this; } maxWaiting(e) { return this.config.max_waiting = e, this; } maxAckPending(e) { return this.config.max_ack_pending = e, this; } idleHeartbeat(e) { return this.config.idle_heartbeat = G(e), this; } flowControl() { return this.config.flow_control = !0, this; } deliverGroup(e) { return this.queue(e), this; } manualAck() { return this.mack = !0, this; } maxMessages(e) { return this.max = e, this; } callback(e) { return this.callbackFn = e, this; } queue(e) { return this.qname = e, this.config.deliver_group = e, this; } orderedConsumer() { return this.ordered = !0, this; } bind(e, t) { return this.stream = e, this.config.durable_name = t, this.isBind = !0, this; } bindStream(e) { return this.stream = e, this; } inactiveEphemeralThreshold(e) { return this.config.inactive_threshold = G(e), this; } maxPullBatch(e) { return this.config.max_batch = e, this; } maxPullRequestExpires(e) { return this.config.max_expires = G(e), this; } memory() { return this.config.mem_storage = !0, this; } numReplicas(e) { return this.config.num_replicas = e, this; } consumerName(e) { return this.config.name = e, this; } } function Be(r) { return new Wi(r); } function _r(r) { return typeof r.getOpts == "function"; } class Yi { 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 rt { static encode(e) { return rt.toB64URLEncoding(Yi.encode(e)); } static decode(e, t = !1) { return rt.decode(rt.fromB64URLEncoding(e), t); } static toB64URLEncoding(e) { return e.replace(/\+/g, "-").replace(/\//g, "_"); } static fromB64URLEncoding(e) { return e.replace(/_/g, "/").replace(/-/g, "+"); } } class at { 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 = ""), Ke.encode(e); } static toAscii(e) { return ge.decode(e); } reset() { this.buffers.length = 0, this.byteLength = 0; } pack() { if (this.buffers.length > 1) { const e = new Uint8Array(this.byteLength); let t = 0; for (let s = 0; s < this.buffers.length; s++) e.set(this.buffers[s], t), t += this.buffers[s].length; this.buffers.length = 0, this.buffers.push(e); } } shift() { if (this.buffers.length) { const e = this.buffers.shift(); if (e) return this.byteLength -= e.length, e; } return new Uint8Array(0); } drain(e) { if (this.buffers.length) { this.pack(); const t = this.buffers.pop(); if (t) { const s = this.byteLength; (e === void 0 || e > s) && (e = s); const i = t.subarray(0, e); return s > e && this.buffers.push(t.subarray(e)), this.byteLength = s - e, i; } } return new Uint8Array(0); } fill(e, ...t) { e && (this.buffers.push(e), this.byteLength += e.length); for (let s = 0; s < t.length; s++) t[s] && t[s].length && (this.buffers.push(t[s]), this.byteLength += t[s].length); } peek() { return this.buffers.length ? (this.pack(), this.buffers[0]) : new Uint8Array(0); } size() { return this.byteLength; } length() { return this.buffers.length; } } function Xi(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 Zi = typeof global < "u" ? global : typeof self < "u" ? self : typeof window < "u" ? window : {}, mt = Zi.performance || {}; mt.now || mt.mozNow || mt.msNow || mt.oNow || mt.webkitNow; var yr = { versions: {} }, Qi = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}; function en(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 ys, ss = { exports: {} }, wr = {}, xr = en(Xi({ __proto__: null, default: wr }, [ wr ])); ys = ss, 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 && yr.versions && yr.versions.node; i ? t = Qi : s && (t = self); var n = !t.JS_SHA256_NO_COMMON_JS && ys.exports, o = !t.JS_SHA256_NO_ARRAY_BUFFER && typeof ArrayBuffer < "u", a = "0123456789abcdef".split(""), d = [ -2147483648, 8388608, 32768, 128 ], p = [ 24, 16, 8, 0 ], g = [ 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 14268