UNPKG

rx-nostr

Version:

A library based on RxJS, which allows Nostr applications to easily communicate with relays.

1,676 lines 137 kB
var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; class RxNostrError extends Error { } class RxNostrWebSocketError extends RxNostrError { constructor(code) { super( `RxNostrWebSocketError: WebSocket was closed with code ${code} by relay.` ); this.code = code; this.name = "RxNostrWebSocketError"; } } class RxNostrInvalidUsageError extends RxNostrError { constructor(message) { super(`RxNostrInvalidUsageError: ${message}`); this.name = "RxNostrInvalidUsageError"; } } class RxNostrEnvironmentError extends RxNostrError { constructor(message) { super(`RxNostrEnvironmentError: ${message}`); this.name = "RxNostrEnvironmentError"; } } class RxNostrLogicError extends RxNostrError { constructor() { super( "RxNostrLogicError: This is rx-nostr's internal bug. Please report to the author of the library." ); this.name = "RxNostrLogicError"; } } class RxNostrAlreadyDisposedError extends RxNostrError { constructor() { super( "RxNostrAlreadyDisposedError: Attempted to access a disposed resource." ); this.name = "RxNostrAlreadyDisposedError"; } } const fill = (config2, defaults) => ({ ...defaults, ...config2 }); function ensureEventFields(event) { if (typeof event.id !== "string") return false; if (typeof event.sig !== "string") return false; if (typeof event.kind !== "number") return false; if (typeof event.pubkey !== "string") return false; if (typeof event.content !== "string") return false; if (typeof event.created_at !== "number") return false; if (!Array.isArray(event.tags)) return false; for (let i = 0; i < event.tags.length; i++) { const tag = event.tags[i]; if (!Array.isArray(tag)) return false; for (let j = 0; j < tag.length; j++) { if (typeof tag[j] === "object") return false; } } return true; } function earlierEvent(a, b) { return compareEvents(a, b) < 0 ? a : b; } function laterEvent(a, b) { return compareEvents(a, b) < 0 ? b : a; } function compareEvents(a, b) { if (a.id === b.id) { return 0; } return a.created_at < b.created_at || // https://github.com/nostr-protocol/nips/blob/master/16.md#replaceable-events a.created_at === b.created_at && a.id < b.id ? -1 : 1; } function inlineThrow(err) { throw err; } function nip07Signer(options) { return { async signEvent(params) { var _a, _b; const event = { ...params, pubkey: params.pubkey ?? await ((_a = window == null ? void 0 : window.nostr) == null ? void 0 : _a.getPublicKey()) ?? inlineThrow( new RxNostrEnvironmentError( "window.nostr.getPublicKey() is not found" ) ), tags: [...params.tags ?? [], ...(options == null ? void 0 : options.tags) ?? []], created_at: params.created_at ?? Math.floor(Date.now() / 1e3) }; if (ensureEventFields(event)) { return event; } return await ((_b = window == null ? void 0 : window.nostr) == null ? void 0 : _b.signEvent(event)) ?? inlineThrow( new RxNostrEnvironmentError("window.nostr.signEvent() is not found") ); }, getPublicKey() { var _a; return ((_a = window == null ? void 0 : window.nostr) == null ? void 0 : _a.getPublicKey()) ?? inlineThrow( new RxNostrEnvironmentError( "window.nostr.getPublicKey() is not found" ) ); } }; } function noopSigner() { return { async signEvent(params) { return params; }, async getPublicKey() { throw new RxNostrInvalidUsageError("noopSigner cannot calculate pubkey."); } }; } const noopVerifier = async () => true; const emptyVerifier = async () => { throw new Error( "You must give some verifier to createRxNostr(). In most cases, @rx-nostr/crypto packages will help you." ); }; const makeRxNostrConfig = (config2) => fill(config2, { signer: nip07Signer(), verifier: emptyVerifier, connectionStrategy: "lazy", retry: { strategy: "exponential", maxCount: 5, initialDelay: 1e3 }, disconnectTimeout: 1e4, eoseTimeout: 30 * 1e3, okTimeout: 30 * 1e3, authTimeout: 30 * 1e3, skipVerify: false, skipValidateFilterMatching: false, skipExpirationCheck: false, skipFetchNip11: false }); function evalFilters(filters) { if ("length" in filters) { return filters.map(evalFilter); } else { return [evalFilter(filters)]; } } function evalFilter(filter2) { return { ...filter2, since: filter2.since ? evalLazyNumber(filter2.since) : void 0, until: filter2.until ? evalLazyNumber(filter2.until) : void 0 }; } function evalLazyNumber(lazyNumber) { return typeof lazyNumber === "number" ? lazyNumber : lazyNumber(); } async function fetchRelayInfo(url) { try { const u = new URL(url); u.protocol = u.protocol.replace(/^ws(s?):/, "http$1:"); const res = await fetch(u.toString(), { headers: { Accept: "application/nostr+json" } }); return await res.json(); } catch { return {}; } } function inlineTry(f, g) { try { return f(); } catch (err) { if (g instanceof Function) { return g(err); } else { return g; } } } function normalizeRelayUrl(url) { let o = ""; try { o = url.trim(); const u = new URL(o); u.hash = ""; u.pathname = inlineTry(() => decodeURI(u.pathname), u.pathname); u.pathname = u.pathname.replace(/\/$/, ""); u.hostname = u.hostname.replace(/\.$/, ""); u.searchParams.sort(); u.search = inlineTry(() => decodeURIComponent(u.search), u.search); let s = u.toString(); if (!u.search) { s = s.replace(/\/$/, ""); } return s; } catch { return o; } } class UrlMap extends Map { constructor(obj) { super(); if (!obj) { return; } for (const [url, v] of Object.entries(obj)) { this.set(normalizeRelayUrl(url), v); } } get(url) { return super.get(normalizeRelayUrl(url)); } getMany(urls) { const vs = []; for (const url of new Set(urls.map(normalizeRelayUrl))) { const v = this.get(url); if (v !== void 0) { vs.push(v); } } return vs; } set(url, v) { return super.set(normalizeRelayUrl(url), v); } has(url) { return super.has(normalizeRelayUrl(url)); } delete(url) { return super.delete(normalizeRelayUrl(url)); } toObject() { const obj = {}; for (const [url, v] of this.entries()) { obj[url] = v; } return obj; } toKeys() { return [...super.keys()]; } toValues() { return [...super.values()]; } copy() { return new UrlMap(this.toObject()); } } class Nip11Registry { static async getValue(url, getter, options) { if (!(options == null ? void 0 : options.skipCache)) { const data = await this.cache.get(url); if (data) { return getter(data); } } if (!(options == null ? void 0 : options.skipFetch)) { const data = await this.fetch(url); if (data) { return getter(data); } } return getter(this.default); } /** * Return cached or `set()`'ed NIP-11 information. */ static get(url) { const v = this.cache.get(url); if (v && !(v instanceof Promise)) { return v; } else { return void 0; } } /** * Cache fetched information then return it. */ static async fetch(url) { const promise = fetchRelayInfo(url); this.cache.set(url, promise); promise.then((v) => { this.cache.set(url, v); }); return promise; } /** * Return cached or `set()`'ed NIP-11 information, * or cache fetched information then return it. */ static async getOrFetch(url) { return this.cache.get(url) ?? this.fetch(url); } /** * Set NIP-11 information manually for given relay URL. */ static set(url, nip11) { this.cache.set(url, nip11); } /** * Get NIP-11 information for fallback. */ static getDefault() { return this.default; } /** * Set NIP-11 information for fallback. */ static setDefault(nip11) { this.default = nip11; } /** * Forget cached NIP-11 information for given relay URL. */ static forget(url) { this.cache.delete(url); } /** * Forget all cached NIP-11 information. * * This doesn't erase `setDefault()`'ed value. * If you want it, you can `setDefault({})` instead. */ static forgetAll() { this.cache.clear(); } } __publicField(Nip11Registry, "cache", new UrlMap()); __publicField(Nip11Registry, "default", {}); function isBytes$1(a) { return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; } function abytes(value, length, title = "") { const bytes = isBytes$1(value); const len = value == null ? void 0 : value.length; const needsLen = length !== void 0; if (!bytes || needsLen && len !== length) { const prefix = title && `"${title}" `; const ofLen = needsLen ? ` of length ${length}` : ""; const got = bytes ? `length=${len}` : `type=${typeof value}`; const message = prefix + "expected Uint8Array" + ofLen + ", got " + got; if (!bytes) throw new TypeError(message); throw new RangeError(message); } return value; } const hasHexBuiltin = /* @__PURE__ */ (() => ( // @ts-ignore typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" ))(); const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); function bytesToHex(bytes) { abytes(bytes); if (hasHexBuiltin) return bytes.toHex(); let hex = ""; for (let i = 0; i < bytes.length; i++) { hex += hexes[bytes[i]]; } return hex; } /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ function isBytes(a) { return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; } function isArrayOf(isString, arr) { if (!Array.isArray(arr)) return false; if (arr.length === 0) return true; if (isString) { return arr.every((item) => typeof item === "string"); } else { return arr.every((item) => Number.isSafeInteger(item)); } } function afn(input) { if (typeof input !== "function") throw new Error("function expected"); return true; } function astr(label, input) { if (typeof input !== "string") throw new Error(`${label}: string expected`); return true; } function anumber(n) { if (!Number.isSafeInteger(n)) throw new Error(`invalid integer: ${n}`); } function aArr(input) { if (!Array.isArray(input)) throw new Error("array expected"); } function astrArr(label, input) { if (!isArrayOf(true, input)) throw new Error(`${label}: array of strings expected`); } function anumArr(label, input) { if (!isArrayOf(false, input)) throw new Error(`${label}: array of numbers expected`); } // @__NO_SIDE_EFFECTS__ function chain(...args) { const id = (a) => a; const wrap = (a, b) => (c) => a(b(c)); const encode = args.map((x) => x.encode).reduceRight(wrap, id); const decode = args.map((x) => x.decode).reduce(wrap, id); return { encode, decode }; } // @__NO_SIDE_EFFECTS__ function alphabet(letters) { const lettersA = typeof letters === "string" ? letters.split("") : letters; const len = lettersA.length; astrArr("alphabet", lettersA); const indexes = new Map(lettersA.map((l, i) => [l, i])); return { encode: (digits) => { aArr(digits); return digits.map((i) => { if (!Number.isSafeInteger(i) || i < 0 || i >= len) throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`); return lettersA[i]; }); }, decode: (input) => { aArr(input); return input.map((letter) => { astr("alphabet.decode", letter); const i = indexes.get(letter); if (i === void 0) throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`); return i; }); } }; } // @__NO_SIDE_EFFECTS__ function join(separator = "") { astr("join", separator); return { encode: (from2) => { astrArr("join.decode", from2); return from2.join(separator); }, decode: (to) => { astr("join.decode", to); return to.split(separator); } }; } const gcd = (a, b) => b === 0 ? a : gcd(b, a % b); const radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from2, to) => from2 + (to - gcd(from2, to)); const powers = /* @__PURE__ */ (() => { let res = []; for (let i = 0; i < 40; i++) res.push(2 ** i); return res; })(); function convertRadix2(data, from2, to, padding) { aArr(data); if (from2 <= 0 || from2 > 32) throw new Error(`convertRadix2: wrong from=${from2}`); if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`); if (/* @__PURE__ */ radix2carry(from2, to) > 32) { throw new Error(`convertRadix2: carry overflow from=${from2} to=${to} carryBits=${/* @__PURE__ */ radix2carry(from2, to)}`); } let carry = 0; let pos = 0; const max = powers[from2]; const mask = powers[to] - 1; const res = []; for (const n of data) { anumber(n); if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from2}`); carry = carry << from2 | n; if (pos + from2 > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from2}`); pos += from2; for (; pos >= to; pos -= to) res.push((carry >> pos - to & mask) >>> 0); const pow = powers[pos]; if (pow === void 0) throw new Error("invalid carry"); carry &= pow - 1; } carry = carry << to - pos & mask; if (!padding && pos >= from2) throw new Error("Excess padding"); if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`); if (padding && pos > 0) res.push(carry >>> 0); return res; } // @__NO_SIDE_EFFECTS__ function radix2(bits, revPadding = false) { anumber(bits); if (bits <= 0 || bits > 32) throw new Error("radix2: bits should be in (0..32]"); if (/* @__PURE__ */ radix2carry(8, bits) > 32 || /* @__PURE__ */ radix2carry(bits, 8) > 32) throw new Error("radix2: carry overflow"); return { encode: (bytes) => { if (!isBytes(bytes)) throw new Error("radix2.encode input should be Uint8Array"); return convertRadix2(Array.from(bytes), 8, bits, !revPadding); }, decode: (digits) => { anumArr("radix2.decode", digits); return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); } }; } function unsafeWrapper(fn) { afn(fn); return function(...args) { try { return fn.apply(null, args); } catch (e) { } }; } const BECH_ALPHABET = /* @__PURE__ */ chain(/* @__PURE__ */ alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), /* @__PURE__ */ join("")); const POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059]; function bech32Polymod(pre) { const b = pre >> 25; let chk = (pre & 33554431) << 5; for (let i = 0; i < POLYMOD_GENERATORS.length; i++) { if ((b >> i & 1) === 1) chk ^= POLYMOD_GENERATORS[i]; } return chk; } function bechChecksum(prefix, words, encodingConst = 1) { const len = prefix.length; let chk = 1; for (let i = 0; i < len; i++) { const c = prefix.charCodeAt(i); if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`); chk = bech32Polymod(chk) ^ c >> 5; } chk = bech32Polymod(chk); for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ prefix.charCodeAt(i) & 31; for (let v of words) chk = bech32Polymod(chk) ^ v; for (let i = 0; i < 6; i++) chk = bech32Polymod(chk); chk ^= encodingConst; return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]], 30, 5, false)); } // @__NO_SIDE_EFFECTS__ function genBech32(encoding) { const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939; const _words = /* @__PURE__ */ radix2(5); const fromWords = _words.decode; const toWords = _words.encode; const fromWordsUnsafe = unsafeWrapper(fromWords); function encode(prefix, words, limit = 90) { astr("bech32.encode prefix", prefix); if (isBytes(words)) words = Array.from(words); anumArr("bech32.encode", words); const plen = prefix.length; if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`); const actualLength = plen + 7 + words.length; if (limit !== false && actualLength > limit) throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); const lowered = prefix.toLowerCase(); const sum = bechChecksum(lowered, words, ENCODING_CONST); return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`; } function decode(str, limit = 90) { astr("bech32.decode input", str); const slen = str.length; if (slen < 8 || limit !== false && slen > limit) throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`); const lowered = str.toLowerCase(); if (str !== lowered && str !== str.toUpperCase()) throw new Error(`String must be lowercase or uppercase`); const sepIndex = lowered.lastIndexOf("1"); if (sepIndex === 0 || sepIndex === -1) throw new Error(`Letter "1" must be present between prefix and data only`); const prefix = lowered.slice(0, sepIndex); const data = lowered.slice(sepIndex + 1); if (data.length < 6) throw new Error("Data must be at least 6 characters long"); const words = BECH_ALPHABET.decode(data).slice(0, -6); const sum = bechChecksum(prefix, words, ENCODING_CONST); if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); return { prefix, words }; } const decodeUnsafe = unsafeWrapper(decode); function decodeToBytes(str) { const { prefix, words } = decode(str, false); return { prefix, words, bytes: fromWords(words) }; } function encodeFromBytes(prefix, bytes) { return encode(prefix, toWords(bytes)); } return { encode, decode, encodeFromBytes, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords }; } const bech32 = /* @__PURE__ */ genBech32("bech32"); function toHex(str) { const { words } = bech32.decode(str); const data = new Uint8Array(bech32.fromWords(words)); return bytesToHex(data); } function isFiltered(event, filters, options) { if (Array.isArray(filters)) { return filters.some((filter2) => _isFiltered(event, filter2, options)); } else { return _isFiltered(event, filters, options); } } function _isFiltered(event, filter2, options) { const { sinceInclusive, untilInclusive } = fill(options ?? {}, { sinceInclusive: true, untilInclusive: true }); if (filter2.ids && filter2.ids.every((prefix) => !event.id.startsWith(prefix))) { return false; } if (filter2.kinds && !filter2.kinds.includes(event.kind)) { return false; } if (filter2.authors && filter2.authors.every((pubkey) => !event.pubkey.startsWith(pubkey))) { return false; } if (filter2.since && (sinceInclusive && !(filter2.since <= event.created_at) || !sinceInclusive && !(filter2.since < event.created_at))) { return false; } if (filter2.until && (untilInclusive && !(event.created_at <= filter2.until) || !untilInclusive && !(event.created_at < filter2.until))) { return false; } for (const [key, needleValues] of Object.entries(filter2)) { if (!key.startsWith("#") || !Array.isArray(needleValues)) { continue; } const needleTagName = key.slice(1); if (!event.tags.find( ([tagName, tagValue]) => needleTagName === tagName && needleValues.includes(tagValue) )) { return false; } } return true; } function isExpired(event, now2) { const tag = event.tags.find((tag2) => tag2[0] === "expiration"); if (!tag) { return false; } try { const timestamp = Number(tag[1]); if (!Number.isInteger(timestamp)) { return false; } return timestamp <= (now2 ?? Math.floor(Date.now() / 1e3)); } catch { return false; } } var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { d2.__proto__ = b2; } || function(d2, b2) { for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve) { resolve(value); }); } return new (P || (P = Promise))(function(resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function(v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function() { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spreadArray(to, from2, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from2.length, ar; i < l; i++) { if (ar || !(i in from2)) { if (!ar) ar = Array.prototype.slice.call(from2, 0, i); ar[i] = from2[i]; } } return to.concat(ar || Array.prototype.slice.call(from2)); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i; function verb(n) { if (g[n]) i[n] = function(v) { return new Promise(function(a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i); function verb(n) { i[n] = o[n] && function(v) { return new Promise(function(resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v2) { resolve({ value: v2, done: d }); }, reject); } } typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; function isFunction(value) { return typeof value === "function"; } function createErrorClass(createImpl) { var _super = function(instance) { Error.call(instance); instance.stack = new Error().stack; }; var ctorFunc = createImpl(_super); ctorFunc.prototype = Object.create(Error.prototype); ctorFunc.prototype.constructor = ctorFunc; return ctorFunc; } var UnsubscriptionError = createErrorClass(function(_super) { return function UnsubscriptionErrorImpl(errors) { _super(this); this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function(err, i) { return i + 1 + ") " + err.toString(); }).join("\n ") : ""; this.name = "UnsubscriptionError"; this.errors = errors; }; }); function arrRemove(arr, item) { if (arr) { var index = arr.indexOf(item); 0 <= index && arr.splice(index, 1); } } var Subscription = function() { function Subscription2(initialTeardown) { this.initialTeardown = initialTeardown; this.closed = false; this._parentage = null; this._finalizers = null; } Subscription2.prototype.unsubscribe = function() { var e_1, _a, e_2, _b; var errors; if (!this.closed) { this.closed = true; var _parentage = this._parentage; if (_parentage) { this._parentage = null; if (Array.isArray(_parentage)) { try { for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) { var parent_1 = _parentage_1_1.value; parent_1.remove(this); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1); } finally { if (e_1) throw e_1.error; } } } else { _parentage.remove(this); } } var initialFinalizer = this.initialTeardown; if (isFunction(initialFinalizer)) { try { initialFinalizer(); } catch (e) { errors = e instanceof UnsubscriptionError ? e.errors : [e]; } } var _finalizers = this._finalizers; if (_finalizers) { this._finalizers = null; try { for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) { var finalizer = _finalizers_1_1.value; try { execFinalizer(finalizer); } catch (err) { errors = errors !== null && errors !== void 0 ? errors : []; if (err instanceof UnsubscriptionError) { errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors)); } else { errors.push(err); } } } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1); } finally { if (e_2) throw e_2.error; } } } if (errors) { throw new UnsubscriptionError(errors); } } }; Subscription2.prototype.add = function(teardown) { var _a; if (teardown && teardown !== this) { if (this.closed) { execFinalizer(teardown); } else { if (teardown instanceof Subscription2) { if (teardown.closed || teardown._hasParent(this)) { return; } teardown._addParent(this); } (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown); } } }; Subscription2.prototype._hasParent = function(parent) { var _parentage = this._parentage; return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent); }; Subscription2.prototype._addParent = function(parent) { var _parentage = this._parentage; this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent; }; Subscription2.prototype._removeParent = function(parent) { var _parentage = this._parentage; if (_parentage === parent) { this._parentage = null; } else if (Array.isArray(_parentage)) { arrRemove(_parentage, parent); } }; Subscription2.prototype.remove = function(teardown) { var _finalizers = this._finalizers; _finalizers && arrRemove(_finalizers, teardown); if (teardown instanceof Subscription2) { teardown._removeParent(this); } }; Subscription2.EMPTY = function() { var empty = new Subscription2(); empty.closed = true; return empty; }(); return Subscription2; }(); var EMPTY_SUBSCRIPTION = Subscription.EMPTY; function isSubscription(value) { return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe); } function execFinalizer(finalizer) { if (isFunction(finalizer)) { finalizer(); } else { finalizer.unsubscribe(); } } var config = { onUnhandledError: null, onStoppedNotification: null, Promise: void 0, useDeprecatedSynchronousErrorHandling: false, useDeprecatedNextContext: false }; var timeoutProvider = { setTimeout: function(handler, timeout2) { var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } var delegate = timeoutProvider.delegate; if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) { return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout2], __read(args))); } return setTimeout.apply(void 0, __spreadArray([handler, timeout2], __read(args))); }, clearTimeout: function(handle) { var delegate = timeoutProvider.delegate; return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle); }, delegate: void 0 }; function reportUnhandledError(err) { timeoutProvider.setTimeout(function() { { throw err; } }); } function noop() { } function errorContext(cb) { { cb(); } } var Subscriber = function(_super) { __extends(Subscriber2, _super); function Subscriber2(destination) { var _this = _super.call(this) || this; _this.isStopped = false; if (destination) { _this.destination = destination; if (isSubscription(destination)) { destination.add(_this); } } else { _this.destination = EMPTY_OBSERVER; } return _this; } Subscriber2.create = function(next, error, complete) { return new SafeSubscriber(next, error, complete); }; Subscriber2.prototype.next = function(value) { if (this.isStopped) ; else { this._next(value); } }; Subscriber2.prototype.error = function(err) { if (this.isStopped) ; else { this.isStopped = true; this._error(err); } }; Subscriber2.prototype.complete = function() { if (this.isStopped) ; else { this.isStopped = true; this._complete(); } }; Subscriber2.prototype.unsubscribe = function() { if (!this.closed) { this.isStopped = true; _super.prototype.unsubscribe.call(this); this.destination = null; } }; Subscriber2.prototype._next = function(value) { this.destination.next(value); }; Subscriber2.prototype._error = function(err) { try { this.destination.error(err); } finally { this.unsubscribe(); } }; Subscriber2.prototype._complete = function() { try { this.destination.complete(); } finally { this.unsubscribe(); } }; return Subscriber2; }(Subscription); var _bind = Function.prototype.bind; function bind(fn, thisArg) { return _bind.call(fn, thisArg); } var ConsumerObserver = function() { function ConsumerObserver2(partialObserver) { this.partialObserver = partialObserver; } ConsumerObserver2.prototype.next = function(value) { var partialObserver = this.partialObserver; if (partialObserver.next) { try { partialObserver.next(value); } catch (error) { handleUnhandledError(error); } } }; ConsumerObserver2.prototype.error = function(err) { var partialObserver = this.partialObserver; if (partialObserver.error) { try { partialObserver.error(err); } catch (error) { handleUnhandledError(error); } } else { handleUnhandledError(err); } }; ConsumerObserver2.prototype.complete = function() { var partialObserver = this.partialObserver; if (partialObserver.complete) { try { partialObserver.complete(); } catch (error) { handleUnhandledError(error); } } }; return ConsumerObserver2; }(); var SafeSubscriber = function(_super) { __extends(SafeSubscriber2, _super); function SafeSubscriber2(observerOrNext, error, complete) { var _this = _super.call(this) || this; var partialObserver; if (isFunction(observerOrNext) || !observerOrNext) { partialObserver = { next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : void 0, error: error !== null && error !== void 0 ? error : void 0, complete: complete !== null && complete !== void 0 ? complete : void 0 }; } else { var context_1; if (_this && config.useDeprecatedNextContext) { context_1 = Object.create(observerOrNext); context_1.unsubscribe = function() { return _this.unsubscribe(); }; partialObserver = { next: observerOrNext.next && bind(observerOrNext.next, context_1), error: observerOrNext.error && bind(observerOrNext.error, context_1), complete: observerOrNext.complete && bind(observerOrNext.complete, context_1) }; } else { partialObserver = observerOrNext; } } _this.destination = new ConsumerObserver(partialObserver); return _this; } return SafeSubscriber2; }(Subscriber); function handleUnhandledError(error) { { reportUnhandledError(error); } } function defaultErrorHandler(err) { throw err; } var EMPTY_OBSERVER = { closed: true, next: noop, error: defaultErrorHandler, complete: noop }; var observable = function() { return typeof Symbol === "function" && Symbol.observable || "@@observable"; }(); function identity(x) { return x; } function pipe() { var fns = []; for (var _i = 0; _i < arguments.length; _i++) { fns[_i] = arguments[_i]; } return pipeFromArray(fns); } function pipeFromArray(fns) { if (fns.length === 0) { return identity; } if (fns.length === 1) { return fns[0]; } return function piped(input) { return fns.reduce(function(prev, fn) { return fn(prev); }, input); }; } var Observable = function() { function Observable2(subscribe) { if (subscribe) { this._subscribe = subscribe; } } Observable2.prototype.lift = function(operator) { var observable2 = new Observable2(); observable2.source = this; observable2.operator = operator; return observable2; }; Observable2.prototype.subscribe = function(observerOrNext, error, complete) { var _this = this; var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete); errorContext(function() { var _a = _this, operator = _a.operator, source = _a.source; subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber)); }); return subscriber; }; Observable2.prototype._trySubscribe = function(sink) { try { return this._subscribe(sink); } catch (err) { sink.error(err); } }; Observable2.prototype.forEach = function(next, promiseCtor) { var _this = this; promiseCtor = getPromiseCtor(promiseCtor); return new promiseCtor(function(resolve, reject) { var subscriber = new SafeSubscriber({ next: function(value) { try { next(value); } catch (err) { reject(err); subscriber.unsubscribe(); } }, error: reject, complete: resolve }); _this.subscribe(subscriber); }); }; Observable2.prototype._subscribe = function(subscriber) { var _a; return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber); }; Observable2.prototype[observable] = function() { return this; }; Observable2.prototype.pipe = function() { var operations = []; for (var _i = 0; _i < arguments.length; _i++) { operations[_i] = arguments[_i]; } return pipeFromArray(operations)(this); }; Observable2.prototype.toPromise = function(promiseCtor) { var _this = this; promiseCtor = getPromiseCtor(promiseCtor); return new promiseCtor(function(resolve, reject) { var value; _this.subscribe(function(x) { return value = x; }, function(err) { return reject(err); }, function() { return resolve(value); }); }); }; Observable2.create = function(subscribe) { return new Observable2(subscribe); }; return Observable2; }(); function getPromiseCtor(promiseCtor) { var _a; return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise; } function isObserver(value) { return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete); } function isSubscriber(value) { return value && value instanceof Subscriber || isObserver(value) && isSubscription(value); } function hasLift(source) { return isFunction(source === null || source === void 0 ? void 0 : source.lift); } function operate(init) { return function(source) { if (hasLift(source)) { return source.lift(function(liftedSource) { try { return init(liftedSource, this); } catch (err) { this.error(err); } }); } throw new TypeError("Unable to lift unknown Observable type"); }; } function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) { return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize); } var OperatorSubscriber = function(_super) { __extends(OperatorSubscriber2, _super); function OperatorSubscriber2(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) { var _this = _super.call(this, destination) || this; _this.onFinalize = onFinalize; _this.shouldUnsubscribe = shouldUnsubscribe; _this._next = onNext ? function(value) { try { onNext(value); } catch (err) { destination.error(err); } } : _super.prototype._next; _this._error = onError ? function(err) { try { onError(err); } catch (err2) { destination.error(err2); } finally { this.unsubscribe(); } } : _super.prototype._error; _this._complete = onComplete ? function() { try { onComplete(); } catch (err) { destination.error(err); } finally { this.unsubscribe(); } } : _super.prototype._complete; return _this; } OperatorSubscriber2.prototype.unsubscribe = function() { var _a; if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) { var closed_1 = this.closed; _super.prototype.unsubscribe.call(this); !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this)); } }; return OperatorSubscriber2; }(Subscriber); var ObjectUnsubscribedError = createErrorClass(function(_super) { return function ObjectUnsubscribedErrorImpl() { _super(this); this.name = "ObjectUnsubscribedError"; this.message = "object unsubscribed"; }; }); var Subject = function(_super) { __extends(Subject2, _super); function Subject2() { var _this = _super.call(this) || this; _this.closed = false; _this.currentObservers = null; _this.observers = []; _this.isStopped = false; _this.hasError = false; _this.thrownError = null; return _this; } Subject2.prototype.lift = function(operator) { var subject = new AnonymousSubject(this, this); subject.operator = operator; return subject; }; Subject2.prototype._throwIfClosed = function() { if (this.closed) { throw new ObjectUnsubscribedError(); } }; Subject2.prototype.next = function(value) { var _this = this; errorContext(function() { var e_1, _a; _this._throwIfClosed(); if (!_this.isStopped) { if (!_this.currentObservers) { _this.currentObservers = Array.from(_this.observers); } try { for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) { var observer = _c.value; observer.next(value); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } } }); }; Subject2.prototype.error = function(err) { var _this = this; errorContext(function() { _this._throwIfClosed(); if (!_this.isStopped) { _this.hasError = _this.isStopped = true; _this.thrownError = err; var observers = _this.observers; while (observers.length) { observers.shift().error(err); } } }); }; Subject2.prototype.complete = function() { var _this = this; errorContext(function() { _this._throwIfClosed(); if (!_this.isStopped) { _this.isStopped = true; var observers = _this.observers; while (observers.length) { observers.shift().complete(); } } }); }; Subject2.prototype.unsubscribe = function() { this.isStopped = this.closed = true; this.observers = this.currentObservers = null; }; Object.defineProperty(Subject2.prototype, "observed", { get: function() { var _a; return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0; }, enumerable: false, configurable: true }); Subject2.prototype._trySubscribe = function(subscriber) { this._throwIfClosed(); return _super.prototype._trySubscribe.call(this, subscriber); }; Subject2.prototype._subscribe = function(subscriber) { this._throwIfClosed(); this._checkFinalizedStatuses(subscriber); return this._innerSubscribe(subscriber); }; Subject2.prototype._innerSubscribe = function(subscriber) { var _this = this; var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers; if (hasError || isStopped) { return EMPTY_SUBSCRIPTION; } this.currentObservers = null; observers.push(subscriber); return new Subscription(function() { _this.currentObservers = null; arrRemove(observers, subscriber); }); }; Subject2.prototype._checkFinalizedStatuses = function(subscriber) { var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped; if (hasError) { subscriber.error(thrownError); } else if (isStopped) { subscriber.complete(); } }; Subject2.prototype.asObservable = function() { var observable2 = new Observable(); observable2.source = this; return observable2; }; Subject2.create = function(destination, source) { return new AnonymousSubject(destination, source); }; return Subject2; }(Observable); var AnonymousSubject = function(_super) { __extends(AnonymousSubject2, _super); function AnonymousSubject2(destination, source) { var _this = _super.call(this) || this; _this.destination = destination; _this.source = source; return _this; } AnonymousSubject2.prototype.next = function(value) { var _a, _b; (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value); }; AnonymousSubject2.prototype.error = function(err) { var _a, _b; (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err); }; AnonymousSubject2.prototype.complete = function() { var _a, _b; (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a); }; AnonymousSubject2.prototype._subscribe = function(subscriber) { var _a, _b; return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION; }; return AnonymousSubject2; }(Subject); var BehaviorSubject = function(_super) { __extends(BehaviorSubject2, _super); function BehaviorSubject2(_value) { var _this = _super.call(this) || this; _this._value = _value; return _this; } Object.defineProperty(BehaviorSubject2.prototype, "value", { get: function() { return this.getValue(); }, enumerable: false, configurable: true }); BehaviorSubject2.prototype._subscribe = function(subscriber) { var subscription = _super.prototype._subscribe.call(this, subscriber); !subscription.closed && subscriber.next(this._value); return subscription; }; BehaviorSubject2.prototype.getValue = function() { var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value; if (hasError) { throw thrownError; } this._throwIfClosed(); return _value; }; BehaviorSubject2.prototype.next = function(value) { _super.prototype.next.call(this, this._value = value); }; return BehaviorSubject2; }(Subject); var dateTimestampProvider = { now: function() { return (dateTimestampProvider.delegate || Date).now(); }, delegate: void 0 }; var Action = function(_super) { __extends(Action2, _super); function Action2(scheduler, work) { return _super.call(this) || this; } Action2.prototype.schedule = function(state, delay2) { return this; }; return Action2; }(Subscription); var intervalProvider = { setIn